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_warning
  15. if TYPE_CHECKING:
  16. from SCons.Script.SConscript import SConsEnvironment
  17. def get_name():
  18. return "Web"
  19. def can_build():
  20. return WhereIs("emcc") is not None
  21. def get_opts():
  22. from SCons.Variables import BoolVariable
  23. return [
  24. ("initial_memory", "Initial WASM memory (in MiB)", 32),
  25. # Matches default values from before Emscripten 3.1.27. New defaults are too low for Godot.
  26. ("stack_size", "WASM stack size (in KiB)", 5120),
  27. ("default_pthread_stack_size", "WASM pthread default stack size (in KiB)", 2048),
  28. BoolVariable("use_assertions", "Use Emscripten runtime assertions", False),
  29. BoolVariable("use_ubsan", "Use Emscripten undefined behavior sanitizer (UBSAN)", False),
  30. BoolVariable("use_asan", "Use Emscripten address sanitizer (ASAN)", False),
  31. BoolVariable("use_lsan", "Use Emscripten leak sanitizer (LSAN)", False),
  32. BoolVariable("use_safe_heap", "Use Emscripten SAFE_HEAP sanitizer", False),
  33. # eval() can be a security concern, so it can be disabled.
  34. BoolVariable("javascript_eval", "Enable JavaScript eval interface", True),
  35. BoolVariable(
  36. "dlink_enabled", "Enable WebAssembly dynamic linking (GDExtension support). Produces bigger binaries", False
  37. ),
  38. BoolVariable("use_closure_compiler", "Use closure compiler to minimize JavaScript code", False),
  39. BoolVariable(
  40. "proxy_to_pthread",
  41. "Use Emscripten PROXY_TO_PTHREAD option to run the main application code to a separate thread",
  42. False,
  43. ),
  44. ]
  45. def get_doc_classes():
  46. return [
  47. "EditorExportPlatformWeb",
  48. ]
  49. def get_doc_path():
  50. return "doc_classes"
  51. def get_flags():
  52. return [
  53. ("arch", "wasm32"),
  54. ("target", "template_debug"),
  55. ("builtin_pcre2_with_jit", False),
  56. ("vulkan", False),
  57. # Embree is heavy and requires too much memory (GH-70621).
  58. ("module_raycast_enabled", False),
  59. # Use -Os to prioritize optimizing for reduced file size. This is
  60. # particularly valuable for the web platform because it directly
  61. # decreases download time.
  62. # -Os reduces file size by around 5 MiB over -O3. -Oz only saves about
  63. # 100 KiB over -Os, which does not justify the negative impact on
  64. # run-time performance.
  65. ("optimize", "size"),
  66. ]
  67. def configure(env: "SConsEnvironment"):
  68. # Validate arch.
  69. supported_arches = ["wasm32"]
  70. if env["arch"] not in supported_arches:
  71. print_error(
  72. 'Unsupported CPU architecture "%s" for Web. Supported architectures are: %s.'
  73. % (env["arch"], ", ".join(supported_arches))
  74. )
  75. sys.exit(255)
  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=["-s", "ASSERTIONS=1"])
  89. if env.editor_build and env["initial_memory"] < 64:
  90. print("Note: Forcing `initial_memory=64` as it is required for the web editor.")
  91. env["initial_memory"] = 64
  92. env.Append(LINKFLAGS=["-s", "INITIAL_MEMORY=%sMB" % env["initial_memory"]])
  93. ## Copy env variables.
  94. env["ENV"] = os.environ
  95. # LTO
  96. if env["lto"] == "auto": # Full LTO for production.
  97. env["lto"] = "full"
  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=["-s", "SAFE_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)}"
  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. env.Prepend(CPPPATH=["#platform/web"])
  161. env.Append(CPPDEFINES=["WEB_ENABLED", "UNIX_ENABLED"])
  162. if env["opengl3"]:
  163. env.AppendUnique(CPPDEFINES=["GLES3_ENABLED"])
  164. # This setting just makes WebGL 2 APIs available, it does NOT disable WebGL 1.
  165. env.Append(LINKFLAGS=["-s", "USE_WEBGL2=1"])
  166. # Allow use to take control of swapping WebGL buffers.
  167. env.Append(LINKFLAGS=["-s", "OFFSCREEN_FRAMEBUFFER=1"])
  168. # Breaking change since emscripten 3.1.51
  169. # https://github.com/emscripten-core/emscripten/blob/main/ChangeLog.md#3151---121323
  170. if cc_semver >= (3, 1, 51):
  171. # Enables the use of *glGetProcAddress()
  172. env.Append(LINKFLAGS=["-s", "GL_ENABLE_GET_PROC_ADDRESS=1"])
  173. if env["javascript_eval"]:
  174. env.Append(CPPDEFINES=["JAVASCRIPT_EVAL_ENABLED"])
  175. stack_size_opt = "STACK_SIZE" if cc_semver >= (3, 1, 25) else "TOTAL_STACK"
  176. env.Append(LINKFLAGS=["-s", "%s=%sKB" % (stack_size_opt, env["stack_size"])])
  177. if env["threads"]:
  178. # Thread support (via SharedArrayBuffer).
  179. env.Append(CPPDEFINES=["PTHREAD_NO_RENAME"])
  180. env.Append(CCFLAGS=["-s", "USE_PTHREADS=1"])
  181. env.Append(LINKFLAGS=["-s", "USE_PTHREADS=1"])
  182. env.Append(LINKFLAGS=["-s", "DEFAULT_PTHREAD_STACK_SIZE=%sKB" % env["default_pthread_stack_size"]])
  183. env.Append(LINKFLAGS=["-s", "PTHREAD_POOL_SIZE=8"])
  184. env.Append(LINKFLAGS=["-s", "WASM_MEM_MAX=2048MB"])
  185. elif env["proxy_to_pthread"]:
  186. print_warning('"threads=no" support requires "proxy_to_pthread=no", disabling proxy to pthread.')
  187. env["proxy_to_pthread"] = False
  188. if env["lto"] != "none":
  189. # Workaround https://github.com/emscripten-core/emscripten/issues/19781.
  190. if cc_semver >= (3, 1, 42) and cc_semver < (3, 1, 46):
  191. env.Append(LINKFLAGS=["-Wl,-u,scalbnf"])
  192. # Workaround https://github.com/emscripten-core/emscripten/issues/16836.
  193. if cc_semver >= (3, 1, 47):
  194. env.Append(LINKFLAGS=["-Wl,-u,_emscripten_run_callback_on_thread"])
  195. if env["dlink_enabled"]:
  196. if env["proxy_to_pthread"]:
  197. print_warning("GDExtension support requires proxy_to_pthread=no, disabling proxy to pthread.")
  198. env["proxy_to_pthread"] = False
  199. if cc_semver < (3, 1, 14):
  200. print_error("GDExtension support requires emscripten >= 3.1.14, detected: %s.%s.%s" % cc_semver)
  201. sys.exit(255)
  202. env.Append(CCFLAGS=["-s", "SIDE_MODULE=2"])
  203. env.Append(LINKFLAGS=["-s", "SIDE_MODULE=2"])
  204. env.Append(CCFLAGS=["-fvisibility=hidden"])
  205. env.Append(LINKFLAGS=["-fvisibility=hidden"])
  206. env.extra_suffix = ".dlink" + env.extra_suffix
  207. # WASM_BIGINT is needed since emscripten ≥ 3.1.41
  208. needs_wasm_bigint = cc_semver >= (3, 1, 41)
  209. # Run the main application in a web worker
  210. if env["proxy_to_pthread"]:
  211. env.Append(LINKFLAGS=["-s", "PROXY_TO_PTHREAD=1"])
  212. env.Append(CPPDEFINES=["PROXY_TO_PTHREAD_ENABLED"])
  213. env.Append(LINKFLAGS=["-s", "EXPORTED_RUNTIME_METHODS=['_emscripten_proxy_main']"])
  214. # https://github.com/emscripten-core/emscripten/issues/18034#issuecomment-1277561925
  215. env.Append(LINKFLAGS=["-s", "TEXTDECODER=0"])
  216. # BigInt support to pass object pointers between contexts
  217. needs_wasm_bigint = True
  218. if needs_wasm_bigint:
  219. env.Append(LINKFLAGS=["-s", "WASM_BIGINT"])
  220. # Reduce code size by generating less support code (e.g. skip NodeJS support).
  221. env.Append(LINKFLAGS=["-s", "ENVIRONMENT=web,worker"])
  222. # Wrap the JavaScript support code around a closure named Godot.
  223. env.Append(LINKFLAGS=["-s", "MODULARIZE=1", "-s", "EXPORT_NAME='Godot'"])
  224. # Allow increasing memory buffer size during runtime. This is efficient
  225. # when using WebAssembly (in comparison to asm.js) and works well for
  226. # us since we don't know requirements at compile-time.
  227. env.Append(LINKFLAGS=["-s", "ALLOW_MEMORY_GROWTH=1"])
  228. # Do not call main immediately when the support code is ready.
  229. env.Append(LINKFLAGS=["-s", "INVOKE_RUN=0"])
  230. # callMain for manual start, cwrap for the mono version.
  231. env.Append(LINKFLAGS=["-s", "EXPORTED_RUNTIME_METHODS=['callMain','cwrap']"])
  232. # Add code that allow exiting runtime.
  233. env.Append(LINKFLAGS=["-s", "EXIT_RUNTIME=1"])
  234. # This workaround creates a closure that prevents the garbage collector from freeing the WebGL context.
  235. # We also only use WebGL2, and changing context version is not widely supported anyway.
  236. env.Append(LINKFLAGS=["-s", "GL_WORKAROUND_SAFARI_GETCONTEXT_BUG=0"])