methods.py 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046
  1. import os
  2. import re
  3. import glob
  4. import subprocess
  5. from collections import OrderedDict
  6. from collections.abc import Mapping
  7. from typing import Iterator
  8. # We need to define our own `Action` method to control the verbosity of output
  9. # and whenever we need to run those commands in a subprocess on some platforms.
  10. from SCons import Node
  11. from SCons.Script import Action
  12. from SCons.Script import ARGUMENTS
  13. from SCons.Script import Glob
  14. from SCons.Variables.BoolVariable import _text2bool
  15. from platform_methods import run_in_subprocess
  16. def add_source_files(self, sources, files):
  17. # Convert string to list of absolute paths (including expanding wildcard)
  18. if isinstance(files, (str, bytes)):
  19. # Keep SCons project-absolute path as they are (no wildcard support)
  20. if files.startswith("#"):
  21. if "*" in files:
  22. print("ERROR: Wildcards can't be expanded in SCons project-absolute path: '{}'".format(files))
  23. return
  24. files = [files]
  25. else:
  26. # Exclude .gen.cpp files from globbing, to avoid including obsolete ones.
  27. # They should instead be added manually.
  28. skip_gen_cpp = "*" in files
  29. dir_path = self.Dir(".").abspath
  30. files = sorted(glob.glob(dir_path + "/" + files))
  31. if skip_gen_cpp:
  32. files = [f for f in files if not f.endswith(".gen.cpp")]
  33. # Add each path as compiled Object following environment (self) configuration
  34. for path in files:
  35. obj = self.Object(path)
  36. if obj in sources:
  37. print('WARNING: Object "{}" already included in environment sources.'.format(obj))
  38. continue
  39. sources.append(obj)
  40. def disable_warnings(self):
  41. # 'self' is the environment
  42. if self.msvc:
  43. # We have to remove existing warning level defines before appending /w,
  44. # otherwise we get: "warning D9025 : overriding '/W3' with '/w'"
  45. warn_flags = ["/Wall", "/W4", "/W3", "/W2", "/W1", "/WX"]
  46. self.Append(CCFLAGS=["/w"])
  47. self.Append(CFLAGS=["/w"])
  48. self.Append(CXXFLAGS=["/w"])
  49. self["CCFLAGS"] = [x for x in self["CCFLAGS"] if not x in warn_flags]
  50. self["CFLAGS"] = [x for x in self["CFLAGS"] if not x in warn_flags]
  51. self["CXXFLAGS"] = [x for x in self["CXXFLAGS"] if not x in warn_flags]
  52. else:
  53. self.Append(CCFLAGS=["-w"])
  54. self.Append(CFLAGS=["-w"])
  55. self.Append(CXXFLAGS=["-w"])
  56. def force_optimization_on_debug(self):
  57. # 'self' is the environment
  58. if self["target"] != "debug":
  59. return
  60. if self.msvc:
  61. self.Append(CCFLAGS=["/O2"])
  62. else:
  63. self.Append(CCFLAGS=["-O3"])
  64. def add_module_version_string(self, s):
  65. self.module_version_string += "." + s
  66. def update_version(module_version_string=""):
  67. build_name = "custom_build"
  68. if os.getenv("BUILD_NAME") != None:
  69. build_name = str(os.getenv("BUILD_NAME"))
  70. print("Using custom build name: " + build_name)
  71. import version
  72. # NOTE: It is safe to generate this file here, since this is still executed serially
  73. f = open("core/version_generated.gen.h", "w")
  74. f.write("/* THIS FILE IS GENERATED DO NOT EDIT */\n")
  75. f.write("#ifndef VERSION_GENERATED_GEN_H\n")
  76. f.write("#define VERSION_GENERATED_GEN_H\n")
  77. f.write('#define VERSION_SHORT_NAME "' + str(version.short_name) + '"\n')
  78. f.write('#define VERSION_NAME "' + str(version.name) + '"\n')
  79. f.write("#define VERSION_MAJOR " + str(version.major) + "\n")
  80. f.write("#define VERSION_MINOR " + str(version.minor) + "\n")
  81. f.write("#define VERSION_PATCH " + str(version.patch) + "\n")
  82. # For dev snapshots (alpha, beta, RC, etc.) we do not commit status change to Git,
  83. # so this define provides a way to override it without having to modify the source.
  84. godot_status = str(version.status)
  85. if os.getenv("GODOT_VERSION_STATUS") != None:
  86. godot_status = str(os.getenv("GODOT_VERSION_STATUS"))
  87. print("Using version status '{}', overriding the original '{}'.".format(godot_status, str(version.status)))
  88. f.write('#define VERSION_STATUS "' + godot_status + '"\n')
  89. f.write('#define VERSION_BUILD "' + str(build_name) + '"\n')
  90. f.write('#define VERSION_MODULE_CONFIG "' + str(version.module_config) + module_version_string + '"\n')
  91. f.write("#define VERSION_YEAR " + str(version.year) + "\n")
  92. f.write('#define VERSION_WEBSITE "' + str(version.website) + '"\n')
  93. f.write('#define VERSION_DOCS_BRANCH "' + str(version.docs) + '"\n')
  94. f.write('#define VERSION_DOCS_URL "https://docs.godotengine.org/en/" VERSION_DOCS_BRANCH\n')
  95. f.write("#endif // VERSION_GENERATED_GEN_H\n")
  96. f.close()
  97. # NOTE: It is safe to generate this file here, since this is still executed serially
  98. fhash = open("core/version_hash.gen.cpp", "w")
  99. fhash.write("/* THIS FILE IS GENERATED DO NOT EDIT */\n")
  100. fhash.write('#include "core/version.h"\n')
  101. githash = ""
  102. gitfolder = ".git"
  103. if os.path.isfile(".git"):
  104. module_folder = open(".git", "r").readline().strip()
  105. if module_folder.startswith("gitdir: "):
  106. gitfolder = module_folder[8:]
  107. if os.path.isfile(os.path.join(gitfolder, "HEAD")):
  108. head = open(os.path.join(gitfolder, "HEAD"), "r", encoding="utf8").readline().strip()
  109. if head.startswith("ref: "):
  110. head = os.path.join(gitfolder, head[5:])
  111. if os.path.isfile(head):
  112. githash = open(head, "r").readline().strip()
  113. else:
  114. githash = head
  115. fhash.write('const char *const VERSION_HASH = "' + githash + '";\n')
  116. fhash.close()
  117. def parse_cg_file(fname, uniforms, sizes, conditionals):
  118. fs = open(fname, "r")
  119. line = fs.readline()
  120. while line:
  121. if re.match(r"^\s*uniform", line):
  122. res = re.match(r"uniform ([\d\w]*) ([\d\w]*)")
  123. type = res.groups(1)
  124. name = res.groups(2)
  125. uniforms.append(name)
  126. if type.find("texobj") != -1:
  127. sizes.append(1)
  128. else:
  129. t = re.match(r"float(\d)x(\d)", type)
  130. if t:
  131. sizes.append(int(t.groups(1)) * int(t.groups(2)))
  132. else:
  133. t = re.match(r"float(\d)", type)
  134. sizes.append(int(t.groups(1)))
  135. if line.find("[branch]") != -1:
  136. conditionals.append(name)
  137. line = fs.readline()
  138. fs.close()
  139. def get_cmdline_bool(option, default):
  140. """We use `ARGUMENTS.get()` to check if options were manually overridden on the command line,
  141. and SCons' _text2bool helper to convert them to booleans, otherwise they're handled as strings.
  142. """
  143. cmdline_val = ARGUMENTS.get(option)
  144. if cmdline_val is not None:
  145. return _text2bool(cmdline_val)
  146. else:
  147. return default
  148. def detect_modules(search_path, recursive=False):
  149. """Detects and collects a list of C++ modules at specified path
  150. `search_path` - a directory path containing modules. The path may point to
  151. a single module, which may have other nested modules. A module must have
  152. "register_types.h", "SCsub", "config.py" files created to be detected.
  153. `recursive` - if `True`, then all subdirectories are searched for modules as
  154. specified by the `search_path`, otherwise collects all modules under the
  155. `search_path` directory. If the `search_path` is a module, it is collected
  156. in all cases.
  157. Returns an `OrderedDict` with module names as keys, and directory paths as
  158. values. If a path is relative, then it is a built-in module. If a path is
  159. absolute, then it is a custom module collected outside of the engine source.
  160. """
  161. modules = OrderedDict()
  162. def add_module(path):
  163. module_name = os.path.basename(path)
  164. module_path = path.replace("\\", "/") # win32
  165. modules[module_name] = module_path
  166. def is_engine(path):
  167. # Prevent recursively detecting modules in self and other
  168. # Godot sources when using `custom_modules` build option.
  169. version_path = os.path.join(path, "version.py")
  170. if os.path.exists(version_path):
  171. with open(version_path) as f:
  172. if 'short_name = "godot"' in f.read():
  173. return True
  174. return False
  175. def get_files(path):
  176. files = glob.glob(os.path.join(path, "*"))
  177. # Sort so that `register_module_types` does not change that often,
  178. # and plugins are registered in alphabetic order as well.
  179. files.sort()
  180. return files
  181. if not recursive:
  182. if is_module(search_path):
  183. add_module(search_path)
  184. for path in get_files(search_path):
  185. if is_engine(path):
  186. continue
  187. if is_module(path):
  188. add_module(path)
  189. else:
  190. to_search = [search_path]
  191. while to_search:
  192. path = to_search.pop()
  193. if is_module(path):
  194. add_module(path)
  195. for child in get_files(path):
  196. if not os.path.isdir(child):
  197. continue
  198. if is_engine(child):
  199. continue
  200. to_search.insert(0, child)
  201. return modules
  202. def is_module(path):
  203. if not os.path.isdir(path):
  204. return False
  205. must_exist = ["register_types.h", "SCsub", "config.py"]
  206. for f in must_exist:
  207. if not os.path.exists(os.path.join(path, f)):
  208. return False
  209. return True
  210. def write_disabled_classes(class_list):
  211. f = open("core/disabled_classes.gen.h", "w")
  212. f.write("/* THIS FILE IS GENERATED DO NOT EDIT */\n")
  213. f.write("#ifndef DISABLED_CLASSES_GEN_H\n")
  214. f.write("#define DISABLED_CLASSES_GEN_H\n\n")
  215. for c in class_list:
  216. cs = c.strip()
  217. if cs != "":
  218. f.write("#define ClassDB_Disable_" + cs + " 1\n")
  219. f.write("\n#endif\n")
  220. def write_modules(modules):
  221. includes_cpp = ""
  222. initialize_cpp = ""
  223. uninitialize_cpp = ""
  224. for name, path in modules.items():
  225. try:
  226. with open(os.path.join(path, "register_types.h")):
  227. includes_cpp += '#include "' + path + '/register_types.h"\n'
  228. initialize_cpp += "#ifdef MODULE_" + name.upper() + "_ENABLED\n"
  229. initialize_cpp += "\tinitialize_" + name + "_module(p_level);\n"
  230. initialize_cpp += "#endif\n"
  231. uninitialize_cpp += "#ifdef MODULE_" + name.upper() + "_ENABLED\n"
  232. uninitialize_cpp += "\tuninitialize_" + name + "_module(p_level);\n"
  233. uninitialize_cpp += "#endif\n"
  234. except OSError:
  235. pass
  236. modules_cpp = """// register_module_types.gen.cpp
  237. /* THIS FILE IS GENERATED DO NOT EDIT */
  238. #include "register_module_types.h"
  239. #include "modules/modules_enabled.gen.h"
  240. %s
  241. void initialize_modules(ModuleInitializationLevel p_level) {
  242. %s
  243. }
  244. void uninitialize_modules(ModuleInitializationLevel p_level) {
  245. %s
  246. }
  247. """ % (
  248. includes_cpp,
  249. initialize_cpp,
  250. uninitialize_cpp,
  251. )
  252. # NOTE: It is safe to generate this file here, since this is still executed serially
  253. with open("modules/register_module_types.gen.cpp", "w") as f:
  254. f.write(modules_cpp)
  255. def convert_custom_modules_path(path):
  256. if not path:
  257. return path
  258. path = os.path.realpath(os.path.expanduser(os.path.expandvars(path)))
  259. err_msg = "Build option 'custom_modules' must %s"
  260. if not os.path.isdir(path):
  261. raise ValueError(err_msg % "point to an existing directory.")
  262. if path == os.path.realpath("modules"):
  263. raise ValueError(err_msg % "be a directory other than built-in `modules` directory.")
  264. return path
  265. def disable_module(self):
  266. self.disabled_modules.append(self.current_module)
  267. def module_check_dependencies(self, module, dependencies, silent=False):
  268. """
  269. Checks if module dependencies are enabled for a given module,
  270. and prints a warning if they aren't.
  271. Meant to be used in module `can_build` methods.
  272. Returns a boolean (True if dependencies are satisfied).
  273. """
  274. missing_deps = []
  275. for dep in dependencies:
  276. opt = "module_{}_enabled".format(dep)
  277. if not opt in self or not self[opt]:
  278. missing_deps.append(dep)
  279. if missing_deps != []:
  280. if not silent:
  281. print(
  282. "Disabling '{}' module as the following dependencies are not satisfied: {}".format(
  283. module, ", ".join(missing_deps)
  284. )
  285. )
  286. return False
  287. else:
  288. return True
  289. def use_windows_spawn_fix(self, platform=None):
  290. if os.name != "nt":
  291. return # not needed, only for windows
  292. # On Windows, due to the limited command line length, when creating a static library
  293. # from a very high number of objects SCons will invoke "ar" once per object file;
  294. # that makes object files with same names to be overwritten so the last wins and
  295. # the library loses symbols defined by overwritten objects.
  296. # By enabling quick append instead of the default mode (replacing), libraries will
  297. # got built correctly regardless the invocation strategy.
  298. # Furthermore, since SCons will rebuild the library from scratch when an object file
  299. # changes, no multiple versions of the same object file will be present.
  300. self.Replace(ARFLAGS="q")
  301. def mySubProcess(cmdline, env):
  302. startupinfo = subprocess.STARTUPINFO()
  303. startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  304. proc = subprocess.Popen(
  305. cmdline,
  306. stdin=subprocess.PIPE,
  307. stdout=subprocess.PIPE,
  308. stderr=subprocess.PIPE,
  309. startupinfo=startupinfo,
  310. shell=False,
  311. env=env,
  312. )
  313. _, err = proc.communicate()
  314. rv = proc.wait()
  315. if rv:
  316. print("=====")
  317. print(err)
  318. print("=====")
  319. return rv
  320. def mySpawn(sh, escape, cmd, args, env):
  321. newargs = " ".join(args[1:])
  322. cmdline = cmd + " " + newargs
  323. rv = 0
  324. env = {str(key): str(value) for key, value in iter(env.items())}
  325. if len(cmdline) > 32000 and cmd.endswith("ar"):
  326. cmdline = cmd + " " + args[1] + " " + args[2] + " "
  327. for i in range(3, len(args)):
  328. rv = mySubProcess(cmdline + args[i], env)
  329. if rv:
  330. break
  331. else:
  332. rv = mySubProcess(cmdline, env)
  333. return rv
  334. self["SPAWN"] = mySpawn
  335. def save_active_platforms(apnames, ap):
  336. for x in ap:
  337. names = ["logo"]
  338. if os.path.isfile(x + "/run_icon.png"):
  339. names.append("run_icon")
  340. for name in names:
  341. pngf = open(x + "/" + name + ".png", "rb")
  342. b = pngf.read(1)
  343. str = " /* AUTOGENERATED FILE, DO NOT EDIT */ \n"
  344. str += " static const unsigned char _" + x[9:] + "_" + name + "[]={"
  345. while len(b) == 1:
  346. str += hex(ord(b))
  347. b = pngf.read(1)
  348. if len(b) == 1:
  349. str += ","
  350. str += "};\n"
  351. pngf.close()
  352. # NOTE: It is safe to generate this file here, since this is still executed serially
  353. wf = x + "/" + name + ".gen.h"
  354. with open(wf, "w") as pngw:
  355. pngw.write(str)
  356. def no_verbose(sys, env):
  357. colors = {}
  358. # Colors are disabled in non-TTY environments such as pipes. This means
  359. # that if output is redirected to a file, it will not contain color codes
  360. if sys.stdout.isatty():
  361. colors["blue"] = "\033[0;94m"
  362. colors["bold_blue"] = "\033[1;94m"
  363. colors["reset"] = "\033[0m"
  364. else:
  365. colors["blue"] = ""
  366. colors["bold_blue"] = ""
  367. colors["reset"] = ""
  368. # There is a space before "..." to ensure that source file names can be
  369. # Ctrl + clicked in the VS Code terminal.
  370. compile_source_message = "{}Compiling {}$SOURCE{} ...{}".format(
  371. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  372. )
  373. java_compile_source_message = "{}Compiling {}$SOURCE{} ...{}".format(
  374. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  375. )
  376. compile_shared_source_message = "{}Compiling shared {}$SOURCE{} ...{}".format(
  377. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  378. )
  379. link_program_message = "{}Linking Program {}$TARGET{} ...{}".format(
  380. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  381. )
  382. link_library_message = "{}Linking Static Library {}$TARGET{} ...{}".format(
  383. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  384. )
  385. ranlib_library_message = "{}Ranlib Library {}$TARGET{} ...{}".format(
  386. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  387. )
  388. link_shared_library_message = "{}Linking Shared Library {}$TARGET{} ...{}".format(
  389. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  390. )
  391. java_library_message = "{}Creating Java Archive {}$TARGET{} ...{}".format(
  392. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  393. )
  394. env.Append(CXXCOMSTR=[compile_source_message])
  395. env.Append(CCCOMSTR=[compile_source_message])
  396. env.Append(SHCCCOMSTR=[compile_shared_source_message])
  397. env.Append(SHCXXCOMSTR=[compile_shared_source_message])
  398. env.Append(ARCOMSTR=[link_library_message])
  399. env.Append(RANLIBCOMSTR=[ranlib_library_message])
  400. env.Append(SHLINKCOMSTR=[link_shared_library_message])
  401. env.Append(LINKCOMSTR=[link_program_message])
  402. env.Append(JARCOMSTR=[java_library_message])
  403. env.Append(JAVACCOMSTR=[java_compile_source_message])
  404. def detect_visual_c_compiler_version(tools_env):
  405. # tools_env is the variable scons uses to call tools that execute tasks, SCons's env['ENV'] that executes tasks...
  406. # (see the SCons documentation for more information on what it does)...
  407. # in order for this function to be well encapsulated i choose to force it to receive SCons's TOOLS env (env['ENV']
  408. # and not scons setup environment (env)... so make sure you call the right environment on it or it will fail to detect
  409. # the proper vc version that will be called
  410. # There is no flag to give to visual c compilers to set the architecture, i.e. scons bits argument (32,64,ARM etc)
  411. # There are many different cl.exe files that are run, and each one compiles & links to a different architecture
  412. # As far as I know, the only way to figure out what compiler will be run when Scons calls cl.exe via Program()
  413. # is to check the PATH variable and figure out which one will be called first. Code below does that and returns:
  414. # the following string values:
  415. # "" Compiler not detected
  416. # "amd64" Native 64 bit compiler
  417. # "amd64_x86" 64 bit Cross Compiler for 32 bit
  418. # "x86" Native 32 bit compiler
  419. # "x86_amd64" 32 bit Cross Compiler for 64 bit
  420. # There are other architectures, but Godot does not support them currently, so this function does not detect arm/amd64_arm
  421. # and similar architectures/compilers
  422. # Set chosen compiler to "not detected"
  423. vc_chosen_compiler_index = -1
  424. vc_chosen_compiler_str = ""
  425. # Start with Pre VS 2017 checks which uses VCINSTALLDIR:
  426. if "VCINSTALLDIR" in tools_env:
  427. # print("Checking VCINSTALLDIR")
  428. # find() works with -1 so big ifs below are needed... the simplest solution, in fact
  429. # First test if amd64 and amd64_x86 compilers are present in the path
  430. vc_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64;")
  431. if vc_amd64_compiler_detection_index > -1:
  432. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  433. vc_chosen_compiler_str = "amd64"
  434. vc_amd64_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64_x86;")
  435. if vc_amd64_x86_compiler_detection_index > -1 and (
  436. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index
  437. ):
  438. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  439. vc_chosen_compiler_str = "amd64_x86"
  440. # Now check the 32 bit compilers
  441. vc_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN;")
  442. if vc_x86_compiler_detection_index > -1 and (
  443. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_compiler_detection_index
  444. ):
  445. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  446. vc_chosen_compiler_str = "x86"
  447. vc_x86_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\x86_amd64;")
  448. if vc_x86_amd64_compiler_detection_index > -1 and (
  449. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index
  450. ):
  451. vc_chosen_compiler_index = vc_x86_amd64_compiler_detection_index
  452. vc_chosen_compiler_str = "x86_amd64"
  453. # and for VS 2017 and newer we check VCTOOLSINSTALLDIR:
  454. if "VCTOOLSINSTALLDIR" in tools_env:
  455. # Newer versions have a different path available
  456. vc_amd64_compiler_detection_index = (
  457. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX64\\X64;")
  458. )
  459. if vc_amd64_compiler_detection_index > -1:
  460. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  461. vc_chosen_compiler_str = "amd64"
  462. vc_amd64_x86_compiler_detection_index = (
  463. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX64\\X86;")
  464. )
  465. if vc_amd64_x86_compiler_detection_index > -1 and (
  466. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index
  467. ):
  468. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  469. vc_chosen_compiler_str = "amd64_x86"
  470. vc_x86_compiler_detection_index = (
  471. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX86\\X86;")
  472. )
  473. if vc_x86_compiler_detection_index > -1 and (
  474. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_compiler_detection_index
  475. ):
  476. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  477. vc_chosen_compiler_str = "x86"
  478. vc_x86_amd64_compiler_detection_index = (
  479. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX86\\X64;")
  480. )
  481. if vc_x86_amd64_compiler_detection_index > -1 and (
  482. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index
  483. ):
  484. vc_chosen_compiler_index = vc_x86_amd64_compiler_detection_index
  485. vc_chosen_compiler_str = "x86_amd64"
  486. return vc_chosen_compiler_str
  487. def find_visual_c_batch_file(env):
  488. from SCons.Tool.MSCommon.vc import (
  489. get_default_version,
  490. get_host_target,
  491. find_batch_file,
  492. )
  493. version = get_default_version(env)
  494. (host_platform, target_platform, _) = get_host_target(env)
  495. return find_batch_file(env, version, host_platform, target_platform)[0]
  496. def generate_cpp_hint_file(filename):
  497. if os.path.isfile(filename):
  498. # Don't overwrite an existing hint file since the user may have customized it.
  499. pass
  500. else:
  501. try:
  502. with open(filename, "w") as fd:
  503. fd.write("#define GDCLASS(m_class, m_inherits)\n")
  504. except OSError:
  505. print("Could not write cpp.hint file.")
  506. def glob_recursive(pattern, node="."):
  507. results = []
  508. for f in Glob(str(node) + "/*", source=True):
  509. if type(f) is Node.FS.Dir:
  510. results += glob_recursive(pattern, f)
  511. results += Glob(str(node) + "/" + pattern, source=True)
  512. return results
  513. def add_to_vs_project(env, sources):
  514. for x in sources:
  515. if type(x) == type(""):
  516. fname = env.File(x).path
  517. else:
  518. fname = env.File(x)[0].path
  519. pieces = fname.split(".")
  520. if len(pieces) > 0:
  521. basename = pieces[0]
  522. basename = basename.replace("\\\\", "/")
  523. if os.path.isfile(basename + ".h"):
  524. env.vs_incs += [basename + ".h"]
  525. elif os.path.isfile(basename + ".hpp"):
  526. env.vs_incs += [basename + ".hpp"]
  527. if os.path.isfile(basename + ".c"):
  528. env.vs_srcs += [basename + ".c"]
  529. elif os.path.isfile(basename + ".cpp"):
  530. env.vs_srcs += [basename + ".cpp"]
  531. def generate_vs_project(env, num_jobs):
  532. batch_file = find_visual_c_batch_file(env)
  533. if batch_file:
  534. class ModuleConfigs(Mapping):
  535. # This version information (Win32, x64, Debug, Release, Release_Debug seems to be
  536. # required for Visual Studio to understand that it needs to generate an NMAKE
  537. # project. Do not modify without knowing what you are doing.
  538. PLATFORMS = ["Win32", "x64"]
  539. PLATFORM_IDS = ["32", "64"]
  540. CONFIGURATIONS = ["debug", "release", "release_debug"]
  541. CONFIGURATION_IDS = ["tools", "opt", "opt.tools"]
  542. @staticmethod
  543. def for_every_variant(value):
  544. return [value for _ in range(len(ModuleConfigs.CONFIGURATIONS) * len(ModuleConfigs.PLATFORMS))]
  545. def __init__(self):
  546. shared_targets_array = []
  547. self.names = []
  548. self.arg_dict = {
  549. "variant": [],
  550. "runfile": shared_targets_array,
  551. "buildtarget": shared_targets_array,
  552. "cpppaths": [],
  553. "cppdefines": [],
  554. "cmdargs": [],
  555. }
  556. self.add_mode() # default
  557. def add_mode(
  558. self,
  559. name: str = "",
  560. includes: str = "",
  561. cli_args: str = "",
  562. defines=None,
  563. ):
  564. if defines is None:
  565. defines = []
  566. self.names.append(name)
  567. self.arg_dict["variant"] += [
  568. f'{config}{f"_[{name}]" if name else ""}|{platform}'
  569. for config in ModuleConfigs.CONFIGURATIONS
  570. for platform in ModuleConfigs.PLATFORMS
  571. ]
  572. self.arg_dict["runfile"] += [
  573. f'bin\\godot.windows.{config_id}.{plat_id}{f".{name}" if name else ""}.exe'
  574. for config_id in ModuleConfigs.CONFIGURATION_IDS
  575. for plat_id in ModuleConfigs.PLATFORM_IDS
  576. ]
  577. self.arg_dict["cpppaths"] += ModuleConfigs.for_every_variant(env["CPPPATH"] + [includes])
  578. self.arg_dict["cppdefines"] += ModuleConfigs.for_every_variant(env["CPPDEFINES"] + defines)
  579. self.arg_dict["cmdargs"] += ModuleConfigs.for_every_variant(cli_args)
  580. def build_commandline(self, commands):
  581. configuration_getter = (
  582. "$(Configuration"
  583. + "".join([f'.Replace("{name}", "")' for name in self.names[1:]])
  584. + '.Replace("_[]", "")'
  585. + ")"
  586. )
  587. common_build_prefix = [
  588. 'cmd /V /C set "plat=$(PlatformTarget)"',
  589. '(if "$(PlatformTarget)"=="x64" (set "plat=x86_amd64"))',
  590. 'set "tools=%s"' % env["tools"],
  591. f'(if "{configuration_getter}"=="release" (set "tools=no"))',
  592. 'call "' + batch_file + '" !plat!',
  593. ]
  594. # Windows allows us to have spaces in paths, so we need
  595. # to double quote off the directory. However, the path ends
  596. # in a backslash, so we need to remove this, lest it escape the
  597. # last double quote off, confusing MSBuild
  598. common_build_postfix = [
  599. "--directory=\"$(ProjectDir.TrimEnd('\\'))\"",
  600. "platform=windows",
  601. f"target={configuration_getter}",
  602. "progress=no",
  603. "tools=!tools!",
  604. "-j%s" % num_jobs,
  605. ]
  606. if env["tests"]:
  607. common_build_postfix.append("tests=yes")
  608. if env["custom_modules"]:
  609. common_build_postfix.append("custom_modules=%s" % env["custom_modules"])
  610. result = " ^& ".join(common_build_prefix + [" ".join([commands] + common_build_postfix)])
  611. return result
  612. # Mappings interface definitions
  613. def __iter__(self) -> Iterator[str]:
  614. for x in self.arg_dict:
  615. yield x
  616. def __len__(self) -> int:
  617. return len(self.names)
  618. def __getitem__(self, k: str):
  619. return self.arg_dict[k]
  620. add_to_vs_project(env, env.core_sources)
  621. add_to_vs_project(env, env.drivers_sources)
  622. add_to_vs_project(env, env.main_sources)
  623. add_to_vs_project(env, env.modules_sources)
  624. add_to_vs_project(env, env.scene_sources)
  625. add_to_vs_project(env, env.servers_sources)
  626. if env["tests"]:
  627. add_to_vs_project(env, env.tests_sources)
  628. add_to_vs_project(env, env.editor_sources)
  629. for header in glob_recursive("**/*.h"):
  630. env.vs_incs.append(str(header))
  631. module_configs = ModuleConfigs()
  632. if env.get("module_mono_enabled"):
  633. import modules.mono.build_scripts.mono_reg_utils as mono_reg
  634. mono_root = env.get("mono_prefix") or mono_reg.find_mono_root_dir(env["bits"])
  635. if mono_root:
  636. module_configs.add_mode(
  637. "mono",
  638. includes=os.path.join(mono_root, "include", "mono-2.0"),
  639. cli_args="module_mono_enabled=yes mono_glue=yes",
  640. defines=[("MONO_GLUE_ENABLED",)],
  641. )
  642. else:
  643. print("Mono installation directory not found. Generated project will not have build variants for Mono.")
  644. env["MSVSBUILDCOM"] = module_configs.build_commandline("scons")
  645. env["MSVSREBUILDCOM"] = module_configs.build_commandline("scons vsproj=yes")
  646. env["MSVSCLEANCOM"] = module_configs.build_commandline("scons --clean")
  647. if not env.get("MSVS"):
  648. env["MSVS"]["PROJECTSUFFIX"] = ".vcxproj"
  649. env["MSVS"]["SOLUTIONSUFFIX"] = ".sln"
  650. env.MSVSProject(
  651. target=["#godot" + env["MSVSPROJECTSUFFIX"]],
  652. incs=env.vs_incs,
  653. srcs=env.vs_srcs,
  654. auto_build_solution=1,
  655. **module_configs,
  656. )
  657. else:
  658. print("Could not locate Visual Studio batch file to set up the build environment. Not generating VS project.")
  659. def precious_program(env, program, sources, **args):
  660. program = env.ProgramOriginal(program, sources, **args)
  661. env.Precious(program)
  662. return program
  663. def add_shared_library(env, name, sources, **args):
  664. library = env.SharedLibrary(name, sources, **args)
  665. env.NoCache(library)
  666. return library
  667. def add_library(env, name, sources, **args):
  668. library = env.Library(name, sources, **args)
  669. env.NoCache(library)
  670. return library
  671. def add_program(env, name, sources, **args):
  672. program = env.Program(name, sources, **args)
  673. env.NoCache(program)
  674. return program
  675. def CommandNoCache(env, target, sources, command, **args):
  676. result = env.Command(target, sources, command, **args)
  677. env.NoCache(result)
  678. return result
  679. def Run(env, function, short_message, subprocess=True):
  680. output_print = short_message if not env["verbose"] else ""
  681. if not subprocess:
  682. return Action(function, output_print)
  683. else:
  684. return Action(run_in_subprocess(function), output_print)
  685. def detect_darwin_sdk_path(platform, env):
  686. sdk_name = ""
  687. if platform == "osx":
  688. sdk_name = "macosx"
  689. var_name = "MACOS_SDK_PATH"
  690. elif platform == "iphone":
  691. sdk_name = "iphoneos"
  692. var_name = "IPHONESDK"
  693. elif platform == "iphonesimulator":
  694. sdk_name = "iphonesimulator"
  695. var_name = "IPHONESDK"
  696. else:
  697. raise Exception("Invalid platform argument passed to detect_darwin_sdk_path")
  698. if not env[var_name]:
  699. try:
  700. sdk_path = subprocess.check_output(["xcrun", "--sdk", sdk_name, "--show-sdk-path"]).strip().decode("utf-8")
  701. if sdk_path:
  702. env[var_name] = sdk_path
  703. except (subprocess.CalledProcessError, OSError):
  704. print("Failed to find SDK path while running xcrun --sdk {} --show-sdk-path.".format(sdk_name))
  705. raise
  706. def is_vanilla_clang(env):
  707. if not using_clang(env):
  708. return False
  709. try:
  710. version = subprocess.check_output([env.subst(env["CXX"]), "--version"]).strip().decode("utf-8")
  711. except (subprocess.CalledProcessError, OSError):
  712. print("Couldn't parse CXX environment variable to infer compiler version.")
  713. return False
  714. return not version.startswith("Apple")
  715. def get_compiler_version(env):
  716. """
  717. Returns an array of version numbers as ints: [major, minor, patch].
  718. The return array should have at least two values (major, minor).
  719. """
  720. if not env.msvc:
  721. # Not using -dumpversion as some GCC distros only return major, and
  722. # Clang used to return hardcoded 4.2.1: # https://reviews.llvm.org/D56803
  723. try:
  724. version = subprocess.check_output([env.subst(env["CXX"]), "--version"]).strip().decode("utf-8")
  725. except (subprocess.CalledProcessError, OSError):
  726. print("Couldn't parse CXX environment variable to infer compiler version.")
  727. return None
  728. else: # TODO: Implement for MSVC
  729. return None
  730. match = re.search(
  731. "(?:(?<=version )|(?<=\) )|(?<=^))"
  732. "(?P<major>\d+)"
  733. "(?:\.(?P<minor>\d*))?"
  734. "(?:\.(?P<patch>\d*))?"
  735. "(?:-(?P<metadata1>[0-9a-zA-Z-]*))?"
  736. "(?:\+(?P<metadata2>[0-9a-zA-Z-]*))?"
  737. "(?: (?P<date>[0-9]{8}|[0-9]{6})(?![0-9a-zA-Z]))?",
  738. version,
  739. )
  740. if match is not None:
  741. return match.groupdict()
  742. else:
  743. return None
  744. def using_gcc(env):
  745. return "gcc" in os.path.basename(env["CC"])
  746. def using_clang(env):
  747. return "clang" in os.path.basename(env["CC"])
  748. def using_emcc(env):
  749. return "emcc" in os.path.basename(env["CC"])
  750. def show_progress(env):
  751. import sys
  752. from SCons.Script import Progress, Command, AlwaysBuild
  753. screen = sys.stdout
  754. # Progress reporting is not available in non-TTY environments since it
  755. # messes with the output (for example, when writing to a file)
  756. show_progress = env["progress"] and sys.stdout.isatty()
  757. node_count = 0
  758. node_count_max = 0
  759. node_count_interval = 1
  760. node_count_fname = str(env.Dir("#")) + "/.scons_node_count"
  761. import time, math
  762. class cache_progress:
  763. # The default is 1 GB cache and 12 hours half life
  764. def __init__(self, path=None, limit=1073741824, half_life=43200):
  765. self.path = path
  766. self.limit = limit
  767. self.exponent_scale = math.log(2) / half_life
  768. if env["verbose"] and path != None:
  769. screen.write(
  770. "Current cache limit is {} (used: {})\n".format(
  771. self.convert_size(limit), self.convert_size(self.get_size(path))
  772. )
  773. )
  774. self.delete(self.file_list())
  775. def __call__(self, node, *args, **kw):
  776. nonlocal node_count, node_count_max, node_count_interval, node_count_fname, show_progress
  777. if show_progress:
  778. # Print the progress percentage
  779. node_count += node_count_interval
  780. if node_count_max > 0 and node_count <= node_count_max:
  781. screen.write("\r[%3d%%] " % (node_count * 100 / node_count_max))
  782. screen.flush()
  783. elif node_count_max > 0 and node_count > node_count_max:
  784. screen.write("\r[100%] ")
  785. screen.flush()
  786. else:
  787. screen.write("\r[Initial build] ")
  788. screen.flush()
  789. def delete(self, files):
  790. if len(files) == 0:
  791. return
  792. if env["verbose"]:
  793. # Utter something
  794. screen.write("\rPurging %d %s from cache...\n" % (len(files), len(files) > 1 and "files" or "file"))
  795. [os.remove(f) for f in files]
  796. def file_list(self):
  797. if self.path is None:
  798. # Nothing to do
  799. return []
  800. # Gather a list of (filename, (size, atime)) within the
  801. # cache directory
  802. file_stat = [(x, os.stat(x)[6:8]) for x in glob.glob(os.path.join(self.path, "*", "*"))]
  803. if file_stat == []:
  804. # Nothing to do
  805. return []
  806. # Weight the cache files by size (assumed to be roughly
  807. # proportional to the recompilation time) times an exponential
  808. # decay since the ctime, and return a list with the entries
  809. # (filename, size, weight).
  810. current_time = time.time()
  811. file_stat = [(x[0], x[1][0], (current_time - x[1][1])) for x in file_stat]
  812. # Sort by the most recently accessed files (most sensible to keep) first
  813. file_stat.sort(key=lambda x: x[2])
  814. # Search for the first entry where the storage limit is
  815. # reached
  816. sum, mark = 0, None
  817. for i, x in enumerate(file_stat):
  818. sum += x[1]
  819. if sum > self.limit:
  820. mark = i
  821. break
  822. if mark is None:
  823. return []
  824. else:
  825. return [x[0] for x in file_stat[mark:]]
  826. def convert_size(self, size_bytes):
  827. if size_bytes == 0:
  828. return "0 bytes"
  829. size_name = ("bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
  830. i = int(math.floor(math.log(size_bytes, 1024)))
  831. p = math.pow(1024, i)
  832. s = round(size_bytes / p, 2)
  833. return "%s %s" % (int(s) if i == 0 else s, size_name[i])
  834. def get_size(self, start_path="."):
  835. total_size = 0
  836. for dirpath, dirnames, filenames in os.walk(start_path):
  837. for f in filenames:
  838. fp = os.path.join(dirpath, f)
  839. total_size += os.path.getsize(fp)
  840. return total_size
  841. def progress_finish(target, source, env):
  842. nonlocal node_count, progressor
  843. try:
  844. with open(node_count_fname, "w") as f:
  845. f.write("%d\n" % node_count)
  846. progressor.delete(progressor.file_list())
  847. except Exception:
  848. pass
  849. try:
  850. with open(node_count_fname) as f:
  851. node_count_max = int(f.readline())
  852. except Exception:
  853. pass
  854. cache_directory = os.environ.get("SCONS_CACHE")
  855. # Simple cache pruning, attached to SCons' progress callback. Trim the
  856. # cache directory to a size not larger than cache_limit.
  857. cache_limit = float(os.getenv("SCONS_CACHE_LIMIT", 1024)) * 1024 * 1024
  858. progressor = cache_progress(cache_directory, cache_limit)
  859. Progress(progressor, interval=node_count_interval)
  860. progress_finish_command = Command("progress_finish", [], progress_finish)
  861. AlwaysBuild(progress_finish_command)
  862. def dump(env):
  863. # Dumps latest build information for debugging purposes and external tools.
  864. from json import dump
  865. def non_serializable(obj):
  866. return "<<non-serializable: %s>>" % (type(obj).__qualname__)
  867. with open(".scons_env.json", "w") as f:
  868. dump(env.Dictionary(), f, indent=4, default=non_serializable)