2
0

detect.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  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 import Environment
  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. return [
  139. ("mingw_prefix", "MinGW prefix", mingw),
  140. # Targeted Windows version: 7 (and later), minimum supported version
  141. # XP support dropped after EOL due to missing API for IPv6 and other issues
  142. # Vista support dropped after EOL due to GH-10243
  143. (
  144. "target_win_version",
  145. "Targeted Windows version, >= 0x0601 (Windows 7)",
  146. "0x0601",
  147. ),
  148. EnumVariable("windows_subsystem", "Windows subsystem", "gui", ("gui", "console")),
  149. (
  150. "msvc_version",
  151. "MSVC version to use. Ignored if VCINSTALLDIR is set in shell env.",
  152. None,
  153. ),
  154. BoolVariable("use_mingw", "Use the Mingw compiler, even if MSVC is installed.", False),
  155. BoolVariable("use_llvm", "Use the LLVM compiler", False),
  156. BoolVariable("use_static_cpp", "Link MinGW/MSVC C++ runtime libraries statically", True),
  157. BoolVariable("use_asan", "Use address sanitizer (ASAN)", False),
  158. BoolVariable("debug_crt", "Compile with MSVC's debug CRT (/MDd)", False),
  159. BoolVariable("incremental_link", "Use MSVC incremental linking. May increase or decrease build times.", False),
  160. ("angle_libs", "Path to the ANGLE static libraries", ""),
  161. # Direct3D 12 support.
  162. ("mesa_libs", "Path to the MESA/NIR static libraries (required for D3D12)", ""),
  163. ("dxc_path", "Path to the DirectX Shader Compiler distribution (required for D3D12)", ""),
  164. ("agility_sdk_path", "Path to the Agility SDK distribution (optional for D3D12)", ""),
  165. BoolVariable(
  166. "agility_sdk_multiarch",
  167. "Whether the Agility SDK DLLs will be stored in arch-specific subdirectories",
  168. False,
  169. ),
  170. ("pix_path", "Path to the PIX runtime distribution (optional for D3D12)", ""),
  171. ]
  172. def get_doc_classes():
  173. return [
  174. "EditorExportPlatformWindows",
  175. ]
  176. def get_doc_path():
  177. return "doc_classes"
  178. def get_flags():
  179. arch = detect_build_env_arch() or detect_arch()
  180. return [
  181. ("arch", arch),
  182. ]
  183. def build_res_file(target, source, env):
  184. arch_aliases = {
  185. "x86_32": "pe-i386",
  186. "x86_64": "pe-x86-64",
  187. "arm32": "armv7-w64-mingw32",
  188. "arm64": "aarch64-w64-mingw32",
  189. }
  190. cmdbase = "windres --include-dir . --target=" + arch_aliases[env["arch"]]
  191. mingw_bin_prefix = get_mingw_bin_prefix(env["mingw_prefix"], env["arch"])
  192. for x in range(len(source)):
  193. ok = True
  194. # Try prefixed executable (MinGW on Linux).
  195. cmd = mingw_bin_prefix + cmdbase + " -i " + str(source[x]) + " -o " + str(target[x])
  196. try:
  197. out = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE).communicate()
  198. if len(out[1]):
  199. ok = False
  200. except Exception:
  201. ok = False
  202. # Try generic executable (MSYS2).
  203. if not ok:
  204. cmd = cmdbase + " -i " + str(source[x]) + " -o " + str(target[x])
  205. try:
  206. out = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE).communicate()
  207. if len(out[1]):
  208. return -1
  209. except Exception:
  210. return -1
  211. return 0
  212. def setup_msvc_manual(env):
  213. """Running from VCVARS environment"""
  214. env_arch = detect_build_env_arch()
  215. if env["arch"] != env_arch:
  216. print(
  217. """
  218. 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).
  219. 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.
  220. """
  221. % (env["arch"], env_arch)
  222. )
  223. sys.exit(200)
  224. print("Found MSVC, arch %s" % (env_arch))
  225. def setup_msvc_auto(env):
  226. """Set up MSVC using SCons's auto-detection logic"""
  227. # If MSVC_VERSION is set by SCons, we know MSVC is installed.
  228. # But we may want a different version or target arch.
  229. # Valid architectures for MSVC's TARGET_ARCH:
  230. # ['amd64', 'emt64', 'i386', 'i486', 'i586', 'i686', 'ia64', 'itanium', 'x86', 'x86_64', 'arm', 'arm64', 'aarch64']
  231. # Our x86_64 and arm64 are the same, and we need to map the 32-bit
  232. # architectures to other names since MSVC isn't as explicit.
  233. # The rest we don't need to worry about because they are
  234. # aliases or aren't supported by Godot (itanium & ia64).
  235. msvc_arch_aliases = {"x86_32": "x86", "arm32": "arm"}
  236. if env["arch"] in msvc_arch_aliases.keys():
  237. env["TARGET_ARCH"] = msvc_arch_aliases[env["arch"]]
  238. else:
  239. env["TARGET_ARCH"] = env["arch"]
  240. # The env may have already been set up with default MSVC tools, so
  241. # reset a few things so we can set it up with the tools we want.
  242. # (Ideally we'd decide on the tool config before configuring any
  243. # environment, and just set the env up once, but this function runs
  244. # on an existing env so this is the simplest way.)
  245. env["MSVC_SETUP_RUN"] = False # Need to set this to re-run the tool
  246. env["MSVS_VERSION"] = None
  247. env["MSVC_VERSION"] = None
  248. if "msvc_version" in env:
  249. env["MSVC_VERSION"] = env["msvc_version"]
  250. env.Tool("msvc")
  251. env.Tool("mssdk") # we want the MS SDK
  252. # Note: actual compiler version can be found in env['MSVC_VERSION'], e.g. "14.1" for VS2015
  253. print("Found MSVC version %s, arch %s" % (env["MSVC_VERSION"], env["arch"]))
  254. def setup_mingw(env):
  255. """Set up env for use with mingw"""
  256. env_arch = detect_build_env_arch()
  257. if os.getenv("MSYSTEM") == "MSYS":
  258. print(
  259. """
  260. Running from base MSYS2 console/environment, use target specific environment instead (e.g., mingw32, mingw64, clang32, clang64).
  261. """
  262. )
  263. sys.exit(201)
  264. if env_arch != "" and env["arch"] != env_arch:
  265. print(
  266. """
  267. Arch argument (%s) is not matching MSYS2 console/environment that is being used to run SCons (%s).
  268. 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.
  269. """
  270. % (env["arch"], env_arch)
  271. )
  272. sys.exit(202)
  273. if not try_cmd("gcc --version", env["mingw_prefix"], env["arch"]) and not try_cmd(
  274. "clang --version", env["mingw_prefix"], env["arch"]
  275. ):
  276. print(
  277. """
  278. No valid compilers found, use MINGW_PREFIX environment variable to set MinGW path.
  279. """
  280. )
  281. sys.exit(202)
  282. print("Using MinGW, arch %s" % (env["arch"]))
  283. def configure_msvc(env, vcvars_msvc_config):
  284. """Configure env to work with MSVC"""
  285. ## Build type
  286. # TODO: Re-evaluate the need for this / streamline with common config.
  287. if env["target"] == "template_release":
  288. env.Append(LINKFLAGS=["/ENTRY:mainCRTStartup"])
  289. if env["windows_subsystem"] == "gui":
  290. env.Append(LINKFLAGS=["/SUBSYSTEM:WINDOWS"])
  291. else:
  292. env.Append(LINKFLAGS=["/SUBSYSTEM:CONSOLE"])
  293. env.AppendUnique(CPPDEFINES=["WINDOWS_SUBSYSTEM_CONSOLE"])
  294. ## Compile/link flags
  295. if env["debug_crt"]:
  296. # Always use dynamic runtime, static debug CRT breaks thread_local.
  297. env.AppendUnique(CCFLAGS=["/MDd"])
  298. else:
  299. if env["use_static_cpp"]:
  300. env.AppendUnique(CCFLAGS=["/MT"])
  301. else:
  302. env.AppendUnique(CCFLAGS=["/MD"])
  303. # MSVC incremental linking is broken and may _increase_ link time (GH-77968).
  304. if not env["incremental_link"]:
  305. env.Append(LINKFLAGS=["/INCREMENTAL:NO"])
  306. if env["arch"] == "x86_32":
  307. env["x86_libtheora_opt_vc"] = True
  308. env.AppendUnique(CCFLAGS=["/Gd", "/GR", "/nologo"])
  309. env.AppendUnique(CCFLAGS=["/utf-8"]) # Force to use Unicode encoding.
  310. env.AppendUnique(CXXFLAGS=["/TP"]) # assume all sources are C++
  311. # Once it was thought that only debug builds would be too large,
  312. # but this has recently stopped being true. See the mingw function
  313. # for notes on why this shouldn't be enabled for gcc
  314. env.AppendUnique(CCFLAGS=["/bigobj"])
  315. if vcvars_msvc_config: # should be automatic if SCons found it
  316. if os.getenv("WindowsSdkDir") is not None:
  317. env.Prepend(CPPPATH=[os.getenv("WindowsSdkDir") + "/Include"])
  318. else:
  319. print("Missing environment variable: WindowsSdkDir")
  320. env.AppendUnique(
  321. CPPDEFINES=[
  322. "WINDOWS_ENABLED",
  323. "WASAPI_ENABLED",
  324. "WINMIDI_ENABLED",
  325. "TYPED_METHOD_BIND",
  326. "WIN32",
  327. "WINVER=%s" % env["target_win_version"],
  328. "_WIN32_WINNT=%s" % env["target_win_version"],
  329. ]
  330. )
  331. env.AppendUnique(CPPDEFINES=["NOMINMAX"]) # disable bogus min/max WinDef.h macros
  332. if env["arch"] == "x86_64":
  333. env.AppendUnique(CPPDEFINES=["_WIN64"])
  334. ## Libs
  335. LIBS = [
  336. "winmm",
  337. "dsound",
  338. "kernel32",
  339. "ole32",
  340. "oleaut32",
  341. "sapi",
  342. "user32",
  343. "gdi32",
  344. "IPHLPAPI",
  345. "Shlwapi",
  346. "wsock32",
  347. "Ws2_32",
  348. "shell32",
  349. "advapi32",
  350. "dinput8",
  351. "dxguid",
  352. "imm32",
  353. "bcrypt",
  354. "Crypt32",
  355. "Avrt",
  356. "dwmapi",
  357. "dwrite",
  358. "wbemuuid",
  359. "ntdll",
  360. ]
  361. if env.debug_features:
  362. LIBS += ["psapi", "dbghelp"]
  363. if env["vulkan"]:
  364. env.AppendUnique(CPPDEFINES=["VULKAN_ENABLED", "RD_ENABLED"])
  365. if not env["use_volk"]:
  366. LIBS += ["vulkan"]
  367. if env["d3d12"]:
  368. env.AppendUnique(CPPDEFINES=["D3D12_ENABLED", "RD_ENABLED"])
  369. LIBS += ["d3d12", "dxgi", "dxguid"]
  370. LIBS += ["version"] # Mesa dependency.
  371. # Needed for avoiding C1128.
  372. if env["target"] == "release_debug":
  373. env.Append(CXXFLAGS=["/bigobj"])
  374. arch_subdir = "arm64" if env["arch"] == "arm64" else "x64"
  375. # PIX
  376. if env["pix_path"] != "":
  377. env.Append(LIBPATH=[env["pix_path"] + "/bin/" + arch_subdir])
  378. LIBS += ["WinPixEventRuntime"]
  379. # Mesa
  380. if env["mesa_libs"] == "":
  381. print("The Direct3D 12 rendering driver requires mesa_libs to be set.")
  382. sys.exit(255)
  383. env.Append(LIBPATH=[env["mesa_libs"] + "/bin"])
  384. LIBS += ["libNIR.windows." + env["arch"]]
  385. if env["opengl3"]:
  386. env.AppendUnique(CPPDEFINES=["GLES3_ENABLED"])
  387. if env["angle_libs"] != "":
  388. env.AppendUnique(CPPDEFINES=["EGL_STATIC"])
  389. env.Append(LIBPATH=[env["angle_libs"]])
  390. LIBS += [
  391. "libANGLE.windows." + env["arch"],
  392. "libEGL.windows." + env["arch"],
  393. "libGLES.windows." + env["arch"],
  394. ]
  395. LIBS += ["dxgi", "d3d9", "d3d11"]
  396. env.Prepend(CPPPATH=["#thirdparty/angle/include"])
  397. env.Append(LINKFLAGS=[p + env["LIBSUFFIX"] for p in LIBS])
  398. if vcvars_msvc_config:
  399. if os.getenv("WindowsSdkDir") is not None:
  400. env.Append(LIBPATH=[os.getenv("WindowsSdkDir") + "/Lib"])
  401. else:
  402. print("Missing environment variable: WindowsSdkDir")
  403. ## LTO
  404. if env["lto"] == "auto": # No LTO by default for MSVC, doesn't help.
  405. env["lto"] = "none"
  406. if env["lto"] != "none":
  407. if env["lto"] == "thin":
  408. print("ThinLTO is only compatible with LLVM, use `use_llvm=yes` or `lto=full`.")
  409. sys.exit(255)
  410. env.AppendUnique(CCFLAGS=["/GL"])
  411. env.AppendUnique(ARFLAGS=["/LTCG"])
  412. if env["progress"]:
  413. env.AppendUnique(LINKFLAGS=["/LTCG:STATUS"])
  414. else:
  415. env.AppendUnique(LINKFLAGS=["/LTCG"])
  416. if vcvars_msvc_config:
  417. env.Prepend(CPPPATH=[p for p in os.getenv("INCLUDE").split(";")])
  418. env.Append(LIBPATH=[p for p in os.getenv("LIB").split(";")])
  419. # Sanitizers
  420. if env["use_asan"]:
  421. env.extra_suffix += ".san"
  422. env.Append(LINKFLAGS=["/INFERASANLIBS"])
  423. env.Append(CCFLAGS=["/fsanitize=address"])
  424. # Incremental linking fix
  425. env["BUILDERS"]["ProgramOriginal"] = env["BUILDERS"]["Program"]
  426. env["BUILDERS"]["Program"] = methods.precious_program
  427. env.Append(LINKFLAGS=["/NATVIS:platform\\windows\\godot.natvis"])
  428. env.AppendUnique(LINKFLAGS=["/STACK:" + str(STACK_SIZE)])
  429. def configure_mingw(env):
  430. # Workaround for MinGW. See:
  431. # https://www.scons.org/wiki/LongCmdLinesOnWin32
  432. env.use_windows_spawn_fix()
  433. ## Build type
  434. if not env["use_llvm"] and not try_cmd("gcc --version", env["mingw_prefix"], env["arch"]):
  435. env["use_llvm"] = True
  436. if env["use_llvm"] and not try_cmd("clang --version", env["mingw_prefix"], env["arch"]):
  437. env["use_llvm"] = False
  438. # TODO: Re-evaluate the need for this / streamline with common config.
  439. if env["target"] == "template_release":
  440. env.Append(CCFLAGS=["-msse2"])
  441. elif env.dev_build:
  442. # Allow big objects. It's supposed not to have drawbacks but seems to break
  443. # GCC LTO, so enabling for debug builds only (which are not built with LTO
  444. # and are the only ones with too big objects).
  445. env.Append(CCFLAGS=["-Wa,-mbig-obj"])
  446. if env["windows_subsystem"] == "gui":
  447. env.Append(LINKFLAGS=["-Wl,--subsystem,windows"])
  448. else:
  449. env.Append(LINKFLAGS=["-Wl,--subsystem,console"])
  450. env.AppendUnique(CPPDEFINES=["WINDOWS_SUBSYSTEM_CONSOLE"])
  451. ## Compiler configuration
  452. if os.name != "nt":
  453. env["PROGSUFFIX"] = env["PROGSUFFIX"] + ".exe" # for linux cross-compilation
  454. if env["arch"] == "x86_32":
  455. if env["use_static_cpp"]:
  456. env.Append(LINKFLAGS=["-static"])
  457. env.Append(LINKFLAGS=["-static-libgcc"])
  458. env.Append(LINKFLAGS=["-static-libstdc++"])
  459. else:
  460. if env["use_static_cpp"]:
  461. env.Append(LINKFLAGS=["-static"])
  462. if env["arch"] in ["x86_32", "x86_64"]:
  463. env["x86_libtheora_opt_gcc"] = True
  464. mingw_bin_prefix = get_mingw_bin_prefix(env["mingw_prefix"], env["arch"])
  465. if env["use_llvm"]:
  466. env["CC"] = mingw_bin_prefix + "clang"
  467. env["CXX"] = mingw_bin_prefix + "clang++"
  468. if try_cmd("as --version", env["mingw_prefix"], env["arch"]):
  469. env["AS"] = mingw_bin_prefix + "as"
  470. if try_cmd("ar --version", env["mingw_prefix"], env["arch"]):
  471. env["AR"] = mingw_bin_prefix + "ar"
  472. if try_cmd("ranlib --version", env["mingw_prefix"], env["arch"]):
  473. env["RANLIB"] = mingw_bin_prefix + "ranlib"
  474. env.extra_suffix = ".llvm" + env.extra_suffix
  475. else:
  476. env["CC"] = mingw_bin_prefix + "gcc"
  477. env["CXX"] = mingw_bin_prefix + "g++"
  478. if try_cmd("as --version", env["mingw_prefix"], env["arch"]):
  479. env["AS"] = mingw_bin_prefix + "as"
  480. if try_cmd("gcc-ar --version", env["mingw_prefix"], env["arch"]):
  481. env["AR"] = mingw_bin_prefix + "gcc-ar"
  482. if try_cmd("gcc-ranlib --version", env["mingw_prefix"], env["arch"]):
  483. env["RANLIB"] = mingw_bin_prefix + "gcc-ranlib"
  484. ## LTO
  485. if env["lto"] == "auto": # Full LTO for production with MinGW.
  486. env["lto"] = "full"
  487. if env["lto"] != "none":
  488. if env["lto"] == "thin":
  489. if not env["use_llvm"]:
  490. print("ThinLTO is only compatible with LLVM, use `use_llvm=yes` or `lto=full`.")
  491. sys.exit(255)
  492. env.Append(CCFLAGS=["-flto=thin"])
  493. env.Append(LINKFLAGS=["-flto=thin"])
  494. elif not env["use_llvm"] and env.GetOption("num_jobs") > 1:
  495. env.Append(CCFLAGS=["-flto"])
  496. env.Append(LINKFLAGS=["-flto=" + str(env.GetOption("num_jobs"))])
  497. else:
  498. env.Append(CCFLAGS=["-flto"])
  499. env.Append(LINKFLAGS=["-flto"])
  500. env.Append(LINKFLAGS=["-Wl,--stack," + str(STACK_SIZE)])
  501. ## Compile flags
  502. if not env["use_llvm"]:
  503. env.Append(CCFLAGS=["-mwindows"])
  504. env.Append(CPPDEFINES=["WINDOWS_ENABLED", "WASAPI_ENABLED", "WINMIDI_ENABLED"])
  505. env.Append(
  506. CPPDEFINES=[
  507. ("WINVER", env["target_win_version"]),
  508. ("_WIN32_WINNT", env["target_win_version"]),
  509. ]
  510. )
  511. env.Append(
  512. LIBS=[
  513. "mingw32",
  514. "dsound",
  515. "ole32",
  516. "d3d9",
  517. "winmm",
  518. "gdi32",
  519. "iphlpapi",
  520. "shlwapi",
  521. "wsock32",
  522. "ws2_32",
  523. "kernel32",
  524. "oleaut32",
  525. "sapi",
  526. "dinput8",
  527. "dxguid",
  528. "ksuser",
  529. "imm32",
  530. "bcrypt",
  531. "crypt32",
  532. "avrt",
  533. "uuid",
  534. "dwmapi",
  535. "dwrite",
  536. "wbemuuid",
  537. "ntdll",
  538. ]
  539. )
  540. if env.debug_features:
  541. env.Append(LIBS=["psapi", "dbghelp"])
  542. if env["vulkan"]:
  543. env.Append(CPPDEFINES=["VULKAN_ENABLED", "RD_ENABLED"])
  544. if not env["use_volk"]:
  545. env.Append(LIBS=["vulkan"])
  546. if env["d3d12"]:
  547. env.AppendUnique(CPPDEFINES=["D3D12_ENABLED", "RD_ENABLED"])
  548. env.Append(LIBS=["d3d12", "dxgi", "dxguid"])
  549. arch_subdir = "arm64" if env["arch"] == "arm64" else "x64"
  550. # PIX
  551. if env["pix_path"] != "":
  552. env.Append(LIBPATH=[env["pix_path"] + "/bin/" + arch_subdir])
  553. env.Append(LIBS=["WinPixEventRuntime"])
  554. # Mesa
  555. if env["mesa_libs"] == "":
  556. print("The Direct3D 12 rendering driver requires mesa_libs to be set.")
  557. sys.exit(255)
  558. env.Append(LIBPATH=[env["mesa_libs"] + "/bin"])
  559. env.Append(LIBS=["libNIR.windows." + env["arch"]])
  560. env.Append(LIBS=["version"]) # Mesa dependency.
  561. if env["opengl3"]:
  562. env.Append(CPPDEFINES=["GLES3_ENABLED"])
  563. if env["angle_libs"] != "":
  564. env.AppendUnique(CPPDEFINES=["EGL_STATIC"])
  565. env.Append(LIBPATH=[env["angle_libs"]])
  566. env.Append(
  567. LIBS=[
  568. "EGL.windows." + env["arch"],
  569. "GLES.windows." + env["arch"],
  570. "ANGLE.windows." + env["arch"],
  571. ]
  572. )
  573. env.Append(LIBS=["dxgi", "d3d9", "d3d11"])
  574. env.Prepend(CPPPATH=["#thirdparty/angle/include"])
  575. env.Append(CPPDEFINES=["MINGW_ENABLED", ("MINGW_HAS_SECURE_API", 1)])
  576. # resrc
  577. env.Append(BUILDERS={"RES": env.Builder(action=build_res_file, suffix=".o", src_suffix=".rc")})
  578. def configure(env: "Environment"):
  579. # Validate arch.
  580. supported_arches = ["x86_32", "x86_64", "arm32", "arm64"]
  581. if env["arch"] not in supported_arches:
  582. print(
  583. 'Unsupported CPU architecture "%s" for Windows. Supported architectures are: %s.'
  584. % (env["arch"], ", ".join(supported_arches))
  585. )
  586. sys.exit()
  587. # At this point the env has been set up with basic tools/compilers.
  588. env.Prepend(CPPPATH=["#platform/windows"])
  589. if os.name == "nt":
  590. env["ENV"] = os.environ # this makes build less repeatable, but simplifies some things
  591. env["ENV"]["TMP"] = os.environ["TMP"]
  592. # First figure out which compiler, version, and target arch we're using
  593. if os.getenv("VCINSTALLDIR") and detect_build_env_arch() and not env["use_mingw"]:
  594. setup_msvc_manual(env)
  595. env.msvc = True
  596. vcvars_msvc_config = True
  597. elif env.get("MSVC_VERSION", "") and not env["use_mingw"]:
  598. setup_msvc_auto(env)
  599. env.msvc = True
  600. vcvars_msvc_config = False
  601. else:
  602. setup_mingw(env)
  603. env.msvc = False
  604. # Now set compiler/linker flags
  605. if env.msvc:
  606. configure_msvc(env, vcvars_msvc_config)
  607. else: # MinGW
  608. configure_mingw(env)