detect.py 14 KB

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