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
/*!
 * Postprocessing module including bloom, ssao, fxaa and tonemapping
 */
use std::borrow::Borrow;
use rinecs::{SystemThreadLocal, EntitiesThreadLocal, ResourcesThreadLocal, system_thread_local};
use crate::renderer::{
    resources::{ScreenRenderBuffer, RenderStage},
};
use rin_graphics::{self as graphics, Mvp, CameraExt};
use rin_window::{Window, WindowExt};
use rin_gl::{self as gl, Renderer2d, fbo::{ColorAttachment, DepthAttachment}};
use rin_math::{pnt2, vec2, convert, Pnt2};
use rin_postpo as postprocessing;
use crate::DeferredScene;
use crate::transformation::Viewport;
use rin_util::LogErr;

pub use postprocessing::{Parameters, PostProcessing, BloomBlend, Tonemap};


pub struct Bundle{
    parameters: Parameters,
    format: Option<gl::fbo::ColorFormat>,
}

impl Bundle{
    pub fn new_with_parameters(parameters: Parameters) -> Bundle {
        Bundle{
            parameters,
            format: None,
        }
    }

    pub fn new_with_format(format: gl::fbo::ColorFormat) -> Bundle {
        let parameters = Parameters::default();
        Bundle{
            parameters,
            format: Some(format),
        }
    }

    pub fn new_with_format_and_parameters(format: gl::fbo::ColorFormat, parameters: Parameters) -> Bundle {
        Bundle{
            parameters,
            format: Some(format),
        }
    }

    pub fn new() -> Bundle {
        let parameters = Parameters::default();
        Bundle{
            parameters,
            format: None,
        }
    }
}

impl crate::Bundle for Bundle{
    type Parameters = Parameters;

    fn parameters(&self) -> Option<&Parameters> {
        Some(&self.parameters)
    }

    fn name(&self) -> &str{
        "postprocessing"
    }

    fn setup(self, world: &mut DeferredScene){
        let postpo;
        let translucent_blit_fbo;
        {
            let gl = world.resource::<gl::Renderer>().unwrap();
            translucent_blit_fbo =  gl.new_fbo().empty().unwrap();
            let surface = world.resource::<ScreenRenderBuffer>()
                .expect("Can't use postprocessing without a screen render buffer");
            let format = self.format.unwrap_or_else(|| surface.color_format());
            let (w, h) = (surface.width(), surface.height());
            postpo = postprocessing::PostProcessing::new(&gl, w, h, format)
                .log_err("Error creating post processing")
                .expect("Error creating post processing");
        }
        world.add_system_thread_local(PostprocessingOpaqueSystem);
        world.add_system_thread_local(PostprocessingTranslucentSystem{fbo: translucent_blit_fbo});
        world.add_resource_thread_local(postpo);
        world.add_resource_thread_local(self.parameters);
    }
}

struct PostprocessingOpaqueSystem;

#[system_thread_local(name = "ssao")]
#[needs(
    "ScreenRenderBuffer",
    "crate::render_stage::RenderSurfaceOpaque",
    "crate::render_stage::AfterRenderSurfaceOpaque",
    rin_postpo::Parameters
)]
#[updates("postprocessing::PostProcessing", "crate::render_stage::PostprocessingOpaque")]
#[reads(gl::Renderer, dyn CameraExt + Send)]
#[gpu_stats]
impl SystemThreadLocal for PostprocessingOpaqueSystem {
    fn run(&mut self, _entities: EntitiesThreadLocal, resources: ResourcesThreadLocal){
        let glin = resources.get::<gl::Renderer<'static>>().unwrap();
        if let Some(fbo) = resources.get::<ScreenRenderBuffer>(){
            #[cfg(glsl_debug)]
            let postpro = {
                let mut postpro = resources.get_mut::<postprocessing::PostProcessing>().unwrap();
                postpro.update();
                postpro
            };

            #[cfg(not(glsl_debug))]
            let postpro = resources.get::<postprocessing::PostProcessing>().unwrap();


            // Postpo until ssao only for opaque geometry
            #[cfg(gl_debug_groups)]
            let _debug_group = glin.new_debug_group(0, "Postprocessing opaque");
            if let glin::fbo::ColorAttachment::TextureLevel(color, _) = fbo.color_attachment() {
                if let Some(glin::fbo::ColorAttachment::TextureLevel(ambient, _)) = fbo.separate_ambient_attachment() {
                    if let DepthAttachment::TextureLevel(depth, _) = fbo.depth_attachment(){
                        let position = if let Some(ColorAttachment::TextureLevel(position, _)) = fbo.position_attachment() {
                            Some(postprocessing::SSAOPosition::Position(
                                depth,
                                position
                            ))
                        }else if let Some(ColorAttachment::TextureLevel(linear_depth, _)) = fbo.linear_depth_attachment() {
                            Some(postprocessing::SSAOPosition::FromLinearDepth(
                                depth,
                                linear_depth
                            ))
                        }else{
                            Some(postprocessing::SSAOPosition::FromDepth(depth))
                        };

                        let normals = fbo.normals_attachment().and_then(|normals|
                            if let glin::fbo::ColorAttachment::TextureLevel(normals, _) = normals{
                                Some(normals)
                            }else{
                                None
                            });
                        let camera = resources.as_trait::<dyn CameraExt + Send>().unwrap();
                        let parameters = resources.get::<Parameters>().unwrap();
                        postpro.process_until_ssao(
                            &glin,
                            &*camera,
                            color,
                            position,
                            normals,
                            ambient,
                            &parameters).log_err("Error postprocessing: ").unwrap();
                    }else{
                        log::error!("Trying to postprocess on render buffer without a texture depth attachment");
                    }
                }
            }else{
                log::error!("Trying to postprocess on render buffer without color attachment");
                panic!("Trying to postprocess on render buffer without color attachment")
            }

        }else{
            log::error!("Trying to postprocess on without render buffer.
You probably need to create the renderer bundle using new_with_render_surface");
            panic!("Trying to postprocess on without render buffer.
You probably need to create the renderer bundle using new_with_render_surface");
        }
    }
}


struct PostprocessingTranslucentSystem{
    fbo: gl::Fbo<(),()>,
}

#[system_thread_local(name = "postprocessing")]
#[needs(
    "ScreenRenderBuffer",
    "crate::render_stage::RenderSurfaceOpaque",
    "crate::render_stage::AfterRenderSurfaceOpaque",
    "crate::render_stage::PostprocessingOpaque",
    "crate::render_stage::AfterPostprocessingOpaque",
    "crate::render_stage::RenderSurfaceTranslucent",
    "crate::render_stage::AfterRenderSurfaceTranslucent",
    rin_postpo::Parameters,
    dyn CameraExt + Send,
    Viewport
)]
#[updates("postprocessing::PostProcessing", "crate::render_stage::Postprocessing")]
#[reads(gl::Renderer)]
#[gpu_stats]
impl SystemThreadLocal for PostprocessingTranslucentSystem {
    fn run(&mut self, _entities: EntitiesThreadLocal, resources: ResourcesThreadLocal){
        let glin = resources.get::<gl::Renderer<'static>>().unwrap();
        let postpro = resources.get_mut::<postprocessing::PostProcessing>().unwrap();
        if let Some(render_surface) = resources.get::<ScreenRenderBuffer>(){
            // Copy translucent to ssao'd opaque to apply final postpo to everything
            if render_surface.last_stage() == RenderStage::Translucent
                || render_surface.last_stage() == RenderStage::AfterTranslucent
            {
                if let glin::fbo::ColorAttachment::TextureLevel(color, _) = render_surface.color_attachment_force_resolve() {
                    #[cfg(gl_debug_groups)]
                    let debug_group = glin.new_debug_group(0, "Surface resolve");
                    let fbo_color = postpro.ssao_color_attachment();
                    let fbo = self.fbo
                        .with::<_, gl::fbo::DepthAttachment,_>(vec![fbo_color], None)
                        .unwrap();

                    let glin = resources.get::<gl::Renderer<'static>>().unwrap();
                    let glin = glin.with_fbo(&fbo);
                    let glin = glin.with_properties(&[
                        glin::Property::Blend(true),
                        glin::Property::BlendFuncSeparate(
                            gl::ONE,
                            gl::ONE_MINUS_SRC_ALPHA,
                            gl::ZERO,
                            gl::ONE),
                    ]);
                    let glin = glin.with_mvp(Mvp::ortho_top_left(fbo.viewport().into()));
                    glin.draw_pos(color, &Pnt2::origin());
                }
            }
            let depth = if let Some(ColorAttachment::TextureLevel(linear_depth, _)) = render_surface.linear_depth_attachment() {
                Some(postprocessing::DofDepth::LinearDepth(
                    linear_depth
                ))
            }else if let DepthAttachment::TextureLevel(depth, _) = render_surface.depth_attachment(){
                Some(postprocessing::DofDepth::Depth(depth))
            }else{
                None
            };

            let parameters = resources.get::<Parameters>().unwrap();
            let camera = resources.as_trait::<dyn CameraExt + Send>().unwrap();
            let viewport = resources.get::<Viewport>().unwrap();

            if render_surface.separate_ambient_attachment().is_some() {
                // If there is an ambient attachment then render is in postpo ssao fbo
                #[cfg(gl_debug_groups)]
                let debug_group = glin.new_debug_group(0, "Postprocessing translucent");
                if let Err(err) = postpro.process_after_ssao(
                    &glin,
                    &*camera,
                    &viewport,
                    postpro.ssao_color_texture(),
                    depth,
                    &parameters)
                {
                    panic!("Error on postprocessing {}", err);
                }
            }else{
                // If not then render is still in render surface
                if let glin::fbo::ColorAttachment::TextureLevel(color, _) = render_surface.color_attachment() {
                    if let Err(err) = postpro.process_after_ssao(
                        &glin,
                        &*camera,
                        &viewport,
                        color,
                        depth,
                        &parameters)
                    {
                        panic!("Error on postprocessing {}", err);
                    }
                }else{
                    log::error!("Trying to postprocess on render buffer without color attachment");
                    panic!("Trying to postprocess on render buffer without color attachment")
                }
            }

        }else{
            log::error!("Trying to postprocess on without render buffer.
You probably need to create the renderer bundle using new_with_render_surface");
            panic!("Trying to postprocess on without render buffer.
You probably need to create the renderer bundle using new_with_render_surface");
        }

        // TODO: move to a window renderer
        let draw_stages = false;
        if draw_stages {
            let window = resources.get::<Window>().unwrap();
            let viewport = window.viewport();
            let glin = glin.with_mvp(graphics::Mvp::ortho_top_left(viewport));
            let parameters = resources.get::<Parameters>().unwrap();

            let mut pos = pnt2(window.width() - 266, 10);
            let ratio = postpro.ssao_texture().width() as f32 / postpro.ssao_texture().height() as f32;

            if *parameters.fxaa.borrow() {
                glin.draw_size(postpro.fxaa_texture(), &convert(pos), &vec2(256., 256. / ratio));
                pos += vec2(0, (256. / ratio) as i32 + 10);
                if pos.y + 256 > window.height() {
                    pos.x -= 266;
                    pos.y = 10;
                }
            }

            if *parameters.bloom.borrow() {
                // glin.draw_size(postpro.bloom_blur_texture0(), &convert(pos), &vec2(256., 256. / ratio));
                // pos += vec2(0, (256. / ratio) as i32 + 10);
                // if pos.y + 256 > window.height() {
                //     pos.x -= 266;
                //     pos.y = 10;
                // }

                // glin.draw_size(postpro.bloom_blur_texture1(), &convert(pos), &vec2(256., 256. / ratio));
                // pos += vec2(0, (256. / ratio) as i32 + 10);
                // if pos.y + 256 > window.height() {
                //     pos.x -= 266;
                //     pos.y = 10;
                // }
            }

            if *parameters.ssao.borrow() {
                glin.draw_size(postpro.ssao_texture(), &convert(pos), &vec2(256., 256. / ratio));
                pos += vec2(0, (256. / ratio) as i32 + 10);
                if pos.y + 256 > window.height() {
                    pos.x -= 266;
                    pos.y = 10;
                }

                glin.draw_size(postpro.ssao_blur_texture(), &convert(pos), &vec2(256., 256. / ratio));
                pos += vec2(0, (256. / ratio) as i32 + 10);
                if pos.y + 256 > window.height() {
                    pos.x -= 266;
                    pos.y = 10;
                }

                glin.draw_size(postpro.ssao_color_texture(), &convert(pos), &vec2(256., 256. / ratio));
                pos += vec2(0, (256. / ratio) as i32 + 10);
                if pos.y + 256 > window.height() {
                    pos.x -= 266;
                    pos.y = 10;
                }
            }
        }
    }
}