detect.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  1. import os
  2. import re
  3. import subprocess
  4. import sys
  5. from typing import TYPE_CHECKING
  6. import methods
  7. from methods import print_error, print_warning
  8. from platform_methods import detect_arch
  9. if TYPE_CHECKING:
  10. from SCons.Script.SConscript import SConsEnvironment
  11. # To match other platforms
  12. STACK_SIZE = 8388608
  13. def get_name():
  14. return "Windows"
  15. def try_cmd(test, prefix, arch):
  16. if arch:
  17. try:
  18. out = subprocess.Popen(
  19. get_mingw_bin_prefix(prefix, arch) + test,
  20. shell=True,
  21. stderr=subprocess.PIPE,
  22. stdout=subprocess.PIPE,
  23. )
  24. out.communicate()
  25. if out.returncode == 0:
  26. return True
  27. except Exception:
  28. pass
  29. else:
  30. for a in ["x86_64", "x86_32", "arm64", "arm32"]:
  31. try:
  32. out = subprocess.Popen(
  33. get_mingw_bin_prefix(prefix, a) + test,
  34. shell=True,
  35. stderr=subprocess.PIPE,
  36. stdout=subprocess.PIPE,
  37. )
  38. out.communicate()
  39. if out.returncode == 0:
  40. return True
  41. except Exception:
  42. pass
  43. return False
  44. def can_build():
  45. if os.name == "nt":
  46. # Building natively on Windows
  47. # If VCINSTALLDIR is set in the OS environ, use traditional Godot logic to set up MSVC
  48. if os.getenv("VCINSTALLDIR"): # MSVC, manual setup
  49. return True
  50. # Otherwise, let SCons find MSVC if installed, or else MinGW.
  51. # Since we're just returning True here, if there's no compiler
  52. # installed, we'll get errors when it tries to build with the
  53. # null compiler.
  54. return True
  55. if os.name == "posix":
  56. # Cross-compiling with MinGW-w64 (old MinGW32 is not supported)
  57. prefix = os.getenv("MINGW_PREFIX", "")
  58. if try_cmd("gcc --version", prefix, "") or try_cmd("clang --version", prefix, ""):
  59. return True
  60. return False
  61. def get_mingw_bin_prefix(prefix, arch):
  62. if not prefix:
  63. mingw_bin_prefix = ""
  64. elif prefix[-1] != "/":
  65. mingw_bin_prefix = prefix + "/bin/"
  66. else:
  67. mingw_bin_prefix = prefix + "bin/"
  68. if arch == "x86_64":
  69. mingw_bin_prefix += "x86_64-w64-mingw32-"
  70. elif arch == "x86_32":
  71. mingw_bin_prefix += "i686-w64-mingw32-"
  72. elif arch == "arm32":
  73. mingw_bin_prefix += "armv7-w64-mingw32-"
  74. elif arch == "arm64":
  75. mingw_bin_prefix += "aarch64-w64-mingw32-"
  76. return mingw_bin_prefix
  77. def detect_build_env_arch():
  78. msvc_target_aliases = {
  79. "amd64": "x86_64",
  80. "i386": "x86_32",
  81. "i486": "x86_32",
  82. "i586": "x86_32",
  83. "i686": "x86_32",
  84. "x86": "x86_32",
  85. "x64": "x86_64",
  86. "x86_64": "x86_64",
  87. "arm": "arm32",
  88. "arm64": "arm64",
  89. "aarch64": "arm64",
  90. }
  91. if os.getenv("VCINSTALLDIR") or os.getenv("VCTOOLSINSTALLDIR"):
  92. if os.getenv("Platform"):
  93. msvc_arch = os.getenv("Platform").lower()
  94. if msvc_arch in msvc_target_aliases.keys():
  95. return msvc_target_aliases[msvc_arch]
  96. if os.getenv("VSCMD_ARG_TGT_ARCH"):
  97. msvc_arch = os.getenv("VSCMD_ARG_TGT_ARCH").lower()
  98. if msvc_arch in msvc_target_aliases.keys():
  99. return msvc_target_aliases[msvc_arch]
  100. # Pre VS 2017 checks.
  101. if os.getenv("VCINSTALLDIR"):
  102. PATH = os.getenv("PATH").upper()
  103. VCINSTALLDIR = os.getenv("VCINSTALLDIR").upper()
  104. path_arch = {
  105. "BIN\\x86_ARM;": "arm32",
  106. "BIN\\amd64_ARM;": "arm32",
  107. "BIN\\x86_ARM64;": "arm64",
  108. "BIN\\amd64_ARM64;": "arm64",
  109. "BIN\\x86_amd64;": "a86_64",
  110. "BIN\\amd64;": "x86_64",
  111. "BIN\\amd64_x86;": "x86_32",
  112. "BIN;": "x86_32",
  113. }
  114. for path, arch in path_arch.items():
  115. final_path = VCINSTALLDIR + path
  116. if final_path in PATH:
  117. return arch
  118. # VS 2017 and newer.
  119. if os.getenv("VCTOOLSINSTALLDIR"):
  120. host_path_index = os.getenv("PATH").upper().find(os.getenv("VCTOOLSINSTALLDIR").upper() + "BIN\\HOST")
  121. if host_path_index > -1:
  122. first_path_arch = os.getenv("PATH").split(";")[0].rsplit("\\", 1)[-1].lower()
  123. return msvc_target_aliases[first_path_arch]
  124. msys_target_aliases = {
  125. "mingw32": "x86_32",
  126. "mingw64": "x86_64",
  127. "ucrt64": "x86_64",
  128. "clang64": "x86_64",
  129. "clang32": "x86_32",
  130. "clangarm64": "arm64",
  131. }
  132. if os.getenv("MSYSTEM"):
  133. msys_arch = os.getenv("MSYSTEM").lower()
  134. if msys_arch in msys_target_aliases.keys():
  135. return msys_target_aliases[msys_arch]
  136. return ""
  137. def get_opts():
  138. from SCons.Variables import BoolVariable, EnumVariable
  139. mingw = os.getenv("MINGW_PREFIX", "")
  140. # Direct3D 12 SDK dependencies folder.
  141. d3d12_deps_folder = os.getenv("LOCALAPPDATA")
  142. if d3d12_deps_folder:
  143. d3d12_deps_folder = os.path.join(d3d12_deps_folder, "Godot", "build_deps")
  144. else:
  145. # Cross-compiling, the deps install script puts things in `bin`.
  146. # Getting an absolute path to it is a bit hacky in Python.
  147. try:
  148. import inspect
  149. caller_frame = inspect.stack()[1]
  150. caller_script_dir = os.path.dirname(os.path.abspath(caller_frame[1]))
  151. d3d12_deps_folder = os.path.join(caller_script_dir, "bin", "build_deps")
  152. except Exception: # Give up.
  153. d3d12_deps_folder = ""
  154. return [
  155. ("mingw_prefix", "MinGW prefix", mingw),
  156. # Targeted Windows version: 7 (and later), minimum supported version
  157. # XP support dropped after EOL due to missing API for IPv6 and other issues
  158. # Vista support dropped after EOL due to GH-10243
  159. (
  160. "target_win_version",
  161. "Targeted Windows version, >= 0x0601 (Windows 7)",
  162. "0x0601",
  163. ),
  164. EnumVariable("windows_subsystem", "Windows subsystem", "gui", ("gui", "console")),
  165. (
  166. "msvc_version",
  167. "MSVC version to use. Ignored if VCINSTALLDIR is set in shell env.",
  168. None,
  169. ),
  170. BoolVariable("use_mingw", "Use the Mingw compiler, even if MSVC is installed.", False),
  171. BoolVariable("use_llvm", "Use the LLVM compiler", False),
  172. BoolVariable("use_static_cpp", "Link MinGW/MSVC C++ runtime libraries statically", True),
  173. BoolVariable("use_asan", "Use address sanitizer (ASAN)", False),
  174. BoolVariable("debug_crt", "Compile with MSVC's debug CRT (/MDd)", False),
  175. BoolVariable("incremental_link", "Use MSVC incremental linking. May increase or decrease build times.", False),
  176. BoolVariable("silence_msvc", "Silence MSVC's cl/link stdout bloat, redirecting any errors to stderr.", True),
  177. ("angle_libs", "Path to the ANGLE static libraries", ""),
  178. # Direct3D 12 support.
  179. (
  180. "mesa_libs",
  181. "Path to the MESA/NIR static libraries (required for D3D12)",
  182. os.path.join(d3d12_deps_folder, "mesa"),
  183. ),
  184. (
  185. "dxc_path",
  186. "Path to the DirectX Shader Compiler distribution (required for D3D12)",
  187. os.path.join(d3d12_deps_folder, "dxc"),
  188. ),
  189. (
  190. "agility_sdk_path",
  191. "Path to the Agility SDK distribution (optional for D3D12)",
  192. os.path.join(d3d12_deps_folder, "agility_sdk"),
  193. ),
  194. BoolVariable(
  195. "agility_sdk_multiarch",
  196. "Whether the Agility SDK DLLs will be stored in arch-specific subdirectories",
  197. False,
  198. ),
  199. BoolVariable("use_pix", "Use PIX (Performance tuning and debugging for DirectX 12) runtime", False),
  200. (
  201. "pix_path",
  202. "Path to the PIX runtime distribution (optional for D3D12)",
  203. os.path.join(d3d12_deps_folder, "pix"),
  204. ),
  205. ]
  206. def get_doc_classes():
  207. return [
  208. "EditorExportPlatformWindows",
  209. ]
  210. def get_doc_path():
  211. return "doc_classes"
  212. def get_flags():
  213. arch = detect_build_env_arch() or detect_arch()
  214. return {
  215. "arch": arch,
  216. "supported": ["mono"],
  217. }
  218. def build_res_file(target, source, env: "SConsEnvironment"):
  219. arch_aliases = {
  220. "x86_32": "pe-i386",
  221. "x86_64": "pe-x86-64",
  222. "arm32": "armv7-w64-mingw32",
  223. "arm64": "aarch64-w64-mingw32",
  224. }
  225. cmdbase = "windres --include-dir . --target=" + arch_aliases[env["arch"]]
  226. mingw_bin_prefix = get_mingw_bin_prefix(env["mingw_prefix"], env["arch"])
  227. for x in range(len(source)):
  228. ok = True
  229. # Try prefixed executable (MinGW on Linux).
  230. cmd = mingw_bin_prefix + cmdbase + " -i " + str(source[x]) + " -o " + str(target[x])
  231. try:
  232. out = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE).communicate()
  233. if len(out[1]):
  234. ok = False
  235. except Exception:
  236. ok = False
  237. # Try generic executable (MSYS2).
  238. if not ok:
  239. cmd = cmdbase + " -i " + str(source[x]) + " -o " + str(target[x])
  240. try:
  241. out = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE).communicate()
  242. if len(out[1]):
  243. return -1
  244. except Exception:
  245. return -1
  246. return 0
  247. def setup_msvc_manual(env: "SConsEnvironment"):
  248. """Running from VCVARS environment"""
  249. env_arch = detect_build_env_arch()
  250. if env["arch"] != env_arch:
  251. print_error(
  252. "Arch argument (%s) is not matching Native/Cross Compile Tools Prompt/Developer Console (or Visual Studio settings) that is being used to run SCons (%s).\n"
  253. "Run SCons again without arch argument (example: scons p=windows) and SCons will attempt to detect what MSVC compiler will be executed and inform you."
  254. % (env["arch"], env_arch)
  255. )
  256. sys.exit(255)
  257. print("Using VCVARS-determined MSVC, arch %s" % (env_arch))
  258. # FIXME: Likely overwrites command-line options for the msvc compiler. See #91883.
  259. def setup_msvc_auto(env: "SConsEnvironment"):
  260. """Set up MSVC using SCons's auto-detection logic"""
  261. # If MSVC_VERSION is set by SCons, we know MSVC is installed.
  262. # But we may want a different version or target arch.
  263. # Valid architectures for MSVC's TARGET_ARCH:
  264. # ['amd64', 'emt64', 'i386', 'i486', 'i586', 'i686', 'ia64', 'itanium', 'x86', 'x86_64', 'arm', 'arm64', 'aarch64']
  265. # Our x86_64 and arm64 are the same, and we need to map the 32-bit
  266. # architectures to other names since MSVC isn't as explicit.
  267. # The rest we don't need to worry about because they are
  268. # aliases or aren't supported by Godot (itanium & ia64).
  269. msvc_arch_aliases = {"x86_32": "x86", "arm32": "arm"}
  270. if env["arch"] in msvc_arch_aliases.keys():
  271. env["TARGET_ARCH"] = msvc_arch_aliases[env["arch"]]
  272. else:
  273. env["TARGET_ARCH"] = env["arch"]
  274. # The env may have already been set up with default MSVC tools, so
  275. # reset a few things so we can set it up with the tools we want.
  276. # (Ideally we'd decide on the tool config before configuring any
  277. # environment, and just set the env up once, but this function runs
  278. # on an existing env so this is the simplest way.)
  279. env["MSVC_SETUP_RUN"] = False # Need to set this to re-run the tool
  280. env["MSVS_VERSION"] = None
  281. env["MSVC_VERSION"] = None
  282. if "msvc_version" in env:
  283. env["MSVC_VERSION"] = env["msvc_version"]
  284. env.Tool("msvc")
  285. env.Tool("mssdk") # we want the MS SDK
  286. # Note: actual compiler version can be found in env['MSVC_VERSION'], e.g. "14.1" for VS2015
  287. print("Using SCons-detected MSVC version %s, arch %s" % (env["MSVC_VERSION"], env["arch"]))
  288. def setup_mingw(env: "SConsEnvironment"):
  289. """Set up env for use with mingw"""
  290. env_arch = detect_build_env_arch()
  291. if os.getenv("MSYSTEM") == "MSYS":
  292. print_error(
  293. "Running from base MSYS2 console/environment, use target specific environment instead (e.g., mingw32, mingw64, clang32, clang64)."
  294. )
  295. sys.exit(255)
  296. if env_arch != "" and env["arch"] != env_arch:
  297. print_error(
  298. "Arch argument (%s) is not matching MSYS2 console/environment that is being used to run SCons (%s).\n"
  299. "Run SCons again without arch argument (example: scons p=windows) and SCons will attempt to detect what MSYS2 compiler will be executed and inform you."
  300. % (env["arch"], env_arch)
  301. )
  302. sys.exit(255)
  303. if not try_cmd("gcc --version", env["mingw_prefix"], env["arch"]) and not try_cmd(
  304. "clang --version", env["mingw_prefix"], env["arch"]
  305. ):
  306. print_error("No valid compilers found, use MINGW_PREFIX environment variable to set MinGW path.")
  307. sys.exit(255)
  308. print("Using MinGW, arch %s" % (env["arch"]))
  309. def configure_msvc(env: "SConsEnvironment", vcvars_msvc_config):
  310. """Configure env to work with MSVC"""
  311. ## Build type
  312. # TODO: Re-evaluate the need for this / streamline with common config.
  313. if env["target"] == "template_release":
  314. env.Append(LINKFLAGS=["/ENTRY:mainCRTStartup"])
  315. if env["windows_subsystem"] == "gui":
  316. env.Append(LINKFLAGS=["/SUBSYSTEM:WINDOWS"])
  317. else:
  318. env.Append(LINKFLAGS=["/SUBSYSTEM:CONSOLE"])
  319. env.AppendUnique(CPPDEFINES=["WINDOWS_SUBSYSTEM_CONSOLE"])
  320. ## Compile/link flags
  321. env["MAXLINELENGTH"] = 8192 # Windows Vista and beyond, so always applicable.
  322. if env["silence_msvc"] and not env.GetOption("clean"):
  323. from tempfile import mkstemp
  324. # Ensure we have a location to write captured output to, in case of false positives.
  325. capture_path = methods.base_folder_path + "platform/windows/msvc_capture.log"
  326. with open(capture_path, "wt", encoding="utf-8"):
  327. pass
  328. old_spawn = env["SPAWN"]
  329. re_redirect_stream = re.compile(r"^[12]?>")
  330. re_cl_capture = re.compile(r"^.+\.(c|cc|cpp|cxx|c[+]{2})$", re.IGNORECASE)
  331. re_link_capture = re.compile(r'\s{3}\S.+\s(?:"[^"]+.lib"|\S+.lib)\s.+\s(?:"[^"]+.exp"|\S+.exp)')
  332. def spawn_capture(sh, escape, cmd, args, env):
  333. # We only care about cl/link, process everything else as normal.
  334. if args[0] not in ["cl", "link"]:
  335. return old_spawn(sh, escape, cmd, args, env)
  336. # Process as normal if the user is manually rerouting output.
  337. for arg in args:
  338. if re_redirect_stream.match(arg):
  339. return old_spawn(sh, escape, cmd, args, env)
  340. tmp_stdout, tmp_stdout_name = mkstemp()
  341. os.close(tmp_stdout)
  342. args.append(f">{tmp_stdout_name}")
  343. ret = old_spawn(sh, escape, cmd, args, env)
  344. try:
  345. with open(tmp_stdout_name, "r", encoding=sys.stdout.encoding, errors="replace") as tmp_stdout:
  346. lines = tmp_stdout.read().splitlines()
  347. os.remove(tmp_stdout_name)
  348. except OSError:
  349. pass
  350. # Early process no lines (OSError)
  351. if not lines:
  352. return ret
  353. is_cl = args[0] == "cl"
  354. content = ""
  355. caught = False
  356. for line in lines:
  357. # These conditions are far from all-encompassing, but are specialized
  358. # for what can be reasonably expected to show up in the repository.
  359. if not caught and (is_cl and re_cl_capture.match(line)) or (not is_cl and re_link_capture.match(line)):
  360. caught = True
  361. try:
  362. with open(capture_path, "a", encoding=sys.stdout.encoding) as log:
  363. log.write(line + "\n")
  364. except OSError:
  365. print_warning(f'Failed to log captured line: "{line}".')
  366. continue
  367. content += line + "\n"
  368. # Content remaining assumed to be an error/warning.
  369. if content:
  370. sys.stderr.write(content)
  371. return ret
  372. env["SPAWN"] = spawn_capture
  373. if env["debug_crt"]:
  374. # Always use dynamic runtime, static debug CRT breaks thread_local.
  375. env.AppendUnique(CCFLAGS=["/MDd"])
  376. else:
  377. if env["use_static_cpp"]:
  378. env.AppendUnique(CCFLAGS=["/MT"])
  379. else:
  380. env.AppendUnique(CCFLAGS=["/MD"])
  381. # MSVC incremental linking is broken and may _increase_ link time (GH-77968).
  382. if not env["incremental_link"]:
  383. env.Append(LINKFLAGS=["/INCREMENTAL:NO"])
  384. if env["arch"] == "x86_32":
  385. env["x86_libtheora_opt_vc"] = True
  386. env.AppendUnique(CCFLAGS=["/Gd", "/GR", "/nologo"])
  387. env.AppendUnique(CCFLAGS=["/utf-8"]) # Force to use Unicode encoding.
  388. env.AppendUnique(CXXFLAGS=["/TP"]) # assume all sources are C++
  389. # Once it was thought that only debug builds would be too large,
  390. # but this has recently stopped being true. See the mingw function
  391. # for notes on why this shouldn't be enabled for gcc
  392. env.AppendUnique(CCFLAGS=["/bigobj"])
  393. if vcvars_msvc_config: # should be automatic if SCons found it
  394. if os.getenv("WindowsSdkDir") is not None:
  395. env.Prepend(CPPPATH=[str(os.getenv("WindowsSdkDir")) + "/Include"])
  396. else:
  397. print_warning("Missing environment variable: WindowsSdkDir")
  398. if int(env["target_win_version"], 16) < 0x0601:
  399. print_error("`target_win_version` should be 0x0601 or higher (Windows 7).")
  400. sys.exit(255)
  401. env.AppendUnique(
  402. CPPDEFINES=[
  403. "WINDOWS_ENABLED",
  404. "WASAPI_ENABLED",
  405. "WINMIDI_ENABLED",
  406. "TYPED_METHOD_BIND",
  407. "WIN32",
  408. "WINVER=%s" % env["target_win_version"],
  409. "_WIN32_WINNT=%s" % env["target_win_version"],
  410. ]
  411. )
  412. env.AppendUnique(CPPDEFINES=["NOMINMAX"]) # disable bogus min/max WinDef.h macros
  413. if env["arch"] == "x86_64":
  414. env.AppendUnique(CPPDEFINES=["_WIN64"])
  415. ## Libs
  416. LIBS = [
  417. "winmm",
  418. "dsound",
  419. "kernel32",
  420. "ole32",
  421. "oleaut32",
  422. "sapi",
  423. "user32",
  424. "gdi32",
  425. "IPHLPAPI",
  426. "Shlwapi",
  427. "wsock32",
  428. "Ws2_32",
  429. "shell32",
  430. "advapi32",
  431. "dinput8",
  432. "dxguid",
  433. "imm32",
  434. "bcrypt",
  435. "Crypt32",
  436. "Avrt",
  437. "dwmapi",
  438. "dwrite",
  439. "wbemuuid",
  440. "ntdll",
  441. ]
  442. if env.debug_features:
  443. LIBS += ["psapi", "dbghelp"]
  444. if env["vulkan"]:
  445. env.AppendUnique(CPPDEFINES=["VULKAN_ENABLED", "RD_ENABLED"])
  446. if not env["use_volk"]:
  447. LIBS += ["vulkan"]
  448. if env["d3d12"]:
  449. # Check whether we have d3d12 dependencies installed.
  450. if not os.path.exists(env["mesa_libs"]):
  451. print_error(
  452. "The Direct3D 12 rendering driver requires dependencies to be installed.\n"
  453. "You can install them by running `python misc\\scripts\\install_d3d12_sdk_windows.py`.\n"
  454. "See the documentation for more information:\n\t"
  455. "https://docs.godotengine.org/en/latest/contributing/development/compiling/compiling_for_windows.html"
  456. )
  457. sys.exit(255)
  458. env.AppendUnique(CPPDEFINES=["D3D12_ENABLED", "RD_ENABLED"])
  459. LIBS += ["dxgi", "dxguid"]
  460. LIBS += ["version"] # Mesa dependency.
  461. # Needed for avoiding C1128.
  462. if env["target"] == "release_debug":
  463. env.Append(CXXFLAGS=["/bigobj"])
  464. # PIX
  465. if env["arch"] not in ["x86_64", "arm64"] or env["pix_path"] == "" or not os.path.exists(env["pix_path"]):
  466. env["use_pix"] = False
  467. if env["use_pix"]:
  468. arch_subdir = "arm64" if env["arch"] == "arm64" else "x64"
  469. env.Append(LIBPATH=[env["pix_path"] + "/bin/" + arch_subdir])
  470. LIBS += ["WinPixEventRuntime"]
  471. env.Append(LIBPATH=[env["mesa_libs"] + "/bin"])
  472. LIBS += ["libNIR.windows." + env["arch"]]
  473. if env["opengl3"]:
  474. env.AppendUnique(CPPDEFINES=["GLES3_ENABLED"])
  475. if env["angle_libs"] != "":
  476. env.AppendUnique(CPPDEFINES=["EGL_STATIC"])
  477. env.Append(LIBPATH=[env["angle_libs"]])
  478. LIBS += [
  479. "libANGLE.windows." + env["arch"],
  480. "libEGL.windows." + env["arch"],
  481. "libGLES.windows." + env["arch"],
  482. ]
  483. LIBS += ["dxgi", "d3d9", "d3d11"]
  484. env.Prepend(CPPPATH=["#thirdparty/angle/include"])
  485. if env["target"] in ["editor", "template_debug"]:
  486. LIBS += ["psapi", "dbghelp"]
  487. env.Append(LINKFLAGS=[p + env["LIBSUFFIX"] for p in LIBS])
  488. if vcvars_msvc_config:
  489. if os.getenv("WindowsSdkDir") is not None:
  490. env.Append(LIBPATH=[str(os.getenv("WindowsSdkDir")) + "/Lib"])
  491. else:
  492. print_warning("Missing environment variable: WindowsSdkDir")
  493. ## LTO
  494. if env["lto"] == "auto": # No LTO by default for MSVC, doesn't help.
  495. env["lto"] = "none"
  496. if env["lto"] != "none":
  497. if env["lto"] == "thin":
  498. print_error("ThinLTO is only compatible with LLVM, use `use_llvm=yes` or `lto=full`.")
  499. sys.exit(255)
  500. env.AppendUnique(CCFLAGS=["/GL"])
  501. env.AppendUnique(ARFLAGS=["/LTCG"])
  502. if env["progress"]:
  503. env.AppendUnique(LINKFLAGS=["/LTCG:STATUS"])
  504. else:
  505. env.AppendUnique(LINKFLAGS=["/LTCG"])
  506. if vcvars_msvc_config:
  507. env.Prepend(CPPPATH=[p for p in str(os.getenv("INCLUDE")).split(";")])
  508. env.Append(LIBPATH=[p for p in str(os.getenv("LIB")).split(";")])
  509. # Sanitizers
  510. if env["use_asan"]:
  511. env.extra_suffix += ".san"
  512. env.Append(LINKFLAGS=["/INFERASANLIBS"])
  513. env.Append(CCFLAGS=["/fsanitize=address"])
  514. # Incremental linking fix
  515. env["BUILDERS"]["ProgramOriginal"] = env["BUILDERS"]["Program"]
  516. env["BUILDERS"]["Program"] = methods.precious_program
  517. env.Append(LINKFLAGS=["/NATVIS:platform\\windows\\godot.natvis"])
  518. env.AppendUnique(LINKFLAGS=["/STACK:" + str(STACK_SIZE)])
  519. def configure_mingw(env: "SConsEnvironment"):
  520. # Workaround for MinGW. See:
  521. # https://www.scons.org/wiki/LongCmdLinesOnWin32
  522. env.use_windows_spawn_fix()
  523. ## Build type
  524. if not env["use_llvm"] and not try_cmd("gcc --version", env["mingw_prefix"], env["arch"]):
  525. env["use_llvm"] = True
  526. if env["use_llvm"] and not try_cmd("clang --version", env["mingw_prefix"], env["arch"]):
  527. env["use_llvm"] = False
  528. # TODO: Re-evaluate the need for this / streamline with common config.
  529. if env["target"] == "template_release":
  530. env.Append(CCFLAGS=["-msse2"])
  531. elif env.dev_build:
  532. # Allow big objects. It's supposed not to have drawbacks but seems to break
  533. # GCC LTO, so enabling for debug builds only (which are not built with LTO
  534. # and are the only ones with too big objects).
  535. env.Append(CCFLAGS=["-Wa,-mbig-obj"])
  536. if env["windows_subsystem"] == "gui":
  537. env.Append(LINKFLAGS=["-Wl,--subsystem,windows"])
  538. else:
  539. env.Append(LINKFLAGS=["-Wl,--subsystem,console"])
  540. env.AppendUnique(CPPDEFINES=["WINDOWS_SUBSYSTEM_CONSOLE"])
  541. ## Compiler configuration
  542. if os.name != "nt":
  543. env["PROGSUFFIX"] = env["PROGSUFFIX"] + ".exe" # for linux cross-compilation
  544. if env["arch"] == "x86_32":
  545. if env["use_static_cpp"]:
  546. env.Append(LINKFLAGS=["-static"])
  547. env.Append(LINKFLAGS=["-static-libgcc"])
  548. env.Append(LINKFLAGS=["-static-libstdc++"])
  549. else:
  550. if env["use_static_cpp"]:
  551. env.Append(LINKFLAGS=["-static"])
  552. if env["arch"] in ["x86_32", "x86_64"]:
  553. env["x86_libtheora_opt_gcc"] = True
  554. mingw_bin_prefix = get_mingw_bin_prefix(env["mingw_prefix"], env["arch"])
  555. if env["use_llvm"]:
  556. env["CC"] = mingw_bin_prefix + "clang"
  557. env["CXX"] = mingw_bin_prefix + "clang++"
  558. if try_cmd("as --version", env["mingw_prefix"], env["arch"]):
  559. env["AS"] = mingw_bin_prefix + "as"
  560. env.Append(ASFLAGS=["-c"])
  561. if try_cmd("ar --version", env["mingw_prefix"], env["arch"]):
  562. env["AR"] = mingw_bin_prefix + "ar"
  563. if try_cmd("ranlib --version", env["mingw_prefix"], env["arch"]):
  564. env["RANLIB"] = mingw_bin_prefix + "ranlib"
  565. env.extra_suffix = ".llvm" + env.extra_suffix
  566. else:
  567. env["CC"] = mingw_bin_prefix + "gcc"
  568. env["CXX"] = mingw_bin_prefix + "g++"
  569. if try_cmd("as --version", env["mingw_prefix"], env["arch"]):
  570. env["AS"] = mingw_bin_prefix + "as"
  571. if try_cmd("gcc-ar --version", env["mingw_prefix"], env["arch"]):
  572. env["AR"] = mingw_bin_prefix + "gcc-ar"
  573. if try_cmd("gcc-ranlib --version", env["mingw_prefix"], env["arch"]):
  574. env["RANLIB"] = mingw_bin_prefix + "gcc-ranlib"
  575. ## LTO
  576. if env["lto"] == "auto": # Full LTO for production with MinGW.
  577. env["lto"] = "full"
  578. if env["lto"] != "none":
  579. if env["lto"] == "thin":
  580. if not env["use_llvm"]:
  581. print("ThinLTO is only compatible with LLVM, use `use_llvm=yes` or `lto=full`.")
  582. sys.exit(255)
  583. env.Append(CCFLAGS=["-flto=thin"])
  584. env.Append(LINKFLAGS=["-flto=thin"])
  585. elif not env["use_llvm"] and env.GetOption("num_jobs") > 1:
  586. env.Append(CCFLAGS=["-flto"])
  587. env.Append(LINKFLAGS=["-flto=" + str(env.GetOption("num_jobs"))])
  588. else:
  589. env.Append(CCFLAGS=["-flto"])
  590. env.Append(LINKFLAGS=["-flto"])
  591. env.Append(LINKFLAGS=["-Wl,--stack," + str(STACK_SIZE)])
  592. ## Compile flags
  593. if int(env["target_win_version"], 16) < 0x0601:
  594. print_error("`target_win_version` should be 0x0601 or higher (Windows 7).")
  595. sys.exit(255)
  596. if not env["use_llvm"]:
  597. env.Append(CCFLAGS=["-mwindows"])
  598. env.Append(CPPDEFINES=["WINDOWS_ENABLED", "WASAPI_ENABLED", "WINMIDI_ENABLED"])
  599. env.Append(
  600. CPPDEFINES=[
  601. ("WINVER", env["target_win_version"]),
  602. ("_WIN32_WINNT", env["target_win_version"]),
  603. ]
  604. )
  605. env.Append(
  606. LIBS=[
  607. "mingw32",
  608. "dsound",
  609. "ole32",
  610. "d3d9",
  611. "winmm",
  612. "gdi32",
  613. "iphlpapi",
  614. "shlwapi",
  615. "wsock32",
  616. "ws2_32",
  617. "kernel32",
  618. "oleaut32",
  619. "sapi",
  620. "dinput8",
  621. "dxguid",
  622. "ksuser",
  623. "imm32",
  624. "bcrypt",
  625. "crypt32",
  626. "avrt",
  627. "uuid",
  628. "dwmapi",
  629. "dwrite",
  630. "wbemuuid",
  631. "ntdll",
  632. ]
  633. )
  634. if env.debug_features:
  635. env.Append(LIBS=["psapi", "dbghelp"])
  636. if env["vulkan"]:
  637. env.Append(CPPDEFINES=["VULKAN_ENABLED", "RD_ENABLED"])
  638. if not env["use_volk"]:
  639. env.Append(LIBS=["vulkan"])
  640. if env["d3d12"]:
  641. # Check whether we have d3d12 dependencies installed.
  642. if not os.path.exists(env["mesa_libs"]):
  643. print_error(
  644. "The Direct3D 12 rendering driver requires dependencies to be installed.\n"
  645. "You can install them by running `python misc\\scripts\\install_d3d12_sdk_windows.py`.\n"
  646. "See the documentation for more information:\n\t"
  647. "https://docs.godotengine.org/en/latest/contributing/development/compiling/compiling_for_windows.html"
  648. )
  649. sys.exit(255)
  650. env.AppendUnique(CPPDEFINES=["D3D12_ENABLED", "RD_ENABLED"])
  651. env.Append(LIBS=["dxgi", "dxguid"])
  652. # PIX
  653. if env["arch"] not in ["x86_64", "arm64"] or env["pix_path"] == "" or not os.path.exists(env["pix_path"]):
  654. env["use_pix"] = False
  655. if env["use_pix"]:
  656. arch_subdir = "arm64" if env["arch"] == "arm64" else "x64"
  657. env.Append(LIBPATH=[env["pix_path"] + "/bin/" + arch_subdir])
  658. env.Append(LIBS=["WinPixEventRuntime"])
  659. env.Append(LIBPATH=[env["mesa_libs"] + "/bin"])
  660. env.Append(LIBS=["libNIR.windows." + env["arch"]])
  661. env.Append(LIBS=["version"]) # Mesa dependency.
  662. if env["opengl3"]:
  663. env.Append(CPPDEFINES=["GLES3_ENABLED"])
  664. if env["angle_libs"] != "":
  665. env.AppendUnique(CPPDEFINES=["EGL_STATIC"])
  666. env.Append(LIBPATH=[env["angle_libs"]])
  667. env.Append(
  668. LIBS=[
  669. "EGL.windows." + env["arch"],
  670. "GLES.windows." + env["arch"],
  671. "ANGLE.windows." + env["arch"],
  672. ]
  673. )
  674. env.Append(LIBS=["dxgi", "d3d9", "d3d11"])
  675. env.Prepend(CPPPATH=["#thirdparty/angle/include"])
  676. env.Append(CPPDEFINES=["MINGW_ENABLED", ("MINGW_HAS_SECURE_API", 1)])
  677. # resrc
  678. env.Append(BUILDERS={"RES": env.Builder(action=build_res_file, suffix=".o", src_suffix=".rc")})
  679. def configure(env: "SConsEnvironment"):
  680. # Validate arch.
  681. supported_arches = ["x86_32", "x86_64", "arm32", "arm64"]
  682. if env["arch"] not in supported_arches:
  683. print_error(
  684. 'Unsupported CPU architecture "%s" for Windows. Supported architectures are: %s.'
  685. % (env["arch"], ", ".join(supported_arches))
  686. )
  687. sys.exit(255)
  688. # At this point the env has been set up with basic tools/compilers.
  689. env.Prepend(CPPPATH=["#platform/windows"])
  690. if os.name == "nt":
  691. env["ENV"] = os.environ # this makes build less repeatable, but simplifies some things
  692. env["ENV"]["TMP"] = os.environ["TMP"]
  693. # First figure out which compiler, version, and target arch we're using
  694. if os.getenv("VCINSTALLDIR") and detect_build_env_arch() and not env["use_mingw"]:
  695. setup_msvc_manual(env)
  696. env.msvc = True
  697. vcvars_msvc_config = True
  698. elif env.get("MSVC_VERSION", "") and not env["use_mingw"]:
  699. setup_msvc_auto(env)
  700. env.msvc = True
  701. vcvars_msvc_config = False
  702. else:
  703. setup_mingw(env)
  704. env.msvc = False
  705. # Now set compiler/linker flags
  706. if env.msvc:
  707. configure_msvc(env, vcvars_msvc_config)
  708. else: # MinGW
  709. configure_mingw(env)