feo_oop_engine/scripting/
mod.rs1use std::any::Any;
14
15use {
16 self::{
17 executor::{Executor, Spawner},
18 globals::{Global, EngineGlobals},
19 swap::Swap
20 },
21 crate::{
22 scene::{
23 game_object::GameObject,
24 },
25 event::UserEvent,
26 },
27 std::{
28 pin::Pin,
29 sync::{
30 Arc,
31 RwLock,
32 mpsc::sync_channel
33 }
34 },
35 futures::future::BoxFuture,
36 winit::event::Event,
37};
38
39pub mod globals;
40pub mod executor;
41pub mod swap;
42
43
44pub trait Scriptable {
46 fn spawn_script_core(&mut self, this: Arc<RwLock<dyn GameObject>>, spawner: Spawner); fn spawn_script_handler(&mut self, this: Arc<RwLock<dyn GameObject>>, spawner: Spawner, event: Event<'static, UserEvent<Arc<dyn Any + Send + Sync>>>);
48 fn get_globals(&self) -> Result<Box<dyn Global>, &'static str>;
49 fn set_globals(&mut self, globals: Box<dyn Global>) -> Result<(), &'static str>;
50}
51
52pub type BoxedStartFn<T> = Pin<Box<fn(Arc<RwLock<T>>, EngineGlobals) -> BoxFuture<'static, Swap>>>;
53pub type BoxedFrameFn<T> = Pin<Box<fn(Arc<RwLock<T>>, EngineGlobals) -> BoxFuture<'static, Swap>>>;
54pub type BoxedEventHandlerFn<T> = Pin<Box<fn(Arc<RwLock<T>>, EngineGlobals, Event<'static, UserEvent<Arc<dyn Any + Send + Sync>>>) -> BoxFuture<'static, Swap>>>;
55
56pub struct Script<T> where T: ?Sized + Send + 'static{
58 pub has_started: bool,
59 pub globals: Option<Box<dyn Global>>,
60 pub start: BoxedStartFn<T>,
61 pub frame: BoxedFrameFn<T>,
62 pub event_handler: Option<BoxedEventHandlerFn<T>>
63}
64
65impl<T: ?Sized + Send + 'static> std::fmt::Debug for Script<T> {
66 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
67 f.debug_struct("Script")
68 .field("has_started", &self.has_started)
69 .field("globals", &self.globals)
70 .field("start", &self.start)
71 .field("frame", &self.frame)
72 .field("event_handler", &self.event_handler).finish()
73 }
74}
75
76impl<T> Script<T> where T: ?Sized + Send + 'static{
77 pub fn new_boxed(
78 start: BoxedStartFn<T>,
79 frame: BoxedFrameFn<T>,
80 event_handler: Option<BoxedEventHandlerFn<T>>) -> Box<Script<T>> {
81 Box::new(Script{
82 has_started: false,
83 globals: None,
84 start,
85 frame,
86 event_handler
87 })
88 }
89}
90
91impl<T> Clone for Script<T> where T: Clone + Send + 'static{
92 fn clone(&self) -> Self {
93 Script{
94 has_started: self.has_started,
95 globals: self.globals.clone(),
96 start: self.start.clone(), frame: self.frame.clone(), event_handler: self.event_handler.clone()
99 }
104 }
105}
106
107pub fn new_executor_and_spawner(engine_globals: EngineGlobals) -> (Executor, Spawner) {
109 const MAX_QUEUED_TASKS: usize = 10_000;
110 let (task_sender, queue) = sync_channel(MAX_QUEUED_TASKS);
111 (Executor {queue, ready: Vec::new() }, Spawner { task_sender, engine_globals })
112}