detect.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. import methods
  2. import os
  3. # To match other platforms
  4. STACK_SIZE = 8388608
  5. def is_active():
  6. return True
  7. def get_name():
  8. return "Windows"
  9. def can_build():
  10. if os.name == "nt":
  11. # Building natively on Windows
  12. # If VCINSTALLDIR is set in the OS environ, use traditional Godot logic to set up MSVC
  13. if os.getenv("VCINSTALLDIR"): # MSVC, manual setup
  14. return True
  15. # Otherwise, let SCons find MSVC if installed, or else Mingw.
  16. # Since we're just returning True here, if there's no compiler
  17. # installed, we'll get errors when it tries to build with the
  18. # null compiler.
  19. return True
  20. if os.name == "posix":
  21. # Cross-compiling with MinGW-w64 (old MinGW32 is not supported)
  22. mingw32 = "i686-w64-mingw32-"
  23. mingw64 = "x86_64-w64-mingw32-"
  24. if os.getenv("MINGW32_PREFIX"):
  25. mingw32 = os.getenv("MINGW32_PREFIX")
  26. if os.getenv("MINGW64_PREFIX"):
  27. mingw64 = os.getenv("MINGW64_PREFIX")
  28. test = "gcc --version > /dev/null 2>&1"
  29. if os.system(mingw64 + test) == 0 or os.system(mingw32 + test) == 0:
  30. return True
  31. return False
  32. def get_opts():
  33. from SCons.Variables import BoolVariable, EnumVariable
  34. mingw32 = ""
  35. mingw64 = ""
  36. if os.name == "posix":
  37. mingw32 = "i686-w64-mingw32-"
  38. mingw64 = "x86_64-w64-mingw32-"
  39. if os.getenv("MINGW32_PREFIX"):
  40. mingw32 = os.getenv("MINGW32_PREFIX")
  41. if os.getenv("MINGW64_PREFIX"):
  42. mingw64 = os.getenv("MINGW64_PREFIX")
  43. return [
  44. ("mingw_prefix_32", "MinGW prefix (Win32)", mingw32),
  45. ("mingw_prefix_64", "MinGW prefix (Win64)", mingw64),
  46. # Targeted Windows version: 7 (and later), minimum supported version
  47. # XP support dropped after EOL due to missing API for IPv6 and other issues
  48. # Vista support dropped after EOL due to GH-10243
  49. ("target_win_version", "Targeted Windows version, >= 0x0601 (Windows 7)", "0x0601"),
  50. EnumVariable("debug_symbols", "Add debugging symbols to release builds", "yes", ("yes", "no", "full")),
  51. BoolVariable("separate_debug_symbols", "Create a separate file containing debugging symbols", False),
  52. ("msvc_version", "MSVC version to use. Ignored if VCINSTALLDIR is set in shell env.", None),
  53. BoolVariable("use_mingw", "Use the Mingw compiler, even if MSVC is installed. Only used on Windows.", False),
  54. BoolVariable("use_llvm", "Use the LLVM compiler", False),
  55. BoolVariable("use_thinlto", "Use ThinLTO", False),
  56. ]
  57. def get_flags():
  58. return []
  59. def build_res_file(target, source, env):
  60. if env["bits"] == "32":
  61. cmdbase = env["mingw_prefix_32"]
  62. else:
  63. cmdbase = env["mingw_prefix_64"]
  64. cmdbase = cmdbase + "windres --include-dir . "
  65. import subprocess
  66. for x in range(len(source)):
  67. cmd = cmdbase + "-i " + str(source[x]) + " -o " + str(target[x])
  68. try:
  69. out = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE).communicate()
  70. if len(out[1]):
  71. return 1
  72. except:
  73. return 1
  74. return 0
  75. def setup_msvc_manual(env):
  76. """Set up env to use MSVC manually, using VCINSTALLDIR"""
  77. if env["bits"] != "default":
  78. print(
  79. """
  80. Bits argument is not supported for MSVC compilation. Architecture depends on the Native/Cross Compile Tools Prompt/Developer Console
  81. (or Visual Studio settings) that is being used to run SCons. As a consequence, bits argument is disabled. Run scons again without bits
  82. argument (example: scons p=windows) and SCons will attempt to detect what MSVC compiler will be executed and inform you.
  83. """
  84. )
  85. raise SCons.Errors.UserError("Bits argument should not be used when using VCINSTALLDIR")
  86. # Force bits arg
  87. # (Actually msys2 mingw can support 64-bit, we could detect that)
  88. env["bits"] = "32"
  89. env["x86_libtheora_opt_vc"] = True
  90. # find compiler manually
  91. compiler_version_str = methods.detect_visual_c_compiler_version(env["ENV"])
  92. print("Found MSVC compiler: " + compiler_version_str)
  93. # If building for 64bit architecture, disable assembly optimisations for 32 bit builds (theora as of writing)... vc compiler for 64bit can not compile _asm
  94. if compiler_version_str == "amd64" or compiler_version_str == "x86_amd64":
  95. env["bits"] = "64"
  96. env["x86_libtheora_opt_vc"] = False
  97. print("Compiled program architecture will be a 64 bit executable (forcing bits=64).")
  98. elif compiler_version_str == "x86" or compiler_version_str == "amd64_x86":
  99. print("Compiled program architecture will be a 32 bit executable. (forcing bits=32).")
  100. else:
  101. print(
  102. "Failed to manually detect MSVC compiler architecture version... Defaulting to 32bit executable settings (forcing bits=32). Compilation attempt will continue, but SCons can not detect for what architecture this build is compiled for. You should check your settings/compilation setup, or avoid setting VCINSTALLDIR."
  103. )
  104. def setup_msvc_auto(env):
  105. """Set up MSVC using SCons's auto-detection logic"""
  106. # If MSVC_VERSION is set by SCons, we know MSVC is installed.
  107. # But we may want a different version or target arch.
  108. # The env may have already been set up with default MSVC tools, so
  109. # reset a few things so we can set it up with the tools we want.
  110. # (Ideally we'd decide on the tool config before configuring any
  111. # environment, and just set the env up once, but this function runs
  112. # on an existing env so this is the simplest way.)
  113. env["MSVC_SETUP_RUN"] = False # Need to set this to re-run the tool
  114. env["MSVS_VERSION"] = None
  115. env["MSVC_VERSION"] = None
  116. env["TARGET_ARCH"] = None
  117. if env["bits"] != "default":
  118. env["TARGET_ARCH"] = {"32": "x86", "64": "x86_64"}[env["bits"]]
  119. if env.has_key("msvc_version"):
  120. env["MSVC_VERSION"] = env["msvc_version"]
  121. env.Tool("msvc")
  122. env.Tool("mssdk") # we want the MS SDK
  123. # Note: actual compiler version can be found in env['MSVC_VERSION'], e.g. "14.1" for VS2015
  124. # Get actual target arch into bits (it may be "default" at this point):
  125. if env["TARGET_ARCH"] in ("amd64", "x86_64"):
  126. env["bits"] = "64"
  127. else:
  128. env["bits"] = "32"
  129. print("Found MSVC version %s, arch %s, bits=%s" % (env["MSVC_VERSION"], env["TARGET_ARCH"], env["bits"]))
  130. if env["TARGET_ARCH"] in ("amd64", "x86_64"):
  131. env["x86_libtheora_opt_vc"] = False
  132. def setup_mingw(env):
  133. """Set up env for use with mingw"""
  134. # Nothing to do here
  135. print("Using MinGW")
  136. pass
  137. def configure_msvc(env, manual_msvc_config):
  138. """Configure env to work with MSVC"""
  139. # Build type
  140. if env["target"] == "release":
  141. if env["optimize"] == "speed": # optimize for speed (default)
  142. env.Append(CCFLAGS=["/O2"])
  143. else: # optimize for size
  144. env.Append(CCFLAGS=["/O1"])
  145. env.Append(LINKFLAGS=["/SUBSYSTEM:WINDOWS"])
  146. env.Append(LINKFLAGS=["/ENTRY:mainCRTStartup"])
  147. env.Append(LINKFLAGS=["/OPT:REF"])
  148. elif env["target"] == "release_debug":
  149. if env["optimize"] == "speed": # optimize for speed (default)
  150. env.Append(CCFLAGS=["/O2"])
  151. else: # optimize for size
  152. env.Append(CCFLAGS=["/O1"])
  153. env.AppendUnique(CPPDEFINES=["DEBUG_ENABLED"])
  154. env.Append(LINKFLAGS=["/SUBSYSTEM:CONSOLE"])
  155. env.Append(LINKFLAGS=["/OPT:REF"])
  156. elif env["target"] == "debug":
  157. env.AppendUnique(CCFLAGS=["/Z7", "/Od", "/EHsc"])
  158. env.AppendUnique(CPPDEFINES=["DEBUG_ENABLED"])
  159. env.Append(LINKFLAGS=["/SUBSYSTEM:CONSOLE"])
  160. env.Append(LINKFLAGS=["/DEBUG"])
  161. if env["debug_symbols"] == "full" or env["debug_symbols"] == "yes":
  162. env.AppendUnique(CCFLAGS=["/Z7"])
  163. env.AppendUnique(LINKFLAGS=["/DEBUG"])
  164. ## Compile/link flags
  165. env.AppendUnique(CCFLAGS=["/MT", "/Gd", "/GR", "/nologo"])
  166. if int(env["MSVC_VERSION"].split(".")[0]) >= 14: # vs2015 and later
  167. env.AppendUnique(CCFLAGS=["/utf-8"])
  168. env.AppendUnique(CXXFLAGS=["/TP"]) # assume all sources are C++
  169. if manual_msvc_config: # should be automatic if SCons found it
  170. if os.getenv("WindowsSdkDir") is not None:
  171. env.Prepend(CPPPATH=[os.getenv("WindowsSdkDir") + "/Include"])
  172. else:
  173. print("Missing environment variable: WindowsSdkDir")
  174. env.AppendUnique(
  175. CPPDEFINES=[
  176. "WINDOWS_ENABLED",
  177. "OPENGL_ENABLED",
  178. "WASAPI_ENABLED",
  179. "WINMIDI_ENABLED",
  180. "TYPED_METHOD_BIND",
  181. "WIN32",
  182. "MSVC",
  183. "WINVER=%s" % env["target_win_version"],
  184. "_WIN32_WINNT=%s" % env["target_win_version"],
  185. ]
  186. )
  187. env.AppendUnique(CPPDEFINES=["NOMINMAX"]) # disable bogus min/max WinDef.h macros
  188. if env["bits"] == "64":
  189. env.AppendUnique(CPPDEFINES=["_WIN64"])
  190. ## Libs
  191. LIBS = [
  192. "winmm",
  193. "opengl32",
  194. "dsound",
  195. "kernel32",
  196. "ole32",
  197. "oleaut32",
  198. "user32",
  199. "gdi32",
  200. "IPHLPAPI",
  201. "Shlwapi",
  202. "wsock32",
  203. "Ws2_32",
  204. "shell32",
  205. "advapi32",
  206. "dinput8",
  207. "dxguid",
  208. "imm32",
  209. "bcrypt",
  210. "Avrt",
  211. "dwmapi",
  212. ]
  213. env.Append(LINKFLAGS=[p + env["LIBSUFFIX"] for p in LIBS])
  214. if manual_msvc_config:
  215. if os.getenv("WindowsSdkDir") is not None:
  216. env.Append(LIBPATH=[os.getenv("WindowsSdkDir") + "/Lib"])
  217. else:
  218. print("Missing environment variable: WindowsSdkDir")
  219. ## LTO
  220. if env["use_lto"]:
  221. env.AppendUnique(CCFLAGS=["/GL"])
  222. env.AppendUnique(ARFLAGS=["/LTCG"])
  223. if env["progress"]:
  224. env.AppendUnique(LINKFLAGS=["/LTCG:STATUS"])
  225. else:
  226. env.AppendUnique(LINKFLAGS=["/LTCG"])
  227. if manual_msvc_config:
  228. env.Prepend(CPPPATH=[p for p in os.getenv("INCLUDE").split(";")])
  229. env.Append(LIBPATH=[p for p in os.getenv("LIB").split(";")])
  230. # Incremental linking fix
  231. env["BUILDERS"]["ProgramOriginal"] = env["BUILDERS"]["Program"]
  232. env["BUILDERS"]["Program"] = methods.precious_program
  233. env.AppendUnique(LINKFLAGS=["/STACK:" + str(STACK_SIZE)])
  234. def configure_mingw(env):
  235. # Workaround for MinGW. See:
  236. # http://www.scons.org/wiki/LongCmdLinesOnWin32
  237. env.use_windows_spawn_fix()
  238. ## Build type
  239. if env["target"] == "release":
  240. env.Append(CCFLAGS=["-msse2"])
  241. if env["optimize"] == "speed": # optimize for speed (default)
  242. if env["bits"] == "64":
  243. env.Append(CCFLAGS=["-O3"])
  244. else:
  245. env.Append(CCFLAGS=["-O2"])
  246. else: # optimize for size
  247. env.Prepend(CCFLAGS=["-Os"])
  248. env.Append(LINKFLAGS=["-Wl,--subsystem,windows"])
  249. if env["debug_symbols"] == "yes":
  250. env.Prepend(CCFLAGS=["-g1"])
  251. if env["debug_symbols"] == "full":
  252. env.Prepend(CCFLAGS=["-g2"])
  253. elif env["target"] == "release_debug":
  254. env.Append(CCFLAGS=["-O2"])
  255. env.Append(CPPDEFINES=["DEBUG_ENABLED"])
  256. if env["debug_symbols"] == "yes":
  257. env.Prepend(CCFLAGS=["-g1"])
  258. if env["debug_symbols"] == "full":
  259. env.Prepend(CCFLAGS=["-g2"])
  260. if env["optimize"] == "speed": # optimize for speed (default)
  261. env.Append(CCFLAGS=["-O2"])
  262. else: # optimize for size
  263. env.Prepend(CCFLAGS=["-Os"])
  264. elif env["target"] == "debug":
  265. env.Append(CCFLAGS=["-g3"])
  266. env.Append(CPPDEFINES=["DEBUG_ENABLED"])
  267. ## Compiler configuration
  268. if os.name == "nt":
  269. # Force splitting libmodules.a in multiple chunks to work around
  270. # issues reaching the linker command line size limit, which also
  271. # seem to induce huge slowdown for 'ar' (GH-30892).
  272. env["split_libmodules"] = True
  273. else:
  274. env["PROGSUFFIX"] = env["PROGSUFFIX"] + ".exe" # for linux cross-compilation
  275. if env["bits"] == "default":
  276. if os.name == "nt":
  277. env["bits"] = "64" if "PROGRAMFILES(X86)" in os.environ else "32"
  278. else: # default to 64-bit on Linux
  279. env["bits"] = "64"
  280. mingw_prefix = ""
  281. if env["bits"] == "32":
  282. env.Append(LINKFLAGS=["-static"])
  283. env.Append(LINKFLAGS=["-static-libgcc"])
  284. env.Append(LINKFLAGS=["-static-libstdc++"])
  285. mingw_prefix = env["mingw_prefix_32"]
  286. else:
  287. env.Append(LINKFLAGS=["-static"])
  288. mingw_prefix = env["mingw_prefix_64"]
  289. if env["use_llvm"]:
  290. env["CC"] = mingw_prefix + "clang"
  291. env["AS"] = mingw_prefix + "as"
  292. env["CXX"] = mingw_prefix + "clang++"
  293. env["AR"] = mingw_prefix + "ar"
  294. env["RANLIB"] = mingw_prefix + "ranlib"
  295. env["LINK"] = mingw_prefix + "clang++"
  296. else:
  297. env["CC"] = mingw_prefix + "gcc"
  298. env["AS"] = mingw_prefix + "as"
  299. env["CXX"] = mingw_prefix + "g++"
  300. env["AR"] = mingw_prefix + "gcc-ar"
  301. env["RANLIB"] = mingw_prefix + "gcc-ranlib"
  302. env["LINK"] = mingw_prefix + "g++"
  303. env["x86_libtheora_opt_gcc"] = True
  304. if env["use_lto"]:
  305. if not env["use_llvm"] and env.GetOption("num_jobs") > 1:
  306. env.Append(CCFLAGS=["-flto"])
  307. env.Append(LINKFLAGS=["-flto=" + str(env.GetOption("num_jobs"))])
  308. else:
  309. if env["use_thinlto"]:
  310. env.Append(CCFLAGS=["-flto=thin"])
  311. env.Append(LINKFLAGS=["-flto=thin"])
  312. else:
  313. env.Append(CCFLAGS=["-flto"])
  314. env.Append(LINKFLAGS=["-flto"])
  315. env.Append(LINKFLAGS=["-Wl,--stack," + str(STACK_SIZE)])
  316. ## Compile flags
  317. env.Append(CCFLAGS=["-mwindows"])
  318. env.Append(CPPDEFINES=["WINDOWS_ENABLED", "OPENGL_ENABLED", "WASAPI_ENABLED", "WINMIDI_ENABLED"])
  319. env.Append(CPPDEFINES=[("WINVER", env["target_win_version"]), ("_WIN32_WINNT", env["target_win_version"])])
  320. env.Append(
  321. LIBS=[
  322. "mingw32",
  323. "opengl32",
  324. "dsound",
  325. "ole32",
  326. "d3d9",
  327. "winmm",
  328. "gdi32",
  329. "iphlpapi",
  330. "shlwapi",
  331. "wsock32",
  332. "ws2_32",
  333. "kernel32",
  334. "oleaut32",
  335. "dinput8",
  336. "dxguid",
  337. "ksuser",
  338. "imm32",
  339. "bcrypt",
  340. "avrt",
  341. "uuid",
  342. "dwmapi",
  343. ]
  344. )
  345. env.Append(CPPDEFINES=["MINGW_ENABLED", ("MINGW_HAS_SECURE_API", 1)])
  346. # resrc
  347. env.Append(BUILDERS={"RES": env.Builder(action=build_res_file, suffix=".o", src_suffix=".rc")})
  348. def configure(env):
  349. # At this point the env has been set up with basic tools/compilers.
  350. env.Prepend(CPPPATH=["#platform/windows"])
  351. print("Configuring for Windows: target=%s, bits=%s" % (env["target"], env["bits"]))
  352. if os.name == "nt":
  353. env["ENV"] = os.environ # this makes build less repeatable, but simplifies some things
  354. env["ENV"]["TMP"] = os.environ["TMP"]
  355. # First figure out which compiler, version, and target arch we're using
  356. if os.getenv("VCINSTALLDIR") and not env["use_mingw"]:
  357. # Manual setup of MSVC
  358. setup_msvc_manual(env)
  359. env.msvc = True
  360. manual_msvc_config = True
  361. elif env.get("MSVC_VERSION", "") and not env["use_mingw"]:
  362. setup_msvc_auto(env)
  363. env.msvc = True
  364. manual_msvc_config = False
  365. else:
  366. setup_mingw(env)
  367. env.msvc = False
  368. # Now set compiler/linker flags
  369. if env.msvc:
  370. configure_msvc(env, manual_msvc_config)
  371. else: # MinGW
  372. configure_mingw(env)