detect.py 28 KB

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