Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat: Implement ScriptContext wrapper for QuickJS

esengine27460a728734
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 9873d326c..3c12cb270 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -139,9 +139,13 @@ else()
# Native platform (GLFW + OpenGL)
list(APPEND ESENGINE_SOURCES
src/esengine/platform/native/NativePlatform.cpp
+ # Scripting (Native only - Web uses Emscripten bindings)
+ src/esengine/scripting/ScriptContext.cpp
)
list(APPEND ESENGINE_HEADERS
src/esengine/platform/native/NativePlatform.hpp
+ # Scripting headers
+ src/esengine/scripting/ScriptContext.hpp
)
endif()
diff --git a/src/esengine/scripting/ScriptContext.cpp b/src/esengine/scripting/ScriptContext.cpp
new file mode 100644
index 000000000..d627b52dc
--- /dev/null
+++ b/src/esengine/scripting/ScriptContext.cpp
@@ -0,0 +1,192 @@
+/**
+ * @file ScriptContext.cpp
+ * @brief JavaScript scripting context implementation
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
+#include "ScriptContext.hpp"
+#include "../core/Log.hpp"
+
+#include <fstream>
+#include <sstream>
+
+namespace esengine {
+
+ScriptContext::~ScriptContext() {
+ if (initialized_) {
+ shutdown();
+ }
+}
+
+bool ScriptContext::init() {
+ if (initialized_) {
+ ES_LOG_WARN("ScriptContext already initialized");
+ return true;
+ }
+
+#ifdef ES_SCRIPTING_ENABLED
+ // Create QuickJS runtime
+ rt_ = JS_NewRuntime();
+ if (!rt_) {
+ lastError_ = "Failed to create QuickJS runtime";
+ ES_LOG_ERROR("{}", lastError_);
+ return false;
+ }
+
+ // Create JavaScript context
+ ctx_ = JS_NewContext(rt_);
+ if (!ctx_) {
+ lastError_ = "Failed to create QuickJS context";
+ ES_LOG_ERROR("{}", lastError_);
+ JS_FreeRuntime(rt_);
+ rt_ = nullptr;
+ return false;
+ }
+
+ initialized_ = true;
+ ES_LOG_INFO("ScriptContext initialized (QuickJS)");
+ return true;
+#else
+ lastError_ = "Scripting not enabled on this platform";
+ ES_LOG_WARN("{}", lastError_);
+ return false;
+#endif
+}
+
+void ScriptContext::shutdown() {
+ if (!initialized_) {
+ return;
+ }
+
+#ifdef ES_SCRIPTING_ENABLED
+ if (ctx_) {
+ JS_FreeContext(ctx_);
+ ctx_ = nullptr;
+ }
+
+ if (rt_) {
+ JS_FreeRuntime(rt_);
+ rt_ = nullptr;
+ }
+
+ ES_LOG_INFO("ScriptContext shutdown");
+#endif
+
+ initialized_ = false;
+ lastError_.clear();
+}
+
+bool ScriptContext::evalString(const std::string& code, const std::string& filename) {
+ if (!initialized_) {
+ lastError_ = "ScriptContext not initialized";
+ ES_LOG_ERROR("{}", lastError_);
+ return false;
+ }
+
+ clearError();
+
+#ifdef ES_SCRIPTING_ENABLED
+ // Execute JavaScript code
+ JSValue result = JS_Eval(
+ ctx_,
+ code.c_str(),
+ code.size(),
+ filename.c_str(),
+ JS_EVAL_TYPE_GLOBAL
+ );
+
+ // Check for exceptions
+ if (JS_IsException(result)) {
+ captureException();
+ JS_FreeValue(ctx_, result);
+ return false;
+ }
+
+ // Free result value
+ JS_FreeValue(ctx_, result);
+
+ ES_LOG_DEBUG("Script executed: {}", filename);
+ return true;
+#else
+ lastError_ = "Scripting not enabled on this platform";
+ return false;
+#endif
+}
+
+bool ScriptContext::evalFile(const std::string& path) {
+ if (!initialized_) {
+ lastError_ = "ScriptContext not initialized";
+ ES_LOG_ERROR("{}", lastError_);
+ return false;
+ }
+
+ // Read file contents
+ std::ifstream file(path, std::ios::in | std::ios::binary);
+ if (!file.is_open()) {
+ lastError_ = "Failed to open script file: " + path;
+ ES_LOG_ERROR("{}", lastError_);
+ return false;
+ }
+
+ std::stringstream buffer;
+ buffer << file.rdbuf();
+ std::string code = buffer.str();
+
+ if (code.empty()) {
+ lastError_ = "Script file is empty: " + path;
+ ES_LOG_WARN("{}", lastError_);
+ return false;
+ }
+
+ // Execute code with file path as filename
+ return evalString(code, path);
+}
+
+#ifdef ES_SCRIPTING_ENABLED
+void ScriptContext::captureException() {
+ if (!ctx_) {
+ lastError_ = "No context available";
+ return;
+ }
+
+ // Get exception object
+ JSValue exception = JS_GetException(ctx_);
+ if (JS_IsNull(exception)) {
+ lastError_ = "Unknown JavaScript error";
+ JS_FreeValue(ctx_, exception);
+ return;
+ }
+
+ // Convert exception to string
+ const char* errorStr = JS_ToCString(ctx_, exception);
+ if (errorStr) {
+ lastError_ = errorStr;
+ JS_FreeCString(ctx_, errorStr);
+ } else {
+ lastError_ = "Failed to convert exception to string";
+ }
+
+ // Try to get stack trace if available
+ JSValue stack = JS_GetPropertyStr(ctx_, exception, "stack");
+ if (!JS_IsUndefined(stack)) {
+ const char* stackStr = JS_ToCString(ctx_, stack);
+ if (stackStr) {
+ lastError_ += "\nStack trace:\n";
+ lastError_ += stackStr;
+ JS_FreeCString(ctx_, stackStr);
+ }
+ JS_FreeValue(ctx_, stack);
+ }
+
+ JS_FreeValue(ctx_, exception);
+
+ ES_LOG_ERROR("JavaScript error: {}", lastError_);
+}
+#endif
+
+} // namespace esengine
diff --git a/src/esengine/scripting/ScriptContext.hpp b/src/esengine/scripting/ScriptContext.hpp
new file mode 100644
index 000000000..d15b95519
--- /dev/null
+++ b/src/esengine/scripting/ScriptContext.hpp
@@ -0,0 +1,129 @@
+/**
+ * @file ScriptContext.hpp
+ * @brief JavaScript scripting context wrapper for QuickJS
+ * @details Provides RAII-based JavaScript runtime management for native platforms.
+ * Web platforms use Emscripten bindings instead.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+#pragma once
+
+#include "../core/Types.hpp"
+#include <string>
+
+#ifdef ES_SCRIPTING_ENABLED
+ #include <quickjs.h>
+#endif
+
+namespace esengine {
+
+/**
+ * @brief JavaScript execution context using QuickJS
+ *
+ * @details Manages QuickJS runtime and context lifecycle. Only available
+ * on native platforms (Windows/Linux/macOS). Web platforms use
+ * browser's native JavaScript engine via Emscripten bindings.
+ *
+ * Usage:
+ * @code
+ * ScriptContext ctx;
+ * ctx.init();
+ * if (ctx.evalString("console.log('Hello from JavaScript!')")) {
+ * // Script executed successfully
+ * } else {
+ * ES_LOG_ERROR("Script error: {}", ctx.getLastError());
+ * }
+ * ctx.shutdown();
+ * @endcode
+ */
+class ScriptContext {
+public:
+ ScriptContext() = default;
+ ~ScriptContext();
+
+ ScriptContext(const ScriptContext&) = delete;
+ ScriptContext& operator=(const ScriptContext&) = delete;
+
+ /**
+ * @brief Initialize JavaScript runtime and context
+ * @return true if successful, false on error
+ */
+ bool init();
+
+ /**
+ * @brief Shutdown JavaScript runtime and free resources
+ */
+ void shutdown();
+
+ /**
+ * @brief Execute JavaScript code from a file
+ * @param path File path to JavaScript source
+ * @return true if execution succeeded, false on error
+ */
+ bool evalFile(const std::string& path);
+
+ /**
+ * @brief Execute JavaScript code from a string
+ * @param code JavaScript source code
+ * @param filename Optional filename for error messages (default: "<eval>")
+ * @return true if execution succeeded, false on error
+ */
+ bool evalString(const std::string& code, const std::string& filename = "<eval>");
+
+ /**
+ * @brief Get last error message
+ * @return Error string, empty if no error
+ */
+ std::string getLastError() const { return lastError_; }
+
+ /**
+ * @brief Check if an error occurred
+ * @return true if there's an error, false otherwise
+ */
+ bool hasError() const { return !lastError_.empty(); }
+
+ /**
+ * @brief Clear error state
+ */
+ void clearError() { lastError_.clear(); }
+
+ /**
+ * @brief Check if context is initialized
+ * @return true if initialized, false otherwise
+ */
+ bool isInitialized() const { return initialized_; }
+
+#ifdef ES_SCRIPTING_ENABLED
+ /**
+ * @brief Get QuickJS context (for advanced bindings)
+ * @return JSContext pointer or nullptr if not initialized
+ */
+ JSContext* getJSContext() { return ctx_; }
+
+ /**
+ * @brief Get QuickJS runtime (for advanced bindings)
+ * @return JSRuntime pointer or nullptr if not initialized
+ */
+ JSRuntime* getJSRuntime() { return rt_; }
+#endif
+
+private:
+ /**
+ * @brief Extract error message from QuickJS exception
+ */
+ void captureException();
+
+ bool initialized_ = false;
+ std::string lastError_;
+
+#ifdef ES_SCRIPTING_ENABLED
+ JSRuntime* rt_ = nullptr;
+ JSContext* ctx_ = nullptr;
+#endif
+};
+
+} // namespace esengine
diff --git a/third_party/CMakeLists.txt b/third_party/CMakeLists.txt
index 04f90107a..ea1d7acb1 100644
--- a/third_party/CMakeLists.txt
+++ b/third_party/CMakeLists.txt
@@ -49,9 +49,9 @@ if(NOT ES_BUILD_WEB AND NOT ES_BUILD_WXGAME)
)
add_library(quickjs STATIC ${QUICKJS_SOURCES})
- # Use PRIVATE to avoid exposing quickjs internal files (like 'version' text file)
- # which could be mistakenly included as headers by the compiler
- target_include_directories(quickjs PRIVATE
+ # Expose QuickJS headers to consumers (esengine scripting module)
+ # Note: We use PUBLIC here so that #include <quickjs.h> works in esengine
+ target_include_directories(quickjs PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/quickjs
)