detect.py 11 KB

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