platform_methods.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. import os
  2. import platform
  3. import shutil
  4. import subprocess
  5. import sys
  6. import methods
  7. # NOTE: The multiprocessing module is not compatible with SCons due to conflict on cPickle
  8. compatibility_platform_aliases = {
  9. "osx": "macos",
  10. "iphone": "ios",
  11. "x11": "linuxbsd",
  12. "javascript": "web",
  13. }
  14. # CPU architecture options.
  15. architectures = ["x86_32", "x86_64", "arm32", "arm64", "rv64", "ppc64", "wasm32", "loongarch64"]
  16. architecture_aliases = {
  17. "x86": "x86_32",
  18. "x64": "x86_64",
  19. "amd64": "x86_64",
  20. "armv7": "arm32",
  21. "armv8": "arm64",
  22. "arm64v8": "arm64",
  23. "aarch64": "arm64",
  24. "rv": "rv64",
  25. "riscv": "rv64",
  26. "riscv64": "rv64",
  27. "ppc64le": "ppc64",
  28. "loong64": "loongarch64",
  29. }
  30. def detect_arch():
  31. host_machine = platform.machine().lower()
  32. if host_machine in architectures:
  33. return host_machine
  34. elif host_machine in architecture_aliases.keys():
  35. return architecture_aliases[host_machine]
  36. elif "86" in host_machine:
  37. # Catches x86, i386, i486, i586, i686, etc.
  38. return "x86_32"
  39. else:
  40. methods.print_warning(f'Unsupported CPU architecture: "{host_machine}". Falling back to x86_64.')
  41. return "x86_64"
  42. def validate_arch(arch, platform_name, supported_arches):
  43. if arch not in supported_arches:
  44. methods.print_error(
  45. 'Unsupported CPU architecture "%s" for %s. Supported architectures are: %s.'
  46. % (arch, platform_name, ", ".join(supported_arches))
  47. )
  48. sys.exit(255)
  49. def get_build_version(short):
  50. import version
  51. name = "custom_build"
  52. if os.getenv("BUILD_NAME") is not None:
  53. name = os.getenv("BUILD_NAME")
  54. v = "%d.%d" % (version.major, version.minor)
  55. if version.patch > 0:
  56. v += ".%d" % version.patch
  57. status = version.status
  58. if not short:
  59. if os.getenv("GODOT_VERSION_STATUS") is not None:
  60. status = str(os.getenv("GODOT_VERSION_STATUS"))
  61. v += ".%s.%s" % (status, name)
  62. return v
  63. def lipo(prefix, suffix):
  64. from pathlib import Path
  65. target_bin = ""
  66. lipo_command = ["lipo", "-create"]
  67. arch_found = 0
  68. for arch in architectures:
  69. bin_name = prefix + "." + arch + suffix
  70. if Path(bin_name).is_file():
  71. target_bin = bin_name
  72. lipo_command += [bin_name]
  73. arch_found += 1
  74. if arch_found > 1:
  75. target_bin = prefix + ".fat" + suffix
  76. lipo_command += ["-output", target_bin]
  77. subprocess.run(lipo_command)
  78. return target_bin
  79. def get_mvk_sdk_path(osname):
  80. def int_or_zero(i):
  81. try:
  82. return int(i)
  83. except (TypeError, ValueError):
  84. return 0
  85. def ver_parse(a):
  86. return [int_or_zero(i) for i in a.split(".")]
  87. dirname = os.path.expanduser("~/VulkanSDK")
  88. if not os.path.exists(dirname):
  89. return ""
  90. ver_min = ver_parse("1.3.231.0")
  91. ver_num = ver_parse("0.0.0.0")
  92. files = os.listdir(dirname)
  93. lib_name_out = dirname
  94. for file in files:
  95. if os.path.isdir(os.path.join(dirname, file)):
  96. ver_comp = ver_parse(file)
  97. if ver_comp > ver_num and ver_comp >= ver_min:
  98. # Try new SDK location.
  99. lib_name = os.path.join(os.path.join(dirname, file), "macOS/lib/MoltenVK.xcframework/" + osname + "/")
  100. if os.path.isfile(os.path.join(lib_name, "libMoltenVK.a")):
  101. ver_num = ver_comp
  102. lib_name_out = os.path.join(os.path.join(dirname, file), "macOS/lib/MoltenVK.xcframework")
  103. else:
  104. # Try old SDK location.
  105. lib_name = os.path.join(
  106. os.path.join(dirname, file), "MoltenVK/MoltenVK.xcframework/" + osname + "/"
  107. )
  108. if os.path.isfile(os.path.join(lib_name, "libMoltenVK.a")):
  109. ver_num = ver_comp
  110. lib_name_out = os.path.join(os.path.join(dirname, file), "MoltenVK/MoltenVK.xcframework")
  111. return lib_name_out
  112. def detect_mvk(env, osname):
  113. mvk_list = [
  114. get_mvk_sdk_path(osname),
  115. "/opt/homebrew/Frameworks/MoltenVK.xcframework",
  116. "/usr/local/homebrew/Frameworks/MoltenVK.xcframework",
  117. "/opt/local/Frameworks/MoltenVK.xcframework",
  118. ]
  119. if env["vulkan_sdk_path"] != "":
  120. mvk_list.insert(0, os.path.expanduser(env["vulkan_sdk_path"]))
  121. mvk_list.insert(
  122. 0,
  123. os.path.join(os.path.expanduser(env["vulkan_sdk_path"]), "macOS/lib/MoltenVK.xcframework"),
  124. )
  125. mvk_list.insert(
  126. 0,
  127. os.path.join(os.path.expanduser(env["vulkan_sdk_path"]), "MoltenVK/MoltenVK.xcframework"),
  128. )
  129. for mvk_path in mvk_list:
  130. if mvk_path and os.path.isfile(os.path.join(mvk_path, f"{osname}/libMoltenVK.a")):
  131. print(f"MoltenVK found at: {mvk_path}")
  132. return mvk_path
  133. return ""
  134. def combine_libs_apple_embedded(target, source, env):
  135. lib_path = target[0].srcnode().abspath
  136. if "osxcross" in env:
  137. libtool = "$APPLE_TOOLCHAIN_PATH/usr/bin/${apple_target_triple}libtool"
  138. else:
  139. libtool = "$APPLE_TOOLCHAIN_PATH/usr/bin/libtool"
  140. env.Execute(
  141. libtool + ' -static -o "' + lib_path + '" ' + " ".join([('"' + lib.srcnode().abspath + '"') for lib in source])
  142. )
  143. def generate_bundle_apple_embedded(platform, framework_dir, framework_dir_sim, use_mkv, target, source, env):
  144. bin_dir = env.Dir("#bin").abspath
  145. # Template bundle.
  146. app_prefix = "godot." + platform
  147. rel_prefix = "libgodot." + platform + "." + "template_release"
  148. dbg_prefix = "libgodot." + platform + "." + "template_debug"
  149. if env.dev_build:
  150. app_prefix += ".dev"
  151. rel_prefix += ".dev"
  152. dbg_prefix += ".dev"
  153. if env["precision"] == "double":
  154. app_prefix += ".double"
  155. rel_prefix += ".double"
  156. dbg_prefix += ".double"
  157. # Lipo template libraries.
  158. #
  159. # env.extra_suffix contains ".simulator" when building for simulator,
  160. # but it's undesired when calling lipo()
  161. extra_suffix = env.extra_suffix.replace(".simulator", "")
  162. rel_target_bin = lipo(bin_dir + "/" + rel_prefix, extra_suffix + ".a")
  163. dbg_target_bin = lipo(bin_dir + "/" + dbg_prefix, extra_suffix + ".a")
  164. rel_target_bin_sim = lipo(bin_dir + "/" + rel_prefix, ".simulator" + extra_suffix + ".a")
  165. dbg_target_bin_sim = lipo(bin_dir + "/" + dbg_prefix, ".simulator" + extra_suffix + ".a")
  166. # Assemble Xcode project bundle.
  167. app_dir = env.Dir("#bin/" + platform + "_xcode").abspath
  168. templ = env.Dir("#misc/dist/apple_embedded_xcode").abspath
  169. if os.path.exists(app_dir):
  170. shutil.rmtree(app_dir)
  171. shutil.copytree(templ, app_dir)
  172. if rel_target_bin != "":
  173. print(f' Copying "{platform}" release framework')
  174. shutil.copy(
  175. rel_target_bin, app_dir + "/libgodot." + platform + ".release.xcframework/" + framework_dir + "/libgodot.a"
  176. )
  177. if dbg_target_bin != "":
  178. print(f' Copying "{platform}" debug framework')
  179. shutil.copy(
  180. dbg_target_bin, app_dir + "/libgodot." + platform + ".debug.xcframework/" + framework_dir + "/libgodot.a"
  181. )
  182. if rel_target_bin_sim != "":
  183. print(f' Copying "{platform}" (simulator) release framework')
  184. shutil.copy(
  185. rel_target_bin_sim,
  186. app_dir + "/libgodot." + platform + ".release.xcframework/" + framework_dir_sim + "/libgodot.a",
  187. )
  188. if dbg_target_bin_sim != "":
  189. print(f' Copying "{platform}" (simulator) debug framework')
  190. shutil.copy(
  191. dbg_target_bin_sim,
  192. app_dir + "/libgodot." + platform + ".debug.xcframework/" + framework_dir_sim + "/libgodot.a",
  193. )
  194. # Remove other platform xcframeworks
  195. for entry in os.listdir(app_dir):
  196. if entry.startswith("libgodot.") and entry.endswith(".xcframework"):
  197. parts = entry.split(".")
  198. if len(parts) >= 3 and parts[1] != platform:
  199. full_path = os.path.join(app_dir, entry)
  200. shutil.rmtree(full_path)
  201. if use_mkv:
  202. mvk_path = detect_mvk(env, "ios-arm64")
  203. if mvk_path != "":
  204. shutil.copytree(mvk_path, app_dir + "/MoltenVK.xcframework")
  205. # ZIP Xcode project bundle.
  206. zip_dir = env.Dir("#bin/" + (app_prefix + extra_suffix).replace(".", "_")).abspath
  207. shutil.make_archive(zip_dir, "zip", root_dir=app_dir)
  208. shutil.rmtree(app_dir)
  209. def setup_swift_builder(env, apple_platform, sdk_path, current_path, bridging_header_filename, all_swift_files):
  210. from SCons.Script import Action, Builder
  211. if apple_platform == "macos":
  212. target_suffix = "macosx10.9"
  213. elif apple_platform == "ios":
  214. target_suffix = "ios14.0" # iOS 14.0 needed for SwiftUI lifecycle
  215. elif apple_platform == "iossimulator":
  216. target_suffix = "ios14.0-simulator" # iOS 14.0 needed for SwiftUI lifecycle
  217. elif apple_platform == "visionos":
  218. target_suffix = "xros26.0"
  219. elif apple_platform == "visionossimulator":
  220. target_suffix = "xros26.0-simulator"
  221. else:
  222. raise Exception("Invalid platform argument passed to detect_darwin_sdk_path")
  223. swiftc_target = env["arch"] + "-apple-" + target_suffix
  224. env["ALL_SWIFT_FILES"] = all_swift_files
  225. env["CURRENT_PATH"] = current_path
  226. frontend_path = "$APPLE_TOOLCHAIN_PATH/usr/bin/swift-frontend"
  227. bridging_header_path = current_path + "/" + bridging_header_filename
  228. env["SWIFTC"] = frontend_path + " -frontend -c" # Swift compiler
  229. env["SWIFTCFLAGS"] = [
  230. "-cxx-interoperability-mode=default",
  231. "-emit-object",
  232. "-target",
  233. swiftc_target,
  234. "-sdk",
  235. sdk_path,
  236. "-import-objc-header",
  237. bridging_header_path,
  238. "-swift-version",
  239. "6",
  240. "-parse-as-library",
  241. "-module-name",
  242. "godot_swift_module",
  243. "-I./", # Pass the current directory as the header root so bridging headers can include files from any point of the hierarchy
  244. ]
  245. if env["debug_symbols"]:
  246. env.Append(SWIFTCFLAGS=["-g"])
  247. if env["optimize"] in ["speed", "speed_trace"]:
  248. env.Append(SWIFTCFLAGS=["-O"])
  249. elif env["optimize"] == "size":
  250. env.Append(SWIFTCFLAGS=["-Osize"])
  251. elif env["optimize"] in ["debug", "none"]:
  252. env.Append(SWIFTCFLAGS=["-Onone"])
  253. def generate_swift_action(source, target, env, for_signature):
  254. fullpath_swift_files = [env["CURRENT_PATH"] + "/" + file for file in env["ALL_SWIFT_FILES"]]
  255. fullpath_swift_files.remove(source[0].abspath)
  256. fullpath_swift_files_string = '"' + '" "'.join(fullpath_swift_files) + '"'
  257. compile_command = "$SWIFTC " + fullpath_swift_files_string + " -primary-file $SOURCE -o $TARGET $SWIFTCFLAGS"
  258. swift_comdstr = env.get("SWIFTCOMSTR")
  259. if swift_comdstr is not None:
  260. swift_action = Action(compile_command, cmdstr=swift_comdstr)
  261. else:
  262. swift_action = Action(compile_command)
  263. return swift_action
  264. # Define Builder for Swift files
  265. swift_builder = Builder(
  266. generator=generate_swift_action, suffix=env["OBJSUFFIX"], src_suffix=".swift", emitter=methods.redirect_emitter
  267. )
  268. env.Append(BUILDERS={"Swift": swift_builder})
  269. env["BUILDERS"]["Library"].add_src_builder("Swift")
  270. env["BUILDERS"]["Object"].add_action(".swift", Action(generate_swift_action, generator=1))