SConstruct 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. #!/usr/bin/env python
  2. import os
  3. import platform
  4. import sys
  5. import subprocess
  6. from binding_generator import scons_generate_bindings, scons_emit_files
  7. from SCons.Errors import UserError
  8. EnsureSConsVersion(4, 0)
  9. def add_sources(sources, dir, extension):
  10. for f in os.listdir(dir):
  11. if f.endswith("." + extension):
  12. sources.append(dir + "/" + f)
  13. def normalize_path(val):
  14. return val if os.path.isabs(val) else os.path.join(env.Dir("#").abspath, val)
  15. def validate_api_file(key, val, env):
  16. if not os.path.isfile(normalize_path(val)):
  17. raise UserError("GDExtension API file ('%s') does not exist: %s" % (key, val))
  18. def validate_gdextension_dir(key, val, env):
  19. if not os.path.isdir(normalize_path(val)):
  20. raise UserError("GDExtension directory ('%s') does not exist: %s" % (key, val))
  21. def get_gdextension_dir(env):
  22. return normalize_path(env.get("gdextension_dir", env.Dir("gdextension").abspath))
  23. def get_api_file(env):
  24. return normalize_path(env.get("custom_api_file", os.path.join(get_gdextension_dir(env), "extension_api.json")))
  25. # Try to detect the host platform automatically.
  26. # This is used if no `platform` argument is passed
  27. if sys.platform.startswith("linux"):
  28. default_platform = "linux"
  29. elif sys.platform == "darwin":
  30. default_platform = "macos"
  31. elif sys.platform == "win32" or sys.platform == "msys":
  32. default_platform = "windows"
  33. elif ARGUMENTS.get("platform", ""):
  34. default_platform = ARGUMENTS.get("platform")
  35. else:
  36. raise ValueError("Could not detect platform automatically, please specify with platform=<platform>")
  37. try:
  38. Import("env")
  39. except:
  40. # Default tools with no platform defaults to gnu toolchain.
  41. # We apply platform specific toolchains via our custom tools.
  42. env = Environment(tools=["default"], PLATFORM="")
  43. env.PrependENVPath("PATH", os.getenv("PATH"))
  44. # Default num_jobs to local cpu count if not user specified.
  45. # SCons has a peculiarity where user-specified options won't be overridden
  46. # by SetOption, so we can rely on this to know if we should use our default.
  47. initial_num_jobs = env.GetOption("num_jobs")
  48. altered_num_jobs = initial_num_jobs + 1
  49. env.SetOption("num_jobs", altered_num_jobs)
  50. if env.GetOption("num_jobs") == altered_num_jobs:
  51. cpu_count = os.cpu_count()
  52. if cpu_count is None:
  53. print("Couldn't auto-detect CPU count to configure build parallelism. Specify it with the -j argument.")
  54. else:
  55. safer_cpu_count = cpu_count if cpu_count <= 4 else cpu_count - 1
  56. print(
  57. "Auto-detected %d CPU cores available for build parallelism. Using %d cores by default. You can override it with the -j argument."
  58. % (cpu_count, safer_cpu_count)
  59. )
  60. env.SetOption("num_jobs", safer_cpu_count)
  61. # Custom options and profile flags.
  62. customs = ["custom.py"]
  63. profile = ARGUMENTS.get("profile", "")
  64. if profile:
  65. if os.path.isfile(profile):
  66. customs.append(profile)
  67. elif os.path.isfile(profile + ".py"):
  68. customs.append(profile + ".py")
  69. opts = Variables(customs, ARGUMENTS)
  70. platforms = ("linux", "macos", "windows", "android", "ios", "javascript")
  71. opts.Add(
  72. EnumVariable(
  73. key="platform",
  74. help="Target platform",
  75. default=env.get("platform", default_platform),
  76. allowed_values=platforms,
  77. ignorecase=2,
  78. )
  79. )
  80. # Editor and template_debug are compatible (i.e. you can use the same binary for Godot editor builds and Godot debug templates).
  81. # Godot release templates are only compatible with "template_release" builds.
  82. # For this reason, we default to template_debug builds, unlike Godot which defaults to editor builds.
  83. opts.Add(
  84. EnumVariable(
  85. key="target",
  86. help="Compilation target",
  87. default=env.get("target", "template_debug"),
  88. allowed_values=("editor", "template_release", "template_debug"),
  89. )
  90. )
  91. opts.Add(
  92. PathVariable(
  93. key="gdextension_dir",
  94. help="Path to a custom directory containing GDExtension interface header and API JSON file",
  95. default=env.get("gdextension_dir", None),
  96. validator=validate_gdextension_dir,
  97. )
  98. )
  99. opts.Add(
  100. PathVariable(
  101. key="custom_api_file",
  102. help="Path to a custom GDExtension API JSON file (takes precedence over `gdextension_dir`)",
  103. default=env.get("custom_api_file", None),
  104. validator=validate_api_file,
  105. )
  106. )
  107. opts.Add(
  108. BoolVariable(
  109. key="generate_bindings",
  110. help="Force GDExtension API bindings generation. Auto-detected by default.",
  111. default=env.get("generate_bindings", False),
  112. )
  113. )
  114. opts.Add(
  115. BoolVariable(
  116. key="generate_template_get_node",
  117. help="Generate a template version of the Node class's get_node.",
  118. default=env.get("generate_template_get_node", True),
  119. )
  120. )
  121. opts.Add(BoolVariable(key="build_library", help="Build the godot-cpp library.", default=env.get("build_library", True)))
  122. opts.Add(
  123. EnumVariable(
  124. key="precision",
  125. help="Set the floating-point precision level",
  126. default=env.get("precision", "single"),
  127. allowed_values=("single", "double"),
  128. )
  129. )
  130. # Add platform options
  131. tools = {}
  132. for pl in platforms:
  133. tool = Tool(pl, toolpath=["tools"])
  134. if hasattr(tool, "options"):
  135. tool.options(opts)
  136. tools[pl] = tool
  137. # CPU architecture options.
  138. architecture_array = ["", "universal", "x86_32", "x86_64", "arm32", "arm64", "rv64", "ppc32", "ppc64", "wasm32"]
  139. architecture_aliases = {
  140. "x64": "x86_64",
  141. "amd64": "x86_64",
  142. "armv7": "arm32",
  143. "armv8": "arm64",
  144. "arm64v8": "arm64",
  145. "aarch64": "arm64",
  146. "rv": "rv64",
  147. "riscv": "rv64",
  148. "riscv64": "rv64",
  149. "ppcle": "ppc32",
  150. "ppc": "ppc32",
  151. "ppc64le": "ppc64",
  152. }
  153. opts.Add(
  154. EnumVariable(
  155. key="arch",
  156. help="CPU architecture",
  157. default=env.get("arch", ""),
  158. allowed_values=architecture_array,
  159. map=architecture_aliases,
  160. )
  161. )
  162. # Targets flags tool (optimizations, debug symbols)
  163. target_tool = Tool("targets", toolpath=["tools"])
  164. target_tool.options(opts)
  165. opts.Update(env)
  166. Help(opts.GenerateHelpText(env))
  167. # Process CPU architecture argument.
  168. if env["arch"] == "":
  169. # No architecture specified. Default to arm64 if building for Android,
  170. # universal if building for macOS or iOS, wasm32 if building for web,
  171. # otherwise default to the host architecture.
  172. if env["platform"] in ["macos", "ios"]:
  173. env["arch"] = "universal"
  174. elif env["platform"] == "android":
  175. env["arch"] = "arm64"
  176. elif env["platform"] == "javascript":
  177. env["arch"] = "wasm32"
  178. else:
  179. host_machine = platform.machine().lower()
  180. if host_machine in architecture_array:
  181. env["arch"] = host_machine
  182. elif host_machine in architecture_aliases.keys():
  183. env["arch"] = architecture_aliases[host_machine]
  184. elif "86" in host_machine:
  185. # Catches x86, i386, i486, i586, i686, etc.
  186. env["arch"] = "x86_32"
  187. else:
  188. print("Unsupported CPU architecture: " + host_machine)
  189. Exit()
  190. tool = Tool(env["platform"], toolpath=["tools"])
  191. if tool is None or not tool.exists(env):
  192. raise ValueError("Required toolchain not found for platform " + env["platform"])
  193. tool.generate(env)
  194. target_tool.generate(env)
  195. # Detect and print a warning listing unknown SCons variables to ease troubleshooting.
  196. unknown = opts.UnknownVariables()
  197. if unknown:
  198. print("WARNING: Unknown SCons variables were passed and will be ignored:")
  199. for item in unknown.items():
  200. print(" " + item[0] + "=" + item[1])
  201. print("Building for architecture " + env["arch"] + " on platform " + env["platform"])
  202. # Require C++17
  203. if env.get("is_msvc", False):
  204. env.Append(CXXFLAGS=["/std:c++17"])
  205. else:
  206. env.Append(CXXFLAGS=["-std=c++17"])
  207. if env["precision"] == "double":
  208. env.Append(CPPDEFINES=["REAL_T_IS_DOUBLE"])
  209. # Generate bindings
  210. env.Append(BUILDERS={"GenerateBindings": Builder(action=scons_generate_bindings, emitter=scons_emit_files)})
  211. bindings = env.GenerateBindings(
  212. env.Dir("."),
  213. [get_api_file(env), os.path.join(get_gdextension_dir(env), "gdextension_interface.h"), "binding_generator.py"],
  214. )
  215. scons_cache_path = os.environ.get("SCONS_CACHE")
  216. if scons_cache_path is not None:
  217. CacheDir(scons_cache_path)
  218. Decider("MD5")
  219. # Forces bindings regeneration.
  220. if env["generate_bindings"]:
  221. AlwaysBuild(bindings)
  222. NoCache(bindings)
  223. # Includes
  224. env.Append(CPPPATH=[[env.Dir(d) for d in [get_gdextension_dir(env), "include", os.path.join("gen", "include")]]])
  225. # Sources to compile
  226. sources = []
  227. add_sources(sources, "src", "cpp")
  228. add_sources(sources, "src/classes", "cpp")
  229. add_sources(sources, "src/core", "cpp")
  230. add_sources(sources, "src/variant", "cpp")
  231. sources.extend([f for f in bindings if str(f).endswith(".cpp")])
  232. suffix = ".{}.{}".format(env["platform"], env["target"])
  233. if env.dev_build:
  234. suffix += ".dev"
  235. if env["precision"] == "double":
  236. suffix += ".double"
  237. suffix += "." + env["arch"]
  238. if env["ios_simulator"]:
  239. suffix += ".simulator"
  240. # Expose it when included from another project
  241. env["suffix"] = suffix
  242. library = None
  243. env["OBJSUFFIX"] = suffix + env["OBJSUFFIX"]
  244. library_name = "libgodot-cpp{}{}".format(suffix, env["LIBSUFFIX"])
  245. if env["build_library"]:
  246. library = env.StaticLibrary(target=env.File("bin/%s" % library_name), source=sources)
  247. Default(library)
  248. env.Append(LIBPATH=[env.Dir("bin")])
  249. env.Append(LIBS=library_name)
  250. Return("env")