bevy_mod_scripting_core 0.18.0

Core traits and structures required for other parts of bevy_mod_scripting
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
use std::{
    any::TypeId,
    future::ready,
    pin::Pin,
    task::{Poll, Waker},
    time::{Duration, Instant},
};

use bevy_ecs::message::{MessageCursor, Messages};
use bevy_log::debug;
use bevy_mod_scripting_bindings::InteropError;
use bevy_mod_scripting_script::ScriptAttachment;
use bevy_platform::collections::HashMap;

use super::*;

/// A reader that removes events immediately when read
/// Also requires they are wrapped in a [`ForPlugin`] event wrapper.
///
/// Allows re-publishing of the same events too
#[derive(SystemParam)]
pub struct StateMachine<'w, 's, T: Send + Sync + 'static, P: IntoScriptPluginParams> {
    events: ResMut<'w, Messages<ForPlugin<T, P>>>,
    cursor: Local<'s, MessageCursor<ForPlugin<T, P>>>,
}

impl<'w, 's, T: Send + Sync + 'static, P: IntoScriptPluginParams> StateMachine<'w, 's, T, P> {
    /// Returns the current number of machines outstanding with this state
    pub fn machines_outstanding(&self) -> usize {
        self.events.len()
    }

    /// returns a draining iterator which will consume all the state machine events for this state.
    ///
    /// Be careful, if intercepting between machine states, make sure to re-send any drained events if you wish for them
    /// to keep being processed, alternatively if you wish to stop the processing of a state machine, simply remove and do not re-send the machine
    pub fn drain(&mut self) -> impl Iterator<Item = T> {
        self.events.drain().map(ForPlugin::inner)
    }

    /// Returns a mutable iterator over the state machines, useful if you don't want to modify the machines but not interrupt the flow.
    pub fn intercept(&mut self) -> impl Iterator<Item = &mut T> {
        *self.cursor = self.events.get_cursor();
        self.cursor
            .read_mut(&mut self.events)
            .map(|p| p.event_mut())
    }

    /// Returns all of the state machines without removing them. Useful if you want to plug into a state machine transition
    /// but not interrupt its outcome
    pub fn iter_cloned(&self) -> Vec<T>
    where
        T: Clone,
    {
        let mut cursor = self.events.get_cursor();
        cursor
            .read(&self.events)
            .cloned()
            .map(ForPlugin::inner)
            .collect()
    }

    /// Consumes an iterator of state machines and writes them to the asset pipe
    pub fn write_batch(&mut self, batch: impl IntoIterator<Item = T>) {
        self.events
            .write_batch(batch.into_iter().map(ForPlugin::new));
    }
}

/// A resource containing all currently running or ready to run machines.
#[derive(Resource)]
pub struct ActiveMachines<P: IntoScriptPluginParams> {
    machines: VecDeque<ScriptMachine<P>>,
    on_state_listeners: HashMap<
        TypeId,
        Vec<
            Arc<
                dyn Fn(
                        &mut dyn MachineState<P>,
                        &mut World,
                        &mut Context,
                    ) -> Result<(), ScriptError>
                    + Send
                    + Sync,
            >,
        >,
    >,
    pub(crate) budget: Option<Duration>,
}

impl<P: IntoScriptPluginParams> Default for ActiveMachines<P> {
    fn default() -> Self {
        Self {
            machines: Default::default(),
            on_state_listeners: Default::default(),
            budget: Default::default(),
        }
    }
}

/// Trait describing subscribers to transition events
pub trait TransitionListener<State>: 'static + Send + Sync {
    /// The hook to call when entering the state being listened to
    fn on_enter(
        &self,
        state: &mut State,
        world: &mut World,
        context: &mut Context,
    ) -> Result<(), ScriptError>;

    /// type erase the listener
    fn erased<P: IntoScriptPluginParams>(
        self,
    ) -> Box<
        dyn Fn(&mut dyn MachineState<P>, &mut World, &mut Context) -> Result<(), ScriptError>
            + Send
            + Sync,
    >
    where
        Self: Sized,
        State: 'static,
    {
        Box::new(move |state, world, context| {
            let typed = (state as &mut dyn Any).downcast_mut::<State>();
            typed
                .ok_or(ScriptError::new_boxed_without_type_info(
                    format!(
                        "could not downcast script machine state to: '{}'. Could not execute transition listener",
                        std::any::type_name::<State>()
                    )
                    .into(),
                ))
                .and_then(|typed| self.on_enter(typed, world, context))
        })
    }
}

impl<P: IntoScriptPluginParams> ActiveMachines<P> {
    /// Returns the currently processing machine
    pub fn current_machine(&self) -> Option<&ScriptMachine<P>> {
        self.machines.front()
    }

    /// Adds a listener to the back of the listener list for the state
    pub fn push_listener<S: 'static>(&mut self, listener: impl TransitionListener<S> + 'static) {
        let erased = listener.erased::<P>();
        self.on_state_listeners
            .entry(std::any::TypeId::of::<S>())
            .or_default()
            .push(erased.into());
    }

    /// Ticks all active machines until either:
    /// - The budget is exhausted
    /// - All the machines are finished
    ///
    /// If no budget is provided machines will be ticked ad infinitum or until they all complete.
    pub fn tick_machines(&mut self, world: &mut World) {
        let start = Instant::now();
        let end = start + self.budget.unwrap_or(Duration::from_secs(99999));
        while !self.machines.is_empty() && Instant::now() < end {
            if let Some(mut next) = self.machines.pop_front() {
                let final_state = next.tick(world, &self.on_state_listeners);
                match final_state {
                    Some(Ok(_)) => {
                        // removed
                    }
                    Some(Err(err)) => {
                        _ = world
                            .write_message(ScriptErrorEvent::new(err.with_language(P::LANGUAGE)));
                        // removed
                    }
                    None => {
                        // re-insert for next tick
                        self.machines.push_front(next);
                    }
                }
            }
        }
    }

    /// Appends a machine to the end of the queue.
    pub fn queue_machine(&mut self, context: Context, state: impl MachineState<P>) {
        self.machines.push_back(ScriptMachine {
            context,
            internal_state: MachineExecutionState::Initialized(Box::new(state)),
        });
    }

    /// Returns the amount of active machines
    pub fn active_machines(&self) -> usize {
        self.machines.len()
    }
}

/// A machine, which combines the inputs to its states with the state of the world and generates state transitions,
/// in an async manner (can span multiple frames)
pub struct ScriptMachine<P> {
    /// Context for the machine
    pub context: Context,
    internal_state: MachineExecutionState<P>,
}

enum MachineExecutionState<P> {
    Initialized(Box<dyn MachineState<P>>),
    Running(
        Pin<Box<dyn Future<Output = Result<Box<dyn MachineState<P>>, ScriptError>> + Send + Sync>>,
    ),
    Finished,
}

impl<P: IntoScriptPluginParams> ScriptMachine<P> {
    /// Ticks the machine until it reaches the Finished state.
    /// Further tick's do nothing.
    /// If the machine has not been started yet, it will be started and the underlying future ticked at least once.
    /// If the machine is finished it will return the final state or an error.
    /// Once the final state has been returned, ticking will return in errors
    pub fn tick(
        &mut self,
        world: &mut World,
        listeners: &HashMap<
            TypeId,
            Vec<
                Arc<
                    dyn Fn(
                            &mut dyn MachineState<P>,
                            &mut World,
                            &mut Context,
                        ) -> Result<(), ScriptError>
                        + Send
                        + Sync,
                >,
            >,
        >,
    ) -> Option<Result<Box<dyn MachineState<P>>, ScriptError>> {
        match &mut self.internal_state {
            MachineExecutionState::Initialized(machine_state) => {
                debug!(
                    "State '{}' entered. For script: {}",
                    machine_state.state_name(),
                    self.context.attachment,
                );

                if let Some(listeners) = listeners.get(&machine_state.as_ref().type_id()) {
                    for on_entered in listeners {
                        if let Err(err) =
                            (on_entered)(machine_state.as_mut(), world, &mut self.context)
                        {
                            _ = world.write_message(ScriptErrorEvent::new(
                                err.with_context(self.context.attachment.to_string())
                                    .with_context(machine_state.state_name())
                                    .with_language(P::LANGUAGE),
                            ))
                        }
                    }
                }
                let next = machine_state.poll_next(&self.context, world);
                self.internal_state = MachineExecutionState::Running(next.into());
                return self.tick(world, listeners);
            }
            MachineExecutionState::Running(future) => {
                let waker = Waker::noop();
                let mut cx = std::task::Context::from_waker(waker);

                if let Poll::Ready(res) = Future::poll(future.as_mut(), &mut cx) {
                    match res {
                        Ok(next) => {
                            if next.is_final() {
                                debug!(
                                    "Reached final state '{}'. For script {}",
                                    next.state_name(),
                                    &self.context.attachment
                                );
                                self.internal_state = MachineExecutionState::Finished;
                                return Some(Ok(next));
                            } else {
                                self.internal_state = MachineExecutionState::Initialized(next)
                            }
                        }
                        res => {
                            debug!(
                                "Error in progressing to next state. For script {}",
                                &self.context.attachment
                            );
                            self.internal_state = MachineExecutionState::Finished;
                            return Some(res);
                        }
                    }
                }
            }
            MachineExecutionState::Finished => {
                return Some(Err(ScriptError::new_boxed_without_type_info(
                    String::from("cannot tick machine twice").into(),
                )
                .with_context(self.context.attachment.to_string())
                .with_language(P::LANGUAGE)));
            }
        }
        None
    }
}

#[derive(Debug, Clone)]
/// Each state machine is run in the context of a script, and can contain additional metadata.
/// The context struct contains all this additional metadata.
pub struct Context {
    /// The script attachment being loaded or reloaded
    pub attachment: ScriptAttachment,

    /// a set of metadata various interceptors can use to pass data along the chain
    pub blackboard: SmallVec<[(&'static str, Arc<dyn Any + Send + Sync + 'static>); 1]>,
}
impl Context {
    /// push a value onto the blackboard
    pub fn insert(&mut self, key: &'static str, val: impl Any + Send + Sync + 'static) {
        self.blackboard.push((key, Arc::new(val)));
    }

    /// tries to find a value and cast it to the given type
    pub fn get_first_typed<T: Any + Clone>(&self, key: &'static str) -> Option<T> {
        self.blackboard
            .iter()
            .find_map(|(k, v)| (*k == key).then_some(v.downcast_ref().cloned()))
            .flatten()
    }
}

/// Describes a state in a finite state machine
pub trait MachineState<P>: Send + Sync + 'static + Any {
    /// A readable state name
    fn state_name(&self) -> &'static str {
        std::any::type_name::<Self>()
    }

    /// Polls the machine for the next state.
    ///
    /// Machines are allowed to take multiple frames in generating it.
    fn poll_next(
        &mut self,
        ctxt: &Context,
        world: &mut World,
    ) -> Box<dyn Future<Output = Result<Box<dyn MachineState<P>>, ScriptError>> + Send + Sync>;

    /// Final states designate that a state machine should complete processing. Returning true will cause the state to be recognize as a final state
    fn is_final(&self) -> bool {
        false
    }
}

/// A script loading state machine state, describes a script which has completed loading and has its context present within [`ScriptContext`]
#[derive(Clone, Copy)]
pub struct LoadingCompleted;

/// A script loading state machine state, describes a script which has completed unloading and its no longer attached
#[derive(Clone, Copy)]
pub struct UnloadingCompleted;

/// A script loading state machine state, describes the starting state of loading every script
#[derive(Clone)]
pub struct LoadingInitialized {
    /// The handle to source the script content and ID from
    pub source: Handle<ScriptAsset>,
    /// The contents of the script asset, preloaded so we don't need more resources.
    pub content: Box<[u8]>,
}

/// A script loading state machine state, describes the starting state of reloading every script
pub struct ReloadingInitialized<P: IntoScriptPluginParams> {
    /// The handle to source the script content and ID from
    pub source: Handle<ScriptAsset>,
    /// The contents of the script asset, preloaded so we don't need more resources.
    pub content: Box<[u8]>,
    /// The context which will be reloaded using the new content
    pub existing_context: Arc<Mutex<P::C>>,
}

/// A script unloading state machine state, describes the starting state of unloading every script.
#[derive(Clone)]
pub struct UnloadingInitialized<P: IntoScriptPluginParams> {
    /// The context that the attachment is being unloaded
    pub existing_context: Arc<Mutex<P::C>>,
}

impl<P: IntoScriptPluginParams> Clone for ReloadingInitialized<P> {
    fn clone(&self) -> Self {
        Self {
            source: self.source.clone(),
            content: self.content.clone(),
            existing_context: self.existing_context.clone(),
        }
    }
}

impl<P: IntoScriptPluginParams> std::fmt::Debug for ReloadingInitialized<P> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ReloadingInitialized")
            .field("source", &self.source)
            .finish()
    }
}

/// A script loading state machine state, describes a script which has a context assigned
pub struct ContextAssigned<P: IntoScriptPluginParams> {
    /// The context assigned for the script, either pre-existing or new
    pub context: Arc<Mutex<P::C>>,

    /// True if this is a new context and not one that was reloaded
    pub is_new_context: bool,
}

impl<P: IntoScriptPluginParams> Clone for ContextAssigned<P> {
    fn clone(&self) -> Self {
        Self {
            context: self.context.clone(),
            is_new_context: self.is_new_context,
        }
    }
}

/// A script unloading state machine state, describes the state in which an attachment is no longer resident in the context, but the context still persists as it
/// was not the last resident
pub struct ResidentRemoved<P: IntoScriptPluginParams> {
    /// The context this attachment was removed from
    pub removed_from_context: Arc<Mutex<P::C>>,
}

impl<P: IntoScriptPluginParams> Clone for ResidentRemoved<P> {
    fn clone(&self) -> Self {
        Self {
            removed_from_context: self.removed_from_context.clone(),
        }
    }
}

/// A script unloading state machine state, describes the state in which an attachment is no longer resident in the context,
/// and the context itself was removed
pub struct ContextRemoved<P: IntoScriptPluginParams> {
    /// The context which was removed
    pub removed_context: Arc<Mutex<P::C>>,
}

impl<P: IntoScriptPluginParams> Clone for ContextRemoved<P> {
    fn clone(&self) -> Self {
        Self {
            removed_context: self.removed_context.clone(),
        }
    }
}

impl<P: IntoScriptPluginParams> MachineState<P> for LoadingInitialized {
    fn poll_next(
        &mut self,
        ctxt: &Context,
        world: &mut World,
    ) -> Box<dyn Future<Output = Result<Box<dyn MachineState<P>>, ScriptError>> + Send + Sync> {
        let attachment = &ctxt.attachment;
        let guard = WorldGuard::new_exclusive(world);
        let ctxt = P::load(attachment, &self.content, guard.clone());
        Box::new(ready(ctxt.map_err(ScriptError::from).map(|context| {
            Box::new(ContextAssigned::<P> {
                context: Arc::new(Mutex::new(context)),
                is_new_context: true,
            }) as Box<dyn MachineState<P>>
        })))
    }
}

impl<P: IntoScriptPluginParams> MachineState<P> for ReloadingInitialized<P> {
    fn poll_next(
        &mut self,
        ctxt: &Context,
        world: &mut World,
    ) -> Box<dyn Future<Output = Result<Box<dyn MachineState<P>>, ScriptError>> + Send + Sync> {
        let attachment = &ctxt.attachment;
        let guard = WorldGuard::new_exclusive(world);
        let mut previous_context_guard = self.existing_context.lock();
        let ctxt = P::reload(
            attachment,
            &self.content,
            &mut previous_context_guard,
            guard.clone(),
        );

        Box::new(ready(ctxt.map_err(ScriptError::from).map(|_| {
            Box::new(ContextAssigned::<P> {
                context: self.existing_context.clone(),
                is_new_context: false,
            }) as Box<dyn MachineState<P>>
        })))
    }
}

impl<P: IntoScriptPluginParams> MachineState<P> for UnloadingInitialized<P> {
    fn poll_next(
        &mut self,
        ctxt: &Context,
        world: &mut World,
    ) -> Box<dyn Future<Output = Result<Box<dyn MachineState<P>>, ScriptError>> + Send + Sync> {
        let attachment = &ctxt.attachment;
        let contexts = world.get_resource_or_init::<ScriptContext<P>>();
        let mut contexts_guard = contexts.write();
        let residents_len = contexts_guard.residents_len(attachment);
        if residents_len == 1 {
            contexts_guard.remove(attachment);
            Box::new(ready(Ok(Box::new(ContextRemoved {
                removed_context: self.existing_context.clone(),
            }) as Box<dyn MachineState<P>>)))
        } else {
            contexts_guard.remove_resident(attachment);
            Box::new(ready(Ok(Box::new(ResidentRemoved {
                removed_from_context: self.existing_context.clone(),
            }) as Box<dyn MachineState<P>>)))
        }
    }
}

impl<P: IntoScriptPluginParams> MachineState<P> for ContextAssigned<P> {
    fn poll_next(
        &mut self,
        ctxt: &Context,
        world: &mut World,
    ) -> Box<dyn Future<Output = Result<Box<dyn MachineState<P>>, ScriptError>> + Send + Sync> {
        let attachment = &ctxt.attachment;
        let contexts = world.get_resource_or_init::<ScriptContext<P>>();
        let mut contexts_guard = contexts.write();

        // drop any strong handles
        match contexts_guard.insert(attachment.clone(), self.context.clone()) {
            Ok(_) => {}
            Err(_) => {
                drop(contexts_guard);
                _ = world.write_message(ScriptErrorEvent::new(
                    ScriptError::from(InteropError::str("no context policy matched"))
                        .with_language(P::LANGUAGE),
                ))
            }
        }
        Box::new(ready(Ok(
            Box::new(LoadingCompleted) as Box<dyn MachineState<P>>
        )))
    }
}

impl<P: IntoScriptPluginParams> MachineState<P> for LoadingCompleted {
    fn poll_next(
        &mut self,
        _ctxt: &Context,
        _world: &mut World,
    ) -> Box<dyn Future<Output = Result<Box<dyn MachineState<P>>, ScriptError>> + Send + Sync> {
        Box::new(ready(Ok(Box::new(Self) as Box<dyn MachineState<P>>)))
    }

    fn is_final(&self) -> bool {
        true
    }
}

impl<P: IntoScriptPluginParams> MachineState<P> for ContextRemoved<P> {
    fn poll_next(
        &mut self,
        _ctxt: &Context,
        _world: &mut World,
    ) -> Box<dyn Future<Output = Result<Box<dyn MachineState<P>>, ScriptError>> + Send + Sync> {
        Box::new(ready(
            Ok(Box::new(self.clone()) as Box<dyn MachineState<P>>),
        ))
    }

    fn is_final(&self) -> bool {
        true
    }
}

impl<P: IntoScriptPluginParams> MachineState<P> for ResidentRemoved<P> {
    fn poll_next(
        &mut self,
        _ctxt: &Context,
        _world: &mut World,
    ) -> Box<dyn Future<Output = Result<Box<dyn MachineState<P>>, ScriptError>> + Send + Sync> {
        Box::new(ready(
            Ok(Box::new(self.clone()) as Box<dyn MachineState<P>>),
        ))
    }

    fn is_final(&self) -> bool {
        true
    }
}