godotcpp.py 20 KB

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