SConstruct 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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. platforms = ("linux", "macos", "windows", "android", "ios", "javascript")
  43. opts = Variables([], ARGUMENTS)
  44. opts.Add(
  45. EnumVariable(
  46. "platform",
  47. "Target platform",
  48. default_platform,
  49. allowed_values=platforms,
  50. ignorecase=2,
  51. )
  52. )
  53. # Must be the same setting as used for cpp_bindings
  54. opts.Add(EnumVariable("target", "Compilation target", "debug", allowed_values=("debug", "release"), ignorecase=2))
  55. opts.Add(
  56. PathVariable(
  57. "headers_dir", "Path to the directory containing Godot headers", "godot-headers", PathVariable.PathIsDir
  58. )
  59. )
  60. opts.Add(PathVariable("custom_api_file", "Path to a custom JSON API file", None, PathVariable.PathIsFile))
  61. opts.Add(
  62. BoolVariable("generate_bindings", "Force GDExtension API bindings generation. Auto-detected by default.", False)
  63. )
  64. opts.Add(BoolVariable("generate_template_get_node", "Generate a template version of the Node class's get_node.", True))
  65. opts.Add(BoolVariable("build_library", "Build the godot-cpp library.", True))
  66. opts.Add(EnumVariable("float", "Floating-point precision", "32", ("32", "64")))
  67. # Add platform options
  68. tools = {}
  69. for pl in platforms:
  70. tool = Tool(pl, toolpath=["tools"])
  71. if hasattr(tool, "options"):
  72. tool.options(opts)
  73. tools[pl] = tool
  74. # CPU architecture options.
  75. architecture_array = ["", "universal", "x86_32", "x86_64", "arm32", "arm64", "rv64", "ppc32", "ppc64", "wasm32"]
  76. architecture_aliases = {
  77. "x64": "x86_64",
  78. "amd64": "x86_64",
  79. "armv7": "arm32",
  80. "armv8": "arm64",
  81. "arm64v8": "arm64",
  82. "aarch64": "arm64",
  83. "rv": "rv64",
  84. "riscv": "rv64",
  85. "riscv64": "rv64",
  86. "ppcle": "ppc32",
  87. "ppc": "ppc32",
  88. "ppc64le": "ppc64",
  89. }
  90. opts.Add(EnumVariable("arch", "CPU architecture", "", architecture_array, architecture_aliases))
  91. opts.Update(env)
  92. Help(opts.GenerateHelpText(env))
  93. # Process CPU architecture argument.
  94. if env["arch"] == "":
  95. # No architecture specified. Default to arm64 if building for Android,
  96. # universal if building for macOS or iOS, wasm32 if building for web,
  97. # otherwise default to the host architecture.
  98. if env["platform"] in ["macos", "ios"]:
  99. env["arch"] = "universal"
  100. elif env["platform"] == "android":
  101. env["arch"] = "arm64"
  102. elif env["platform"] == "javascript":
  103. env["arch"] = "wasm32"
  104. else:
  105. host_machine = platform.machine().lower()
  106. if host_machine in architecture_array:
  107. env["arch"] = host_machine
  108. elif host_machine in architecture_aliases.keys():
  109. env["arch"] = architecture_aliases[host_machine]
  110. elif "86" in host_machine:
  111. # Catches x86, i386, i486, i586, i686, etc.
  112. env["arch"] = "x86_32"
  113. else:
  114. print("Unsupported CPU architecture: " + host_machine)
  115. Exit()
  116. tool = Tool(env["platform"], toolpath=["tools"])
  117. if tool is None or not tool.exists(env):
  118. raise ValueError("Required toolchain not found for platform " + env["platform"])
  119. tool.generate(env)
  120. # Detect and print a warning listing unknown SCons variables to ease troubleshooting.
  121. unknown = opts.UnknownVariables()
  122. if unknown:
  123. print("WARNING: Unknown SCons variables were passed and will be ignored:")
  124. for item in unknown.items():
  125. print(" " + item[0] + "=" + item[1])
  126. print("Building for architecture " + env["arch"] + " on platform " + env["platform"])
  127. # Require C++17
  128. if env.get("is_msvc", False):
  129. env.Append(CXXFLAGS=["/std:c++17"])
  130. else:
  131. env.Append(CXXFLAGS=["-std=c++17"])
  132. if env["target"] == "debug":
  133. env.Append(CPPDEFINES=["DEBUG_ENABLED", "DEBUG_METHODS_ENABLED"])
  134. if env["float"] == "64":
  135. env.Append(CPPDEFINES=["REAL_T_IS_DOUBLE"])
  136. # Generate bindings
  137. env.Append(BUILDERS={"GenerateBindings": Builder(action=scons_generate_bindings, emitter=scons_emit_files)})
  138. json_api_file = ""
  139. if "custom_api_file" in env:
  140. json_api_file = env["custom_api_file"]
  141. else:
  142. json_api_file = os.path.join(os.getcwd(), env["headers_dir"], "extension_api.json")
  143. bindings = env.GenerateBindings(
  144. env.Dir("."), [json_api_file, os.path.join(env["headers_dir"], "godot", "gdnative_interface.h")]
  145. )
  146. # Forces bindings regeneration.
  147. if env["generate_bindings"]:
  148. AlwaysBuild(bindings)
  149. # Includes
  150. env.Append(CPPPATH=[[env.Dir(d) for d in [env["headers_dir"], "include", os.path.join("gen", "include")]]])
  151. # Sources to compile
  152. sources = []
  153. add_sources(sources, "src", "cpp")
  154. add_sources(sources, "src/classes", "cpp")
  155. add_sources(sources, "src/core", "cpp")
  156. add_sources(sources, "src/variant", "cpp")
  157. sources.extend([f for f in bindings if str(f).endswith(".cpp")])
  158. env["arch_suffix"] = env["arch"]
  159. if env["ios_simulator"]:
  160. env["arch_suffix"] += ".simulator"
  161. library = None
  162. env["OBJSUFFIX"] = ".{}.{}.{}{}".format(env["platform"], env["target"], env["arch_suffix"], env["OBJSUFFIX"])
  163. library_name = "libgodot-cpp.{}.{}.{}{}".format(env["platform"], env["target"], env["arch_suffix"], env["LIBSUFFIX"])
  164. if env["build_library"]:
  165. library = env.StaticLibrary(target=env.File("bin/%s" % library_name), source=sources)
  166. Default(library)
  167. env.Append(LIBPATH=[env.Dir("bin")])
  168. env.Append(LIBS=library_name)
  169. Return("env")