SConstruct 18 KB

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