detect.py 32 KB

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