methods.py 27 KB

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