methods.py 42 KB

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