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
use crossbeam_queue::SegQueue;

use crate::{prelude::*, world::EntitiesRes};

struct Queue<T>(SegQueue<T>);

impl<T> Default for Queue<T> {
    fn default() -> Self {
        Self(SegQueue::new())
    }
}

#[cfg(feature = "parallel")]
pub trait LazyUpdateInternal: Send + Sync {
    fn update(self: Box<Self>, world: &mut World);
}

#[cfg(not(feature = "parallel"))]
pub trait LazyUpdateInternal {
    fn update(self: Box<Self>, world: &mut World);
}

/// Generates two versions of functions within the macro call:
///
/// * One with `Send + Sync` bounds when the `"parallel"` feature is enabled.
/// * One without `Send + Sync` bounds when the `"parallel"` feature is
///   disabled.
///
/// TODO: When trait aliases land on stable we can remove this macro.
/// See <https://github.com/rust-lang/rust/issues/41517>.
///
/// ```rust,ignore
/// #![cfg(feature = "parallel")]
/// trait ComponentBound = Component + Send + Sync;
/// #![cfg(not(feature = "parallel"))]
/// trait ComponentBound = Component;
/// ```
///
/// Alternative solutions are listed in:
/// <https://github.com/amethyst/specs/pull/674#issuecomment-585013726>
macro_rules! parallel_feature {
    (
        $(
            $(#[$attrs:meta])* $($words:ident)+<$($ty_params:ident),+> $args:tt $(-> $return_ty:ty)?
            where
                $($ty_param:ident:
                    $bound_first:ident $(< $ty_type:ident = $ty_bound:tt >)? $(($($fn_bound:tt)*))?
                    $(+ $bound:tt $($bound_2:ident)?)*,)+
            $body:block
        )+
    ) =>
    {
        $(
            $(#[$attrs])*
            #[cfg(feature = "parallel")]
            $($words)+<$($ty_params),+> $args $(-> $return_ty)?
            where
                $($ty_param:
                    Send + Sync +
                    $bound_first $(< $ty_type = $ty_bound >)? $(($($fn_bound)*))?
                    $(+ $bound $($bound_2)?)*,)+
            $body

            $(#[$attrs])*
            #[cfg(not(feature = "parallel"))]
            $($words)+<$($ty_params),+> $args $(-> $return_ty)?
            where
                $($ty_param:
                    $bound_first $(< $ty_type = $ty_bound >)? $(($($fn_bound)*))?
                    $(+ $bound $($bound_2)?)*,)+
            $body
        )+
    };
}

/// Like `EntityBuilder`, but inserts the component
/// lazily, meaning on `maintain`.
/// If you need those components to exist immediately,
/// you have to insert them into the storages yourself.
#[must_use = "Please call .build() on this to finish building it."]
pub struct LazyBuilder<'a> {
    /// The entity that we're inserting components for.
    pub entity: Entity,
    /// The lazy update reference.
    pub lazy: &'a LazyUpdate,
}

impl<'a> Builder for LazyBuilder<'a> {
    parallel_feature! {
        /// Inserts a component using [LazyUpdate].
        ///
        /// If a component was already associated with the entity, it will
        /// overwrite the previous component.
        fn with<C>(self, component: C) -> Self
        where
            C: Component,
        {
            let entity = self.entity;
            self.lazy.exec(move |world| {
                let mut storage: WriteStorage<C> = SystemData::fetch(world);
                if storage.insert(entity, component).is_err() {
                    log::warn!(
                        "Lazy insert of component failed because {:?} was dead.",
                        entity
                    );
                }
            });

            self
        }
    }

    /// Finishes the building and returns the built entity.
    /// Please note that no component is associated to this
    /// entity until you call [`World::maintain`].
    fn build(self) -> Entity {
        self.entity
    }
}

#[cfg(feature = "parallel")]
impl<F> LazyUpdateInternal for F
where
    F: FnOnce(&mut World) + Send + Sync + 'static,
{
    fn update(self: Box<Self>, world: &mut World) {
        self(world);
    }
}

#[cfg(not(feature = "parallel"))]
impl<F> LazyUpdateInternal for F
where
    F: FnOnce(&mut World) + 'static,
{
    fn update(self: Box<Self>, world: &mut World) {
        self(world);
    }
}

/// Lazy updates can be used for world updates
/// that need to borrow a lot of resources
/// and as such should better be done at the end.
/// They work lazily in the sense that they are
/// dispatched when calling `world.maintain()`.
///
/// Lazy updates are dispatched in the order that they
/// are requested. Multiple updates sent from one system
/// may be overridden by updates sent from other systems.
///
/// Please note that the provided methods take `&self`
/// so there's no need to get `LazyUpdate` mutably.
/// This resource is added to the world by default.
pub struct LazyUpdate {
    queue: Option<Queue<Box<dyn LazyUpdateInternal>>>,
}

impl Default for LazyUpdate {
    fn default() -> Self {
        Self {
            queue: Some(Default::default()),
        }
    }
}

impl LazyUpdate {
    parallel_feature! {
        /// Lazily inserts a component for an entity.
        ///
        /// ## Examples
        ///
        /// ```
        /// # use specs::prelude::*;
        /// #
        /// struct Pos(f32, f32);
        ///
        /// impl Component for Pos {
        ///     type Storage = VecStorage<Self>;
        /// }
        ///
        /// struct InsertPos;
        ///
        /// impl<'a> System<'a> for InsertPos {
        ///     type SystemData = (Entities<'a>, Read<'a, LazyUpdate>);
        ///
        ///     fn run(&mut self, (ent, lazy): Self::SystemData) {
        ///         let a = ent.create();
        ///         lazy.insert(a, Pos(1.0, 1.0));
        ///     }
        /// }
        /// ```
        pub fn insert<C>(&self, e: Entity, c: C)
        where
            C: Component,
        {
            self.exec(move |world| {
                let mut storage: WriteStorage<C> = SystemData::fetch(world);
                if storage.insert(e, c).is_err() {
                    log::warn!("Lazy insert of component failed because {:?} was dead.", e);
                }
            });
        }

        /// Lazily inserts components for entities.
        ///
        /// ## Examples
        ///
        /// ```
        /// # use specs::prelude::*;
        /// #
        /// struct Pos(f32, f32);
        ///
        /// impl Component for Pos {
        ///     type Storage = VecStorage<Self>;
        /// }
        ///
        /// struct InsertPos;
        ///
        /// impl<'a> System<'a> for InsertPos {
        ///     type SystemData = (Entities<'a>, Read<'a, LazyUpdate>);
        ///
        ///     fn run(&mut self, (ent, lazy): Self::SystemData) {
        ///         let a = ent.create();
        ///         let b = ent.create();
        ///
        ///         lazy.insert_all(vec![(a, Pos(3.0, 1.0)), (b, Pos(0.0, 4.0))]);
        ///     }
        /// }
        /// ```
        pub fn insert_all<C, I>(&self, iter: I)
        where
            C: Component,
            I: IntoIterator<Item = (Entity, C)> + 'static,
        {
            self.exec(move |world| {
                let mut storage: WriteStorage<C> = SystemData::fetch(world);
                for (e, c) in iter {
                    if storage.insert(e, c).is_err() {
                        log::warn!("Lazy insert of component failed because {:?} was dead.", e);
                    }
                }
            });
        }

        /// Lazily removes a component.
        ///
        /// ## Examples
        ///
        /// ```
        /// # use specs::prelude::*;
        /// #
        /// struct Pos;
        ///
        /// impl Component for Pos {
        ///     type Storage = VecStorage<Self>;
        /// }
        ///
        /// struct RemovePos;
        ///
        /// impl<'a> System<'a> for RemovePos {
        ///     type SystemData = (Entities<'a>, Read<'a, LazyUpdate>);
        ///
        ///     fn run(&mut self, (ent, lazy): Self::SystemData) {
        ///         for entity in ent.join() {
        ///             lazy.remove::<Pos>(entity);
        ///         }
        ///     }
        /// }
        /// ```
        pub fn remove<C>(&self, e: Entity)
        where
            C: Component,
        {
            self.exec(move |world| {
                let mut storage: WriteStorage<C> = SystemData::fetch(world);
                storage.remove(e);
            });
        }

        /// Lazily executes a closure with world access.
        ///
        /// ## Examples
        ///
        /// ```
        /// # use specs::prelude::*;
        /// #
        /// struct Pos;
        ///
        /// impl Component for Pos {
        ///     type Storage = VecStorage<Self>;
        /// }
        ///
        /// struct Execution;
        ///
        /// impl<'a> System<'a> for Execution {
        ///     type SystemData = (Entities<'a>, Read<'a, LazyUpdate>);
        ///
        ///     fn run(&mut self, (ent, lazy): Self::SystemData) {
        ///         for entity in ent.join() {
        ///             lazy.exec(move |world| {
        ///                 if world.is_alive(entity) {
        ///                     println!("Entity {:?} is alive.", entity);
        ///                 }
        ///             });
        ///         }
        ///     }
        /// }
        /// ```
        pub fn exec<F>(&self, f: F)
        where
            F: FnOnce(&mut World) + 'static,
        {
            self.queue
                .as_ref()
                .unwrap()
                .0
                .push(Box::new(|w: &mut World| f(w)));
        }

        /// Lazily executes a closure with mutable world access.
        ///
        /// This can be used to add a resource to the `World` from a system.
        ///
        /// ## Examples
        ///
        /// ```
        /// # use specs::prelude::*;
        /// #
        ///
        /// struct Sys;
        ///
        /// impl<'a> System<'a> for Sys {
        ///     type SystemData = (Entities<'a>, Read<'a, LazyUpdate>);
        ///
        ///     fn run(&mut self, (ent, lazy): Self::SystemData) {
        ///         for entity in ent.join() {
        ///             lazy.exec_mut(move |world| {
        ///                 // complete extermination!
        ///                 world.delete_all();
        ///             });
        ///         }
        ///     }
        /// }
        /// ```
        pub fn exec_mut<F>(&self, f: F)
        where
            F: FnOnce(&mut World) + 'static,
        {
            self.queue.as_ref().unwrap().0.push(Box::new(f));
        }
    }

    /// Creates a new `LazyBuilder` which inserts components
    /// using `LazyUpdate`. This means that the components won't
    /// be available immediately, but only after a `maintain`
    /// on `World` is performed.
    ///
    /// ## Examples
    ///
    /// ```
    /// # use specs::prelude::*;
    /// # let mut world = World::new();
    /// struct Pos(f32, f32);
    ///
    /// impl Component for Pos {
    ///     type Storage = VecStorage<Self>;
    /// }
    ///
    /// # let lazy = world.read_resource::<LazyUpdate>();
    /// # let entities = world.entities();
    /// let my_entity = lazy.create_entity(&entities).with(Pos(1.0, 3.0)).build();
    /// ```
    pub fn create_entity(&self, ent: &EntitiesRes) -> LazyBuilder {
        let entity = ent.create();

        LazyBuilder { entity, lazy: self }
    }

    /// Allows to temporarily take the inner queue.
    pub(super) fn take(&mut self) -> Self {
        Self {
            queue: self.queue.take(),
        }
    }

    /// Needs to be called to restore the inner queue.
    pub(super) fn restore(&mut self, mut maintained: Self) {
        use std::mem::swap;

        swap(&mut self.queue, &mut maintained.queue);
    }

    pub(super) fn maintain(&mut self, world: &mut World) {
        let lazy = &mut self.queue.as_mut().unwrap().0;

        while let Ok(l) = lazy.pop() {
            l.update(world);
        }
    }
}

impl Drop for LazyUpdate {
    fn drop(&mut self) {
        // TODO: remove as soon as leak is fixed in crossbeam
        if let Some(queue) = self.queue.as_mut() {
            while queue.0.pop().is_ok() {}
        }
    }
}