methods.py 28 KB

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