detect.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. import os
  2. import sys
  3. from pathlib import Path
  4. from typing import TYPE_CHECKING
  5. from emscripten_helpers import (
  6. add_js_externs,
  7. add_js_libraries,
  8. add_js_post,
  9. add_js_pre,
  10. create_engine_file,
  11. create_template_zip,
  12. get_template_zip_path,
  13. run_closure_compiler,
  14. )
  15. from SCons.Util import WhereIs
  16. from methods import get_compiler_version, print_error, print_info, print_warning
  17. from platform_methods import validate_arch
  18. if TYPE_CHECKING:
  19. from SCons.Script.SConscript import SConsEnvironment
  20. def get_name():
  21. return "Web"
  22. def can_build():
  23. return WhereIs("emcc") is not None
  24. def get_tools(env: "SConsEnvironment"):
  25. # Use generic POSIX build toolchain for Emscripten.
  26. return ["cc", "c++", "ar", "link", "textfile", "zip"]
  27. def get_opts():
  28. from SCons.Variables import BoolVariable
  29. return [
  30. ("initial_memory", "Initial WASM memory (in MiB)", 32),
  31. # Matches default values from before Emscripten 3.1.27. New defaults are too low for Godot.
  32. ("stack_size", "WASM stack size (in KiB)", 5120),
  33. ("default_pthread_stack_size", "WASM pthread default stack size (in KiB)", 2048),
  34. BoolVariable("use_assertions", "Use Emscripten runtime assertions", False),
  35. BoolVariable("use_ubsan", "Use Emscripten undefined behavior sanitizer (UBSAN)", False),
  36. BoolVariable("use_asan", "Use Emscripten address sanitizer (ASAN)", False),
  37. BoolVariable("use_lsan", "Use Emscripten leak sanitizer (LSAN)", False),
  38. BoolVariable("use_safe_heap", "Use Emscripten SAFE_HEAP sanitizer", False),
  39. # eval() can be a security concern, so it can be disabled.
  40. BoolVariable("javascript_eval", "Enable JavaScript eval interface", True),
  41. BoolVariable(
  42. "dlink_enabled", "Enable WebAssembly dynamic linking (GDExtension support). Produces bigger binaries", False
  43. ),
  44. BoolVariable("use_closure_compiler", "Use closure compiler to minimize JavaScript code", False),
  45. BoolVariable(
  46. "proxy_to_pthread",
  47. "Use Emscripten PROXY_TO_PTHREAD option to run the main application code to a separate thread",
  48. False,
  49. ),
  50. BoolVariable("wasm_simd", "Use WebAssembly SIMD to improve CPU performance", True),
  51. ]
  52. def get_doc_classes():
  53. return [
  54. "EditorExportPlatformWeb",
  55. ]
  56. def get_doc_path():
  57. return "doc_classes"
  58. def get_flags():
  59. return {
  60. "arch": "wasm32",
  61. "target": "template_debug",
  62. "builtin_pcre2_with_jit": False,
  63. "vulkan": False,
  64. # Embree is heavy and requires too much memory (GH-70621).
  65. "module_raycast_enabled": False,
  66. # Use -Os to prioritize optimizing for reduced file size. This is
  67. # particularly valuable for the web platform because it directly
  68. # decreases download time.
  69. # -Os reduces file size by around 5 MiB over -O3. -Oz only saves about
  70. # 100 KiB over -Os, which does not justify the negative impact on
  71. # run-time performance.
  72. # Note that this overrides the "auto" behavior for target/dev_build.
  73. "optimize": "size",
  74. }
  75. def library_emitter(target, source, env):
  76. # Make every source file dependent on the compiler version.
  77. # This makes sure that when emscripten is updated, that the cached files
  78. # aren't used and are recompiled instead.
  79. env.Depends(source, env.Value(get_compiler_version(env)))
  80. return target, source
  81. def configure(env: "SConsEnvironment"):
  82. env["CC"] = "emcc"
  83. env["CXX"] = "em++"
  84. env["AR"] = "emar"
  85. env["RANLIB"] = "emranlib"
  86. # Get version info for checks below.
  87. cc_version = get_compiler_version(env)
  88. cc_semver = (cc_version["major"], cc_version["minor"], cc_version["patch"])
  89. # Minimum emscripten requirements.
  90. if cc_semver < (4, 0, 0):
  91. print_error("The minimum Emscripten version to build Godot is 4.0.0, detected: %s.%s.%s" % cc_semver)
  92. sys.exit(255)
  93. env.Append(LIBEMITTER=[library_emitter])
  94. env["EXPORTED_FUNCTIONS"] = ["_main"]
  95. env["EXPORTED_RUNTIME_METHODS"] = []
  96. # Validate arch.
  97. supported_arches = ["wasm32"]
  98. validate_arch(env["arch"], get_name(), supported_arches)
  99. try:
  100. env["initial_memory"] = int(env["initial_memory"])
  101. except Exception:
  102. print_error("Initial memory must be a valid integer")
  103. sys.exit(255)
  104. # Add Emscripten to the included paths (for compile_commands.json completion)
  105. emcc_path = Path(str(WhereIs("emcc")))
  106. while emcc_path.is_symlink():
  107. # For some reason, mypy trips on `Path.readlink` not being defined, somehow.
  108. emcc_path = emcc_path.readlink() # type: ignore[attr-defined]
  109. emscripten_include_path = emcc_path.parent.joinpath("cache", "sysroot", "include")
  110. env.Append(CPPPATH=[emscripten_include_path])
  111. ## Build type
  112. if env.debug_features:
  113. # Retain function names for backtraces at the cost of file size.
  114. env.Append(LINKFLAGS=["--profiling-funcs"])
  115. else:
  116. env["use_assertions"] = True
  117. if env["use_assertions"]:
  118. env.Append(LINKFLAGS=["-sASSERTIONS=1"])
  119. if env.editor_build and env["initial_memory"] < 64:
  120. print_info("Forcing `initial_memory=64` as it is required for the web editor.")
  121. env["initial_memory"] = 64
  122. env.Append(LINKFLAGS=["-sINITIAL_MEMORY=%sMB" % env["initial_memory"]])
  123. ## Copy env variables.
  124. env["ENV"] = os.environ
  125. # This makes `wasm-ld` treat all warnings as errors.
  126. if env["werror"]:
  127. env.Append(LINKFLAGS=["-Wl,--fatal-warnings"])
  128. # LTO
  129. if env["lto"] == "auto": # Enable LTO for production.
  130. env["lto"] = "thin"
  131. if env["lto"] == "thin" and cc_semver < (4, 0, 9):
  132. print_warning(
  133. '"lto=thin" support requires Emscripten 4.0.9 (detected %s.%s.%s), using "lto=full" instead.' % cc_semver
  134. )
  135. env["lto"] = "full"
  136. if env["lto"] != "none":
  137. if env["lto"] == "thin":
  138. env.Append(CCFLAGS=["-flto=thin"])
  139. env.Append(LINKFLAGS=["-flto=thin"])
  140. else:
  141. env.Append(CCFLAGS=["-flto"])
  142. env.Append(LINKFLAGS=["-flto"])
  143. # Sanitizers
  144. if env["use_ubsan"]:
  145. env.Append(CCFLAGS=["-fsanitize=undefined"])
  146. env.Append(LINKFLAGS=["-fsanitize=undefined"])
  147. if env["use_asan"]:
  148. env.Append(CCFLAGS=["-fsanitize=address"])
  149. env.Append(LINKFLAGS=["-fsanitize=address"])
  150. if env["use_lsan"]:
  151. env.Append(CCFLAGS=["-fsanitize=leak"])
  152. env.Append(LINKFLAGS=["-fsanitize=leak"])
  153. if env["use_safe_heap"]:
  154. env.Append(LINKFLAGS=["-sSAFE_HEAP=1"])
  155. # Closure compiler
  156. if env["use_closure_compiler"] and cc_semver < (4, 0, 11):
  157. print_warning(
  158. '"use_closure_compiler=yes" support requires Emscripten 4.0.11 (detected %s.%s.%s), using "use_closure_compiler=no" instead.'
  159. % cc_semver
  160. )
  161. env["use_closure_compiler"] = False
  162. if env["use_closure_compiler"]:
  163. # For emscripten support code.
  164. env.Append(LINKFLAGS=["--closure", "1"])
  165. # Register builder for our Engine files
  166. jscc = env.Builder(generator=run_closure_compiler, suffix=".cc.js", src_suffix=".js")
  167. env.Append(BUILDERS={"BuildJS": jscc})
  168. # Add helper method for adding libraries, externs, pre-js, post-js.
  169. env["JS_LIBS"] = []
  170. env["JS_PRE"] = []
  171. env["JS_POST"] = []
  172. env["JS_EXTERNS"] = []
  173. env.AddMethod(add_js_libraries, "AddJSLibraries")
  174. env.AddMethod(add_js_pre, "AddJSPre")
  175. env.AddMethod(add_js_post, "AddJSPost")
  176. env.AddMethod(add_js_externs, "AddJSExterns")
  177. # Add method that joins/compiles our Engine files.
  178. env.AddMethod(create_engine_file, "CreateEngineFile")
  179. # Add method for getting the final zip path
  180. env.AddMethod(get_template_zip_path, "GetTemplateZipPath")
  181. # Add method for creating the final zip file
  182. env.AddMethod(create_template_zip, "CreateTemplateZip")
  183. # Use TempFileMunge since some AR invocations are too long for cmd.exe.
  184. # Use POSIX-style paths, required with TempFileMunge.
  185. env["ARCOM_POSIX"] = env["ARCOM"].replace("$TARGET", "$TARGET.posix").replace("$SOURCES", "$SOURCES.posix")
  186. env["ARCOM"] = "${TEMPFILE('$ARCOM_POSIX','$ARCOMSTR')}"
  187. # All intermediate files are just object files.
  188. env["OBJPREFIX"] = ""
  189. env["OBJSUFFIX"] = ".o"
  190. env["PROGPREFIX"] = ""
  191. # Program() output consists of multiple files, so specify suffixes manually at builder.
  192. env["PROGSUFFIX"] = ""
  193. env["LIBPREFIX"] = "lib"
  194. env["LIBSUFFIX"] = ".a"
  195. env["LIBPREFIXES"] = ["$LIBPREFIX"]
  196. env["LIBSUFFIXES"] = ["$LIBSUFFIX"]
  197. env.Prepend(CPPPATH=["#platform/web"])
  198. env.Append(CPPDEFINES=["WEB_ENABLED", "UNIX_ENABLED", "UNIX_SOCKET_UNAVAILABLE"])
  199. if env["opengl3"]:
  200. env.AppendUnique(CPPDEFINES=["GLES3_ENABLED"])
  201. # This setting just makes WebGL 2 APIs available, it does NOT disable WebGL 1.
  202. env.Append(LINKFLAGS=["-sMAX_WEBGL_VERSION=2"])
  203. # Allow use to take control of swapping WebGL buffers.
  204. env.Append(LINKFLAGS=["-sOFFSCREEN_FRAMEBUFFER=1"])
  205. # Disables the use of *glGetProcAddress() which is inefficient.
  206. # See https://emscripten.org/docs/tools_reference/settings_reference.html#gl-enable-get-proc-address
  207. env.Append(LINKFLAGS=["-sGL_ENABLE_GET_PROC_ADDRESS=0"])
  208. if env["javascript_eval"]:
  209. env.Append(CPPDEFINES=["JAVASCRIPT_EVAL_ENABLED"])
  210. env.Append(LINKFLAGS=["-s%s=%sKB" % ("STACK_SIZE", env["stack_size"])])
  211. if env["threads"]:
  212. # Thread support (via SharedArrayBuffer).
  213. env.Append(CPPDEFINES=["PTHREAD_NO_RENAME"])
  214. env.Append(CCFLAGS=["-sUSE_PTHREADS=1"])
  215. env.Append(LINKFLAGS=["-sUSE_PTHREADS=1"])
  216. env.Append(LINKFLAGS=["-sDEFAULT_PTHREAD_STACK_SIZE=%sKB" % env["default_pthread_stack_size"]])
  217. env.Append(LINKFLAGS=["-sPTHREAD_POOL_SIZE=\"Module['emscriptenPoolSize']||8\""])
  218. env.Append(LINKFLAGS=["-sWASM_MEM_MAX=2048MB"])
  219. if not env["dlink_enabled"]:
  220. # Workaround https://github.com/emscripten-core/emscripten/issues/21844#issuecomment-2116936414.
  221. # Not needed (and potentially dangerous) when dlink_enabled=yes, since we set EXPORT_ALL=1 in that case.
  222. env["EXPORTED_FUNCTIONS"] += ["__emscripten_thread_crashed"]
  223. elif env["proxy_to_pthread"]:
  224. print_warning('"threads=no" support requires "proxy_to_pthread=no", disabling proxy to pthread.')
  225. env["proxy_to_pthread"] = False
  226. if env["lto"] != "none":
  227. # Workaround https://github.com/emscripten-core/emscripten/issues/16836.
  228. env.Append(LINKFLAGS=["-Wl,-u,_emscripten_run_callback_on_thread"])
  229. if env["dlink_enabled"]:
  230. if env["proxy_to_pthread"]:
  231. print_warning("GDExtension support requires proxy_to_pthread=no, disabling proxy to pthread.")
  232. env["proxy_to_pthread"] = False
  233. env.Append(CPPDEFINES=["WEB_DLINK_ENABLED"])
  234. env.Append(CCFLAGS=["-sSIDE_MODULE=2"])
  235. env.Append(LINKFLAGS=["-sSIDE_MODULE=2"])
  236. env.Append(CCFLAGS=["-fvisibility=hidden"])
  237. env.Append(LINKFLAGS=["-fvisibility=hidden"])
  238. env.extra_suffix = ".dlink" + env.extra_suffix
  239. env.Append(LINKFLAGS=["-sWASM_BIGINT"])
  240. # Run the main application in a web worker
  241. if env["proxy_to_pthread"]:
  242. env.Append(LINKFLAGS=["-sPROXY_TO_PTHREAD=1"])
  243. env.Append(CPPDEFINES=["PROXY_TO_PTHREAD_ENABLED"])
  244. env["EXPORTED_RUNTIME_METHODS"] += ["_emscripten_proxy_main"]
  245. # https://github.com/emscripten-core/emscripten/issues/18034#issuecomment-1277561925
  246. env.Append(LINKFLAGS=["-sTEXTDECODER=0"])
  247. # Enable WebAssembly SIMD
  248. if env["wasm_simd"]:
  249. env.Append(CCFLAGS=["-msimd128"])
  250. # Reduce code size by generating less support code (e.g. skip NodeJS support).
  251. env.Append(LINKFLAGS=["-sENVIRONMENT=web,worker"])
  252. # Wrap the JavaScript support code around a closure named Godot.
  253. env.Append(LINKFLAGS=["-sMODULARIZE=1", "-sEXPORT_NAME='Godot'"])
  254. # Force long jump mode to 'wasm'
  255. env.Append(CCFLAGS=["-sSUPPORT_LONGJMP='wasm'"])
  256. env.Append(LINKFLAGS=["-sSUPPORT_LONGJMP='wasm'"])
  257. # Allow increasing memory buffer size during runtime. This is efficient
  258. # when using WebAssembly (in comparison to asm.js) and works well for
  259. # us since we don't know requirements at compile-time.
  260. env.Append(LINKFLAGS=["-sALLOW_MEMORY_GROWTH=1"])
  261. # Do not call main immediately when the support code is ready.
  262. env.Append(LINKFLAGS=["-sINVOKE_RUN=0"])
  263. # callMain for manual start, cwrap for the mono version.
  264. # Make sure also to have those memory-related functions available.
  265. heap_arrays = [f"HEAP{heap_type}{heap_size}" for heap_size in [8, 16, 32, 64] for heap_type in ["", "U"]] + [
  266. "HEAPF32",
  267. "HEAPF64",
  268. ]
  269. env["EXPORTED_RUNTIME_METHODS"] += ["callMain", "cwrap"] + heap_arrays
  270. env["EXPORTED_FUNCTIONS"] += ["_malloc", "_free"]
  271. # Add code that allow exiting runtime.
  272. env.Append(LINKFLAGS=["-sEXIT_RUNTIME=1"])
  273. # This workaround creates a closure that prevents the garbage collector from freeing the WebGL context.
  274. # We also only use WebGL2, and changing context version is not widely supported anyway.
  275. env.Append(LINKFLAGS=["-sGL_WORKAROUND_SAFARI_GETCONTEXT_BUG=0"])
  276. # Disable GDScript LSP (as the Web platform is not compatible with TCP).
  277. env.Append(CPPDEFINES=["GDSCRIPT_NO_LSP"])