bevy_mod_scripting_core 0.21.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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
use std::{
    future::ready,
    pin::Pin,
    task::{Poll, Waker},
    time::Duration,
};

use bevy_ecs::{event::Event, world::Mut};
use bevy_log::trace;
use bevy_mod_scripting_bindings::{
    CurrentScriptAttachment, InteropError, ScriptValue, WorldExtensions,
};
use bevy_mod_scripting_script::ScriptAttachment;
use bevy_mod_scripting_world::{WorldAccessGuard, WorldGuard};
use bevy_platform::{collections::HashMap, time::Instant};

use super::*;

#[derive(Default)]
/// Data used by the script pipeline, stored against each attachment as it's loading
pub struct MachineData {
    /// the state stored by a machine during unloads and reloads
    /// used to re-store state between reloads
    pub reload_state: ScriptValue,
}

#[derive(Resource, Default)]
/// Stores [`MachineData`] related to each script attachment, cleared between loads for each attachment
pub struct ActiveMachinesData(pub HashMap<ScriptAttachment, MachineData>);

/// A resource containing all currently running or ready to run machines.
#[derive(Resource)]
pub struct ActiveMachines<P: IntoScriptPluginParams> {
    active_machine: Option<ScriptMachine<P>>,
    initialized_machines: VecDeque<(MachineContext, Box<dyn MachineState<P>>)>,
    uninitialized_machines: VecDeque<ScriptPipelineEvent>,
    /// The current time budget per frame
    pub budget: Option<Duration>,
}

impl<P: IntoScriptPluginParams> Default for ActiveMachines<P> {
    fn default() -> Self {
        Self {
            active_machine: Default::default(),
            initialized_machines: Default::default(),
            uninitialized_machines: Default::default(),
            budget: Default::default(),
        }
    }
}

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

    /// 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));

        let left = end - Instant::now();
        while (self.queued_machines() > 0 || self.active_machine.is_some())
            && left > Duration::default()
        {
            bevy_log::trace!("Ticking machines for up to {:?}", left);

            if self.active_machine.is_some() {
                let final_state = match &mut self.active_machine {
                    Some(next) => next.tick(world),
                    None => continue, // pick up the next machine, should be unreachable
                };

                match final_state {
                    Some(Ok(_)) => {
                        self.active_machine = None;
                    }
                    Some(Err(err)) => {
                        _ = world
                            .write_message(ScriptErrorEvent::new(err.with_language(P::LANGUAGE)));

                        if let Some(active_machine) = self.active_machine.as_mut() {
                            let failed_state =
                                ProcessInterrupted(active_machine.context.attachment.clone());
                            world.trigger(failed_state);
                        } // Else unreachable

                        self.active_machine = None;
                    }
                    None => {
                        // keeping it as active
                    }
                }
            } else {
                // initialize a machine and re-check
                if let Some(event) = self.uninitialized_machines.pop_front() {
                    world.resource_scope(|world, mut assets: Mut<Assets<ScriptAsset>>| {
                        world.resource_scope(|_world, mut contexts: Mut<ScriptContexts<P>>| {
                            self.initialized_machines.extend(
                                event.process(&mut assets, &mut contexts).into_iter().map(
                                    |(attachment, machine)| {
                                        (MachineContext { attachment }, machine)
                                    },
                                ),
                            );
                            if let Some((context, machine)) = self.initialized_machines.pop_front()
                            {
                                trace!(
                                    "State machine '{}' queued. For script: {}",
                                    machine.state_name(),
                                    context.attachment,
                                );
                                self.active_machine = Some(ScriptMachine {
                                    context,
                                    internal_state: MachineExecutionState::Initialized(machine),
                                });
                            }
                        })
                    })
                }
            }
        }
    }

    /// Appends a machine to the end of the queue.
    pub fn queue_machine(&mut self, event: ScriptPipelineEvent) {
        self.uninitialized_machines.push_back(event);
    }

    /// Appends a machine to the end of the queue.
    pub fn queue_machines(&mut self, events: impl IntoIterator<Item = ScriptPipelineEvent>) {
        self.uninitialized_machines.extend(events);
    }

    /// Returns the amount of queued machines minus any currently processing ones
    pub fn queued_machines(&self) -> usize {
        self.uninitialized_machines.len() + self.initialized_machines.len()
    }

    /// Returns the amount of queued and processing machines
    pub fn processing_and_queued_machines(&self) -> usize {
        self.queued_machines() + self.current_machine().map(|_| 1).unwrap_or(0)
    }
}

/// 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: MachineContext,
    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,
    ) -> Option<Result<Box<dyn MachineState<P>>, ScriptError>> {
        match &mut self.internal_state {
            MachineExecutionState::Initialized(machine_state) => {
                trace!(
                    "State '{}' entered. For script: {}",
                    machine_state.state_name(),
                    self.context.attachment,
                );

                // trigger observers, modify state potentially
                machine_state.trigger_event(world);
                world.flush();

                let next = machine_state.poll_next(&self.context, world);
                self.internal_state = MachineExecutionState::Running(next.into());
                return self.tick(world);
            }
            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() {
                                trace!(
                                    "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 => {
                            trace!(
                                "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 MachineContext {
    /// The script attachment being loaded or reloaded
    pub attachment: ScriptAttachment,
}

/// Describes a state in a finite state machine
pub trait MachineState<P: IntoScriptPluginParams>: 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: &MachineContext,
        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
    }

    /// Triggers an event corresponding to this machine state, the reason we need to repeat this logic in every implementation is
    /// that [`Event`] is not `dyn` safe.
    ///
    /// Implementors should emit their own type.
    fn trigger_event(&mut self, world: &mut World);

    /// Build script error event with the most context possible
    fn build_script_error_event(
        &self,
        attachment: &ScriptAttachment,
        base_error: ScriptError,
    ) -> ScriptErrorEvent {
        ScriptErrorEvent::new(
            base_error
                .with_context(attachment.to_string())
                .with_context(self.state_name())
                .with_language(P::LANGUAGE),
        )
    }
}

#[derive(Clone, Event)]
/// A catchall state for error transitions. If any loading/reloading or unloading process is interrupted
/// unexpectedly, it reaches this state.
pub struct ProcessInterrupted(pub ScriptAttachment);

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

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

/// A script loading state machine state, describes the starting state of loading every script
#[derive(Clone, Event)]
pub struct LoadingInitialized {
    /// The attachment being loaded
    pub attachment: ScriptAttachment,
    /// 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
#[derive(Event)]
pub struct ReloadingInitialized<P: IntoScriptPluginParams> {
    /// The attachment being reloaded
    pub attachment: ScriptAttachment,
    /// 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, Event)]
pub struct UnloadingInitialized<P: IntoScriptPluginParams> {
    /// The attachment being unloaded
    pub attachment: ScriptAttachment,
    /// 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 {
            attachment: self.attachment.clone(),
            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
#[derive(Event)]
pub struct ContextAssigned<P: IntoScriptPluginParams> {
    /// The attachment which got the context assigned
    pub attachment: ScriptAttachment,

    /// 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,
            attachment: self.attachment.clone(),
        }
    }
}

/// 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
#[derive(Event)]
pub struct ResidentRemoved<P: IntoScriptPluginParams> {
    /// The attachment having a resident removed
    pub attachment: ScriptAttachment,

    /// 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(),
            attachment: self.attachment.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
#[derive(Event)]
pub struct ContextRemoved<P: IntoScriptPluginParams> {
    /// The attachment having its context removed
    pub attachment: ScriptAttachment,

    /// 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(),
            attachment: self.attachment.clone(),
        }
    }
}

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

    fn trigger_event(&mut self, world: &mut World) {
        world.trigger_ref(self);
    }
}

impl<P: IntoScriptPluginParams> MachineState<P> for ReloadingInitialized<P> {
    fn poll_next(
        &mut self,
        ctxt: &MachineContext,
        world: &mut World,
    ) -> Box<dyn Future<Output = Result<Box<dyn MachineState<P>>, ScriptError>> + Send + Sync> {
        let attachment = &ctxt.attachment;
        let cache =
            WorldAccessGuard::setup_cache(world, CurrentScriptAttachment(Some(attachment.clone())));
        let guard = WorldGuard::new_exclusive(world, cache);
        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> {
                attachment: attachment.clone(),
                context: self.existing_context.clone(),
                is_new_context: false,
            }) as Box<dyn MachineState<P>>
        })))
    }

    fn trigger_event(&mut self, world: &mut World) {
        world.trigger_ref(self)
    }
}

impl<P: IntoScriptPluginParams> MachineState<P> for UnloadingInitialized<P> {
    fn poll_next(
        &mut self,
        ctxt: &MachineContext,
        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::<ScriptContexts<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 {
                attachment: attachment.clone(),
                removed_context: self.existing_context.clone(),
            }) as Box<dyn MachineState<P>>)))
        } else {
            contexts_guard.remove_resident(attachment);
            // TODO: handle failures here
            let _ = contexts_guard.mark_active_if_not_loading(attachment);
            Box::new(ready(Ok(Box::new(ResidentRemoved {
                attachment: attachment.clone(),
                removed_from_context: self.existing_context.clone(),
            }) as Box<dyn MachineState<P>>)))
        }
    }

    fn trigger_event(&mut self, world: &mut World) {
        world.trigger_ref(self)
    }
}

impl<P: IntoScriptPluginParams> MachineState<P> for ContextAssigned<P> {
    fn poll_next(
        &mut self,
        ctxt: &MachineContext,
        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::<ScriptContexts<P>>();
        let mut contexts_guard = contexts.write();

        // drop any strong handles
        match contexts_guard.insert(
            attachment.clone(),
            crate::script::Context::LoadedAndActive(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(attachment.clone())) as Box<dyn MachineState<P>>
        )))
    }
    fn trigger_event(&mut self, world: &mut World) {
        world.trigger_ref(self)
    }
}

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

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

    fn trigger_event(&mut self, world: &mut World) {
        world.trigger_ref(self)
    }
}

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

    fn trigger_event(&mut self, world: &mut World) {
        world.trigger_ref(self)
    }
}

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

    fn trigger_event(&mut self, world: &mut World) {
        world.trigger_ref(self)
    }
}

impl<P: IntoScriptPluginParams> MachineState<P> for UnloadingCompleted {
    fn poll_next(
        &mut self,
        _ctxt: &MachineContext,
        _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
    }

    fn trigger_event(&mut self, world: &mut World) {
        world.trigger_ref(self)
    }
}