Skip to main content

ssao/
ssao.rs

1//! A scene showcasing screen space ambient occlusion.
2
3use bevy::{
4    anti_alias::taa::TemporalAntiAliasing,
5    camera::Hdr,
6    math::ops,
7    pbr::{ScreenSpaceAmbientOcclusion, ScreenSpaceAmbientOcclusionQualityLevel},
8    prelude::*,
9    render::camera::TemporalJitter,
10};
11use std::f32::consts::PI;
12
13fn main() {
14    App::new()
15        .insert_resource(GlobalAmbientLight {
16            brightness: 1000.,
17            ..default()
18        })
19        .add_plugins(DefaultPlugins)
20        .add_systems(Startup, setup)
21        .add_systems(Update, update)
22        .run();
23}
24
25fn setup(
26    mut commands: Commands,
27    mut meshes: ResMut<Assets<Mesh>>,
28    mut materials: ResMut<Assets<StandardMaterial>>,
29) {
30    commands.spawn((
31        Camera3d::default(),
32        Transform::from_xyz(-2.0, 2.0, -2.0).looking_at(Vec3::ZERO, Vec3::Y),
33        Hdr,
34        Msaa::Off,
35        ScreenSpaceAmbientOcclusion::default(),
36        TemporalAntiAliasing::default(),
37    ));
38
39    let material = materials.add(StandardMaterial {
40        base_color: Color::srgb(0.5, 0.5, 0.5),
41        perceptual_roughness: 1.0,
42        reflectance: 0.0,
43        ..default()
44    });
45    commands.spawn((
46        Mesh3d(meshes.add(Cuboid::default())),
47        MeshMaterial3d(material.clone()),
48        Transform::from_xyz(0.0, 0.0, 1.0),
49    ));
50    commands.spawn((
51        Mesh3d(meshes.add(Cuboid::default())),
52        MeshMaterial3d(material.clone()),
53        Transform::from_xyz(0.0, -1.0, 0.0),
54    ));
55    commands.spawn((
56        Mesh3d(meshes.add(Cuboid::default())),
57        MeshMaterial3d(material),
58        Transform::from_xyz(1.0, 0.0, 0.0),
59    ));
60    commands.spawn((
61        Mesh3d(meshes.add(Sphere::new(0.4).mesh().uv(72, 36))),
62        MeshMaterial3d(materials.add(StandardMaterial {
63            base_color: Color::srgb(0.4, 0.4, 0.4),
64            perceptual_roughness: 1.0,
65            reflectance: 0.0,
66            ..default()
67        })),
68        SphereMarker,
69    ));
70
71    commands.spawn((
72        DirectionalLight {
73            shadow_maps_enabled: true,
74            ..default()
75        },
76        Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, PI * -0.15, PI * -0.15)),
77    ));
78
79    commands.spawn((
80        Text::default(),
81        Node {
82            position_type: PositionType::Absolute,
83            bottom: px(12),
84            left: px(12),
85            ..default()
86        },
87    ));
88}
89
90fn update(
91    camera: Single<
92        (
93            Entity,
94            Option<&ScreenSpaceAmbientOcclusion>,
95            Option<&TemporalJitter>,
96        ),
97        With<Camera>,
98    >,
99    mut text: Single<&mut Text>,
100    mut sphere: Single<&mut Transform, With<SphereMarker>>,
101    mut commands: Commands,
102    keycode: Res<ButtonInput<KeyCode>>,
103    time: Res<Time>,
104) {
105    sphere.translation.y = ops::sin(time.elapsed_secs() / 1.7) * 0.7;
106
107    let (camera_entity, ssao, temporal_jitter) = *camera;
108    let current_ssao = ssao.cloned().unwrap_or_default();
109
110    let mut commands = commands.entity(camera_entity);
111    commands
112        .insert_if(
113            ScreenSpaceAmbientOcclusion {
114                quality_level: ScreenSpaceAmbientOcclusionQualityLevel::Low,
115                ..current_ssao
116            },
117            || keycode.just_pressed(KeyCode::Digit2),
118        )
119        .insert_if(
120            ScreenSpaceAmbientOcclusion {
121                quality_level: ScreenSpaceAmbientOcclusionQualityLevel::Medium,
122                ..current_ssao
123            },
124            || keycode.just_pressed(KeyCode::Digit3),
125        )
126        .insert_if(
127            ScreenSpaceAmbientOcclusion {
128                quality_level: ScreenSpaceAmbientOcclusionQualityLevel::High,
129                ..current_ssao
130            },
131            || keycode.just_pressed(KeyCode::Digit4),
132        )
133        .insert_if(
134            ScreenSpaceAmbientOcclusion {
135                quality_level: ScreenSpaceAmbientOcclusionQualityLevel::Ultra,
136                ..current_ssao
137            },
138            || keycode.just_pressed(KeyCode::Digit5),
139        )
140        .insert_if(
141            ScreenSpaceAmbientOcclusion {
142                constant_object_thickness: (current_ssao.constant_object_thickness * 2.0).min(4.0),
143                ..current_ssao
144            },
145            || keycode.just_pressed(KeyCode::ArrowUp),
146        )
147        .insert_if(
148            ScreenSpaceAmbientOcclusion {
149                constant_object_thickness: (current_ssao.constant_object_thickness * 0.5)
150                    .max(0.0625),
151                ..current_ssao
152            },
153            || keycode.just_pressed(KeyCode::ArrowDown),
154        );
155    if keycode.just_pressed(KeyCode::Digit1) {
156        commands.remove::<ScreenSpaceAmbientOcclusion>();
157    }
158    if keycode.just_pressed(KeyCode::Space) {
159        if temporal_jitter.is_some() {
160            commands.remove::<TemporalJitter>();
161        } else {
162            commands.insert(TemporalJitter::default());
163        }
164    }
165
166    text.clear();
167
168    let (o, l, m, h, u) = match ssao.map(|s| s.quality_level) {
169        None => ("*", "", "", "", ""),
170        Some(ScreenSpaceAmbientOcclusionQualityLevel::Low) => ("", "*", "", "", ""),
171        Some(ScreenSpaceAmbientOcclusionQualityLevel::Medium) => ("", "", "*", "", ""),
172        Some(ScreenSpaceAmbientOcclusionQualityLevel::High) => ("", "", "", "*", ""),
173        Some(ScreenSpaceAmbientOcclusionQualityLevel::Ultra) => ("", "", "", "", "*"),
174        _ => unreachable!(),
175    };
176
177    if let Some(thickness) = ssao.map(|s| s.constant_object_thickness) {
178        text.push_str(&format!(
179            "Constant object thickness: {thickness} (Up/Down)\n\n"
180        ));
181    }
182
183    text.push_str("SSAO Quality:\n");
184    text.push_str(&format!("(1) {o}Off{o}\n"));
185    text.push_str(&format!("(2) {l}Low{l}\n"));
186    text.push_str(&format!("(3) {m}Medium{m}\n"));
187    text.push_str(&format!("(4) {h}High{h}\n"));
188    text.push_str(&format!("(5) {u}Ultra{u}\n\n"));
189
190    text.push_str("Temporal Antialiasing:\n");
191    text.push_str(match temporal_jitter {
192        Some(_) => "(Space) Enabled",
193        None => "(Space) Disabled",
194    });
195}
196
197#[derive(Component)]
198struct SphereMarker;