diff --git a/Sources/main.cpp b/Sources/main.cpp index e98646a..01a205f 100644 --- a/Sources/main.cpp +++ b/Sources/main.cpp @@ -94,6 +94,8 @@ bool show_window = false; #include "viewport_server.h" #endif +#include "async_engine.h" + // TODO //#ifdef KINC_KONG //#include @@ -1387,6 +1389,51 @@ namespace { args.GetReturnValue().Set(buffer); } + void runt_load_blob_async(const FunctionCallbackInfo &args) { + HandleScope scope(args.GetIsolate()); + if (args.Length() < 2 || !args[1]->IsFunction()) return; + + String::Utf8Value utf8_value(isolate, args[0]); + std::string filepath(*utf8_value); + + Local cb = Local::Cast(args[1]); + auto persistent_cb = std::make_shared>(isolate, cb); + + EngineManager::AsyncEngine::instance().execute_io([filepath, persistent_cb]() { + kinc_file_reader_t reader; + bool success = kinc_file_reader_open(&reader, filepath.c_str(), KINC_FILE_TYPE_ASSET); + std::vector bytes; + if (success) { + uint32_t size = (uint32_t)kinc_file_reader_size(&reader); + bytes.resize(size); + kinc_file_reader_read(&reader, bytes.data(), size); + kinc_file_reader_close(&reader); + } + + EngineManager::AsyncEngine::instance().push_event([persistent_cb, bytes = std::move(bytes), success]() { + Locker locker{isolate}; + Isolate::Scope isolate_scope(isolate); + HandleScope handle_scope(isolate); + Local context = Local::New(isolate, global_context); + Context::Scope context_scope(context); + TryCatch try_catch(isolate); + + Local cb = Local::New(isolate, *persistent_cb); + if (success && !bytes.empty()) { + Local buffer = ArrayBuffer::New(isolate, bytes.size()); + memcpy(buffer->GetBackingStore()->Data(), bytes.data(), bytes.size()); + Local argv[1] = { buffer }; + (void)cb->Call(context, context->Global(), 1, argv); + } else { + Local argv[1] = { Null(isolate) }; + (void)cb->Call(context, context->Global(), 1, argv); + } + if (try_catch.HasCaught()) handle_exception(&try_catch); + persistent_cb->Reset(); + }); + }); + } + void runt_load_url(const FunctionCallbackInfo &args) { HandleScope scope(args.GetIsolate()); String::Utf8Value utf8_value(isolate, args[0]); @@ -2718,6 +2765,7 @@ namespace { SET_FUNCTION(runt, "getSamplesPerSecond", runt_get_samples_per_second); #endif SET_FUNCTION(runt, "loadBlob", runt_load_blob); + SET_FUNCTION(runt, "loadBlobAsync", runt_load_blob_async); SET_FUNCTION(runt, "loadUrl", runt_load_url); SET_FUNCTION(runt, "copyToClipboard", runt_copy_to_clipboard); SET_FUNCTION(runt, "getConstantLocation", runt_get_constant_location); @@ -3053,6 +3101,7 @@ namespace { #endif execute_timers(); + EngineManager::AsyncEngine::instance().process_events(); #ifdef WITH_VIEWPORT if (viewport_server_mode && viewport_server_is_enabled()) {