methods.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. import os
  2. import re
  3. import glob
  4. import subprocess
  5. from compat import iteritems, isbasestring, decode_utf8
  6. def add_source_files(self, sources, files, warn_duplicates=True):
  7. # Convert string to list of absolute paths (including expanding wildcard)
  8. if isbasestring(files):
  9. # Keep SCons project-absolute path as they are (no wildcard support)
  10. if files.startswith('#'):
  11. if '*' in files:
  12. print("ERROR: Wildcards can't be expanded in SCons project-absolute path: '{}'".format(files))
  13. return
  14. files = [files]
  15. else:
  16. dir_path = self.Dir('.').abspath
  17. files = sorted(glob.glob(dir_path + "/" + files))
  18. # Add each path as compiled Object following environment (self) configuration
  19. for path in files:
  20. obj = self.Object(path)
  21. if obj in sources:
  22. if warn_duplicates:
  23. print("WARNING: Object \"{}\" already included in environment sources.".format(obj))
  24. else:
  25. continue
  26. sources.append(obj)
  27. def disable_warnings(self):
  28. # 'self' is the environment
  29. if self.msvc:
  30. # We have to remove existing warning level defines before appending /w,
  31. # otherwise we get: "warning D9025 : overriding '/W3' with '/w'"
  32. warn_flags = ['/Wall', '/W4', '/W3', '/W2', '/W1', '/WX']
  33. self.Append(CCFLAGS=['/w'])
  34. self.Append(CFLAGS=['/w'])
  35. self.Append(CXXFLAGS=['/w'])
  36. self['CCFLAGS'] = [x for x in self['CCFLAGS'] if not x in warn_flags]
  37. self['CFLAGS'] = [x for x in self['CFLAGS'] if not x in warn_flags]
  38. self['CXXFLAGS'] = [x for x in self['CXXFLAGS'] if not x in warn_flags]
  39. else:
  40. self.Append(CCFLAGS=['-w'])
  41. self.Append(CFLAGS=['-w'])
  42. self.Append(CXXFLAGS=['-w'])
  43. def add_module_version_string(self,s):
  44. self.module_version_string += "." + s
  45. def update_version(module_version_string=""):
  46. build_name = "custom_build"
  47. if os.getenv("BUILD_NAME") != None:
  48. build_name = os.getenv("BUILD_NAME")
  49. print("Using custom build name: " + build_name)
  50. import version
  51. # NOTE: It is safe to generate this file here, since this is still executed serially
  52. f = open("core/version_generated.gen.h", "w")
  53. f.write("#define VERSION_SHORT_NAME \"" + str(version.short_name) + "\"\n")
  54. f.write("#define VERSION_NAME \"" + str(version.name) + "\"\n")
  55. f.write("#define VERSION_MAJOR " + str(version.major) + "\n")
  56. f.write("#define VERSION_MINOR " + str(version.minor) + "\n")
  57. f.write("#define VERSION_PATCH " + str(version.patch) + "\n")
  58. f.write("#define VERSION_STATUS \"" + str(version.status) + "\"\n")
  59. f.write("#define VERSION_BUILD \"" + str(build_name) + "\"\n")
  60. f.write("#define VERSION_MODULE_CONFIG \"" + str(version.module_config) + module_version_string + "\"\n")
  61. f.write("#define VERSION_YEAR " + str(version.year) + "\n")
  62. f.write("#define VERSION_WEBSITE \"" + str(version.website) + "\"\n")
  63. f.close()
  64. # NOTE: It is safe to generate this file here, since this is still executed serially
  65. fhash = open("core/version_hash.gen.h", "w")
  66. githash = ""
  67. gitfolder = ".git"
  68. if os.path.isfile(".git"):
  69. module_folder = open(".git", "r").readline().strip()
  70. if module_folder.startswith("gitdir: "):
  71. gitfolder = module_folder[8:]
  72. if os.path.isfile(os.path.join(gitfolder, "HEAD")):
  73. head = open(os.path.join(gitfolder, "HEAD"), "r").readline().strip()
  74. if head.startswith("ref: "):
  75. head = os.path.join(gitfolder, head[5:])
  76. if os.path.isfile(head):
  77. githash = open(head, "r").readline().strip()
  78. else:
  79. githash = head
  80. fhash.write("#define VERSION_HASH \"" + githash + "\"")
  81. fhash.close()
  82. def parse_cg_file(fname, uniforms, sizes, conditionals):
  83. fs = open(fname, "r")
  84. line = fs.readline()
  85. while line:
  86. if re.match(r"^\s*uniform", line):
  87. res = re.match(r"uniform ([\d\w]*) ([\d\w]*)")
  88. type = res.groups(1)
  89. name = res.groups(2)
  90. uniforms.append(name)
  91. if type.find("texobj") != -1:
  92. sizes.append(1)
  93. else:
  94. t = re.match(r"float(\d)x(\d)", type)
  95. if t:
  96. sizes.append(int(t.groups(1)) * int(t.groups(2)))
  97. else:
  98. t = re.match(r"float(\d)", type)
  99. sizes.append(int(t.groups(1)))
  100. if line.find("[branch]") != -1:
  101. conditionals.append(name)
  102. line = fs.readline()
  103. fs.close()
  104. def detect_modules():
  105. module_list = []
  106. includes_cpp = ""
  107. register_cpp = ""
  108. unregister_cpp = ""
  109. files = glob.glob("modules/*")
  110. files.sort() # so register_module_types does not change that often, and also plugins are registered in alphabetic order
  111. for x in files:
  112. if not os.path.isdir(x):
  113. continue
  114. if not os.path.exists(x + "/config.py"):
  115. continue
  116. x = x.replace("modules/", "") # rest of world
  117. x = x.replace("modules\\", "") # win32
  118. module_list.append(x)
  119. try:
  120. with open("modules/" + x + "/register_types.h"):
  121. includes_cpp += '#include "modules/' + x + '/register_types.h"\n'
  122. register_cpp += '#ifdef MODULE_' + x.upper() + '_ENABLED\n'
  123. register_cpp += '\tregister_' + x + '_types();\n'
  124. register_cpp += '#endif\n'
  125. unregister_cpp += '#ifdef MODULE_' + x.upper() + '_ENABLED\n'
  126. unregister_cpp += '\tunregister_' + x + '_types();\n'
  127. unregister_cpp += '#endif\n'
  128. except IOError:
  129. pass
  130. modules_cpp = """
  131. // modules.cpp - THIS FILE IS GENERATED, DO NOT EDIT!!!!!!!
  132. #include "register_module_types.h"
  133. """ + includes_cpp + """
  134. void register_module_types() {
  135. """ + register_cpp + """
  136. }
  137. void unregister_module_types() {
  138. """ + unregister_cpp + """
  139. }
  140. """
  141. # NOTE: It is safe to generate this file here, since this is still executed serially
  142. with open("modules/register_module_types.gen.cpp", "w") as f:
  143. f.write(modules_cpp)
  144. return module_list
  145. def disable_module(self):
  146. self.disabled_modules.append(self.current_module)
  147. def use_windows_spawn_fix(self, platform=None):
  148. if (os.name != "nt"):
  149. return # not needed, only for windows
  150. # On Windows, due to the limited command line length, when creating a static library
  151. # from a very high number of objects SCons will invoke "ar" once per object file;
  152. # that makes object files with same names to be overwritten so the last wins and
  153. # the library looses symbols defined by overwritten objects.
  154. # By enabling quick append instead of the default mode (replacing), libraries will
  155. # got built correctly regardless the invocation strategy.
  156. # Furthermore, since SCons will rebuild the library from scratch when an object file
  157. # changes, no multiple versions of the same object file will be present.
  158. self.Replace(ARFLAGS='q')
  159. def mySubProcess(cmdline, env):
  160. startupinfo = subprocess.STARTUPINFO()
  161. startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  162. proc = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  163. stderr=subprocess.PIPE, startupinfo=startupinfo, shell=False, env=env)
  164. _, err = proc.communicate()
  165. rv = proc.wait()
  166. if rv:
  167. print("=====")
  168. print(err)
  169. print("=====")
  170. return rv
  171. def mySpawn(sh, escape, cmd, args, env):
  172. newargs = ' '.join(args[1:])
  173. cmdline = cmd + " " + newargs
  174. rv = 0
  175. env = {str(key): str(value) for key, value in iteritems(env)}
  176. if len(cmdline) > 32000 and cmd.endswith("ar"):
  177. cmdline = cmd + " " + args[1] + " " + args[2] + " "
  178. for i in range(3, len(args)):
  179. rv = mySubProcess(cmdline + args[i], env)
  180. if rv:
  181. break
  182. else:
  183. rv = mySubProcess(cmdline, env)
  184. return rv
  185. self['SPAWN'] = mySpawn
  186. def split_lib(self, libname, src_list = None, env_lib = None):
  187. env = self
  188. num = 0
  189. cur_base = ""
  190. max_src = 64
  191. list = []
  192. lib_list = []
  193. if src_list is None:
  194. src_list = getattr(env, libname + "_sources")
  195. if type(env_lib) == type(None):
  196. env_lib = env
  197. for f in src_list:
  198. fname = ""
  199. if type(f) == type(""):
  200. fname = env.File(f).path
  201. else:
  202. fname = env.File(f)[0].path
  203. fname = fname.replace("\\", "/")
  204. base = "/".join(fname.split("/")[:2])
  205. if base != cur_base and len(list) > max_src:
  206. if num > 0:
  207. lib = env_lib.add_library(libname + str(num), list)
  208. lib_list.append(lib)
  209. list = []
  210. num = num + 1
  211. cur_base = base
  212. list.append(f)
  213. lib = env_lib.add_library(libname + str(num), list)
  214. lib_list.append(lib)
  215. lib_base = []
  216. env_lib.add_source_files(lib_base, "*.cpp")
  217. lib = env_lib.add_library(libname, lib_base)
  218. lib_list.insert(0, lib)
  219. env.Prepend(LIBS=lib_list)
  220. # When we split modules into arbitrary chunks, we end up with linking issues
  221. # due to symbol dependencies split over several libs, which may not be linked
  222. # in the required order. We use --start-group and --end-group to tell the
  223. # linker that those archives should be searched repeatedly to resolve all
  224. # undefined references.
  225. # As SCons doesn't give us much control over how inserting libs in LIBS
  226. # impacts the linker call, we need to hack our way into the linking commands
  227. # LINKCOM and SHLINKCOM to set those flags.
  228. if '-Wl,--start-group' in env['LINKCOM'] and '-Wl,--start-group' in env['SHLINKCOM']:
  229. # Already added by a previous call, skip.
  230. return
  231. env['LINKCOM'] = str(env['LINKCOM']).replace('$_LIBFLAGS',
  232. '-Wl,--start-group $_LIBFLAGS -Wl,--end-group')
  233. env['SHLINKCOM'] = str(env['LINKCOM']).replace('$_LIBFLAGS',
  234. '-Wl,--start-group $_LIBFLAGS -Wl,--end-group')
  235. def save_active_platforms(apnames, ap):
  236. for x in ap:
  237. names = ['logo']
  238. if os.path.isfile(x + "/run_icon.png"):
  239. names.append('run_icon')
  240. for name in names:
  241. pngf = open(x + "/" + name + ".png", "rb")
  242. b = pngf.read(1)
  243. str = " /* AUTOGENERATED FILE, DO NOT EDIT */ \n"
  244. str += " static const unsigned char _" + x[9:] + "_" + name + "[]={"
  245. while len(b) == 1:
  246. str += hex(ord(b))
  247. b = pngf.read(1)
  248. if (len(b) == 1):
  249. str += ","
  250. str += "};\n"
  251. pngf.close()
  252. # NOTE: It is safe to generate this file here, since this is still executed serially
  253. wf = x + "/" + name + ".gen.h"
  254. with open(wf, "w") as pngw:
  255. pngw.write(str)
  256. def no_verbose(sys, env):
  257. colors = {}
  258. # Colors are disabled in non-TTY environments such as pipes. This means
  259. # that if output is redirected to a file, it will not contain color codes
  260. if sys.stdout.isatty():
  261. colors['cyan'] = '\033[96m'
  262. colors['purple'] = '\033[95m'
  263. colors['blue'] = '\033[94m'
  264. colors['green'] = '\033[92m'
  265. colors['yellow'] = '\033[93m'
  266. colors['red'] = '\033[91m'
  267. colors['end'] = '\033[0m'
  268. else:
  269. colors['cyan'] = ''
  270. colors['purple'] = ''
  271. colors['blue'] = ''
  272. colors['green'] = ''
  273. colors['yellow'] = ''
  274. colors['red'] = ''
  275. colors['end'] = ''
  276. compile_source_message = '%sCompiling %s==> %s$SOURCE%s' % (colors['blue'], colors['purple'], colors['yellow'], colors['end'])
  277. java_compile_source_message = '%sCompiling %s==> %s$SOURCE%s' % (colors['blue'], colors['purple'], colors['yellow'], colors['end'])
  278. compile_shared_source_message = '%sCompiling shared %s==> %s$SOURCE%s' % (colors['blue'], colors['purple'], colors['yellow'], colors['end'])
  279. link_program_message = '%sLinking Program %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  280. link_library_message = '%sLinking Static Library %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  281. ranlib_library_message = '%sRanlib Library %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  282. link_shared_library_message = '%sLinking Shared Library %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  283. java_library_message = '%sCreating Java Archive %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  284. env.Append(CXXCOMSTR=[compile_source_message])
  285. env.Append(CCCOMSTR=[compile_source_message])
  286. env.Append(SHCCCOMSTR=[compile_shared_source_message])
  287. env.Append(SHCXXCOMSTR=[compile_shared_source_message])
  288. env.Append(ARCOMSTR=[link_library_message])
  289. env.Append(RANLIBCOMSTR=[ranlib_library_message])
  290. env.Append(SHLINKCOMSTR=[link_shared_library_message])
  291. env.Append(LINKCOMSTR=[link_program_message])
  292. env.Append(JARCOMSTR=[java_library_message])
  293. env.Append(JAVACCOMSTR=[java_compile_source_message])
  294. def detect_visual_c_compiler_version(tools_env):
  295. # tools_env is the variable scons uses to call tools that execute tasks, SCons's env['ENV'] that executes tasks...
  296. # (see the SCons documentation for more information on what it does)...
  297. # in order for this function to be well encapsulated i choose to force it to receive SCons's TOOLS env (env['ENV']
  298. # and not scons setup environment (env)... so make sure you call the right environment on it or it will fail to detect
  299. # the proper vc version that will be called
  300. # There is no flag to give to visual c compilers to set the architecture, ie scons bits argument (32,64,ARM etc)
  301. # There are many different cl.exe files that are run, and each one compiles & links to a different architecture
  302. # As far as I know, the only way to figure out what compiler will be run when Scons calls cl.exe via Program()
  303. # is to check the PATH variable and figure out which one will be called first. Code below does that and returns:
  304. # the following string values:
  305. # "" Compiler not detected
  306. # "amd64" Native 64 bit compiler
  307. # "amd64_x86" 64 bit Cross Compiler for 32 bit
  308. # "x86" Native 32 bit compiler
  309. # "x86_amd64" 32 bit Cross Compiler for 64 bit
  310. # There are other architectures, but Godot does not support them currently, so this function does not detect arm/amd64_arm
  311. # and similar architectures/compilers
  312. # Set chosen compiler to "not detected"
  313. vc_chosen_compiler_index = -1
  314. vc_chosen_compiler_str = ""
  315. # Start with Pre VS 2017 checks which uses VCINSTALLDIR:
  316. if 'VCINSTALLDIR' in tools_env:
  317. # print("Checking VCINSTALLDIR")
  318. # find() works with -1 so big ifs below are needed... the simplest solution, in fact
  319. # First test if amd64 and amd64_x86 compilers are present in the path
  320. vc_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64;")
  321. if(vc_amd64_compiler_detection_index > -1):
  322. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  323. vc_chosen_compiler_str = "amd64"
  324. vc_amd64_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64_x86;")
  325. if(vc_amd64_x86_compiler_detection_index > -1
  326. and (vc_chosen_compiler_index == -1
  327. or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index)):
  328. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  329. vc_chosen_compiler_str = "amd64_x86"
  330. # Now check the 32 bit compilers
  331. vc_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN;")
  332. if(vc_x86_compiler_detection_index > -1
  333. and (vc_chosen_compiler_index == -1
  334. or vc_chosen_compiler_index > vc_x86_compiler_detection_index)):
  335. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  336. vc_chosen_compiler_str = "x86"
  337. vc_x86_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env['VCINSTALLDIR'] + "BIN\\x86_amd64;")
  338. if(vc_x86_amd64_compiler_detection_index > -1
  339. and (vc_chosen_compiler_index == -1
  340. or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index)):
  341. vc_chosen_compiler_index = vc_x86_amd64_compiler_detection_index
  342. vc_chosen_compiler_str = "x86_amd64"
  343. # and for VS 2017 and newer we check VCTOOLSINSTALLDIR:
  344. if 'VCTOOLSINSTALLDIR' in tools_env:
  345. # Newer versions have a different path available
  346. vc_amd64_compiler_detection_index = tools_env["PATH"].upper().find(tools_env['VCTOOLSINSTALLDIR'].upper() + "BIN\\HOSTX64\\X64;")
  347. if(vc_amd64_compiler_detection_index > -1):
  348. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  349. vc_chosen_compiler_str = "amd64"
  350. vc_amd64_x86_compiler_detection_index = tools_env["PATH"].upper().find(tools_env['VCTOOLSINSTALLDIR'].upper() + "BIN\\HOSTX64\\X86;")
  351. if(vc_amd64_x86_compiler_detection_index > -1
  352. and (vc_chosen_compiler_index == -1
  353. or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index)):
  354. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  355. vc_chosen_compiler_str = "amd64_x86"
  356. vc_x86_compiler_detection_index = tools_env["PATH"].upper().find(tools_env['VCTOOLSINSTALLDIR'].upper() + "BIN\\HOSTX86\\X86;")
  357. if(vc_x86_compiler_detection_index > -1
  358. and (vc_chosen_compiler_index == -1
  359. or vc_chosen_compiler_index > vc_x86_compiler_detection_index)):
  360. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  361. vc_chosen_compiler_str = "x86"
  362. vc_x86_amd64_compiler_detection_index = tools_env["PATH"].upper().find(tools_env['VCTOOLSINSTALLDIR'].upper() + "BIN\\HOSTX86\\X64;")
  363. if(vc_x86_amd64_compiler_detection_index > -1
  364. and (vc_chosen_compiler_index == -1
  365. or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index)):
  366. vc_chosen_compiler_index = vc_x86_amd64_compiler_detection_index
  367. vc_chosen_compiler_str = "x86_amd64"
  368. return vc_chosen_compiler_str
  369. def find_visual_c_batch_file(env):
  370. from SCons.Tool.MSCommon.vc import get_default_version, get_host_target, find_batch_file
  371. version = get_default_version(env)
  372. (host_platform, target_platform, _) = get_host_target(env)
  373. return find_batch_file(env, version, host_platform, target_platform)[0]
  374. def generate_cpp_hint_file(filename):
  375. if os.path.isfile(filename):
  376. # Don't overwrite an existing hint file since the user may have customized it.
  377. pass
  378. else:
  379. try:
  380. with open(filename, "w") as fd:
  381. fd.write("#define GDCLASS(m_class, m_inherits)\n")
  382. except IOError:
  383. print("Could not write cpp.hint file.")
  384. def generate_vs_project(env, num_jobs):
  385. batch_file = find_visual_c_batch_file(env)
  386. if batch_file:
  387. def build_commandline(commands):
  388. common_build_prefix = ['cmd /V /C set "plat=$(PlatformTarget)"',
  389. '(if "$(PlatformTarget)"=="x64" (set "plat=x86_amd64"))',
  390. 'set "tools=yes"',
  391. '(if "$(Configuration)"=="release" (set "tools=no"))',
  392. 'call "' + batch_file + '" !plat!']
  393. result = " ^& ".join(common_build_prefix + [commands])
  394. return result
  395. env.AddToVSProject(env.core_sources)
  396. env.AddToVSProject(env.main_sources)
  397. env.AddToVSProject(env.modules_sources)
  398. env.AddToVSProject(env.scene_sources)
  399. env.AddToVSProject(env.servers_sources)
  400. env.AddToVSProject(env.editor_sources)
  401. # windows allows us to have spaces in paths, so we need
  402. # to double quote off the directory. However, the path ends
  403. # in a backslash, so we need to remove this, lest it escape the
  404. # last double quote off, confusing MSBuild
  405. env['MSVSBUILDCOM'] = build_commandline('scons --directory="$(ProjectDir.TrimEnd(\'\\\'))" platform=windows progress=no target=$(Configuration) tools=!tools! -j' + str(num_jobs))
  406. env['MSVSREBUILDCOM'] = build_commandline('scons --directory="$(ProjectDir.TrimEnd(\'\\\'))" platform=windows progress=no target=$(Configuration) tools=!tools! vsproj=yes -j' + str(num_jobs))
  407. env['MSVSCLEANCOM'] = build_commandline('scons --directory="$(ProjectDir.TrimEnd(\'\\\'))" --clean platform=windows progress=no target=$(Configuration) tools=!tools! -j' + str(num_jobs))
  408. # This version information (Win32, x64, Debug, Release, Release_Debug seems to be
  409. # required for Visual Studio to understand that it needs to generate an NMAKE
  410. # project. Do not modify without knowing what you are doing.
  411. debug_variants = ['debug|Win32'] + ['debug|x64']
  412. release_variants = ['release|Win32'] + ['release|x64']
  413. release_debug_variants = ['release_debug|Win32'] + ['release_debug|x64']
  414. variants = debug_variants + release_variants + release_debug_variants
  415. debug_targets = ['bin\\godot.windows.tools.32.exe'] + ['bin\\godot.windows.tools.64.exe']
  416. release_targets = ['bin\\godot.windows.opt.32.exe'] + ['bin\\godot.windows.opt.64.exe']
  417. release_debug_targets = ['bin\\godot.windows.opt.tools.32.exe'] + ['bin\\godot.windows.opt.tools.64.exe']
  418. targets = debug_targets + release_targets + release_debug_targets
  419. if not env.get('MSVS'):
  420. env['MSVS']['PROJECTSUFFIX'] = '.vcxproj'
  421. env['MSVS']['SOLUTIONSUFFIX'] = '.sln'
  422. env.MSVSProject(
  423. target=['#godot' + env['MSVSPROJECTSUFFIX']],
  424. incs=env.vs_incs,
  425. srcs=env.vs_srcs,
  426. runfile=targets,
  427. buildtarget=targets,
  428. auto_build_solution=1,
  429. variant=variants)
  430. else:
  431. print("Could not locate Visual Studio batch file for setting up the build environment. Not generating VS project.")
  432. def precious_program(env, program, sources, **args):
  433. program = env.ProgramOriginal(program, sources, **args)
  434. env.Precious(program)
  435. return program
  436. def add_shared_library(env, name, sources, **args):
  437. library = env.SharedLibrary(name, sources, **args)
  438. env.NoCache(library)
  439. return library
  440. def add_library(env, name, sources, **args):
  441. library = env.Library(name, sources, **args)
  442. env.NoCache(library)
  443. return library
  444. def add_program(env, name, sources, **args):
  445. program = env.Program(name, sources, **args)
  446. env.NoCache(program)
  447. return program
  448. def CommandNoCache(env, target, sources, command, **args):
  449. result = env.Command(target, sources, command, **args)
  450. env.NoCache(result)
  451. return result
  452. def detect_darwin_sdk_path(platform, env):
  453. sdk_name = ''
  454. if platform == 'osx':
  455. sdk_name = 'macosx'
  456. var_name = 'MACOS_SDK_PATH'
  457. elif platform == 'iphone':
  458. sdk_name = 'iphoneos'
  459. var_name = 'IPHONESDK'
  460. elif platform == 'iphonesimulator':
  461. sdk_name = 'iphonesimulator'
  462. var_name = 'IPHONESDK'
  463. else:
  464. raise Exception("Invalid platform argument passed to detect_darwin_sdk_path")
  465. if not env[var_name]:
  466. try:
  467. sdk_path = decode_utf8(subprocess.check_output(['xcrun', '--sdk', sdk_name, '--show-sdk-path']).strip())
  468. if sdk_path:
  469. env[var_name] = sdk_path
  470. except (subprocess.CalledProcessError, OSError):
  471. print("Failed to find SDK path while running xcrun --sdk {} --show-sdk-path.".format(sdk_name))
  472. raise
  473. def get_compiler_version(env):
  474. """
  475. Returns an array of version numbers as ints: [major, minor, patch].
  476. The return array should have at least two values (major, minor).
  477. """
  478. if not env.msvc:
  479. # Not using -dumpversion as some GCC distros only return major, and
  480. # Clang used to return hardcoded 4.2.1: # https://reviews.llvm.org/D56803
  481. try:
  482. version = decode_utf8(subprocess.check_output([env.subst(env['CXX']), '--version']).strip())
  483. except (subprocess.CalledProcessError, OSError):
  484. print("Couldn't parse CXX environment variable to infer compiler version.")
  485. return None
  486. else: # TODO: Implement for MSVC
  487. return None
  488. match = re.search('[0-9]+\.[0-9.]+', version)
  489. if match is not None:
  490. return list(map(int, match.group().split('.')))
  491. else:
  492. return None
  493. def using_gcc(env):
  494. return 'gcc' in os.path.basename(env["CC"])
  495. def using_clang(env):
  496. return 'clang' in os.path.basename(env["CC"])