use threadpool on C API

This commit is contained in:
Nick Fisher
2023-04-20 11:49:12 +08:00
parent dd01249547
commit c91362eefe
148 changed files with 17290 additions and 131 deletions

View File

@@ -198,7 +198,7 @@ public class SwiftPolyvoxFilamentPlugin: NSObject, FlutterPlugin, FlutterTexture
clear_assets(self.viewer)
clear_lights(self.viewer)
destroy_swap_chain(self.viewer)
filament_viewer_delete(self.viewer)
delete_filament_viewer(self.viewer)
}
print("Initializing with size \(width)x\(height)")
@@ -209,7 +209,7 @@ public class SwiftPolyvoxFilamentPlugin: NSObject, FlutterPlugin, FlutterTexture
loadResourcePtr = unsafeBitCast(loadResource, to: UnsafeMutableRawPointer.self)
freeResourcePtr = unsafeBitCast(freeResource, to: UnsafeMutableRawPointer.self)
viewer = filament_viewer_new_ios(
viewer = create_filament_viewer_ios(
nil,
loadResourcePtr!,
freeResourcePtr!,

View File

@@ -4,15 +4,14 @@
#include "ResourceBuffer.hpp"
#include <stddef.h>
#include "dart/dart_api_dl.h"
typedef struct ResourceBuffer ResourceBuffer;
typedef int32_t EntityId;
///
/// struct to facilitate passing bone animation frame data between Dart/native.
///
intptr_t init_dart_api_dl(void* data);
void register_filament_port(Dart_Port port);
void* create_filament_viewer(void *context, ResourceBuffer (*loadResource)(const char *), void (*freeResource)(uint32_t));
void delete_filament_viewer(void *viewer);
void* get_asset_manager(void* viewer);

View File

@@ -0,0 +1,79 @@
/*
* This file is licensed under the zlib/libpng license, included in this
* distribution in the file COPYING.
*/
#include <future>
#include <thread>
#include <deque>
#include <vector>
#include <utility>
#include <chrono>
#include <functional>
#include <type_traits>
#ifndef _THREADPOOL_HPP
#define _THREADPOOL_HPP
namespace polyvox {
class ThreadPool {
std::vector<std::thread> pool;
bool stop;
std::mutex access;
std::condition_variable cond;
std::deque<std::function<void()>> tasks;
public:
explicit ThreadPool(int nr = 1) : stop(false) {
while(nr-->0) {
add_worker();
}
}
~ThreadPool() {
stop = true;
for(std::thread &t : pool) {
t.join();
}
pool.clear();
}
template<class Rt>
auto add_task(std::packaged_task<Rt()>& pt) -> std::future<Rt> {
std::unique_lock<std::mutex> lock(access);
auto ret = pt.get_future();
tasks.push_back([pt=std::make_shared<packaged_task<Rt()>>(std::move(pt))]{ (*pt)();});
cond.notify_one();
return ret;
}
private:
void add_worker() {
std::thread t([this]() {
while(!stop) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(access);
if(tasks.empty()) {
cond.wait_for(lock, std::chrono::duration<int, std::milli>(5));
continue;
}
task = std::move(tasks.front());
tasks.pop_front();
}
task();
}
});
pool.push_back(std::move(t));
}
};
}
#endif//_THREADPOOL_HPP
// vim: syntax=cpp11

4084
ios/include/dart/dart_api.h Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,150 @@
/*
* Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
* for details. All rights reserved. Use of this source code is governed by a
* BSD-style license that can be found in the LICENSE file.
*/
#ifndef RUNTIME_INCLUDE_DART_API_DL_H_
#define RUNTIME_INCLUDE_DART_API_DL_H_
#include "dart_api.h" /* NOLINT */
#include "dart_native_api.h" /* NOLINT */
/** \mainpage Dynamically Linked Dart API
*
* This exposes a subset of symbols from dart_api.h and dart_native_api.h
* available in every Dart embedder through dynamic linking.
*
* All symbols are postfixed with _DL to indicate that they are dynamically
* linked and to prevent conflicts with the original symbol.
*
* Link `dart_api_dl.c` file into your library and invoke
* `Dart_InitializeApiDL` with `NativeApi.initializeApiDLData`.
*/
DART_EXPORT intptr_t Dart_InitializeApiDL(void* data);
// ============================================================================
// IMPORTANT! Never update these signatures without properly updating
// DART_API_DL_MAJOR_VERSION and DART_API_DL_MINOR_VERSION.
//
// Verbatim copy of `dart_native_api.h` and `dart_api.h` symbol names and types
// to trigger compile-time errors if the sybols in those files are updated
// without updating these.
//
// Function return and argument types, and typedefs are carbon copied. Structs
// are typechecked nominally in C/C++, so they are not copied, instead a
// comment is added to their definition.
typedef int64_t Dart_Port_DL;
typedef void (*Dart_NativeMessageHandler_DL)(Dart_Port_DL dest_port_id,
Dart_CObject* message);
// dart_native_api.h symbols can be called on any thread.
#define DART_NATIVE_API_DL_SYMBOLS(F) \
/***** dart_native_api.h *****/ \
/* Dart_Port */ \
F(Dart_PostCObject, bool, (Dart_Port_DL port_id, Dart_CObject * message)) \
F(Dart_PostInteger, bool, (Dart_Port_DL port_id, int64_t message)) \
F(Dart_NewNativePort, Dart_Port_DL, \
(const char* name, Dart_NativeMessageHandler_DL handler, \
bool handle_concurrently)) \
F(Dart_CloseNativePort, bool, (Dart_Port_DL native_port_id))
// dart_api.h symbols can only be called on Dart threads.
#define DART_API_DL_SYMBOLS(F) \
/***** dart_api.h *****/ \
/* Errors */ \
F(Dart_IsError, bool, (Dart_Handle handle)) \
F(Dart_IsApiError, bool, (Dart_Handle handle)) \
F(Dart_IsUnhandledExceptionError, bool, (Dart_Handle handle)) \
F(Dart_IsCompilationError, bool, (Dart_Handle handle)) \
F(Dart_IsFatalError, bool, (Dart_Handle handle)) \
F(Dart_GetError, const char*, (Dart_Handle handle)) \
F(Dart_ErrorHasException, bool, (Dart_Handle handle)) \
F(Dart_ErrorGetException, Dart_Handle, (Dart_Handle handle)) \
F(Dart_ErrorGetStackTrace, Dart_Handle, (Dart_Handle handle)) \
F(Dart_NewApiError, Dart_Handle, (const char* error)) \
F(Dart_NewCompilationError, Dart_Handle, (const char* error)) \
F(Dart_NewUnhandledExceptionError, Dart_Handle, (Dart_Handle exception)) \
F(Dart_PropagateError, void, (Dart_Handle handle)) \
/* Dart_Handle, Dart_PersistentHandle, Dart_WeakPersistentHandle */ \
F(Dart_HandleFromPersistent, Dart_Handle, (Dart_PersistentHandle object)) \
F(Dart_HandleFromWeakPersistent, Dart_Handle, \
(Dart_WeakPersistentHandle object)) \
F(Dart_NewPersistentHandle, Dart_PersistentHandle, (Dart_Handle object)) \
F(Dart_SetPersistentHandle, void, \
(Dart_PersistentHandle obj1, Dart_Handle obj2)) \
F(Dart_DeletePersistentHandle, void, (Dart_PersistentHandle object)) \
F(Dart_NewWeakPersistentHandle, Dart_WeakPersistentHandle, \
(Dart_Handle object, void* peer, intptr_t external_allocation_size, \
Dart_HandleFinalizer callback)) \
F(Dart_DeleteWeakPersistentHandle, void, (Dart_WeakPersistentHandle object)) \
F(Dart_UpdateExternalSize, void, \
(Dart_WeakPersistentHandle object, intptr_t external_allocation_size)) \
F(Dart_NewFinalizableHandle, Dart_FinalizableHandle, \
(Dart_Handle object, void* peer, intptr_t external_allocation_size, \
Dart_HandleFinalizer callback)) \
F(Dart_DeleteFinalizableHandle, void, \
(Dart_FinalizableHandle object, Dart_Handle strong_ref_to_object)) \
F(Dart_UpdateFinalizableExternalSize, void, \
(Dart_FinalizableHandle object, Dart_Handle strong_ref_to_object, \
intptr_t external_allocation_size)) \
/* Dart_Port */ \
F(Dart_Post, bool, (Dart_Port_DL port_id, Dart_Handle object)) \
F(Dart_NewSendPort, Dart_Handle, (Dart_Port_DL port_id)) \
F(Dart_SendPortGetId, Dart_Handle, \
(Dart_Handle port, Dart_Port_DL * port_id)) \
/* Scopes */ \
F(Dart_EnterScope, void, (void)) \
F(Dart_ExitScope, void, (void))
#define DART_API_ALL_DL_SYMBOLS(F) \
DART_NATIVE_API_DL_SYMBOLS(F) \
DART_API_DL_SYMBOLS(F)
// IMPORTANT! Never update these signatures without properly updating
// DART_API_DL_MAJOR_VERSION and DART_API_DL_MINOR_VERSION.
//
// End of verbatim copy.
// ============================================================================
// Copy of definition of DART_EXPORT without 'used' attribute.
//
// The 'used' attribute cannot be used with DART_API_ALL_DL_SYMBOLS because
// they are not function declarations, but variable declarations with a
// function pointer type.
//
// The function pointer variables are initialized with the addresses of the
// functions in the VM. If we were to use function declarations instead, we
// would need to forward the call to the VM adding indirection.
#if defined(__CYGWIN__)
#error Tool chain and platform not supported.
#elif defined(_WIN32)
#if defined(DART_SHARED_LIB)
#define DART_EXPORT_DL DART_EXTERN_C __declspec(dllexport)
#else
#define DART_EXPORT_DL DART_EXTERN_C
#endif
#else
#if __GNUC__ >= 4
#if defined(DART_SHARED_LIB)
#define DART_EXPORT_DL DART_EXTERN_C __attribute__((visibility("default")))
#else
#define DART_EXPORT_DL DART_EXTERN_C
#endif
#else
#error Tool chain not supported.
#endif
#endif
#define DART_API_DL_DECLARATIONS(name, R, A) \
typedef R(*name##_Type) A; \
DART_EXPORT_DL name##_Type name##_DL;
DART_API_ALL_DL_SYMBOLS(DART_API_DL_DECLARATIONS)
#undef DART_API_DL_DECLARATIONS
#undef DART_EXPORT_DL
#endif /* RUNTIME_INCLUDE_DART_API_DL_H_ */ /* NOLINT */

View File

@@ -0,0 +1,204 @@
/*
* Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
* for details. All rights reserved. Use of this source code is governed by a
* BSD-style license that can be found in the LICENSE file.
*/
#ifndef RUNTIME_INCLUDE_DART_NATIVE_API_H_
#define RUNTIME_INCLUDE_DART_NATIVE_API_H_
#include "dart_api.h" /* NOLINT */
/*
* ==========================================
* Message sending/receiving from native code
* ==========================================
*/
/**
* A Dart_CObject is used for representing Dart objects as native C
* data outside the Dart heap. These objects are totally detached from
* the Dart heap. Only a subset of the Dart objects have a
* representation as a Dart_CObject.
*
* The string encoding in the 'value.as_string' is UTF-8.
*
* All the different types from dart:typed_data are exposed as type
* kTypedData. The specific type from dart:typed_data is in the type
* field of the as_typed_data structure. The length in the
* as_typed_data structure is always in bytes.
*
* The data for kTypedData is copied on message send and ownership remains with
* the caller. The ownership of data for kExternalTyped is passed to the VM on
* message send and returned when the VM invokes the
* Dart_HandleFinalizer callback; a non-NULL callback must be provided.
*
* Note that Dart_CObject_kNativePointer is intended for internal use by
* dart:io implementation and has no connection to dart:ffi Pointer class.
* It represents a pointer to a native resource of a known type.
* The receiving side will only see this pointer as an integer and will not
* see the specified finalizer.
* The specified finalizer will only be invoked if the message is not delivered.
*/
typedef enum {
Dart_CObject_kNull = 0,
Dart_CObject_kBool,
Dart_CObject_kInt32,
Dart_CObject_kInt64,
Dart_CObject_kDouble,
Dart_CObject_kString,
Dart_CObject_kArray,
Dart_CObject_kTypedData,
Dart_CObject_kExternalTypedData,
Dart_CObject_kSendPort,
Dart_CObject_kCapability,
Dart_CObject_kNativePointer,
Dart_CObject_kUnsupported,
Dart_CObject_kNumberOfTypes
} Dart_CObject_Type;
typedef struct _Dart_CObject {
Dart_CObject_Type type;
union {
bool as_bool;
int32_t as_int32;
int64_t as_int64;
double as_double;
char* as_string;
struct {
Dart_Port id;
Dart_Port origin_id;
} as_send_port;
struct {
int64_t id;
} as_capability;
struct {
intptr_t length;
struct _Dart_CObject** values;
} as_array;
struct {
Dart_TypedData_Type type;
intptr_t length; /* in elements, not bytes */
uint8_t* values;
} as_typed_data;
struct {
Dart_TypedData_Type type;
intptr_t length; /* in elements, not bytes */
uint8_t* data;
void* peer;
Dart_HandleFinalizer callback;
} as_external_typed_data;
struct {
intptr_t ptr;
intptr_t size;
Dart_HandleFinalizer callback;
} as_native_pointer;
} value;
} Dart_CObject;
// This struct is versioned by DART_API_DL_MAJOR_VERSION, bump the version when
// changing this struct.
/**
* Posts a message on some port. The message will contain the Dart_CObject
* object graph rooted in 'message'.
*
* While the message is being sent the state of the graph of Dart_CObject
* structures rooted in 'message' should not be accessed, as the message
* generation will make temporary modifications to the data. When the message
* has been sent the graph will be fully restored.
*
* If true is returned, the message was enqueued, and finalizers for external
* typed data will eventually run, even if the receiving isolate shuts down
* before processing the message. If false is returned, the message was not
* enqueued and ownership of external typed data in the message remains with the
* caller.
*
* This function may be called on any thread when the VM is running (that is,
* after Dart_Initialize has returned and before Dart_Cleanup has been called).
*
* \param port_id The destination port.
* \param message The message to send.
*
* \return True if the message was posted.
*/
DART_EXPORT bool Dart_PostCObject(Dart_Port port_id, Dart_CObject* message);
/**
* Posts a message on some port. The message will contain the integer 'message'.
*
* \param port_id The destination port.
* \param message The message to send.
*
* \return True if the message was posted.
*/
DART_EXPORT bool Dart_PostInteger(Dart_Port port_id, int64_t message);
/**
* A native message handler.
*
* This handler is associated with a native port by calling
* Dart_NewNativePort.
*
* The message received is decoded into the message structure. The
* lifetime of the message data is controlled by the caller. All the
* data references from the message are allocated by the caller and
* will be reclaimed when returning to it.
*/
typedef void (*Dart_NativeMessageHandler)(Dart_Port dest_port_id,
Dart_CObject* message);
/**
* Creates a new native port. When messages are received on this
* native port, then they will be dispatched to the provided native
* message handler.
*
* \param name The name of this port in debugging messages.
* \param handler The C handler to run when messages arrive on the port.
* \param handle_concurrently Is it okay to process requests on this
* native port concurrently?
*
* \return If successful, returns the port id for the native port. In
* case of error, returns ILLEGAL_PORT.
*/
DART_EXPORT Dart_Port Dart_NewNativePort(const char* name,
Dart_NativeMessageHandler handler,
bool handle_concurrently);
/* TODO(turnidge): Currently handle_concurrently is ignored. */
/**
* Closes the native port with the given id.
*
* The port must have been allocated by a call to Dart_NewNativePort.
*
* \param native_port_id The id of the native port to close.
*
* \return Returns true if the port was closed successfully.
*/
DART_EXPORT bool Dart_CloseNativePort(Dart_Port native_port_id);
/*
* ==================
* Verification Tools
* ==================
*/
/**
* Forces all loaded classes and functions to be compiled eagerly in
* the current isolate..
*
* TODO(turnidge): Document.
*/
DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_CompileAll(void);
/**
* Finalizes all classes.
*/
DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_FinalizeAllClasses(void);
/* This function is intentionally undocumented.
*
* It should not be used outside internal tests.
*/
DART_EXPORT void* Dart_ExecuteInternalCommand(const char* command, void* arg);
#endif /* INCLUDE_DART_NATIVE_API_H_ */ /* NOLINT */

View File

@@ -0,0 +1,538 @@
// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#ifndef RUNTIME_INCLUDE_DART_TOOLS_API_H_
#define RUNTIME_INCLUDE_DART_TOOLS_API_H_
#include "dart_api.h" /* NOLINT */
/** \mainpage Dart Tools Embedding API Reference
*
* This reference describes the Dart embedding API for tools. Tools include
* a debugger, service protocol, and timeline.
*
* NOTE: The APIs described in this file are unstable and subject to change.
*
* This reference is generated from the header include/dart_tools_api.h.
*/
/*
* ========
* Debugger
* ========
*/
/**
* ILLEGAL_ISOLATE_ID is a number guaranteed never to be associated with a
* valid isolate.
*/
#define ILLEGAL_ISOLATE_ID ILLEGAL_PORT
/*
* =======
* Service
* =======
*/
/**
* A service request callback function.
*
* These callbacks, registered by the embedder, are called when the VM receives
* a service request it can't handle and the service request command name
* matches one of the embedder registered handlers.
*
* The return value of the callback indicates whether the response
* should be used as a regular result or an error result.
* Specifically, if the callback returns true, a regular JSON-RPC
* response is built in the following way:
*
* {
* "jsonrpc": "2.0",
* "result": <json_object>,
* "id": <some sequence id>,
* }
*
* If the callback returns false, a JSON-RPC error is built like this:
*
* {
* "jsonrpc": "2.0",
* "error": <json_object>,
* "id": <some sequence id>,
* }
*
* \param method The rpc method name.
* \param param_keys Service requests can have key-value pair parameters. The
* keys and values are flattened and stored in arrays.
* \param param_values The values associated with the keys.
* \param num_params The length of the param_keys and param_values arrays.
* \param user_data The user_data pointer registered with this handler.
* \param result A C string containing a valid JSON object. The returned
* pointer will be freed by the VM by calling free.
*
* \return True if the result is a regular JSON-RPC response, false if the
* result is a JSON-RPC error.
*/
typedef bool (*Dart_ServiceRequestCallback)(const char* method,
const char** param_keys,
const char** param_values,
intptr_t num_params,
void* user_data,
const char** json_object);
/**
* Register a Dart_ServiceRequestCallback to be called to handle
* requests for the named rpc on a specific isolate. The callback will
* be invoked with the current isolate set to the request target.
*
* \param method The name of the method that this callback is responsible for.
* \param callback The callback to invoke.
* \param user_data The user data passed to the callback.
*
* NOTE: If multiple callbacks with the same name are registered, only
* the last callback registered will be remembered.
*/
DART_EXPORT void Dart_RegisterIsolateServiceRequestCallback(
const char* method,
Dart_ServiceRequestCallback callback,
void* user_data);
/**
* Register a Dart_ServiceRequestCallback to be called to handle
* requests for the named rpc. The callback will be invoked without a
* current isolate.
*
* \param method The name of the command that this callback is responsible for.
* \param callback The callback to invoke.
* \param user_data The user data passed to the callback.
*
* NOTE: If multiple callbacks with the same name are registered, only
* the last callback registered will be remembered.
*/
DART_EXPORT void Dart_RegisterRootServiceRequestCallback(
const char* method,
Dart_ServiceRequestCallback callback,
void* user_data);
/**
* Embedder information which can be requested by the VM for internal or
* reporting purposes.
*
* The pointers in this structure are not going to be cached or freed by the VM.
*/
#define DART_EMBEDDER_INFORMATION_CURRENT_VERSION (0x00000001)
typedef struct {
int32_t version;
const char* name; // [optional] The name of the embedder
int64_t current_rss; // [optional] the current RSS of the embedder
int64_t max_rss; // [optional] the maximum RSS of the embedder
} Dart_EmbedderInformation;
/**
* Callback provided by the embedder that is used by the vm to request
* information.
*
* \return Returns a pointer to a Dart_EmbedderInformation structure.
* The embedder keeps the ownership of the structure and any field in it.
* The embedder must ensure that the structure will remain valid until the
* next invokation of the callback.
*/
typedef void (*Dart_EmbedderInformationCallback)(
Dart_EmbedderInformation* info);
/**
* Register a Dart_ServiceRequestCallback to be called to handle
* requests for the named rpc. The callback will be invoked without a
* current isolate.
*
* \param method The name of the command that this callback is responsible for.
* \param callback The callback to invoke.
* \param user_data The user data passed to the callback.
*
* NOTE: If multiple callbacks with the same name are registered, only
* the last callback registered will be remembered.
*/
DART_EXPORT void Dart_SetEmbedderInformationCallback(
Dart_EmbedderInformationCallback callback);
/**
* Invoke a vm-service method and wait for its result.
*
* \param request_json The utf8-encoded json-rpc request.
* \param request_json_length The length of the json-rpc request.
*
* \param response_json The returned utf8-encoded json response, must be
* free()ed by caller.
* \param response_json_length The length of the returned json response.
* \param error An optional error, must be free()ed by caller.
*
* \return Whether the call was sucessfully performed.
*
* NOTE: This method does not need a current isolate and must not have the
* vm-isolate being the current isolate. It must be called after
* Dart_Initialize() and before Dart_Cleanup().
*/
DART_EXPORT bool Dart_InvokeVMServiceMethod(uint8_t* request_json,
intptr_t request_json_length,
uint8_t** response_json,
intptr_t* response_json_length,
char** error);
/*
* ========
* Event Streams
* ========
*/
/**
* A callback invoked when the VM service gets a request to listen to
* some stream.
*
* \return Returns true iff the embedder supports the named stream id.
*/
typedef bool (*Dart_ServiceStreamListenCallback)(const char* stream_id);
/**
* A callback invoked when the VM service gets a request to cancel
* some stream.
*/
typedef void (*Dart_ServiceStreamCancelCallback)(const char* stream_id);
/**
* Adds VM service stream callbacks.
*
* \param listen_callback A function pointer to a listen callback function.
* A listen callback function should not be already set when this function
* is called. A NULL value removes the existing listen callback function
* if any.
*
* \param cancel_callback A function pointer to a cancel callback function.
* A cancel callback function should not be already set when this function
* is called. A NULL value removes the existing cancel callback function
* if any.
*
* \return Success if the callbacks were added. Otherwise, returns an
* error handle.
*/
DART_EXPORT char* Dart_SetServiceStreamCallbacks(
Dart_ServiceStreamListenCallback listen_callback,
Dart_ServiceStreamCancelCallback cancel_callback);
/**
* Sends a data event to clients of the VM Service.
*
* A data event is used to pass an array of bytes to subscribed VM
* Service clients. For example, in the standalone embedder, this is
* function used to provide WriteEvents on the Stdout and Stderr
* streams.
*
* If the embedder passes in a stream id for which no client is
* subscribed, then the event is ignored.
*
* \param stream_id The id of the stream on which to post the event.
*
* \param event_kind A string identifying what kind of event this is.
* For example, 'WriteEvent'.
*
* \param bytes A pointer to an array of bytes.
*
* \param bytes_length The length of the byte array.
*
* \return NULL if the arguments are well formed. Otherwise, returns an
* error string. The caller is responsible for freeing the error message.
*/
DART_EXPORT char* Dart_ServiceSendDataEvent(const char* stream_id,
const char* event_kind,
const uint8_t* bytes,
intptr_t bytes_length);
/**
* Usage statistics for a space/generation at a particular moment in time.
*
* \param used Amount of memory used, in bytes.
*
* \param capacity Memory capacity, in bytes.
*
* \param external External memory, in bytes.
*
* \param collections How many times the garbage collector has run in this
* space.
*
* \param time Cumulative time spent collecting garbage in this space, in
* seconds.
*
* \param avg_collection_period Average time between garbage collector running
* in this space, in milliseconds.
*/
typedef struct {
intptr_t used;
intptr_t capacity;
intptr_t external;
intptr_t collections;
double time;
double avg_collection_period;
} Dart_GCStats;
/**
* A Garbage Collection event with memory usage statistics.
*
* \param type The event type. Static lifetime.
*
* \param reason The reason for the GC event. Static lifetime.
*
* \param new_space Data for New Space.
*
* \param old_space Data for Old Space.
*/
typedef struct {
const char* type;
const char* reason;
const char* isolate_id;
Dart_GCStats new_space;
Dart_GCStats old_space;
} Dart_GCEvent;
/**
* A callback invoked when the VM emits a GC event.
*
* \param event The GC event data. Pointer only valid for the duration of the
* callback.
*/
typedef void (*Dart_GCEventCallback)(Dart_GCEvent* event);
/**
* Sets the native GC event callback.
*
* \param callback A function pointer to an event handler callback function.
* A NULL value removes the existing listen callback function if any.
*/
DART_EXPORT void Dart_SetGCEventCallback(Dart_GCEventCallback callback);
/*
* ========
* Reload support
* ========
*
* These functions are used to implement reloading in the Dart VM.
* This is an experimental feature, so embedders should be prepared
* for these functions to change.
*/
/**
* A callback which determines whether the file at some url has been
* modified since some time. If the file cannot be found, true should
* be returned.
*/
typedef bool (*Dart_FileModifiedCallback)(const char* url, int64_t since);
DART_EXPORT char* Dart_SetFileModifiedCallback(
Dart_FileModifiedCallback file_modified_callback);
/**
* Returns true if isolate is currently reloading.
*/
DART_EXPORT bool Dart_IsReloading();
/*
* ========
* Timeline
* ========
*/
/**
* Enable tracking of specified timeline category. This is operational
* only when systrace timeline functionality is turned on.
*
* \param categories A comma seperated list of categories that need to
* be enabled, the categories are
* "all" : All categories
* "API" - Execution of Dart C API functions
* "Compiler" - Execution of Dart JIT compiler
* "CompilerVerbose" - More detailed Execution of Dart JIT compiler
* "Dart" - Execution of Dart code
* "Debugger" - Execution of Dart debugger
* "Embedder" - Execution of Dart embedder code
* "GC" - Execution of Dart Garbage Collector
* "Isolate" - Dart Isolate lifecycle execution
* "VM" - Excution in Dart VM runtime code
* "" - None
*
* When "all" is specified all the categories are enabled.
* When a comma seperated list of categories is specified, the categories
* that are specified will be enabled and the rest will be disabled.
* When "" is specified all the categories are disabled.
* The category names are case sensitive.
* eg: Dart_EnableTimelineCategory("all");
* Dart_EnableTimelineCategory("GC,API,Isolate");
* Dart_EnableTimelineCategory("GC,Debugger,Dart");
*
* \return True if the categories were successfully enabled, False otherwise.
*/
DART_EXPORT bool Dart_SetEnabledTimelineCategory(const char* categories);
/**
* Returns a timestamp in microseconds. This timestamp is suitable for
* passing into the timeline system, and uses the same monotonic clock
* as dart:developer's Timeline.now.
*
* \return A timestamp that can be passed to the timeline system.
*/
DART_EXPORT int64_t Dart_TimelineGetMicros();
/**
* Returns a raw timestamp in from the monotonic clock.
*
* \return A raw timestamp from the monotonic clock.
*/
DART_EXPORT int64_t Dart_TimelineGetTicks();
/**
* Returns the frequency of the monotonic clock.
*
* \return The frequency of the monotonic clock.
*/
DART_EXPORT int64_t Dart_TimelineGetTicksFrequency();
typedef enum {
Dart_Timeline_Event_Begin, // Phase = 'B'.
Dart_Timeline_Event_End, // Phase = 'E'.
Dart_Timeline_Event_Instant, // Phase = 'i'.
Dart_Timeline_Event_Duration, // Phase = 'X'.
Dart_Timeline_Event_Async_Begin, // Phase = 'b'.
Dart_Timeline_Event_Async_End, // Phase = 'e'.
Dart_Timeline_Event_Async_Instant, // Phase = 'n'.
Dart_Timeline_Event_Counter, // Phase = 'C'.
Dart_Timeline_Event_Flow_Begin, // Phase = 's'.
Dart_Timeline_Event_Flow_Step, // Phase = 't'.
Dart_Timeline_Event_Flow_End, // Phase = 'f'.
} Dart_Timeline_Event_Type;
/**
* Add a timeline event to the embedder stream.
*
* \param label The name of the event. Its lifetime must extend at least until
* Dart_Cleanup.
* \param timestamp0 The first timestamp of the event.
* \param timestamp1_or_async_id The second timestamp of the event or
* the async id.
* \param argument_count The number of argument names and values.
* \param argument_names An array of names of the arguments. The lifetime of the
* names must extend at least until Dart_Cleanup. The array may be reclaimed
* when this call returns.
* \param argument_values An array of values of the arguments. The values and
* the array may be reclaimed when this call returns.
*/
DART_EXPORT void Dart_TimelineEvent(const char* label,
int64_t timestamp0,
int64_t timestamp1_or_async_id,
Dart_Timeline_Event_Type type,
intptr_t argument_count,
const char** argument_names,
const char** argument_values);
/**
* Associates a name with the current thread. This name will be used to name
* threads in the timeline. Can only be called after a call to Dart_Initialize.
*
* \param name The name of the thread.
*/
DART_EXPORT void Dart_SetThreadName(const char* name);
/*
* =======
* Metrics
* =======
*/
/**
* Return metrics gathered for the VM and individual isolates.
*
* NOTE: Non-heap metrics are not available in PRODUCT builds of Dart.
* Calling the non-heap metric functions on a PRODUCT build might return invalid metrics.
*/
DART_EXPORT int64_t Dart_VMIsolateCountMetric(); // Counter
DART_EXPORT int64_t Dart_VMCurrentRSSMetric(); // Byte
DART_EXPORT int64_t Dart_VMPeakRSSMetric(); // Byte
DART_EXPORT int64_t
Dart_IsolateHeapOldUsedMetric(Dart_Isolate isolate); // Byte
DART_EXPORT int64_t
Dart_IsolateHeapOldUsedMaxMetric(Dart_Isolate isolate); // Byte
DART_EXPORT int64_t
Dart_IsolateHeapOldCapacityMetric(Dart_Isolate isolate); // Byte
DART_EXPORT int64_t
Dart_IsolateHeapOldCapacityMaxMetric(Dart_Isolate isolate); // Byte
DART_EXPORT int64_t
Dart_IsolateHeapOldExternalMetric(Dart_Isolate isolate); // Byte
DART_EXPORT int64_t
Dart_IsolateHeapNewUsedMetric(Dart_Isolate isolate); // Byte
DART_EXPORT int64_t
Dart_IsolateHeapNewUsedMaxMetric(Dart_Isolate isolate); // Byte
DART_EXPORT int64_t
Dart_IsolateHeapNewCapacityMetric(Dart_Isolate isolate); // Byte
DART_EXPORT int64_t
Dart_IsolateHeapNewCapacityMaxMetric(Dart_Isolate isolate); // Byte
DART_EXPORT int64_t
Dart_IsolateHeapNewExternalMetric(Dart_Isolate isolate); // Byte
DART_EXPORT int64_t
Dart_IsolateHeapGlobalUsedMetric(Dart_Isolate isolate); // Byte
DART_EXPORT int64_t
Dart_IsolateHeapGlobalUsedMaxMetric(Dart_Isolate isolate); // Byte
DART_EXPORT int64_t
Dart_IsolateRunnableLatencyMetric(Dart_Isolate isolate); // Microsecond
DART_EXPORT int64_t
Dart_IsolateRunnableHeapSizeMetric(Dart_Isolate isolate); // Byte
/*
* ========
* UserTags
* ========
*/
/*
* Gets the current isolate's currently set UserTag instance.
*
* \return The currently set UserTag instance.
*/
DART_EXPORT Dart_Handle Dart_GetCurrentUserTag();
/*
* Gets the current isolate's default UserTag instance.
*
* \return The default UserTag with label 'Default'
*/
DART_EXPORT Dart_Handle Dart_GetDefaultUserTag();
/*
* Creates a new UserTag instance.
*
* \param label The name of the new UserTag.
*
* \return The newly created UserTag instance or an error handle.
*/
DART_EXPORT Dart_Handle Dart_NewUserTag(const char* label);
/*
* Updates the current isolate's UserTag to a new value.
*
* \param user_tag The UserTag to be set as the current UserTag.
*
* \return The previously set UserTag instance or an error handle.
*/
DART_EXPORT Dart_Handle Dart_SetCurrentUserTag(Dart_Handle user_tag);
/*
* Returns the label of a given UserTag instance.
*
* \param user_tag The UserTag from which the label will be retrieved.
*
* \return The UserTag's label. NULL if the user_tag is invalid. The caller is
* responsible for freeing the returned label.
*/
DART_EXPORT DART_WARN_UNUSED_RESULT char* Dart_GetUserTagLabel(
Dart_Handle user_tag);
#endif // RUNTIME_INCLUDE_DART_TOOLS_API_H_

View File

@@ -0,0 +1,16 @@
/*
* Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
* for details. All rights reserved. Use of this source code is governed by a
* BSD-style license that can be found in the LICENSE file.
*/
#ifndef RUNTIME_INCLUDE_DART_VERSION_H_
#define RUNTIME_INCLUDE_DART_VERSION_H_
// On breaking changes the major version is increased.
// On backwards compatible changes the minor version is increased.
// The versioning covers the symbols exposed in dart_api_dl.h
#define DART_API_DL_MAJOR_VERSION 2
#define DART_API_DL_MINOR_VERSION 0
#endif /* RUNTIME_INCLUDE_DART_VERSION_H_ */ /* NOLINT */

View File

@@ -0,0 +1,21 @@
/*
* Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
* for details. All rights reserved. Use of this source code is governed by a
* BSD-style license that can be found in the LICENSE file.
*/
#ifndef RUNTIME_INCLUDE_INTERNAL_DART_API_DL_IMPL_H_
#define RUNTIME_INCLUDE_INTERNAL_DART_API_DL_IMPL_H_
typedef struct {
const char* name;
void (*function)(void);
} DartApiEntry;
typedef struct {
const int major;
const int minor;
const DartApiEntry* const functions;
} DartApi;
#endif /* RUNTIME_INCLUDE_INTERNAL_DART_API_DL_IMPL_H_ */ /* NOLINT */

View File

@@ -214,6 +214,7 @@ FilamentAsset* AssetManager::getAssetByEntityId(EntityId entityId) {
void AssetManager::updateAnimations() {
auto now = high_resolution_clock::now();
RenderableManager &rm = _engine->getRenderableManager();
@@ -529,6 +530,7 @@ void AssetManager::playAnimation(EntityId e, int index, bool loop, bool reverse)
asset.mAnimations[index+2].mStart = std::chrono::high_resolution_clock::now();
asset.mAnimations[index+2].mLoop = loop;
asset.mAnimations[index+2].mReverse = reverse;
Log("new start %d", std::chrono::duration_cast<std::chrono::milliseconds>(asset.mAnimations[index+2].mStart.time_since_epoch()).count());
asset.mAnimating = true;
}

View File

@@ -3,22 +3,56 @@
#include "FilamentViewer.hpp"
#include "filament/LightManager.h"
#include "Log.hpp"
#include "ThreadPool.hpp"
#include <thread>
#include "dart/dart_api_dl.h"
using namespace polyvox;
#define FLUTTER_PLUGIN_EXPORT __attribute__((visibility("default")))
static ThreadPool* _tp;
static Dart_Port _port;
extern "C" {
#include "PolyvoxFilamentApi.h"
FLUTTER_PLUGIN_EXPORT void* create_filament_viewer(void* context, ResourceBuffer (*loadResource)(char const*), void (*freeResource)(unsigned int)) {
FilamentViewer* v = new FilamentViewer(context, loadResource, freeResource);
return (void*)v;
FLUTTER_PLUGIN_EXPORT intptr_t init_dart_api_dl(void* data) {
return Dart_InitializeApiDL(data);
}
FLUTTER_PLUGIN_EXPORT void register_filament_port(Dart_Port port) {
_port = port;
}
FLUTTER_PLUGIN_EXPORT void* create_filament_viewer(void* context, ResourceBuffer (*loadResource)(char const*), void (*freeResource)(unsigned int)) {
if(!_tp) {
_tp = new ThreadPool();
}
std::packaged_task<void*()> lambda([=]() mutable {
return (void*) new FilamentViewer(context, loadResource, freeResource);
});
auto fut = _tp->add_task(lambda);
fut.wait();
return fut.get();
}
// Dart_CObject dart_object;
// dart_object.type = Dart_CObject_kInt64;
// dart_object.value.as_int64 = (size_t)viewer;
// const bool result = Dart_PostCObject_DL(_port, &dart_object);
// if (!result) {
// std::cout << "TTS: C : Posting message to port failed." << std::endl;
// }
FLUTTER_PLUGIN_EXPORT void create_render_target(void* viewer, uint32_t textureId, uint32_t width, uint32_t height) {
((FilamentViewer*)viewer)->createRenderTarget(textureId, width, height);
std::packaged_task<void()> lambda([=]() mutable {
((FilamentViewer*)viewer)->createRenderTarget(textureId, width, height);
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT void delete_filament_viewer(void* viewer) {
@@ -26,137 +60,270 @@ extern "C" {
}
FLUTTER_PLUGIN_EXPORT void set_background_color(void* viewer, const float r, const float g, const float b, const float a) {
((FilamentViewer*)viewer)->setBackgroundColor(r, g, b, a);
std::packaged_task<void()> lambda([=]() mutable {
((FilamentViewer*)viewer)->setBackgroundColor(r, g, b, a);
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT void clear_background_image(void* viewer) {
((FilamentViewer*)viewer)->clearBackgroundImage();
std::packaged_task<void()> lambda([=]() mutable {
((FilamentViewer*)viewer)->clearBackgroundImage();
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT void set_background_image(void* viewer, const char* path) {
((FilamentViewer*)viewer)->setBackgroundImage(path);
std::packaged_task<void()> lambda([=]() mutable {
((FilamentViewer*)viewer)->setBackgroundImage(path);
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT void set_background_image_position(void* viewer, float x, float y, bool clamp) {
((FilamentViewer*)viewer)->setBackgroundImagePosition(x, y, clamp);
std::packaged_task<void()> lambda([=]() mutable {
((FilamentViewer*)viewer)->setBackgroundImagePosition(x, y, clamp);
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT void load_skybox(void* viewer, const char* skyboxPath) {
((FilamentViewer*)viewer)->loadSkybox(skyboxPath);
std::packaged_task<void()> lambda([=]() mutable {
((FilamentViewer*)viewer)->loadSkybox(skyboxPath);
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT void load_ibl(void* viewer, const char* iblPath, float intensity) {
((FilamentViewer*)viewer)->loadIbl(iblPath, intensity);
std::packaged_task<void()> lambda([=]() mutable {
((FilamentViewer*)viewer)->loadIbl(iblPath, intensity);
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT void remove_skybox(void* viewer) {
((FilamentViewer*)viewer)->removeSkybox();
std::packaged_task<void()> lambda([=]() mutable {
((FilamentViewer*)viewer)->removeSkybox();
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT void remove_ibl(void* viewer) {
((FilamentViewer*)viewer)->removeIbl();
std::packaged_task<void()> lambda([=]() mutable {
((FilamentViewer*)viewer)->removeIbl();
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT int32_t add_light(void* viewer, uint8_t type, float colour, float intensity, float posX, float posY, float posZ, float dirX, float dirY, float dirZ, bool shadows) {
return ((FilamentViewer*)viewer)->addLight((LightManager::Type)type, colour, intensity, posX, posY, posZ, dirX, dirY, dirZ, shadows);
FLUTTER_PLUGIN_EXPORT EntityId add_light(void* viewer, uint8_t type, float colour, float intensity, float posX, float posY, float posZ, float dirX, float dirY, float dirZ, bool shadows) {
std::packaged_task<EntityId()> lambda([=]() mutable {
return ((FilamentViewer*)viewer)->addLight((LightManager::Type)type, colour, intensity, posX, posY, posZ, dirX, dirY, dirZ, shadows);
});
auto fut = _tp->add_task(lambda);
fut.wait();
return fut.get();
}
FLUTTER_PLUGIN_EXPORT void remove_light(void* viewer, int32_t entityId) {
((FilamentViewer*)viewer)->removeLight(entityId);
std::packaged_task<void()> lambda([=]() mutable {
((FilamentViewer*)viewer)->removeLight(entityId);
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT void clear_lights(void* viewer) {
((FilamentViewer*)viewer)->clearLights();
std::packaged_task<void()> lambda([=]() mutable {
((FilamentViewer*)viewer)->clearLights();
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT EntityId load_glb(void* assetManager, const char* assetPath, bool unlit) {
return ((AssetManager*)assetManager)->loadGlb(assetPath, unlit);
std::packaged_task<EntityId()> lambda([=]() mutable {
return ((AssetManager*)assetManager)->loadGlb(assetPath, unlit);
});
auto fut = _tp->add_task(lambda);
fut.wait();
return fut.get();
}
FLUTTER_PLUGIN_EXPORT EntityId load_gltf(void* assetManager, const char* assetPath, const char* relativePath) {
return ((AssetManager*)assetManager)->loadGltf(assetPath, relativePath);
std::packaged_task<EntityId()> lambda([=]() mutable {
return ((AssetManager*)assetManager)->loadGltf(assetPath, relativePath);
});
auto fut = _tp->add_task(lambda);
fut.wait();
return fut.get();
}
FLUTTER_PLUGIN_EXPORT bool set_camera(void* viewer, EntityId asset, const char* nodeName) {
return ((FilamentViewer*)viewer)->setCamera(asset, nodeName);
std::packaged_task<bool()> lambda([=]() mutable {
return ((FilamentViewer*)viewer)->setCamera(asset, nodeName);
});
auto fut = _tp->add_task(lambda);
fut.wait();
return fut.get();
}
FLUTTER_PLUGIN_EXPORT void set_camera_exposure(void* viewer, float aperture, float shutterSpeed, float sensitivity) {
((FilamentViewer*)viewer)->setCameraExposure(aperture, shutterSpeed, sensitivity);
std::packaged_task<void()> lambda([=]() mutable {
((FilamentViewer*)viewer)->setCameraExposure(aperture, shutterSpeed, sensitivity);
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT void set_camera_position(void* viewer, float x, float y, float z) {
((FilamentViewer*)viewer)->setCameraPosition(x, y, z);
std::packaged_task<void()> lambda([=]() mutable {
((FilamentViewer*)viewer)->setCameraPosition(x, y, z);
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT void set_camera_rotation(void* viewer, float rads, float x, float y, float z) {
((FilamentViewer*)viewer)->setCameraRotation(rads, x, y, z);
std::packaged_task<void()> lambda([=]() mutable {
((FilamentViewer*)viewer)->setCameraRotation(rads, x, y, z);
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT void set_camera_model_matrix(void* viewer, const float* const matrix) {
((FilamentViewer*)viewer)->setCameraModelMatrix(matrix);
std::packaged_task<void()> lambda([=]() mutable {
((FilamentViewer*)viewer)->setCameraModelMatrix(matrix);
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT void set_camera_focal_length(void* viewer, float focalLength) {
((FilamentViewer*)viewer)->setCameraFocalLength(focalLength);
std::packaged_task<void()> lambda([=]() mutable {
((FilamentViewer*)viewer)->setCameraFocalLength(focalLength);
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT void render(
void* viewer,
uint64_t frameTimeInNanos
) {
((FilamentViewer*)viewer)->render(frameTimeInNanos);
std::packaged_task<void()> lambda([=]() mutable {
((FilamentViewer*)viewer)->render(frameTimeInNanos);
});
_tp->add_task(lambda);
}
FLUTTER_PLUGIN_EXPORT void set_frame_interval(
void* viewer,
float frameInterval
) {
((FilamentViewer*)viewer)->setFrameInterval(frameInterval);
std::packaged_task<void()> lambda([=]() mutable {
((FilamentViewer*)viewer)->setFrameInterval(frameInterval);
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT void destroy_swap_chain(void* viewer) {
((FilamentViewer*)viewer)->destroySwapChain();
std::packaged_task<void()> lambda([=]() mutable {
((FilamentViewer*)viewer)->destroySwapChain();
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT void create_swap_chain(void* viewer, void* surface=nullptr, uint32_t width=0, uint32_t height=0) {
((FilamentViewer*)viewer)->createSwapChain(surface, width, height);
std::packaged_task<void()> lambda([=]() mutable {
((FilamentViewer*)viewer)->createSwapChain(surface, width, height);
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT void* get_renderer(void* viewer) {
return ((FilamentViewer*)viewer)->getRenderer();
std::packaged_task<void*()> lambda([=]() mutable {
return ((FilamentViewer*)viewer)->getRenderer();
});
auto fut = _tp->add_task(lambda);
fut.wait();
return fut.get();
}
FLUTTER_PLUGIN_EXPORT void update_viewport_and_camera_projection(void* viewer, int width, int height, float scaleFactor) {
return ((FilamentViewer*)viewer)->updateViewportAndCameraProjection(width, height, scaleFactor);
std::packaged_task<void()> lambda([=]() mutable {
return ((FilamentViewer*)viewer)->updateViewportAndCameraProjection(width, height, scaleFactor);
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT void scroll_update(void* viewer, float x, float y, float delta) {
((FilamentViewer*)viewer)->scrollUpdate(x, y, delta);
std::packaged_task<void()> lambda([=]() mutable {
((FilamentViewer*)viewer)->scrollUpdate(x, y, delta);
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT void scroll_begin(void* viewer) {
((FilamentViewer*)viewer)->scrollBegin();
std::packaged_task<void()> lambda([=]() mutable {
((FilamentViewer*)viewer)->scrollBegin();
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT void scroll_end(void* viewer) {
((FilamentViewer*)viewer)->scrollEnd();
std::packaged_task<void()> lambda([=]() mutable {
((FilamentViewer*)viewer)->scrollEnd();
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT void grab_begin(void* viewer, float x, float y, bool pan) {
((FilamentViewer*)viewer)->grabBegin(x, y, pan);
std::packaged_task<void()> lambda([=]() mutable {
((FilamentViewer*)viewer)->grabBegin(x, y, pan);
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT void grab_update(void* viewer, float x, float y) {
((FilamentViewer*)viewer)->grabUpdate(x, y);
std::packaged_task<void()> lambda([=]() mutable {
((FilamentViewer*)viewer)->grabUpdate(x, y);
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT void grab_end(void* viewer) {
((FilamentViewer*)viewer)->grabEnd();
std::packaged_task<void()> lambda([=]() mutable {
((FilamentViewer*)viewer)->grabEnd();
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT void* get_asset_manager(void* viewer) {
return (void*)((FilamentViewer*)viewer)->getAssetManager();
std::packaged_task<void*()> lambda([=]() mutable {
return (void*)((FilamentViewer*)viewer)->getAssetManager();
});
auto fut = _tp->add_task(lambda);
fut.wait();
return fut.get();
}
FLUTTER_PLUGIN_EXPORT void apply_weights(
@@ -165,7 +332,11 @@ extern "C" {
const char* const entityName,
float* const weights,
int count) {
// std::packaged_task<void()> lambda([=]() mutable {
// ((AssetManager*)assetManager)->setMorphTargetWeights(asset, entityName, weights, count);
// });
// auto fut = _tp->add_task(lambda);
// fut.wait();
}
FLUTTER_PLUGIN_EXPORT void set_morph_animation(
@@ -176,14 +347,19 @@ extern "C" {
int numMorphWeights,
int numFrames,
float frameLengthInMs) {
((AssetManager*)assetManager)->setMorphAnimationBuffer(
asset,
entityName,
morphData,
numMorphWeights,
numFrames,
frameLengthInMs
);
std::packaged_task<void()> lambda([=]() mutable {
((AssetManager*)assetManager)->setMorphAnimationBuffer(
asset,
entityName,
morphData,
numMorphWeights,
numFrames,
frameLengthInMs
);
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT void set_bone_animation(
@@ -195,15 +371,19 @@ extern "C" {
const float* const frameData,
int numFrames,
float frameLengthInMs) {
((AssetManager*)assetManager)->setBoneAnimationBuffer(
asset,
length,
boneNames,
meshNames,
frameData,
numFrames,
frameLengthInMs
);
std::packaged_task<void()> lambda([=]() mutable {
((AssetManager*)assetManager)->setBoneAnimationBuffer(
asset,
length,
boneNames,
meshNames,
frameData,
numFrames,
frameLengthInMs
);
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
@@ -242,7 +422,13 @@ extern "C" {
int index,
bool loop,
bool reverse) {
((AssetManager*)assetManager)->playAnimation(asset, index, loop, reverse);
std::packaged_task<void()> lambda([=]() mutable {
std::cout << "Playing animation" << std::endl;
((AssetManager*)assetManager)->playAnimation(asset, index, loop, reverse);
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT void set_animation_frame(
@@ -250,14 +436,23 @@ extern "C" {
EntityId asset,
int animationIndex,
int animationFrame) {
// std::packaged_task<void()> lambda([=]() mutable {
// ((AssetManager*)assetManager)->setAnimationFrame(asset, animationIndex, animationFrame);
// });
// auto fut = _tp->add_task(lambda);
// fut.wait();
}
FLUTTER_PLUGIN_EXPORT int get_animation_count(
void* assetManager,
EntityId asset) {
auto names = ((AssetManager*)assetManager)->getAnimationNames(asset);
return names->size();
std::packaged_task<int()> lambda([=]() mutable {
auto names = ((AssetManager*)assetManager)->getAnimationNames(asset);
return names->size();
});
auto fut = _tp->add_task(lambda);
fut.wait();
return fut.get();
}
FLUTTER_PLUGIN_EXPORT void get_animation_name(
@@ -266,28 +461,49 @@ extern "C" {
char* const outPtr,
int index
) {
auto names = ((AssetManager*)assetManager)->getAnimationNames(asset);
string name = names->at(index);
strcpy(outPtr, name.c_str());
std::packaged_task<void()> lambda([=]() mutable {
auto names = ((AssetManager*)assetManager)->getAnimationNames(asset);
string name = names->at(index);
strcpy(outPtr, name.c_str());
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT int get_morph_target_name_count(void* assetManager, EntityId asset, const char* meshName) {
unique_ptr<vector<string>> names = ((AssetManager*)assetManager)->getMorphTargetNames(asset, meshName);
return names->size();
std::packaged_task<int()> lambda([=]() mutable {
unique_ptr<vector<string>> names = ((AssetManager*)assetManager)->getMorphTargetNames(asset, meshName);
return names->size();
});
auto fut = _tp->add_task(lambda);
fut.wait();
return fut.get();
}
FLUTTER_PLUGIN_EXPORT void get_morph_target_name(void* assetManager, EntityId asset, const char* meshName, char* const outPtr, int index ) {
unique_ptr<vector<string>> names = ((AssetManager*)assetManager)->getMorphTargetNames(asset, meshName);
string name = names->at(index);
strcpy(outPtr, name.c_str());
std::packaged_task<void()> lambda([=]() mutable {
unique_ptr<vector<string>> names = ((AssetManager*)assetManager)->getMorphTargetNames(asset, meshName);
string name = names->at(index);
strcpy(outPtr, name.c_str());
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT void remove_asset(void* viewer, EntityId asset) {
((FilamentViewer*)viewer)->removeAsset(asset);
std::packaged_task<void()> lambda([=]() mutable {
((FilamentViewer*)viewer)->removeAsset(asset);
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT void clear_assets(void* viewer) {
((FilamentViewer*)viewer)->clearAssets();
std::packaged_task<void()> lambda([=]() mutable {
((FilamentViewer*)viewer)->clearAssets();
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT void load_texture(void* assetManager, EntityId asset, const char* assetPath, int renderableIndex) {
@@ -299,23 +515,43 @@ extern "C" {
}
FLUTTER_PLUGIN_EXPORT void transform_to_unit_cube(void* assetManager, EntityId asset) {
((AssetManager*)assetManager)->transformToUnitCube(asset);
std::packaged_task<void()> lambda([=]() mutable {
((AssetManager*)assetManager)->transformToUnitCube(asset);
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT void set_position(void* assetManager, EntityId asset, float x, float y, float z) {
((AssetManager*)assetManager)->setPosition(asset, x, y, z);
std::packaged_task<void()> lambda([=]() mutable {
((AssetManager*)assetManager)->setPosition(asset, x, y, z);
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT void set_rotation(void* assetManager, EntityId asset, float rads, float x, float y, float z) {
((AssetManager*)assetManager)->setRotation(asset, rads, x, y, z);
std::packaged_task<void()> lambda([=]() mutable {
((AssetManager*)assetManager)->setRotation(asset, rads, x, y, z);
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT void set_scale(void* assetManager, EntityId asset, float scale) {
((AssetManager*)assetManager)->setScale(asset, scale);
std::packaged_task<void()> lambda([=]() mutable {
((AssetManager*)assetManager)->setScale(asset, scale);
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
FLUTTER_PLUGIN_EXPORT void stop_animation(void* assetManager, EntityId asset, int index) {
((AssetManager*)assetManager)->stopAnimation(asset, index);
std::packaged_task<void()> lambda([=]() mutable {
((AssetManager*)assetManager)->stopAnimation(asset, index);
});
auto fut = _tp->add_task(lambda);
fut.wait();
}
}

59
ios/src/dart_api_dl.c Normal file
View File

@@ -0,0 +1,59 @@
/*
* Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
* for details. All rights reserved. Use of this source code is governed by a
* BSD-style license that can be found in the LICENSE file.
*/
#include "dart_api_dl.h" /* NOLINT */
#include "dart_version.h" /* NOLINT */
#include "internal/dart_api_dl_impl.h" /* NOLINT */
#include <string.h>
#define DART_API_DL_DEFINITIONS(name, R, A) name##_Type name##_DL = NULL;
DART_API_ALL_DL_SYMBOLS(DART_API_DL_DEFINITIONS)
#undef DART_API_DL_DEFINITIONS
typedef void* DartApiEntry_function;
DartApiEntry_function FindFunctionPointer(const DartApiEntry* entries,
const char* name) {
while (entries->name != NULL) {
if (strcmp(entries->name, name) == 0) return entries->function;
entries++;
}
return NULL;
}
intptr_t Dart_InitializeApiDL(void* data) {
DartApi* dart_api_data = (DartApi*)data;
if (dart_api_data->major != DART_API_DL_MAJOR_VERSION) {
// If the DartVM we're running on does not have the same version as this
// file was compiled against, refuse to initialize. The symbols are not
// compatible.
return -1;
}
// Minor versions are allowed to be different.
// If the DartVM has a higher minor version, it will provide more symbols
// than we initialize here.
// If the DartVM has a lower minor version, it will not provide all symbols.
// In that case, we leave the missing symbols un-initialized. Those symbols
// should not be used by the Dart and native code. The client is responsible
// for checking the minor version number himself based on which symbols it
// is using.
// (If we would error out on this case, recompiling native code against a
// newer SDK would break all uses on older SDKs, which is too strict.)
const DartApiEntry* dart_api_function_pointers = dart_api_data->functions;
#define DART_API_DL_INIT(name, R, A) \
name##_DL = \
(name##_Type)(FindFunctionPointer(dart_api_function_pointers, #name));
DART_API_ALL_DL_SYMBOLS(DART_API_DL_INIT)
#undef DART_API_DL_INIT
return 0;
}