detect.py 11 KB

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