SConstruct 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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-temp", 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", "x86_64", ["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["target"] == "debug":
  138. env.Append(CPPDEFINES=["DEBUG_ENABLED", "DEBUG_METHODS_ENABLED"])
  139. if env["platform"] == "linux" or env["platform"] == "freebsd":
  140. if env["use_llvm"]:
  141. env["CXX"] = "clang++"
  142. env.Append(CCFLAGS=["-fPIC", "-std=c++17", "-Wwrite-strings"])
  143. env.Append(LINKFLAGS=["-Wl,-R,'$$ORIGIN'"])
  144. if env["target"] == "debug":
  145. env.Append(CCFLAGS=["-Og", "-g"])
  146. elif env["target"] == "release":
  147. env.Append(CCFLAGS=["-O3"])
  148. if env["bits"] == "64":
  149. env.Append(CCFLAGS=["-m64"])
  150. env.Append(LINKFLAGS=["-m64"])
  151. elif env["bits"] == "32":
  152. env.Append(CCFLAGS=["-m32"])
  153. env.Append(LINKFLAGS=["-m32"])
  154. elif env["platform"] == "osx":
  155. # Use Clang on macOS by default
  156. env["CXX"] = "clang++"
  157. if env["bits"] == "32":
  158. raise ValueError("Only 64-bit builds are supported for the macOS target.")
  159. env.Append(CCFLAGS=["-std=c++17", "-arch", env["macos_arch"]])
  160. if env["macos_deployment_target"] != "default":
  161. env.Append(CCFLAGS=["-mmacosx-version-min=" + env["macos_deployment_target"]])
  162. env.Append(LINKFLAGS=["-mmacosx-version-min=" + env["macos_deployment_target"]])
  163. if env["macos_sdk_path"]:
  164. env.Append(CCFLAGS=["-isysroot", env["macos_sdk_path"]])
  165. env.Append(LINKFLAGS=["-isysroot", env["macos_sdk_path"]])
  166. env.Append(
  167. LINKFLAGS=[
  168. "-arch",
  169. env["macos_arch"],
  170. "-framework",
  171. "Cocoa",
  172. "-Wl,-undefined,dynamic_lookup",
  173. ]
  174. )
  175. if env["target"] == "debug":
  176. env.Append(CCFLAGS=["-Og", "-g"])
  177. elif env["target"] == "release":
  178. env.Append(CCFLAGS=["-O3"])
  179. elif env["platform"] == "ios":
  180. if env["ios_simulator"]:
  181. sdk_name = "iphonesimulator"
  182. env.Append(CCFLAGS=["-mios-simulator-version-min=10.0"])
  183. env["LIBSUFFIX"] = ".simulator" + env["LIBSUFFIX"]
  184. else:
  185. sdk_name = "iphoneos"
  186. env.Append(CCFLAGS=["-miphoneos-version-min=10.0"])
  187. try:
  188. sdk_path = decode_utf8(subprocess.check_output(["xcrun", "--sdk", sdk_name, "--show-sdk-path"]).strip())
  189. except (subprocess.CalledProcessError, OSError):
  190. raise ValueError("Failed to find SDK path while running xcrun --sdk {} --show-sdk-path.".format(sdk_name))
  191. compiler_path = env["IPHONEPATH"] + "/usr/bin/"
  192. env["ENV"]["PATH"] = env["IPHONEPATH"] + "/Developer/usr/bin/:" + env["ENV"]["PATH"]
  193. env["CC"] = compiler_path + "clang"
  194. env["CXX"] = compiler_path + "clang++"
  195. env["AR"] = compiler_path + "ar"
  196. env["RANLIB"] = compiler_path + "ranlib"
  197. env.Append(CCFLAGS=["-std=c++17", "-arch", env["ios_arch"], "-isysroot", sdk_path])
  198. env.Append(
  199. LINKFLAGS=[
  200. "-arch",
  201. env["ios_arch"],
  202. "-framework",
  203. "Cocoa",
  204. "-Wl,-undefined,dynamic_lookup",
  205. "-isysroot",
  206. sdk_path,
  207. "-F" + sdk_path,
  208. ]
  209. )
  210. if env["target"] == "debug":
  211. env.Append(CCFLAGS=["-Og", "-g"])
  212. elif env["target"] == "release":
  213. env.Append(CCFLAGS=["-O3"])
  214. elif env["platform"] == "windows":
  215. if host_platform == "windows" and not env["use_mingw"]:
  216. # MSVC
  217. env.Append(LINKFLAGS=["/WX"])
  218. if env["target"] == "debug":
  219. env.Append(CCFLAGS=["/Z7", "/Od", "/EHsc", "/D_DEBUG", "/MDd"])
  220. elif env["target"] == "release":
  221. env.Append(CCFLAGS=["/O2", "/EHsc", "/DNDEBUG", "/MD"])
  222. elif host_platform == "linux" or host_platform == "freebsd" or host_platform == "osx":
  223. # Cross-compilation using MinGW
  224. if env["bits"] == "64":
  225. env["CXX"] = "x86_64-w64-mingw32-g++"
  226. env["AR"] = "x86_64-w64-mingw32-ar"
  227. env["RANLIB"] = "x86_64-w64-mingw32-ranlib"
  228. env["LINK"] = "x86_64-w64-mingw32-g++"
  229. elif env["bits"] == "32":
  230. env["CXX"] = "i686-w64-mingw32-g++"
  231. env["AR"] = "i686-w64-mingw32-ar"
  232. env["RANLIB"] = "i686-w64-mingw32-ranlib"
  233. env["LINK"] = "i686-w64-mingw32-g++"
  234. elif host_platform == "windows" and env["use_mingw"]:
  235. # Don't Clone the environment. Because otherwise, SCons will pick up msvc stuff.
  236. env = Environment(ENV=os.environ, tools=["mingw"])
  237. opts.Update(env)
  238. # env = env.Clone(tools=['mingw'])
  239. env["SPAWN"] = mySpawn
  240. # Native or cross-compilation using MinGW
  241. if host_platform == "linux" or host_platform == "freebsd" or host_platform == "osx" or env["use_mingw"]:
  242. # These options are for a release build even using target=debug
  243. env.Append(CCFLAGS=["-O3", "-std=c++17", "-Wwrite-strings"])
  244. env.Append(
  245. LINKFLAGS=[
  246. "--static",
  247. "-Wl,--no-undefined",
  248. "-static-libgcc",
  249. "-static-libstdc++",
  250. ]
  251. )
  252. elif env["platform"] == "android":
  253. if host_platform == "windows":
  254. # Don't Clone the environment. Because otherwise, SCons will pick up msvc stuff.
  255. env = Environment(ENV=os.environ, tools=["mingw"])
  256. opts.Update(env)
  257. # env = env.Clone(tools=['mingw'])
  258. env["SPAWN"] = mySpawn
  259. # Verify NDK root
  260. if not "ANDROID_NDK_ROOT" in env:
  261. raise ValueError(
  262. "To build for Android, ANDROID_NDK_ROOT must be defined. Please set ANDROID_NDK_ROOT to the root folder of your Android NDK installation."
  263. )
  264. # Validate API level
  265. api_level = int(env["android_api_level"])
  266. if env["android_arch"] in ["x86_64", "arm64v8"] and api_level < 21:
  267. print("WARN: 64-bit Android architectures require an API level of at least 21; setting android_api_level=21")
  268. env["android_api_level"] = "21"
  269. api_level = 21
  270. # Setup toolchain
  271. toolchain = env["ANDROID_NDK_ROOT"] + "/toolchains/llvm/prebuilt/"
  272. if host_platform == "windows":
  273. toolchain += "windows"
  274. import platform as pltfm
  275. if pltfm.machine().endswith("64"):
  276. toolchain += "-x86_64"
  277. elif host_platform == "linux":
  278. toolchain += "linux-x86_64"
  279. elif host_platform == "osx":
  280. toolchain += "darwin-x86_64"
  281. env.PrependENVPath("PATH", toolchain + "/bin") # This does nothing half of the time, but we'll put it here anyways
  282. # Get architecture info
  283. arch_info_table = {
  284. "armv7": {
  285. "march": "armv7-a",
  286. "target": "armv7a-linux-androideabi",
  287. "tool_path": "arm-linux-androideabi",
  288. "compiler_path": "armv7a-linux-androideabi",
  289. "ccflags": ["-mfpu=neon"],
  290. },
  291. "arm64v8": {
  292. "march": "armv8-a",
  293. "target": "aarch64-linux-android",
  294. "tool_path": "aarch64-linux-android",
  295. "compiler_path": "aarch64-linux-android",
  296. "ccflags": [],
  297. },
  298. "x86": {
  299. "march": "i686",
  300. "target": "i686-linux-android",
  301. "tool_path": "i686-linux-android",
  302. "compiler_path": "i686-linux-android",
  303. "ccflags": ["-mstackrealign"],
  304. },
  305. "x86_64": {
  306. "march": "x86-64",
  307. "target": "x86_64-linux-android",
  308. "tool_path": "x86_64-linux-android",
  309. "compiler_path": "x86_64-linux-android",
  310. "ccflags": [],
  311. },
  312. }
  313. arch_info = arch_info_table[env["android_arch"]]
  314. # Setup tools
  315. env["CC"] = toolchain + "/bin/clang"
  316. env["CXX"] = toolchain + "/bin/clang++"
  317. env["AR"] = toolchain + "/bin/" + arch_info["tool_path"] + "-ar"
  318. env.Append(
  319. CCFLAGS=["--target=" + arch_info["target"] + env["android_api_level"], "-march=" + arch_info["march"], "-fPIC"]
  320. ) # , '-fPIE', '-fno-addrsig', '-Oz'])
  321. env.Append(CCFLAGS=arch_info["ccflags"])
  322. if env["target"] == "debug":
  323. env.Append(CCFLAGS=["-Og", "-g"])
  324. elif env["target"] == "release":
  325. env.Append(CCFLAGS=["-O3"])
  326. elif env["platform"] == "javascript":
  327. env["ENV"] = os.environ
  328. env["CC"] = "emcc"
  329. env["CXX"] = "em++"
  330. env["AR"] = "emar"
  331. env["RANLIB"] = "emranlib"
  332. env.Append(CPPFLAGS=["-s", "SIDE_MODULE=1"])
  333. env.Append(LINKFLAGS=["-s", "SIDE_MODULE=1"])
  334. env["SHOBJSUFFIX"] = ".bc"
  335. env["SHLIBSUFFIX"] = ".wasm"
  336. # Use TempFileMunge since some AR invocations are too long for cmd.exe.
  337. # Use POSIX-style paths, required with TempFileMunge.
  338. env["ARCOM_POSIX"] = env["ARCOM"].replace("$TARGET", "$TARGET.posix").replace("$SOURCES", "$SOURCES.posix")
  339. env["ARCOM"] = "${TEMPFILE(ARCOM_POSIX)}"
  340. # All intermediate files are just LLVM bitcode.
  341. env["OBJPREFIX"] = ""
  342. env["OBJSUFFIX"] = ".bc"
  343. env["PROGPREFIX"] = ""
  344. # Program() output consists of multiple files, so specify suffixes manually at builder.
  345. env["PROGSUFFIX"] = ""
  346. env["LIBPREFIX"] = "lib"
  347. env["LIBSUFFIX"] = ".a"
  348. env["LIBPREFIXES"] = ["$LIBPREFIX"]
  349. env["LIBSUFFIXES"] = ["$LIBSUFFIX"]
  350. env.Replace(SHLINKFLAGS="$LINKFLAGS")
  351. env.Replace(SHLINKFLAGS="$LINKFLAGS")
  352. if env["target"] == "debug":
  353. env.Append(CCFLAGS=["-O0", "-g"])
  354. elif env["target"] == "release":
  355. env.Append(CCFLAGS=["-O3"])
  356. env.Append(
  357. CPPPATH=[
  358. ".",
  359. env["headers_dir"],
  360. "#include",
  361. "#gen/include",
  362. ]
  363. )
  364. # Generate bindings?
  365. json_api_file = ""
  366. if "custom_api_file" in env:
  367. json_api_file = env["custom_api_file"]
  368. else:
  369. json_api_file = os.path.join(os.getcwd(), env["headers_dir"], "extension_api.json")
  370. if env["generate_bindings"] == "auto":
  371. # Check if generated files exist
  372. should_generate_bindings = not os.path.isfile(os.path.join(os.getcwd(), "gen", "src", "classes", "object.cpp"))
  373. else:
  374. should_generate_bindings = env["generate_bindings"] in ["yes", "true"]
  375. if should_generate_bindings:
  376. # Actually create the bindings here
  377. import binding_generator
  378. binding_generator.generate_bindings(json_api_file, env["generate_template_get_node"])
  379. # Sources to compile
  380. sources = []
  381. add_sources(sources, "src", "cpp")
  382. add_sources(sources, "src/core", "cpp")
  383. add_sources(sources, "src/variant", "cpp")
  384. add_sources(sources, "gen/src/variant", "cpp")
  385. add_sources(sources, "gen/src/classes", "cpp")
  386. arch_suffix = env["bits"]
  387. if env["platform"] == "android":
  388. arch_suffix = env["android_arch"]
  389. if env["platform"] == "ios":
  390. arch_suffix = env["ios_arch"]
  391. if env["platform"] == "javascript":
  392. arch_suffix = "wasm"
  393. library = env.StaticLibrary(
  394. target="bin/" + "libgodot-cpp.{}.{}.{}{}".format(env["platform"], env["target"], arch_suffix, env["LIBSUFFIX"]),
  395. source=sources,
  396. )
  397. Default(library)