methods.py 25 KB

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