godotcpp.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. import os
  2. import platform
  3. import sys
  4. from SCons import __version__ as scons_raw_version
  5. from SCons.Action import Action
  6. from SCons.Builder import Builder
  7. from SCons.Errors import UserError
  8. from SCons.Script import ARGUMENTS
  9. from SCons.Tool import Tool
  10. from SCons.Variables import BoolVariable, EnumVariable, PathVariable
  11. from SCons.Variables.BoolVariable import _text2bool
  12. from binding_generator import _generate_bindings, _get_file_list, get_file_list
  13. from build_profile import generate_trimmed_api
  14. from doc_source_generator import scons_generate_doc_source
  15. def get_cmdline_bool(option, default):
  16. """We use `ARGUMENTS.get()` to check if options were manually overridden on the command line,
  17. and SCons' _text2bool helper to convert them to booleans, otherwise they're handled as strings.
  18. """
  19. cmdline_val = ARGUMENTS.get(option)
  20. if cmdline_val is not None:
  21. return _text2bool(cmdline_val)
  22. else:
  23. return default
  24. def normalize_path(val, env):
  25. """Normalize a path that was provided by the user on the command line
  26. and is thus either an absolute path, or relative to the top level directory (#)
  27. where the command was run.
  28. """
  29. # If val is an absolute path, it will not be joined.
  30. return os.path.join(env.Dir("#").abspath, val)
  31. def validate_file(key, val, env):
  32. if not os.path.isfile(normalize_path(val, env)):
  33. raise UserError("'%s' is not a file: %s" % (key, val))
  34. def validate_dir(key, val, env):
  35. if not os.path.isdir(normalize_path(val, env)):
  36. raise UserError("'%s' is not a directory: %s" % (key, val))
  37. def validate_parent_dir(key, val, env):
  38. if not os.path.isdir(normalize_path(os.path.dirname(val), env)):
  39. raise UserError("'%s' is not a directory: %s" % (key, os.path.dirname(val)))
  40. def get_platform_tools_paths(env):
  41. path = env.get("custom_tools", None)
  42. tools_path = env.Dir("tools").srcnode().abspath
  43. if path is None:
  44. return [tools_path]
  45. return [normalize_path(path, env), tools_path]
  46. def get_custom_platforms(env):
  47. path = env.get("custom_tools", None)
  48. if path is None:
  49. return []
  50. platforms = []
  51. for x in os.listdir(normalize_path(path, env)):
  52. if not x.endswith(".py"):
  53. continue
  54. platforms.append(x.removesuffix(".py"))
  55. return platforms
  56. def no_verbose(env):
  57. colors = {}
  58. # Colors are disabled in non-TTY environments such as pipes. This means
  59. # that if output is redirected to a file, it will not contain color codes
  60. if sys.stdout.isatty():
  61. colors["blue"] = "\033[0;94m"
  62. colors["bold_blue"] = "\033[1;94m"
  63. colors["reset"] = "\033[0m"
  64. else:
  65. colors["blue"] = ""
  66. colors["bold_blue"] = ""
  67. colors["reset"] = ""
  68. # There is a space before "..." to ensure that source file names can be
  69. # Ctrl + clicked in the VS Code terminal.
  70. compile_source_message = "{}Compiling {}$SOURCE{} ...{}".format(
  71. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  72. )
  73. java_compile_source_message = "{}Compiling {}$SOURCE{} ...{}".format(
  74. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  75. )
  76. compile_shared_source_message = "{}Compiling shared {}$SOURCE{} ...{}".format(
  77. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  78. )
  79. link_program_message = "{}Linking Program {}$TARGET{} ...{}".format(
  80. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  81. )
  82. link_library_message = "{}Linking Static Library {}$TARGET{} ...{}".format(
  83. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  84. )
  85. ranlib_library_message = "{}Ranlib Library {}$TARGET{} ...{}".format(
  86. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  87. )
  88. link_shared_library_message = "{}Linking Shared Library {}$TARGET{} ...{}".format(
  89. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  90. )
  91. java_library_message = "{}Creating Java Archive {}$TARGET{} ...{}".format(
  92. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  93. )
  94. compiled_resource_message = "{}Creating Compiled Resource {}$TARGET{} ...{}".format(
  95. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  96. )
  97. generated_file_message = "{}Generating {}$TARGET{} ...{}".format(
  98. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  99. )
  100. env.Append(CXXCOMSTR=[compile_source_message])
  101. env.Append(CCCOMSTR=[compile_source_message])
  102. env.Append(SHCCCOMSTR=[compile_shared_source_message])
  103. env.Append(SHCXXCOMSTR=[compile_shared_source_message])
  104. env.Append(ARCOMSTR=[link_library_message])
  105. env.Append(RANLIBCOMSTR=[ranlib_library_message])
  106. env.Append(SHLINKCOMSTR=[link_shared_library_message])
  107. env.Append(LINKCOMSTR=[link_program_message])
  108. env.Append(JARCOMSTR=[java_library_message])
  109. env.Append(JAVACCOMSTR=[java_compile_source_message])
  110. env.Append(RCCOMSTR=[compiled_resource_message])
  111. env.Append(GENCOMSTR=[generated_file_message])
  112. def scons_emit_files(target, source, env):
  113. profile_filepath = env.get("build_profile", "")
  114. if profile_filepath:
  115. profile_filepath = normalize_path(profile_filepath, env)
  116. # Always clean all files
  117. env.Clean(target, [env.File(f) for f in get_file_list(str(source[0]), target[0].abspath, True, True)])
  118. api = generate_trimmed_api(str(source[0]), profile_filepath)
  119. files = []
  120. for f in _get_file_list(api, target[0].abspath, True, True):
  121. file = env.File(f)
  122. if profile_filepath:
  123. env.Depends(file, profile_filepath)
  124. files.append(file)
  125. env["godot_cpp_gen_dir"] = target[0].abspath
  126. return files, source
  127. def scons_generate_bindings(target, source, env):
  128. profile_filepath = env.get("build_profile", "")
  129. if profile_filepath:
  130. profile_filepath = normalize_path(profile_filepath, env)
  131. api = generate_trimmed_api(str(source[0]), profile_filepath)
  132. _generate_bindings(
  133. api,
  134. str(source[0]),
  135. env["generate_template_get_node"],
  136. "32" if "32" in env["arch"] else "64",
  137. env["precision"],
  138. env["godot_cpp_gen_dir"],
  139. )
  140. return None
  141. platforms = ["linux", "macos", "windows", "android", "ios", "web"]
  142. # CPU architecture options.
  143. architecture_array = [
  144. "",
  145. "universal",
  146. "x86_32",
  147. "x86_64",
  148. "arm32",
  149. "arm64",
  150. "rv64",
  151. "ppc32",
  152. "ppc64",
  153. "wasm32",
  154. ]
  155. architecture_aliases = {
  156. "x64": "x86_64",
  157. "amd64": "x86_64",
  158. "armv7": "arm32",
  159. "armv8": "arm64",
  160. "arm64v8": "arm64",
  161. "aarch64": "arm64",
  162. "rv": "rv64",
  163. "riscv": "rv64",
  164. "riscv64": "rv64",
  165. "ppcle": "ppc32",
  166. "ppc": "ppc32",
  167. "ppc64le": "ppc64",
  168. }
  169. def exists(env):
  170. return True
  171. def options(opts, env):
  172. # Try to detect the host platform automatically.
  173. # This is used if no `platform` argument is passed
  174. if sys.platform.startswith("linux"):
  175. default_platform = "linux"
  176. elif sys.platform == "darwin":
  177. default_platform = "macos"
  178. elif sys.platform == "win32" or sys.platform == "msys":
  179. default_platform = "windows"
  180. elif ARGUMENTS.get("platform", ""):
  181. default_platform = ARGUMENTS.get("platform")
  182. else:
  183. raise ValueError("Could not detect platform automatically, please specify with platform=<platform>")
  184. opts.Add(
  185. PathVariable(
  186. key="custom_tools",
  187. help="Path to directory containing custom tools",
  188. default=env.get("custom_tools", None),
  189. validator=validate_dir,
  190. )
  191. )
  192. opts.Update(env)
  193. custom_platforms = get_custom_platforms(env)
  194. opts.Add(
  195. EnumVariable(
  196. key="platform",
  197. help="Target platform",
  198. default=env.get("platform", default_platform),
  199. allowed_values=platforms + custom_platforms,
  200. ignorecase=2,
  201. )
  202. )
  203. # Editor and template_debug are compatible (i.e. you can use the same binary for Godot editor builds and Godot debug templates).
  204. # Godot release templates are only compatible with "template_release" builds.
  205. # For this reason, we default to template_debug builds, unlike Godot which defaults to editor builds.
  206. opts.Add(
  207. EnumVariable(
  208. key="target",
  209. help="Compilation target",
  210. default=env.get("target", "template_debug"),
  211. allowed_values=("editor", "template_release", "template_debug"),
  212. )
  213. )
  214. opts.Add(
  215. PathVariable(
  216. key="gdextension_dir",
  217. help="Path to a custom directory containing GDExtension interface header and API JSON file",
  218. default=env.get("gdextension_dir", None),
  219. validator=validate_dir,
  220. )
  221. )
  222. opts.Add(
  223. PathVariable(
  224. key="custom_api_file",
  225. help="Path to a custom GDExtension API JSON file (takes precedence over `gdextension_dir`)",
  226. default=env.get("custom_api_file", None),
  227. validator=validate_file,
  228. )
  229. )
  230. opts.Add(
  231. BoolVariable(
  232. key="generate_bindings",
  233. help="Force GDExtension API bindings generation. Auto-detected by default.",
  234. default=env.get("generate_bindings", False),
  235. )
  236. )
  237. opts.Add(
  238. BoolVariable(
  239. key="generate_template_get_node",
  240. help="Generate a template version of the Node class's get_node.",
  241. default=env.get("generate_template_get_node", True),
  242. )
  243. )
  244. opts.Add(
  245. BoolVariable(
  246. key="build_library",
  247. help="Build the godot-cpp library.",
  248. default=env.get("build_library", True),
  249. )
  250. )
  251. opts.Add(
  252. EnumVariable(
  253. key="precision",
  254. help="Set the floating-point precision level",
  255. default=env.get("precision", "single"),
  256. allowed_values=("single", "double"),
  257. )
  258. )
  259. opts.Add(
  260. EnumVariable(
  261. key="arch",
  262. help="CPU architecture",
  263. default=env.get("arch", ""),
  264. allowed_values=architecture_array,
  265. map=architecture_aliases,
  266. )
  267. )
  268. opts.Add(BoolVariable(key="threads", help="Enable threading support", default=env.get("threads", True)))
  269. # compiledb
  270. opts.Add(
  271. BoolVariable(
  272. key="compiledb",
  273. help="Generate compilation DB (`compile_commands.json`) for external tools",
  274. default=env.get("compiledb", False),
  275. )
  276. )
  277. opts.Add(
  278. PathVariable(
  279. key="compiledb_file",
  280. help="Path to a custom `compile_commands.json` file",
  281. default=env.get("compiledb_file", "compile_commands.json"),
  282. validator=validate_parent_dir,
  283. )
  284. )
  285. opts.Add(
  286. PathVariable(
  287. "build_profile",
  288. "Path to a file containing a feature build profile",
  289. default=env.get("build_profile", None),
  290. validator=validate_file,
  291. )
  292. )
  293. opts.Add(
  294. BoolVariable(
  295. key="use_hot_reload",
  296. help="Enable the extra accounting required to support hot reload.",
  297. default=env.get("use_hot_reload", None),
  298. )
  299. )
  300. opts.Add(
  301. BoolVariable(
  302. "disable_exceptions", "Force disabling exception handling code", default=env.get("disable_exceptions", True)
  303. )
  304. )
  305. opts.Add(
  306. EnumVariable(
  307. key="symbols_visibility",
  308. help="Symbols visibility on GNU platforms. Use 'auto' to apply the default value.",
  309. default=env.get("symbols_visibility", "hidden"),
  310. allowed_values=["auto", "visible", "hidden"],
  311. )
  312. )
  313. opts.Add(
  314. EnumVariable(
  315. "optimize",
  316. "The desired optimization flags",
  317. "speed_trace",
  318. ("none", "custom", "debug", "speed", "speed_trace", "size"),
  319. )
  320. )
  321. opts.Add(
  322. EnumVariable(
  323. "lto",
  324. "Link-time optimization",
  325. "none",
  326. ("none", "auto", "thin", "full"),
  327. )
  328. )
  329. opts.Add(BoolVariable("debug_symbols", "Build with debugging symbols", True))
  330. opts.Add(BoolVariable("dev_build", "Developer build with dev-only debugging code (DEV_ENABLED)", False))
  331. opts.Add(BoolVariable("verbose", "Enable verbose output for the compilation", False))
  332. # Add platform options (custom tools can override platforms)
  333. for pl in sorted(set(platforms + custom_platforms)):
  334. tool = Tool(pl, toolpath=get_platform_tools_paths(env))
  335. if hasattr(tool, "options"):
  336. tool.options(opts)
  337. def generate(env):
  338. env.scons_version = env._get_major_minor_revision(scons_raw_version)
  339. # Default num_jobs to local cpu count if not user specified.
  340. # SCons has a peculiarity where user-specified options won't be overridden
  341. # by SetOption, so we can rely on this to know if we should use our default.
  342. initial_num_jobs = env.GetOption("num_jobs")
  343. altered_num_jobs = initial_num_jobs + 1
  344. env.SetOption("num_jobs", altered_num_jobs)
  345. if env.GetOption("num_jobs") == altered_num_jobs:
  346. cpu_count = os.cpu_count()
  347. if cpu_count is None:
  348. print("Couldn't auto-detect CPU count to configure build parallelism. Specify it with the -j argument.")
  349. else:
  350. safer_cpu_count = cpu_count if cpu_count <= 4 else cpu_count - 1
  351. print(
  352. "Auto-detected %d CPU cores available for build parallelism. Using %d cores by default. You can override it with the -j argument."
  353. % (cpu_count, safer_cpu_count)
  354. )
  355. env.SetOption("num_jobs", safer_cpu_count)
  356. # Process CPU architecture argument.
  357. if env["arch"] == "":
  358. # No architecture specified. Default to arm64 if building for Android,
  359. # universal if building for macOS or iOS, wasm32 if building for web,
  360. # otherwise default to the host architecture.
  361. if env["platform"] in ["macos", "ios"]:
  362. env["arch"] = "universal"
  363. elif env["platform"] == "android":
  364. env["arch"] = "arm64"
  365. elif env["platform"] == "web":
  366. env["arch"] = "wasm32"
  367. else:
  368. host_machine = platform.machine().lower()
  369. if host_machine in architecture_array:
  370. env["arch"] = host_machine
  371. elif host_machine in architecture_aliases.keys():
  372. env["arch"] = architecture_aliases[host_machine]
  373. elif "86" in host_machine:
  374. # Catches x86, i386, i486, i586, i686, etc.
  375. env["arch"] = "x86_32"
  376. else:
  377. print("Unsupported CPU architecture: " + host_machine)
  378. env.Exit(1)
  379. print("Building for architecture " + env["arch"] + " on platform " + env["platform"])
  380. # These defaults may be needed by platform tools
  381. env.use_hot_reload = env.get("use_hot_reload", env["target"] != "template_release")
  382. env.editor_build = env["target"] == "editor"
  383. env.dev_build = env["dev_build"]
  384. env.debug_features = env["target"] in ["editor", "template_debug"]
  385. if env.dev_build:
  386. opt_level = "none"
  387. elif env.debug_features:
  388. opt_level = "speed_trace"
  389. else: # Release
  390. opt_level = "speed"
  391. # Allow marking includes as external/system to avoid raising warnings.
  392. if env.scons_version < (4, 2):
  393. env["_CPPEXTINCFLAGS"] = "${_concat(EXTINCPREFIX, CPPEXTPATH, EXTINCSUFFIX, __env__, RDirs, TARGET, SOURCE)}"
  394. else:
  395. env["_CPPEXTINCFLAGS"] = (
  396. "${_concat(EXTINCPREFIX, CPPEXTPATH, EXTINCSUFFIX, __env__, RDirs, TARGET, SOURCE, affect_signature=False)}"
  397. )
  398. env["CPPEXTPATH"] = []
  399. env["EXTINCPREFIX"] = "-isystem "
  400. env["EXTINCSUFFIX"] = ""
  401. env["optimize"] = ARGUMENTS.get("optimize", opt_level)
  402. env["debug_symbols"] = get_cmdline_bool("debug_symbols", env.dev_build)
  403. tool = Tool(env["platform"], toolpath=get_platform_tools_paths(env))
  404. if tool is None or not tool.exists(env):
  405. raise ValueError("Required toolchain not found for platform " + env["platform"])
  406. tool.generate(env)
  407. if env["threads"]:
  408. env.Append(CPPDEFINES=["THREADS_ENABLED"])
  409. if env.use_hot_reload:
  410. env.Append(CPPDEFINES=["HOT_RELOAD_ENABLED"])
  411. if env.editor_build:
  412. env.Append(CPPDEFINES=["TOOLS_ENABLED"])
  413. # Configuration of build targets:
  414. # - Editor or template
  415. # - Debug features (DEBUG_ENABLED code)
  416. # - Dev only code (DEV_ENABLED code)
  417. # - Optimization level
  418. # - Debug symbols for crash traces / debuggers
  419. # Keep this configuration in sync with SConstruct in upstream Godot.
  420. if env.debug_features:
  421. # DEBUG_ENABLED enables debugging *features* and debug-only code, which is intended
  422. # to give *users* extra debugging information for their game development.
  423. env.Append(CPPDEFINES=["DEBUG_ENABLED"])
  424. if env.dev_build:
  425. # DEV_ENABLED enables *engine developer* code which should only be compiled for those
  426. # working on the engine itself.
  427. env.Append(CPPDEFINES=["DEV_ENABLED"])
  428. else:
  429. # Disable assert() for production targets (only used in thirdparty code).
  430. env.Append(CPPDEFINES=["NDEBUG"])
  431. if env["precision"] == "double":
  432. env.Append(CPPDEFINES=["REAL_T_IS_DOUBLE"])
  433. # Allow detecting when building as a GDExtension.
  434. env.Append(CPPDEFINES=["GDEXTENSION"])
  435. # Suffix
  436. suffix = ".{}.{}".format(env["platform"], env["target"])
  437. if env.dev_build:
  438. suffix += ".dev"
  439. if env["precision"] == "double":
  440. suffix += ".double"
  441. suffix += "." + env["arch"]
  442. if env["ios_simulator"]:
  443. suffix += ".simulator"
  444. if not env["threads"]:
  445. suffix += ".nothreads"
  446. env["suffix"] = suffix # Exposed when included from another project
  447. env["OBJSUFFIX"] = suffix + env["OBJSUFFIX"]
  448. # compile_commands.json
  449. env.Tool("compilation_db")
  450. env.Alias("compiledb", env.CompilationDatabase(normalize_path(env["compiledb_file"], env)))
  451. # Formatting
  452. if not env["verbose"]:
  453. no_verbose(env)
  454. # Builders
  455. env.Append(
  456. BUILDERS={
  457. "GodotCPPBindings": Builder(action=Action(scons_generate_bindings, "$GENCOMSTR"), emitter=scons_emit_files),
  458. "GodotCPPDocData": Builder(action=scons_generate_doc_source),
  459. }
  460. )
  461. env.AddMethod(_godot_cpp, "GodotCPP")
  462. def _godot_cpp(env):
  463. extension_dir = normalize_path(env.get("gdextension_dir", default=env.Dir("gdextension").srcnode().abspath), env)
  464. api_file = normalize_path(
  465. env.get("custom_api_file", default=os.path.join(extension_dir, "extension_api.json")), env
  466. )
  467. bindings = env.GodotCPPBindings(
  468. env.Dir("."),
  469. [
  470. api_file,
  471. os.path.join(extension_dir, "gdextension_interface.h"),
  472. "binding_generator.py",
  473. ],
  474. )
  475. # Forces bindings regeneration.
  476. if env["generate_bindings"]:
  477. env.AlwaysBuild(bindings)
  478. env.NoCache(bindings)
  479. # Sources to compile
  480. sources = [
  481. *env.Glob("src/*.cpp"),
  482. *env.Glob("src/classes/*.cpp"),
  483. *env.Glob("src/core/*.cpp"),
  484. *env.Glob("src/variant/*.cpp"),
  485. *tuple(f for f in bindings if str(f).endswith(".cpp")),
  486. ]
  487. # Includes
  488. env.AppendUnique(
  489. CPPPATH=[
  490. env.Dir(extension_dir),
  491. env.Dir("include").srcnode(),
  492. env.Dir("gen/include"),
  493. ]
  494. )
  495. library = None
  496. library_name = "libgodot-cpp" + env["suffix"] + env["LIBSUFFIX"]
  497. if env["build_library"]:
  498. library = env.StaticLibrary(target=env.File("bin/%s" % library_name), source=sources)
  499. env.NoCache(library)
  500. default_args = [library]
  501. # Add compiledb if the option is set
  502. if env.get("compiledb", False):
  503. default_args += ["compiledb"]
  504. env.Default(*default_args)
  505. env.AppendUnique(LIBS=[env.File("bin/%s" % library_name)])
  506. return library