set(src_texel
  enginecontrol.cpp  enginecontrol.hpp
                     searchparams.hpp
  texel.cpp
  uciprotocol.cpp    uciprotocol.hpp
  )

# tuigame is the interactive text-mode game driven from stdin.  It is
# unreachable in the WASM build (main() is replaced by uciCommand()) and
# would only add dead code to the binary.
if(NOT EMSCRIPTEN)
  list(APPEND src_texel
    tuigame.cpp      tuigame.hpp
    )
endif()

add_executable(texel ${src_texel})
target_link_libraries(texel texellib)

if(EMSCRIPTEN)
  # "worker" is what ships.  Set to "worker,node" to produce a module that
  # can also be driven from node, which is how the engine is regression
  # tested and how strength calibration games are run.
  set(TEXEL_WASM_ENVIRONMENT "worker" CACHE STRING
    "Emscripten ENVIRONMENT list for the WASM build")

  # Single-threaded module for a Web Worker.  Deliberately absent:
  #   -pthread          would require SharedArrayBuffer and therefore
  #                     COOP/COEP headers on the host page.
  #   ASYNCIFY          not needed; the search blocks the worker instead.
  #   FILESYSTEM        no tablebases or opening books are loaded.
  target_link_options(texel PRIVATE
    "-sMODULARIZE=1"
    "-sEXPORT_NAME=Texel"
    "-sENVIRONMENT=${TEXEL_WASM_ENVIRONMENT}"
    "-sALLOW_MEMORY_GROWTH=1"
    # Emscripten defaults to a 64 KB stack; native builds get 8 MB.  Texel's
    # search is deeply recursive (negaScout -> quiesce) and each frame holds
    # a MoveList by value, so 64 KB overflows a few hundred ms into any real
    # search.  The failure surfaces as a corrupted-looking C++ exception
    # rather than a clean error, so do not lower this without testing a long
    # search in a tactical position.
    "-sSTACK_SIZE=8MB"
    "-sEXPORTED_FUNCTIONS=['_uciCommand','_malloc','_free']"
    "-sEXPORTED_RUNTIME_METHODS=['ccall','cwrap']"
    "-sNO_EXIT_RUNTIME=1"
    "-sINVOKE_RUN=0"
    )
endif()
