SConstruct 8.6 KB

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