detect.py 14 KB

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