SConstruct 7.7 KB

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