detect.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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.Append(LIBEMITTER=[library_emitter])
  83. env["EXPORTED_FUNCTIONS"] = ["_main"]
  84. env["EXPORTED_RUNTIME_METHODS"] = []
  85. # Validate arch.
  86. supported_arches = ["wasm32"]
  87. validate_arch(env["arch"], get_name(), supported_arches)
  88. try:
  89. env["initial_memory"] = int(env["initial_memory"])
  90. except Exception:
  91. print_error("Initial memory must be a valid integer")
  92. sys.exit(255)
  93. # Add Emscripten to the included paths (for compile_commands.json completion)
  94. emcc_path = Path(str(WhereIs("emcc")))
  95. while emcc_path.is_symlink():
  96. # For some reason, mypy trips on `Path.readlink` not being defined, somehow.
  97. emcc_path = emcc_path.readlink() # type: ignore[attr-defined]
  98. emscripten_include_path = emcc_path.parent.joinpath("cache", "sysroot", "include")
  99. env.Append(CPPPATH=[emscripten_include_path])
  100. ## Build type
  101. if env.debug_features:
  102. # Retain function names for backtraces at the cost of file size.
  103. env.Append(LINKFLAGS=["--profiling-funcs"])
  104. else:
  105. env["use_assertions"] = True
  106. if env["use_assertions"]:
  107. env.Append(LINKFLAGS=["-sASSERTIONS=1"])
  108. if env.editor_build and env["initial_memory"] < 64:
  109. print_info("Forcing `initial_memory=64` as it is required for the web editor.")
  110. env["initial_memory"] = 64
  111. env.Append(LINKFLAGS=["-sINITIAL_MEMORY=%sMB" % env["initial_memory"]])
  112. ## Copy env variables.
  113. env["ENV"] = os.environ
  114. # This makes `wasm-ld` treat all warnings as errors.
  115. if env["werror"]:
  116. env.Append(LINKFLAGS=["-Wl,--fatal-warnings"])
  117. # LTO
  118. if env["lto"] == "auto": # Enable LTO for production.
  119. env["lto"] = "thin"
  120. if env["lto"] != "none":
  121. if env["lto"] == "thin":
  122. env.Append(CCFLAGS=["-flto=thin"])
  123. env.Append(LINKFLAGS=["-flto=thin"])
  124. else:
  125. env.Append(CCFLAGS=["-flto"])
  126. env.Append(LINKFLAGS=["-flto"])
  127. # Sanitizers
  128. if env["use_ubsan"]:
  129. env.Append(CCFLAGS=["-fsanitize=undefined"])
  130. env.Append(LINKFLAGS=["-fsanitize=undefined"])
  131. if env["use_asan"]:
  132. env.Append(CCFLAGS=["-fsanitize=address"])
  133. env.Append(LINKFLAGS=["-fsanitize=address"])
  134. if env["use_lsan"]:
  135. env.Append(CCFLAGS=["-fsanitize=leak"])
  136. env.Append(LINKFLAGS=["-fsanitize=leak"])
  137. if env["use_safe_heap"]:
  138. env.Append(LINKFLAGS=["-sSAFE_HEAP=1"])
  139. # Closure compiler
  140. if env["use_closure_compiler"]:
  141. # For emscripten support code.
  142. env.Append(LINKFLAGS=["--closure", "1"])
  143. # Register builder for our Engine files
  144. jscc = env.Builder(generator=run_closure_compiler, suffix=".cc.js", src_suffix=".js")
  145. env.Append(BUILDERS={"BuildJS": jscc})
  146. # Add helper method for adding libraries, externs, pre-js, post-js.
  147. env["JS_LIBS"] = []
  148. env["JS_PRE"] = []
  149. env["JS_POST"] = []
  150. env["JS_EXTERNS"] = []
  151. env.AddMethod(add_js_libraries, "AddJSLibraries")
  152. env.AddMethod(add_js_pre, "AddJSPre")
  153. env.AddMethod(add_js_post, "AddJSPost")
  154. env.AddMethod(add_js_externs, "AddJSExterns")
  155. # Add method that joins/compiles our Engine files.
  156. env.AddMethod(create_engine_file, "CreateEngineFile")
  157. # Add method for getting the final zip path
  158. env.AddMethod(get_template_zip_path, "GetTemplateZipPath")
  159. # Add method for creating the final zip file
  160. env.AddMethod(create_template_zip, "CreateTemplateZip")
  161. env["CC"] = "emcc"
  162. env["CXX"] = "em++"
  163. env["AR"] = "emar"
  164. env["RANLIB"] = "emranlib"
  165. # Use TempFileMunge since some AR invocations are too long for cmd.exe.
  166. # Use POSIX-style paths, required with TempFileMunge.
  167. env["ARCOM_POSIX"] = env["ARCOM"].replace("$TARGET", "$TARGET.posix").replace("$SOURCES", "$SOURCES.posix")
  168. env["ARCOM"] = "${TEMPFILE('$ARCOM_POSIX','$ARCOMSTR')}"
  169. # All intermediate files are just object files.
  170. env["OBJPREFIX"] = ""
  171. env["OBJSUFFIX"] = ".o"
  172. env["PROGPREFIX"] = ""
  173. # Program() output consists of multiple files, so specify suffixes manually at builder.
  174. env["PROGSUFFIX"] = ""
  175. env["LIBPREFIX"] = "lib"
  176. env["LIBSUFFIX"] = ".a"
  177. env["LIBPREFIXES"] = ["$LIBPREFIX"]
  178. env["LIBSUFFIXES"] = ["$LIBSUFFIX"]
  179. # Get version info for checks below.
  180. cc_version = get_compiler_version(env)
  181. cc_semver = (cc_version["major"], cc_version["minor"], cc_version["patch"])
  182. # Minimum emscripten requirements.
  183. if cc_semver < (3, 1, 62):
  184. print_error("The minimum emscripten version to build Godot is 3.1.62, detected: %s.%s.%s" % cc_semver)
  185. sys.exit(255)
  186. env.Prepend(CPPPATH=["#platform/web"])
  187. env.Append(CPPDEFINES=["WEB_ENABLED", "UNIX_ENABLED", "UNIX_SOCKET_UNAVAILABLE"])
  188. if env["opengl3"]:
  189. env.AppendUnique(CPPDEFINES=["GLES3_ENABLED"])
  190. # This setting just makes WebGL 2 APIs available, it does NOT disable WebGL 1.
  191. env.Append(LINKFLAGS=["-sMAX_WEBGL_VERSION=2"])
  192. # Allow use to take control of swapping WebGL buffers.
  193. env.Append(LINKFLAGS=["-sOFFSCREEN_FRAMEBUFFER=1"])
  194. # Disables the use of *glGetProcAddress() which is inefficient.
  195. # See https://emscripten.org/docs/tools_reference/settings_reference.html#gl-enable-get-proc-address
  196. env.Append(LINKFLAGS=["-sGL_ENABLE_GET_PROC_ADDRESS=0"])
  197. if env["javascript_eval"]:
  198. env.Append(CPPDEFINES=["JAVASCRIPT_EVAL_ENABLED"])
  199. env.Append(LINKFLAGS=["-s%s=%sKB" % ("STACK_SIZE", env["stack_size"])])
  200. if env["threads"]:
  201. # Thread support (via SharedArrayBuffer).
  202. env.Append(CPPDEFINES=["PTHREAD_NO_RENAME"])
  203. env.Append(CCFLAGS=["-sUSE_PTHREADS=1"])
  204. env.Append(LINKFLAGS=["-sUSE_PTHREADS=1"])
  205. env.Append(LINKFLAGS=["-sDEFAULT_PTHREAD_STACK_SIZE=%sKB" % env["default_pthread_stack_size"]])
  206. env.Append(LINKFLAGS=["-sPTHREAD_POOL_SIZE=\"Module['emscriptenPoolSize']||8\""])
  207. env.Append(LINKFLAGS=["-sWASM_MEM_MAX=2048MB"])
  208. if not env["dlink_enabled"]:
  209. # Workaround https://github.com/emscripten-core/emscripten/issues/21844#issuecomment-2116936414.
  210. # Not needed (and potentially dangerous) when dlink_enabled=yes, since we set EXPORT_ALL=1 in that case.
  211. env["EXPORTED_FUNCTIONS"] += ["__emscripten_thread_crashed"]
  212. elif env["proxy_to_pthread"]:
  213. print_warning('"threads=no" support requires "proxy_to_pthread=no", disabling proxy to pthread.')
  214. env["proxy_to_pthread"] = False
  215. if env["lto"] != "none":
  216. # Workaround https://github.com/emscripten-core/emscripten/issues/16836.
  217. env.Append(LINKFLAGS=["-Wl,-u,_emscripten_run_callback_on_thread"])
  218. if env["dlink_enabled"]:
  219. if env["proxy_to_pthread"]:
  220. print_warning("GDExtension support requires proxy_to_pthread=no, disabling proxy to pthread.")
  221. env["proxy_to_pthread"] = False
  222. env.Append(CPPDEFINES=["WEB_DLINK_ENABLED"])
  223. env.Append(CCFLAGS=["-sSIDE_MODULE=2"])
  224. env.Append(LINKFLAGS=["-sSIDE_MODULE=2"])
  225. env.Append(CCFLAGS=["-fvisibility=hidden"])
  226. env.Append(LINKFLAGS=["-fvisibility=hidden"])
  227. env.extra_suffix = ".dlink" + env.extra_suffix
  228. env.Append(LINKFLAGS=["-sWASM_BIGINT"])
  229. # Run the main application in a web worker
  230. if env["proxy_to_pthread"]:
  231. env.Append(LINKFLAGS=["-sPROXY_TO_PTHREAD=1"])
  232. env.Append(CPPDEFINES=["PROXY_TO_PTHREAD_ENABLED"])
  233. env["EXPORTED_RUNTIME_METHODS"] += ["_emscripten_proxy_main"]
  234. # https://github.com/emscripten-core/emscripten/issues/18034#issuecomment-1277561925
  235. env.Append(LINKFLAGS=["-sTEXTDECODER=0"])
  236. # Enable WebAssembly SIMD
  237. if env["wasm_simd"]:
  238. env.Append(CCFLAGS=["-msimd128"])
  239. # Reduce code size by generating less support code (e.g. skip NodeJS support).
  240. env.Append(LINKFLAGS=["-sENVIRONMENT=web,worker"])
  241. # Wrap the JavaScript support code around a closure named Godot.
  242. env.Append(LINKFLAGS=["-sMODULARIZE=1", "-sEXPORT_NAME='Godot'"])
  243. # Force long jump mode to 'wasm'
  244. env.Append(CCFLAGS=["-sSUPPORT_LONGJMP='wasm'"])
  245. env.Append(LINKFLAGS=["-sSUPPORT_LONGJMP='wasm'"])
  246. # Allow increasing memory buffer size during runtime. This is efficient
  247. # when using WebAssembly (in comparison to asm.js) and works well for
  248. # us since we don't know requirements at compile-time.
  249. env.Append(LINKFLAGS=["-sALLOW_MEMORY_GROWTH=1"])
  250. # Do not call main immediately when the support code is ready.
  251. env.Append(LINKFLAGS=["-sINVOKE_RUN=0"])
  252. # callMain for manual start, cwrap for the mono version.
  253. # Make sure also to have those memory-related functions available.
  254. heap_arrays = [f"HEAP{heap_type}{heap_size}" for heap_size in [8, 16, 32, 64] for heap_type in ["", "U"]] + [
  255. "HEAPF32",
  256. "HEAPF64",
  257. ]
  258. env["EXPORTED_RUNTIME_METHODS"] += ["callMain", "cwrap"] + heap_arrays
  259. env["EXPORTED_FUNCTIONS"] += ["_malloc", "_free"]
  260. # Add code that allow exiting runtime.
  261. env.Append(LINKFLAGS=["-sEXIT_RUNTIME=1"])
  262. # This workaround creates a closure that prevents the garbage collector from freeing the WebGL context.
  263. # We also only use WebGL2, and changing context version is not widely supported anyway.
  264. env.Append(LINKFLAGS=["-sGL_WORKAROUND_SAFARI_GETCONTEXT_BUG=0"])