SConstruct 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. #!/usr/bin/env python
  2. import os
  3. import sys
  4. import subprocess
  5. if sys.version_info < (3,):
  6. def decode_utf8(x):
  7. return x
  8. else:
  9. import codecs
  10. def decode_utf8(x):
  11. return codecs.utf_8_decode(x)[0]
  12. # Workaround for MinGW. See:
  13. # http://www.scons.org/wiki/LongCmdLinesOnWin32
  14. if os.name == "nt":
  15. import subprocess
  16. def mySubProcess(cmdline, env):
  17. # print "SPAWNED : " + cmdline
  18. startupinfo = subprocess.STARTUPINFO()
  19. startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  20. proc = subprocess.Popen(
  21. cmdline,
  22. stdin=subprocess.PIPE,
  23. stdout=subprocess.PIPE,
  24. stderr=subprocess.PIPE,
  25. startupinfo=startupinfo,
  26. shell=False,
  27. env=env,
  28. )
  29. data, err = proc.communicate()
  30. rv = proc.wait()
  31. if rv:
  32. print("=====")
  33. print(err.decode("utf-8"))
  34. print("=====")
  35. return rv
  36. def mySpawn(sh, escape, cmd, args, env):
  37. newargs = " ".join(args[1:])
  38. cmdline = cmd + " " + newargs
  39. rv = 0
  40. if len(cmdline) > 32000 and cmd.endswith("ar"):
  41. cmdline = cmd + " " + args[1] + " " + args[2] + " "
  42. for i in range(3, len(args)):
  43. rv = mySubProcess(cmdline + args[i], env)
  44. if rv:
  45. break
  46. else:
  47. rv = mySubProcess(cmdline, env)
  48. return rv
  49. def add_sources(sources, dir, extension):
  50. for f in os.listdir(dir):
  51. if f.endswith("." + extension):
  52. sources.append(dir + "/" + f)
  53. # Try to detect the host platform automatically.
  54. # This is used if no `platform` argument is passed
  55. if sys.platform.startswith("linux"):
  56. host_platform = "linux"
  57. elif sys.platform.startswith("freebsd"):
  58. host_platform = "freebsd"
  59. elif sys.platform == "darwin":
  60. host_platform = "osx"
  61. elif sys.platform == "win32" or sys.platform == "msys":
  62. host_platform = "windows"
  63. else:
  64. raise ValueError("Could not detect platform automatically, please specify with platform=<platform>")
  65. env = Environment(ENV=os.environ)
  66. is64 = sys.maxsize > 2 ** 32
  67. if (
  68. env["TARGET_ARCH"] == "amd64"
  69. or env["TARGET_ARCH"] == "emt64"
  70. or env["TARGET_ARCH"] == "x86_64"
  71. or env["TARGET_ARCH"] == "arm64-v8a"
  72. ):
  73. is64 = True
  74. opts = Variables([], ARGUMENTS)
  75. opts.Add(
  76. EnumVariable(
  77. "platform",
  78. "Target platform",
  79. host_platform,
  80. allowed_values=("linux", "freebsd", "osx", "windows", "android", "ios", "javascript"),
  81. ignorecase=2,
  82. )
  83. )
  84. opts.Add(EnumVariable("bits", "Target platform bits", "64" if is64 else "32", ("32", "64")))
  85. opts.Add(BoolVariable("use_llvm", "Use the LLVM compiler - only effective when targeting Linux or FreeBSD", False))
  86. opts.Add(BoolVariable("use_mingw", "Use the MinGW compiler instead of MSVC - only effective on Windows", False))
  87. # Must be the same setting as used for cpp_bindings
  88. opts.Add(EnumVariable("target", "Compilation target", "debug", allowed_values=("debug", "release"), ignorecase=2))
  89. opts.Add(
  90. PathVariable(
  91. "headers_dir", "Path to the directory containing Godot headers", "godot-headers", PathVariable.PathIsDir
  92. )
  93. )
  94. opts.Add(PathVariable("custom_api_file", "Path to a custom JSON API file", None, PathVariable.PathIsFile))
  95. opts.Add(
  96. EnumVariable(
  97. "generate_bindings",
  98. "Generate GDNative API bindings",
  99. "auto",
  100. allowed_values=["yes", "no", "auto", "true"],
  101. ignorecase=2,
  102. )
  103. )
  104. opts.Add(EnumVariable("android_arch", "Target Android architecture", "armv7", ["armv7", "arm64v8", "x86", "x86_64"]))
  105. opts.Add("macos_deployment_target", "macOS deployment target", "default")
  106. opts.Add("macos_sdk_path", "macOS SDK path", "")
  107. opts.Add(EnumVariable("macos_arch", "Target macOS architecture", "universal", ["universal", "x86_64", "arm64"]))
  108. opts.Add(EnumVariable("ios_arch", "Target iOS architecture", "arm64", ["armv7", "arm64", "x86_64"]))
  109. opts.Add(BoolVariable("ios_simulator", "Target iOS Simulator", False))
  110. opts.Add(
  111. "IPHONEPATH",
  112. "Path to iPhone toolchain",
  113. "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain",
  114. )
  115. opts.Add(
  116. "android_api_level",
  117. "Target Android API level",
  118. "18" if ARGUMENTS.get("android_arch", "armv7") in ["armv7", "x86"] else "21",
  119. )
  120. opts.Add(
  121. "ANDROID_NDK_ROOT",
  122. "Path to your Android NDK installation. By default, uses ANDROID_NDK_ROOT from your defined environment variables.",
  123. os.environ.get("ANDROID_NDK_ROOT", None),
  124. )
  125. opts.Add(BoolVariable("generate_template_get_node", "Generate a template version of the Node class's get_node.", True))
  126. opts.Update(env)
  127. Help(opts.GenerateHelpText(env))
  128. # This makes sure to keep the session environment variables on Windows.
  129. # This way, you can run SCons in a Visual Studio 2017 prompt and it will find
  130. # all the required tools
  131. if host_platform == "windows" and env["platform"] != "android":
  132. if env["bits"] == "64":
  133. env = Environment(TARGET_ARCH="amd64")
  134. elif env["bits"] == "32":
  135. env = Environment(TARGET_ARCH="x86")
  136. opts.Update(env)
  137. if env["platform"] == "linux" or env["platform"] == "freebsd":
  138. if env["use_llvm"]:
  139. env["CXX"] = "clang++"
  140. env.Append(CCFLAGS=["-fPIC", "-std=c++14", "-Wwrite-strings"])
  141. env.Append(LINKFLAGS=["-Wl,-R,'$$ORIGIN'"])
  142. if env["target"] == "debug":
  143. env.Append(CCFLAGS=["-Og", "-g"])
  144. elif env["target"] == "release":
  145. env.Append(CCFLAGS=["-O3"])
  146. if env["bits"] == "64":
  147. env.Append(CCFLAGS=["-m64"])
  148. env.Append(LINKFLAGS=["-m64"])
  149. elif env["bits"] == "32":
  150. env.Append(CCFLAGS=["-m32"])
  151. env.Append(LINKFLAGS=["-m32"])
  152. elif env["platform"] == "osx":
  153. # Use Clang on macOS by default
  154. env["CXX"] = "clang++"
  155. if env["bits"] == "32":
  156. raise ValueError("Only 64-bit builds are supported for the macOS target.")
  157. if env["macos_arch"] == "universal":
  158. env.Append(LINKFLAGS=["-arch", "x86_64", "-arch", "arm64"])
  159. env.Append(CCFLAGS=["-arch", "x86_64", "-arch", "arm64"])
  160. else:
  161. env.Append(LINKFLAGS=["-arch", env["macos_arch"]])
  162. env.Append(CCFLAGS=["-arch", env["macos_arch"]])
  163. env.Append(CCFLAGS=["-std=c++14"])
  164. if env["macos_deployment_target"] != "default":
  165. env.Append(CCFLAGS=["-mmacosx-version-min=" + env["macos_deployment_target"]])
  166. env.Append(LINKFLAGS=["-mmacosx-version-min=" + env["macos_deployment_target"]])
  167. if env["macos_sdk_path"]:
  168. env.Append(CCFLAGS=["-isysroot", env["macos_sdk_path"]])
  169. env.Append(LINKFLAGS=["-isysroot", env["macos_sdk_path"]])
  170. env.Append(
  171. LINKFLAGS=[
  172. "-framework",
  173. "Cocoa",
  174. "-Wl,-undefined,dynamic_lookup",
  175. ]
  176. )
  177. if env["target"] == "debug":
  178. env.Append(CCFLAGS=["-Og", "-g"])
  179. elif env["target"] == "release":
  180. env.Append(CCFLAGS=["-O3"])
  181. elif env["platform"] == "ios":
  182. if env["ios_simulator"]:
  183. sdk_name = "iphonesimulator"
  184. env.Append(CCFLAGS=["-mios-simulator-version-min=10.0"])
  185. env["LIBSUFFIX"] = ".simulator" + env["LIBSUFFIX"]
  186. else:
  187. sdk_name = "iphoneos"
  188. env.Append(CCFLAGS=["-miphoneos-version-min=10.0"])
  189. try:
  190. sdk_path = decode_utf8(subprocess.check_output(["xcrun", "--sdk", sdk_name, "--show-sdk-path"]).strip())
  191. except (subprocess.CalledProcessError, OSError):
  192. raise ValueError("Failed to find SDK path while running xcrun --sdk {} --show-sdk-path.".format(sdk_name))
  193. compiler_path = env["IPHONEPATH"] + "/usr/bin/"
  194. env["ENV"]["PATH"] = env["IPHONEPATH"] + "/Developer/usr/bin/:" + env["ENV"]["PATH"]
  195. env["CC"] = compiler_path + "clang"
  196. env["CXX"] = compiler_path + "clang++"
  197. env["AR"] = compiler_path + "ar"
  198. env["RANLIB"] = compiler_path + "ranlib"
  199. env.Append(CCFLAGS=["-std=c++14", "-arch", env["ios_arch"], "-isysroot", sdk_path])
  200. env.Append(
  201. LINKFLAGS=[
  202. "-arch",
  203. env["ios_arch"],
  204. "-framework",
  205. "Cocoa",
  206. "-Wl,-undefined,dynamic_lookup",
  207. "-isysroot",
  208. sdk_path,
  209. "-F" + sdk_path,
  210. ]
  211. )
  212. if env["target"] == "debug":
  213. env.Append(CCFLAGS=["-Og", "-g"])
  214. elif env["target"] == "release":
  215. env.Append(CCFLAGS=["-O3"])
  216. elif env["platform"] == "windows":
  217. if host_platform == "windows" and not env["use_mingw"]:
  218. # MSVC
  219. env.Append(LINKFLAGS=["/WX"])
  220. if env["target"] == "debug":
  221. env.Append(CCFLAGS=["/Z7", "/Od", "/EHsc", "/D_DEBUG", "/MDd"])
  222. elif env["target"] == "release":
  223. env.Append(CCFLAGS=["/O2", "/EHsc", "/DNDEBUG", "/MD"])
  224. elif host_platform == "linux" or host_platform == "freebsd" or host_platform == "osx":
  225. # Cross-compilation using MinGW
  226. if env["bits"] == "64":
  227. env["CXX"] = "x86_64-w64-mingw32-g++"
  228. env["AR"] = "x86_64-w64-mingw32-ar"
  229. env["RANLIB"] = "x86_64-w64-mingw32-ranlib"
  230. env["LINK"] = "x86_64-w64-mingw32-g++"
  231. elif env["bits"] == "32":
  232. env["CXX"] = "i686-w64-mingw32-g++"
  233. env["AR"] = "i686-w64-mingw32-ar"
  234. env["RANLIB"] = "i686-w64-mingw32-ranlib"
  235. env["LINK"] = "i686-w64-mingw32-g++"
  236. elif host_platform == "windows" and env["use_mingw"]:
  237. # Don't Clone the environment. Because otherwise, SCons will pick up msvc stuff.
  238. env = Environment(ENV=os.environ, tools=["mingw"])
  239. opts.Update(env)
  240. # env = env.Clone(tools=['mingw'])
  241. env["SPAWN"] = mySpawn
  242. # Native or cross-compilation using MinGW
  243. if host_platform == "linux" or host_platform == "freebsd" or host_platform == "osx" or env["use_mingw"]:
  244. # These options are for a release build even using target=debug
  245. env.Append(CCFLAGS=["-O3", "-std=c++14", "-Wwrite-strings"])
  246. env.Append(
  247. LINKFLAGS=[
  248. "--static",
  249. "-Wl,--no-undefined",
  250. "-static-libgcc",
  251. "-static-libstdc++",
  252. ]
  253. )
  254. elif env["platform"] == "android":
  255. if host_platform == "windows":
  256. # Don't Clone the environment. Because otherwise, SCons will pick up msvc stuff.
  257. env = Environment(ENV=os.environ, tools=["mingw"])
  258. opts.Update(env)
  259. # env = env.Clone(tools=['mingw'])
  260. env["SPAWN"] = mySpawn
  261. # Verify NDK root
  262. if not "ANDROID_NDK_ROOT" in env:
  263. raise ValueError(
  264. "To build for Android, ANDROID_NDK_ROOT must be defined. Please set ANDROID_NDK_ROOT to the root folder of your Android NDK installation."
  265. )
  266. # Validate API level
  267. api_level = int(env["android_api_level"])
  268. if env["android_arch"] in ["x86_64", "arm64v8"] and api_level < 21:
  269. print("WARN: 64-bit Android architectures require an API level of at least 21; setting android_api_level=21")
  270. env["android_api_level"] = "21"
  271. api_level = 21
  272. # Setup toolchain
  273. toolchain = env["ANDROID_NDK_ROOT"] + "/toolchains/llvm/prebuilt/"
  274. if host_platform == "windows":
  275. toolchain += "windows"
  276. import platform as pltfm
  277. if pltfm.machine().endswith("64"):
  278. toolchain += "-x86_64"
  279. elif host_platform == "linux":
  280. toolchain += "linux-x86_64"
  281. elif host_platform == "osx":
  282. toolchain += "darwin-x86_64"
  283. env.PrependENVPath("PATH", toolchain + "/bin") # This does nothing half of the time, but we'll put it here anyways
  284. # Get architecture info
  285. arch_info_table = {
  286. "armv7": {
  287. "march": "armv7-a",
  288. "target": "armv7a-linux-androideabi",
  289. "tool_path": "arm-linux-androideabi",
  290. "compiler_path": "armv7a-linux-androideabi",
  291. "ccflags": ["-mfpu=neon"],
  292. },
  293. "arm64v8": {
  294. "march": "armv8-a",
  295. "target": "aarch64-linux-android",
  296. "tool_path": "aarch64-linux-android",
  297. "compiler_path": "aarch64-linux-android",
  298. "ccflags": [],
  299. },
  300. "x86": {
  301. "march": "i686",
  302. "target": "i686-linux-android",
  303. "tool_path": "i686-linux-android",
  304. "compiler_path": "i686-linux-android",
  305. "ccflags": ["-mstackrealign"],
  306. },
  307. "x86_64": {
  308. "march": "x86-64",
  309. "target": "x86_64-linux-android",
  310. "tool_path": "x86_64-linux-android",
  311. "compiler_path": "x86_64-linux-android",
  312. "ccflags": [],
  313. },
  314. }
  315. arch_info = arch_info_table[env["android_arch"]]
  316. # Setup tools
  317. env["CC"] = toolchain + "/bin/clang"
  318. env["CXX"] = toolchain + "/bin/clang++"
  319. env["AR"] = toolchain + "/bin/" + arch_info["tool_path"] + "-ar"
  320. env["AS"] = toolchain + "/bin/" + arch_info["tool_path"] + "-as"
  321. env["LD"] = toolchain + "/bin/" + arch_info["tool_path"] + "-ld"
  322. env["STRIP"] = toolchain + "/bin/" + arch_info["tool_path"] + "-strip"
  323. env["RANLIB"] = toolchain + "/bin/" + arch_info["tool_path"] + "-ranlib"
  324. env.Append(
  325. CCFLAGS=["--target=" + arch_info["target"] + env["android_api_level"], "-march=" + arch_info["march"], "-fPIC"]
  326. )
  327. env.Append(CCFLAGS=arch_info["ccflags"])
  328. if env["target"] == "debug":
  329. env.Append(CCFLAGS=["-Og", "-g"])
  330. elif env["target"] == "release":
  331. env.Append(CCFLAGS=["-O3"])
  332. elif env["platform"] == "javascript":
  333. env["ENV"] = os.environ
  334. env["CC"] = "emcc"
  335. env["CXX"] = "em++"
  336. env["AR"] = "emar"
  337. env["RANLIB"] = "emranlib"
  338. env.Append(CPPFLAGS=["-s", "SIDE_MODULE=1"])
  339. env.Append(LINKFLAGS=["-s", "SIDE_MODULE=1"])
  340. env["SHOBJSUFFIX"] = ".bc"
  341. env["SHLIBSUFFIX"] = ".wasm"
  342. # Use TempFileMunge since some AR invocations are too long for cmd.exe.
  343. # Use POSIX-style paths, required with TempFileMunge.
  344. env["ARCOM_POSIX"] = env["ARCOM"].replace("$TARGET", "$TARGET.posix").replace("$SOURCES", "$SOURCES.posix")
  345. env["ARCOM"] = "${TEMPFILE(ARCOM_POSIX)}"
  346. # All intermediate files are just LLVM bitcode.
  347. env["OBJPREFIX"] = ""
  348. env["OBJSUFFIX"] = ".bc"
  349. env["PROGPREFIX"] = ""
  350. # Program() output consists of multiple files, so specify suffixes manually at builder.
  351. env["PROGSUFFIX"] = ""
  352. env["LIBPREFIX"] = "lib"
  353. env["LIBSUFFIX"] = ".a"
  354. env["LIBPREFIXES"] = ["$LIBPREFIX"]
  355. env["LIBSUFFIXES"] = ["$LIBSUFFIX"]
  356. env.Replace(SHLINKFLAGS="$LINKFLAGS")
  357. env.Replace(SHLINKFLAGS="$LINKFLAGS")
  358. if env["target"] == "debug":
  359. env.Append(CCFLAGS=["-O0", "-g"])
  360. elif env["target"] == "release":
  361. env.Append(CCFLAGS=["-O3"])
  362. env.Append(
  363. CPPPATH=[
  364. ".",
  365. env["headers_dir"],
  366. "include",
  367. "include/gen",
  368. "include/core",
  369. ]
  370. )
  371. # Generate bindings?
  372. json_api_file = ""
  373. if "custom_api_file" in env:
  374. json_api_file = env["custom_api_file"]
  375. else:
  376. json_api_file = os.path.join(os.getcwd(), env["headers_dir"], "api.json")
  377. if env["generate_bindings"] == "auto":
  378. # Check if generated files exist
  379. should_generate_bindings = not os.path.isfile(os.path.join(os.getcwd(), "src", "gen", "Object.cpp"))
  380. else:
  381. should_generate_bindings = env["generate_bindings"] in ["yes", "true"]
  382. if should_generate_bindings:
  383. # Actually create the bindings here
  384. import binding_generator
  385. binding_generator.generate_bindings(json_api_file, env["generate_template_get_node"])
  386. # Sources to compile
  387. sources = []
  388. add_sources(sources, "src/core", "cpp")
  389. add_sources(sources, "src/gen", "cpp")
  390. arch_suffix = env["bits"]
  391. if env["platform"] == "android":
  392. arch_suffix = env["android_arch"]
  393. elif env["platform"] == "ios":
  394. arch_suffix = env["ios_arch"]
  395. elif env["platform"] == "osx":
  396. if env["macos_arch"] != "universal":
  397. arch_suffix = env["macos_arch"]
  398. elif env["platform"] == "javascript":
  399. arch_suffix = "wasm"
  400. library = env.StaticLibrary(
  401. target="bin/" + "libgodot-cpp.{}.{}.{}{}".format(env["platform"], env["target"], arch_suffix, env["LIBSUFFIX"]),
  402. source=sources,
  403. )
  404. Default(library)