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
use crate::{
    dispatch::Dispatcher, world::ResourceId, Accessor, AccessorCow, DynamicSystemData, RunningTime,
    System, SystemData, World,
};

/// The `BatchAccessor` is used to notify the main dispatcher of the read and
/// write resources of the `System`s contained in the batch ("sub systems").
#[derive(Debug)]
pub struct BatchAccessor {
    reads: Vec<ResourceId>,
    writes: Vec<ResourceId>,
}

impl BatchAccessor {
    /// Creates a `BatchAccessor`
    pub fn new(reads: Vec<ResourceId>, writes: Vec<ResourceId>) -> Self {
        BatchAccessor { reads, writes }
    }
}

impl Accessor for BatchAccessor {
    fn try_new() -> Option<Self> {
        None
    }

    fn reads(&self) -> Vec<ResourceId> {
        self.reads.clone()
    }

    fn writes(&self) -> Vec<ResourceId> {
        self.writes.clone()
    }
}

/// The `BatchUncheckedWorld` wraps an instance of the world.
/// You have to specify this as `SystemData` for a `System` implementing `BatchController`.
pub struct BatchUncheckedWorld<'a>(pub &'a World);

impl<'a> DynamicSystemData<'a> for BatchUncheckedWorld<'a> {
    type Accessor = BatchAccessor;

    fn setup(_accessor: &Self::Accessor, _world: &mut World) {}

    fn fetch(_access: &Self::Accessor, world: &'a World) -> Self {
        BatchUncheckedWorld(world)
    }
}

/// The `BatchController` is the additional trait that a normal System must
/// implement in order to be used as a system controlling the execution of a batch.
///
/// Note that the `System` must also implement `Send` because the `Dispatcher`
/// is by default un-send.
/// The safety of implementing `Send` is ensured by `BatchAccessor` which keeps
/// tracks of all used resources and thus the `System` can be safely executed in
/// with multiple threads.
pub trait BatchController<'a, 'b> {
    /// This associated type has to contain all resources batch controller uses directly.
    ///
    /// These have to be specified here, instead of `SystemData` (as
    /// a normal `System` does) because the sub `System`s can use the same `Resource`s
    /// of the `BatchController`.
    /// This make necessary to drop the references to the
    /// fetched `Resource`s in the batch controller before dispatching
    /// the sub `System`s.
    ///
    /// Now is easy to understand that specify the `BatchController`
    /// `Resource` in the `SystemData` doesn't allow to drop the reference
    /// before the sub dispatching; resulting in `Panic`.
    ///
    /// So this mechanism allows you to fetch safely the specified `Resource`
    /// in the `BatchController`.
    /// The example "examples/batch_dispatching.rs" show how to use it.
    ///
    /// Note that it's not required to specify the sub systems resources here
    /// because they are handled automatically.
    type BatchSystemData: SystemData<'a>;

    /// Creates an instance of the `BatchControllerSystem`.
    ///
    /// Usually this function is called internally by the `DispatcherBuilder`
    /// which creates the `BatchAccessor` correctly.
    /// The `Dispatcher` is constructed by the user elsewhere and passed to the
    /// `DispatcherBuilder` through the functions `with_batch` or `add_batch` and
    /// passed as argument to this function.
    ///
    /// This function is unsafe because an implementor of `BatchController` is expected
    /// to uphold quarantees of `Send` only when it's created with
    /// correctly constructed `BatchAccessor`.
    /// `BatchAccessor` is meant for tracking which resourced are being used by the controller.
    unsafe fn create(accessor: BatchAccessor, dispatcher: Dispatcher<'a, 'b>) -> Self;
}

/// The `DefaultBatchControllerSystem` is a simple implementation that will
/// dispatch the inner dispatcher one time.
///
/// Usually you want to create your own `Dispatcher`.
///
/// Is safe to implement `Send` and `Sync` because the `BatchAccessor` keep
/// tracks of all used resources and thus the `System` can be safely executed in
/// multi thread.
pub struct DefaultBatchControllerSystem<'a, 'b> {
    accessor: BatchAccessor,
    dispatcher: Dispatcher<'a, 'b>,
}

impl<'a, 'b> BatchController<'a, 'b> for DefaultBatchControllerSystem<'a, 'b> {
    type BatchSystemData = ();

    unsafe fn create(accessor: BatchAccessor, dispatcher: Dispatcher<'a, 'b>) -> Self {
        DefaultBatchControllerSystem {
            accessor,
            dispatcher,
        }
    }
}

impl<'a> System<'a> for DefaultBatchControllerSystem<'_, '_> {
    type SystemData = BatchUncheckedWorld<'a>;

    fn run(&mut self, data: Self::SystemData) {
        self.dispatcher.dispatch(data.0);
    }

    fn running_time(&self) -> RunningTime {
        RunningTime::VeryLong
    }

    fn accessor<'c>(&'c self) -> AccessorCow<'a, 'c, Self> {
        AccessorCow::Ref(&self.accessor)
    }

    fn setup(&mut self, world: &mut World) {
        self.dispatcher.setup(world);
    }
}

/// Is safe to implement `Send` and `Sync` because the `BatchAccessor` keep
/// tracks of all used resources and thus the `System` can be safely executed in
/// multi thread.
unsafe impl<'a, 'b> Send for DefaultBatchControllerSystem<'a, 'b> {}

#[cfg(test)]
mod tests {

    use crate::{
        AccessorCow, BatchAccessor, BatchController, BatchUncheckedWorld, Dispatcher,
        DispatcherBuilder, RunningTime, System, World, Write,
    };

    /// This test demonstrate that the batch system is able to correctly setup
    /// its resources to default datas.
    #[test]
    fn test_setup() {
        let mut dispatcher = DispatcherBuilder::new()
            .with_batch::<CustomBatchControllerSystem>(
                DispatcherBuilder::new()
                    .with(BuyTomatoSystem, "buy_tomato_system", &[])
                    .with(BuyPotatoSystem, "buy_potato_system", &[]),
                "BatchSystemTest",
                &[],
            )
            .build();

        let mut world = World::empty();
        dispatcher.setup(&mut world);

        let potato_store = world.fetch::<PotatoStore>();
        let tomato_store = world.fetch::<TomatoStore>();
        assert!(!potato_store.is_store_open);
        assert!(!tomato_store.is_store_open);
        assert_eq!(potato_store.potato_count, 50);
        assert_eq!(tomato_store.tomato_count, 50);
    }

    /// This test demonstrate that the `CustomBatchControllerSystem` is able to
    /// dispatch its systems three times per dispatching in parallel.
    ///
    /// The parallel dispatching happen because there is no dependency between
    /// the two systems.
    ///
    /// Also the `OpenStoresSystem' and the `CloseStoresSystem` which request
    /// mutable access to the same dependencies used by the store systems
    /// are dispatched in sequence; respectivelly before and after the
    /// batch.
    ///
    /// Note that the Setup of the dispatcher is able to correctly create the
    /// store objects with default data.
    #[test]
    fn test_parallel_batch_execution() {
        let mut dispatcher = DispatcherBuilder::new()
            .with(OpenStoresSystem, "open_stores_system", &[])
            .with_batch::<CustomBatchControllerSystem>(
                DispatcherBuilder::new()
                    .with(BuyTomatoSystem, "buy_tomato_system", &[])
                    .with(BuyPotatoSystem, "buy_potato_system", &[]),
                "BatchSystemTest",
                &[],
            )
            .with(CloseStoresSystem, "close_stores_system", &[])
            .build();

        let mut world = World::empty();

        dispatcher.setup(&mut world);

        {
            // Initial assertion
            let potato_store = world.fetch::<PotatoStore>();
            let tomato_store = world.fetch::<TomatoStore>();
            assert!(!potato_store.is_store_open);
            assert!(!tomato_store.is_store_open);
            assert_eq!(potato_store.potato_count, 50);
            assert_eq!(tomato_store.tomato_count, 50);
        }

        // Running phase
        for _i in 0..10 {
            dispatcher.dispatch(&world);
        }

        {
            // This demonstrate that the batch system dispatch three times per
            // dispatch.
            let potato_store = world.fetch::<PotatoStore>();
            let tomato_store = world.fetch::<TomatoStore>();
            assert!(!potato_store.is_store_open);
            assert!(!tomato_store.is_store_open);
            assert_eq!(potato_store.potato_count, 50 - (1 * 3 * 10));
            assert_eq!(tomato_store.tomato_count, 50 - (1 * 3 * 10));
        }
    }

    /// This test demonstrate that the `CustomBatchControllerSystem` is able to
    /// dispatch its systems three times per dispatching in sequence.
    ///
    /// The sequence dispatching happen because there is a dependency between
    /// the two systems.
    ///
    /// Also the `OpenStoresSystem' and the `CloseStoresSystem` which request
    /// mutable access to the same dependencies used by the store systems
    /// are dispatched in sequence; respectivelly before and after the
    /// batch.
    ///
    /// The Setup of the dispatcher is able to correctly create the
    /// store objects with default data.
    /// Note the CustomWallet is created by the Batch setup demonstrating once
    /// again that it works.
    #[test]
    fn test_sequence_batch_execution() {
        let mut dispatcher = DispatcherBuilder::new()
            .with(OpenStoresSystem, "open_stores_system", &[])
            .with_batch::<CustomBatchControllerSystem>(
                DispatcherBuilder::new()
                    .with(BuyTomatoWalletSystem, "buy_tomato_system", &[])
                    .with(BuyPotatoWalletSystem, "buy_potato_system", &[]),
                "BatchSystemTest",
                &[],
            )
            .with(CloseStoresSystem, "close_stores_system", &[])
            .build();

        let mut world = World::empty();

        dispatcher.setup(&mut world);

        {
            // Initial assertion
            let potato_store = world.fetch::<PotatoStore>();
            let tomato_store = world.fetch::<TomatoStore>();
            let customer_wallet = world.fetch::<CustomerWallet>();
            assert!(!potato_store.is_store_open);
            assert!(!tomato_store.is_store_open);
            assert_eq!(potato_store.potato_count, 50);
            assert_eq!(tomato_store.tomato_count, 50);
            assert_eq!(customer_wallet.cents_count, 2000);
        }

        // Running phase
        for _i in 0..10 {
            dispatcher.dispatch(&world);
        }

        {
            // This demonstrate that the batch system dispatch three times per
            // dispatch.
            let potato_store = world.fetch::<PotatoStore>();
            let tomato_store = world.fetch::<TomatoStore>();
            let customer_wallet = world.fetch::<CustomerWallet>();
            assert!(!potato_store.is_store_open);
            assert!(!tomato_store.is_store_open);
            assert_eq!(potato_store.potato_count, 50 - (1 * 3 * 10));
            assert_eq!(tomato_store.tomato_count, 50 - (1 * 3 * 10));
            assert_eq!(customer_wallet.cents_count, 2000 - ((50 + 150) * 3 * 10));
        }
    }

    // Resources

    #[derive(Debug, Clone, Copy)]
    pub struct PotatoStore {
        pub is_store_open: bool,
        pub potato_count: i32,
    }

    impl Default for PotatoStore {
        fn default() -> Self {
            PotatoStore {
                is_store_open: false,
                potato_count: 50,
            }
        }
    }

    #[derive(Debug, Clone, Copy)]
    pub struct TomatoStore {
        pub is_store_open: bool,
        pub tomato_count: i32,
    }

    impl Default for TomatoStore {
        fn default() -> Self {
            TomatoStore {
                is_store_open: false,
                tomato_count: 50,
            }
        }
    }

    #[derive(Debug, Clone, Copy)]
    pub struct CustomerWallet {
        pub cents_count: i32,
    }

    impl Default for CustomerWallet {
        fn default() -> Self {
            CustomerWallet { cents_count: 2000 }
        }
    }

    // Open / Close Systems

    pub struct OpenStoresSystem;

    impl<'a> System<'a> for OpenStoresSystem {
        type SystemData = (Write<'a, PotatoStore>, Write<'a, TomatoStore>);

        fn run(&mut self, mut data: Self::SystemData) {
            data.0.is_store_open = true;
            data.1.is_store_open = true;
        }
    }

    pub struct CloseStoresSystem;

    impl<'a> System<'a> for CloseStoresSystem {
        type SystemData = (Write<'a, PotatoStore>, Write<'a, TomatoStore>);

        fn run(&mut self, mut data: Self::SystemData) {
            data.0.is_store_open = false;
            data.1.is_store_open = false;
        }
    }

    // Buy Systems

    pub struct BuyPotatoSystem;

    impl<'a> System<'a> for BuyPotatoSystem {
        type SystemData = (Write<'a, PotatoStore>);

        fn run(&mut self, mut potato_store: Self::SystemData) {
            assert!(potato_store.is_store_open);
            potato_store.potato_count -= 1;
        }
    }

    pub struct BuyTomatoSystem;

    impl<'a> System<'a> for BuyTomatoSystem {
        type SystemData = (Write<'a, TomatoStore>);

        fn run(&mut self, mut tomato_store: Self::SystemData) {
            assert!(tomato_store.is_store_open);
            tomato_store.tomato_count -= 1;
        }
    }

    // Buy systems with wallet

    pub struct BuyPotatoWalletSystem;

    impl<'a> System<'a> for BuyPotatoWalletSystem {
        type SystemData = (Write<'a, PotatoStore>, Write<'a, CustomerWallet>);

        fn run(&mut self, (mut potato_store, mut customer_wallet): Self::SystemData) {
            assert!(potato_store.is_store_open);
            potato_store.potato_count -= 1;
            customer_wallet.cents_count -= 50;
        }
    }

    pub struct BuyTomatoWalletSystem;

    impl<'a> System<'a> for BuyTomatoWalletSystem {
        type SystemData = (Write<'a, TomatoStore>, Write<'a, CustomerWallet>);

        fn run(&mut self, (mut tomato_store, mut customer_wallet): Self::SystemData) {
            assert!(tomato_store.is_store_open);
            tomato_store.tomato_count -= 1;
            customer_wallet.cents_count -= 150;
        }
    }

    // Custom Batch Controller which dispatch the systems three times

    pub struct CustomBatchControllerSystem<'a, 'b> {
        accessor: BatchAccessor,
        dispatcher: Dispatcher<'a, 'b>,
    }

    impl<'a, 'b> BatchController<'a, 'b> for CustomBatchControllerSystem<'a, 'b> {
        type BatchSystemData = ();

        unsafe fn create(accessor: BatchAccessor, dispatcher: Dispatcher<'a, 'b>) -> Self {
            CustomBatchControllerSystem {
                accessor,
                dispatcher,
            }
        }
    }

    impl<'a> System<'a> for CustomBatchControllerSystem<'_, '_> {
        type SystemData = BatchUncheckedWorld<'a>;

        fn run(&mut self, data: Self::SystemData) {
            for _i in 0..3 {
                self.dispatcher.dispatch(data.0);
            }
        }

        fn running_time(&self) -> RunningTime {
            RunningTime::VeryLong
        }

        fn accessor<'c>(&'c self) -> AccessorCow<'a, 'c, Self> {
            AccessorCow::Ref(&self.accessor)
        }

        fn setup(&mut self, world: &mut World) {
            self.dispatcher.setup(world);
        }
    }

    unsafe impl<'a, 'b> Send for CustomBatchControllerSystem<'a, 'b> {}

}