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
use super::{Scene, DeferredScene};
use rinecs::{
    System, SystemThreadLocal, Entities, Resources, EntitiesThreadLocal, ResourcesThreadLocal,
    SystemConditionSend, SystemConditionThreadLocal, SystemId, Read, barrier, StorageRegistry
};
use crate::time::Clock;
#[cfg(any(feature="desktop", feature="desktop_gles", feature="web"))]
use rin_window::Window;
use rin_window::{self as window, events::{Event, MouseEvent, KeyEvent, WindowEvent}, WindowExt};
use rin_events::{StreamExt, Stream, TryIter, Property};
use rin_math::Rect;
use std::any::TypeId;
use std::path::PathBuf;
#[cfg(gui)]
use rin_gui::ParameterGroup;
#[cfg(feature = "dynamic_systems")]
use std::marker::PhantomData;
#[cfg(feature="web")]
use rin_window::events::WebFile;

pub trait Bundle{
    #[cfg(gui)]
    type Parameters: ParameterGroup;
    #[cfg(not(gui))]
    type Parameters;

    fn parameters(&self) -> Option<&Self::Parameters>;
    fn name(&self) -> &str;
    fn setup(self, scene: &mut DeferredScene);
    fn after_all_bundles_registered(_: &mut Scene){}
}

#[barrier(name = "barrier (update | render)")]
pub struct UpdateRenderBarrier;

pub trait UpdateSystem: Send{
    fn update(&mut self, clock: &Clock, entities: Entities, resources: Resources);
    fn checks(_: &mut StorageRegistry) -> Option<SystemConditionSend> where Self: Sized { None }
    fn name() -> Option<&'static str> where Self: Sized { None }
    fn before() -> Vec<SystemId> where Self: Sized { vec![] }
    fn after() -> Vec<SystemId> where Self: Sized { vec![] }
    fn updates() -> Vec<TypeId> where Self: Sized { vec![] }
    fn needs() -> Vec<TypeId> where Self: Sized { vec![] }
    fn reads() -> Vec<TypeId> where Self: Sized { vec![] }
    fn writes() -> Vec<TypeId> where Self: Sized { vec![] }
    fn file_line_info(&self) -> &'static str { "" }
}

impl<F> UpdateSystem for F
where F: Fn(&Clock, Entities, Resources) + Send
{

    fn update(&mut self, clock: &Clock, entities: Entities, resources: Resources) {
        (*self)(clock, entities, resources)
    }
}

pub struct UpdateWrapper<U>(pub(crate) U);

impl<U: UpdateSystem> System for UpdateWrapper<U> {
    fn run(&mut self, entities: Entities, resources: Resources){
        let clock = resources.get::<Clock>().unwrap();
        self.0.update(&clock, entities, resources)
    }
    fn checks(e: &mut StorageRegistry) -> Option<SystemConditionSend> where Self: Sized {
        U::checks(e)
    }
    fn name() -> Option<&'static str> where Self: Sized { U::name() }
    fn before() -> Vec<SystemId> where Self: Sized {
        let mut before = U::before();
        before.push(SystemId::barrier::<UpdateRenderBarrier>());
        before
    }
    fn after() -> Vec<SystemId> where Self: Sized { U::after() }
    fn updates() -> Vec<TypeId> where Self: Sized { U::updates() }
    fn needs() -> Vec<TypeId> where Self: Sized {
        let mut needs = U::needs();
        needs.push(TypeId::of::<Clock>());
        needs
    }
    fn reads() -> Vec<TypeId> where Self: Sized { U::reads() }
    fn writes() -> Vec<TypeId> where Self: Sized { U::writes() }
}

pub trait UpdateSystemThreadLocal {
    fn update(
        &mut self,
        clock: &Clock,
        entities: EntitiesThreadLocal,
        resources: ResourcesThreadLocal);
    fn checks(_: &mut StorageRegistry) -> Option<SystemConditionThreadLocal> where Self: Sized {
        None
    }
    fn name() -> Option<&'static str> where Self: Sized { None }
    fn before() -> Vec<SystemId> where Self: Sized { vec![] }
    fn after() -> Vec<SystemId> where Self: Sized { vec![] }
    fn updates() -> Vec<TypeId> where Self: Sized { vec![] }
    fn needs() -> Vec<TypeId> where Self: Sized { vec![] }
    fn reads() -> Vec<TypeId> where Self: Sized { vec![] }
    fn writes() -> Vec<TypeId> where Self: Sized { vec![] }
    fn file_line_info(&self) -> &'static str { "" }
}

impl<F> UpdateSystemThreadLocal for F
where F: Fn(&Clock, EntitiesThreadLocal, ResourcesThreadLocal) + Send
{

    fn update(
        &mut self,
        clock: &Clock,
        entities: EntitiesThreadLocal,
        resources: ResourcesThreadLocal)
    {
        (*self)(clock, entities, resources)
    }
}

impl<U: UpdateSystemThreadLocal> SystemThreadLocal for UpdateWrapper<U> {
    fn run(&mut self, entities: EntitiesThreadLocal, resources: ResourcesThreadLocal){
        let clock = resources.get::<Clock>().unwrap();
        self.0.update(&clock, entities, resources)
    }
    fn checks(e: &mut StorageRegistry) -> Option<SystemConditionThreadLocal> where Self: Sized {
        U::checks(e)
    }
    fn name() -> Option<&'static str> where Self: Sized { U::name() }
    fn before() -> Vec<SystemId> where Self: Sized {
        let mut before = U::before();
        before.push(SystemId::barrier::<UpdateRenderBarrier>());
        before
    }
    fn after() -> Vec<SystemId> where Self: Sized { U::after() }
    fn updates() -> Vec<TypeId> where Self: Sized { U::updates() }
    fn needs() -> Vec<TypeId> where Self: Sized {
        let mut needs = U::needs();
        needs.push(TypeId::of::<Clock>());
        needs
    }
    fn reads() -> Vec<TypeId> where Self: Sized { U::reads() }
    fn writes() -> Vec<TypeId> where Self: Sized { U::writes() }
    fn file_line_info(&self) -> &'static str { "" }
}

pub trait EventsSystem: Send{
    fn mouse(&mut self, _: &MouseEvent, _: Entities, _: Resources){}
    fn key(&mut self, _: &KeyEvent, _: Entities, _: Resources){}
    fn window(&mut self, _: &WindowEvent, _: Entities, _: Resources){}
    fn dropped(&mut self, _: &[PathBuf], _: Entities, _: Resources){}
    #[cfg(feature="web")]
    fn dropped_web_file(&mut self, _: &WebFile, _: Entities, _: Resources){}
    fn focus_gained(&mut self, _: Entities, _: Resources){}
    fn focus_lost(&mut self, _: Entities, _: Resources){}
    fn checks(_: &mut StorageRegistry) -> Option<SystemConditionSend> where Self: Sized { None }
    fn name() -> Option<&'static str> where Self: Sized { None }
    fn before() -> Vec<SystemId> where Self: Sized { vec![] }
    fn after() -> Vec<SystemId> where Self: Sized { vec![] }
    fn updates() -> Vec<TypeId> where Self: Sized { vec![] }
    fn needs() -> Vec<TypeId> where Self: Sized { vec![] }
    fn reads() -> Vec<TypeId> where Self: Sized { vec![] }
    fn writes() -> Vec<TypeId> where Self: Sized { vec![] }
    fn file_line_info(&self) -> &'static str { "" }
}

pub trait EventsSystemThreadLocal{
    fn mouse(&mut self, _: &MouseEvent, _: EntitiesThreadLocal, _: ResourcesThreadLocal){}
    fn key(&mut self, _: &KeyEvent, _: EntitiesThreadLocal, _: ResourcesThreadLocal){}
    fn window(&mut self, _: &WindowEvent, _: EntitiesThreadLocal, _: ResourcesThreadLocal){}
    fn dropped(&mut self, _: &[PathBuf], _: EntitiesThreadLocal, _: ResourcesThreadLocal){}
    #[cfg(feature="web")]
    fn dropped_web_file(&mut self, _: &WebFile, _: EntitiesThreadLocal, _: ResourcesThreadLocal){}
    fn focus_gained(&mut self, _: EntitiesThreadLocal, _: ResourcesThreadLocal){}
    fn focus_lost(&mut self, _: EntitiesThreadLocal, _: ResourcesThreadLocal){}
    fn checks(_: EntitiesThreadLocal) -> Option<SystemConditionThreadLocal> where Self: Sized {
        None
    }
    fn name() -> Option<&'static str> where Self: Sized { None }
    fn before() -> Vec<SystemId> where Self: Sized { vec![] }
    fn after() -> Vec<SystemId> where Self: Sized { vec![] }
    fn updates() -> Vec<TypeId> where Self: Sized { vec![] }
    fn needs() -> Vec<TypeId> where Self: Sized { vec![] }
    fn reads() -> Vec<TypeId> where Self: Sized { vec![] }
    fn writes() -> Vec<TypeId> where Self: Sized { vec![] }
    fn file_line_info(&self) -> &'static str { "" }
}

pub struct EventsWrapper<S>{
    system: S,
    window_events: TryIter<'static, Event>,
}

impl<S> EventsWrapper<S>{
    pub fn new<E>(system: S, window_events: E) -> EventsWrapper<S>
    where E: StreamExt<'static, Event> + 'static
    {
        EventsWrapper{
            system,
            window_events: window_events.try_iter(),
        }
    }
}

impl<S: EventsSystem> System for EventsWrapper<S>{
    fn run(&mut self, mut entities: Entities, resources: Resources){
        for event in self.window_events.by_ref(){
            match event {
                Event::MousePressed{ pos, button, mods } =>
                    self.system.mouse(&MouseEvent::Pressed{pos, button, mods}, entities.clone(), resources.clone()),
                Event::MouseReleased{ pos, button, mods } =>
                    self.system.mouse(&MouseEvent::Released{pos, button, mods}, entities.clone(), resources.clone()),
                Event::MouseMoved{ pos } =>
                    self.system.mouse(&MouseEvent::Moved{pos}, entities.clone(), resources.clone()),
                Event::Scroll{ scroll } =>
                    self.system.mouse(&MouseEvent::Scrolled{scroll}, entities.clone(), resources.clone()),
                Event::KeyPressed{ key, mods, repeat } =>
                    self.system.key(&KeyEvent::Pressed{key, mods, repeat}, entities.clone(), resources.clone()),
                Event::KeyReleased{ key } =>
                    self.system.key(&KeyEvent::Released{key}, entities.clone(), resources.clone()),
                Event::Char{character} =>
                    self.system.key(&KeyEvent::Char{character}, entities.clone(), resources.clone()),
                Event::WindowMoved{ pos } =>
                    self.system.window(&WindowEvent::Moved{ pos }, entities.clone(), resources.clone()),
                Event::WindowResized{ size } =>
                    self.system.window(&WindowEvent::Resized{ size }, entities.clone(), resources.clone()),
                Event::WindowClosing =>
                    self.system.window(&WindowEvent::Closing, entities.clone(), resources.clone()),
                Event::Dropped{paths} =>
                    self.system.dropped(&paths, entities.clone(), resources.clone()),
                #[cfg(feature="web")]
                Event::DroppedWebFile{file} =>
                    self.system.dropped_web_file(&file, entities, resources),
                Event::Update{..} => (),
                Event::FocusLost =>
                    self.system.focus_lost(entities.clone(), resources.clone()),
                Event::FocusGained =>
                    self.system.focus_gained(entities.clone(), resources.clone()),
            }
        }
    }
    fn checks(e: &mut StorageRegistry) -> Option<SystemConditionSend> where Self: Sized {
        S::checks(e)
    }
    fn name() -> Option<&'static str> where Self: Sized { S::name() }
    fn before() -> Vec<SystemId> where Self: Sized { S::before() }
    fn after() -> Vec<SystemId> where Self: Sized { S::after() }
    fn updates() -> Vec<TypeId> where Self: Sized { S::updates() }
    fn needs() -> Vec<TypeId> where Self: Sized {
        let mut needs = S::needs();
        needs.push(TypeId::of::<Clock>());
        needs
    }
    fn reads() -> Vec<TypeId> where Self: Sized { S::reads() }
    fn writes() -> Vec<TypeId> where Self: Sized { S::writes() }
}



impl<S: EventsSystemThreadLocal> SystemThreadLocal for EventsWrapper<S>{
    fn run(&mut self, mut entities: EntitiesThreadLocal, resources: ResourcesThreadLocal){
        for event in self.window_events.by_ref(){
            match event {
                Event::MousePressed{ pos, button, mods } =>
                    self.system.mouse(&MouseEvent::Pressed{pos, button, mods}, entities.clone(), resources.clone()),
                Event::MouseReleased{ pos, button, mods } =>
                    self.system.mouse(&MouseEvent::Released{pos, button, mods}, entities.clone(), resources.clone()),
                Event::MouseMoved{ pos } =>
                    self.system.mouse(&MouseEvent::Moved{pos}, entities.clone(), resources.clone()),
                Event::Scroll{ scroll } =>
                    self.system.mouse(&MouseEvent::Scrolled{scroll}, entities.clone(), resources.clone()),
                Event::KeyPressed{ key, mods, repeat } =>
                    self.system.key(&KeyEvent::Pressed{key, mods, repeat}, entities.clone(), resources.clone()),
                Event::KeyReleased{ key } =>
                    self.system.key(&KeyEvent::Released{key}, entities.clone(), resources.clone()),
                Event::Char{character} =>
                    self.system.key(&KeyEvent::Char{character}, entities.clone(), resources.clone()),
                Event::WindowMoved{ pos } =>
                    self.system.window(&WindowEvent::Moved{ pos }, entities.clone(), resources.clone()),
                Event::WindowResized{ size } =>
                    self.system.window(&WindowEvent::Resized{ size }, entities.clone(), resources.clone()),
                Event::WindowClosing =>
                    self.system.window(&WindowEvent::Closing, entities.clone(), resources.clone()),
                Event::Dropped{paths} =>
                    self.system.dropped(&paths, entities.clone(), resources.clone()),
                #[cfg(feature="web")]
                Event::DroppedWebFile{file} =>
                    self.system.dropped_web_file(&file, entities, resources),
                Event::Update{..} => (),
                Event::FocusLost =>
                    self.system.focus_lost(entities.clone(), resources.clone()),
                Event::FocusGained =>
                    self.system.focus_gained(entities.clone(), resources.clone()),
            }
        }
    }
    fn checks(_: &mut StorageRegistry) -> Option<SystemConditionThreadLocal> where Self: Sized {
        None
    }
    fn name() -> Option<&'static str> where Self: Sized { None }
    fn before() -> Vec<SystemId> where Self: Sized { vec![] }
    fn after() -> Vec<SystemId> where Self: Sized { vec![] }
    fn updates() -> Vec<TypeId> where Self: Sized { vec![] }
    fn needs() -> Vec<TypeId> where Self: Sized { vec![] }
}

#[cfg(any(feature="desktop", feature="desktop_gles", feature="web"))]
pub trait RendererBundle {
    #[cfg(feature="gui")]
    type Parameters: ParameterGroup;

    #[cfg(not(feature="gui"))]
    type Parameters;

    fn parameters(&self) -> Option<&Self::Parameters>{ None }
    fn name(&self) -> &str{ std::any::type_name::<Self>() }
    fn setup(self, scene: &mut DeferredScene);
    fn viewport(&mut self) -> Property<'static, Rect<i32>>;
    fn window(&self) -> Option<&Window>;
    fn window_mut(&mut self) -> Option<&mut Window>;
    fn event_stream(&mut self) -> Stream<'static, window::Event>;
    fn file_line_info(&self) -> &'static str { "" }
}

/// The order of rendering is:
/// - render all opaque geometry
/// - apply poostprocessing to opaque geometry
/// - render all translucent geometry
/// - apply postprocessing common to opaque and ranslucent geometry
/// - render the result to the window
///
/// Each of this enum's variants allow a `RenderSystem` to render after each of this stages
/// to the render surface the stage rendered to.
///
/// For example a RenderSystem that renders to RenderStage::RenderSurfaceOpaque will render after the
/// opaque geometry in the scene has been rendered and will be passed a gl::Renderer using the same
/// fbo where that geometry was rendered
pub enum RenderStage{
    RenderSurfaceOpaque,
    AfterPostprocessingOpaque,
    RenderSurfaceTranslucent,
    AfterPostprocessing,
    Window,
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum RendersTo{
    MainRenderSurface,
    RenderPlane(rinecs::Entity),
}

impl RendersTo{
    pub(crate) fn entity(&self) -> Option<&rinecs::Entity>{
        match self{
            RendersTo::MainRenderSurface => None,
            RendersTo::RenderPlane(e) => Some(e),
        }
    }
}

pub mod render_stage{
    pub struct RenderSurfaceOpaque;
    pub struct AfterRenderSurfaceOpaque;
    pub struct PostprocessingOpaque;
    pub struct AfterPostprocessingOpaque;
    pub struct RenderSurfaceTranslucent;
    pub struct AfterRenderSurfaceTranslucent;
    pub struct Postprocessing;
    pub struct AfterPostprocessing;
    pub struct FinalSurface;
    pub struct FinalSurfaceBlit;
    pub struct Window;
}