Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/examples/3d/post_processing.rs
9312 views
1
//! Demonstrates Bevy's built-in postprocessing features.
2
//!
3
//! Includes:
4
//!
5
//! - Chromatic Aberration
6
//! - Vignette
7
8
use std::f32::consts::PI;
9
10
use bevy::{
11
camera::Hdr,
12
light::CascadeShadowConfigBuilder,
13
post_process::effect_stack::{ChromaticAberration, Vignette},
14
prelude::*,
15
};
16
17
/// The number of units per frame to add to or subtract from intensity when the
18
/// arrow keys are held.
19
const ADJUSTMENT_SPEED: f32 = 0.005;
20
21
/// The maximum supported chromatic aberration intensity level.
22
const MAX_CHROMATIC_ABERRATION_INTENSITY: f32 = 0.4;
23
24
/// The settings that the user can control.
25
#[derive(Resource)]
26
struct AppSettings {
27
/// The index of the currently selected UI item.
28
selected: usize,
29
/// The intensity of the chromatic aberration effect.
30
chromatic_aberration_intensity: f32,
31
/// The intensity of the vignette effect.
32
vignette_intensity: f32,
33
/// The radius of the vignette.
34
vignette_radius: f32,
35
/// The smoothness of the vignette.
36
vignette_smoothness: f32,
37
/// The roundness of the vignette.
38
vignette_roundness: f32,
39
/// The edge compensation of the vignette.
40
vignette_edge_compensation: f32,
41
}
42
43
/// The entry point.
44
fn main() {
45
App::new()
46
.init_resource::<AppSettings>()
47
.add_plugins(DefaultPlugins)
48
.add_systems(Startup, setup)
49
.add_systems(Update, handle_keyboard_input)
50
.add_systems(
51
Update,
52
(update_chromatic_aberration_settings, update_help_text)
53
.run_if(resource_changed::<AppSettings>)
54
.after(handle_keyboard_input),
55
)
56
.run();
57
}
58
59
/// Creates the example scene and spawns the UI.
60
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
61
// Spawn the camera.
62
spawn_camera(&mut commands, &asset_server);
63
64
// Create the scene.
65
spawn_scene(&mut commands, &asset_server);
66
67
// Spawn the help text.
68
spawn_text(&mut commands);
69
}
70
71
/// Spawns the camera, including the [`ChromaticAberration`] component.
72
fn spawn_camera(commands: &mut Commands, asset_server: &AssetServer) {
73
commands.spawn((
74
Camera3d::default(),
75
Hdr,
76
Transform::from_xyz(0.7, 0.7, 1.0).looking_at(Vec3::new(0.0, 0.3, 0.0), Vec3::Y),
77
DistanceFog {
78
color: Color::srgb_u8(43, 44, 47),
79
falloff: FogFalloff::Linear {
80
start: 1.0,
81
end: 8.0,
82
},
83
..default()
84
},
85
EnvironmentMapLight {
86
diffuse_map: asset_server.load("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2"),
87
specular_map: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"),
88
intensity: 2000.0,
89
..default()
90
},
91
// Include the `ChromaticAberration` component.
92
ChromaticAberration::default(),
93
// Include the `Vignette` component.
94
Vignette::default(),
95
));
96
}
97
98
/// Spawns the scene.
99
///
100
/// This is just the tonemapping test scene, chosen for the fact that it uses a
101
/// variety of colors.
102
fn spawn_scene(commands: &mut Commands, asset_server: &AssetServer) {
103
// Spawn the main scene.
104
commands.spawn(SceneRoot(asset_server.load(
105
GltfAssetLabel::Scene(0).from_asset("models/TonemappingTest/TonemappingTest.gltf"),
106
)));
107
108
// Spawn the flight helmet.
109
commands.spawn((
110
SceneRoot(
111
asset_server
112
.load(GltfAssetLabel::Scene(0).from_asset("models/FlightHelmet/FlightHelmet.gltf")),
113
),
114
Transform::from_xyz(0.5, 0.0, -0.5).with_rotation(Quat::from_rotation_y(-0.15 * PI)),
115
));
116
117
// Spawn the light.
118
commands.spawn((
119
DirectionalLight {
120
illuminance: 15000.0,
121
shadow_maps_enabled: true,
122
..default()
123
},
124
Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, PI * -0.15, PI * -0.15)),
125
CascadeShadowConfigBuilder {
126
maximum_distance: 3.0,
127
first_cascade_far_bound: 0.9,
128
..default()
129
}
130
.build(),
131
));
132
}
133
134
/// Spawns the help text.
135
fn spawn_text(commands: &mut Commands) {
136
commands.spawn((
137
Text::default(),
138
Node {
139
position_type: PositionType::Absolute,
140
top: px(12),
141
left: px(12),
142
..default()
143
},
144
));
145
}
146
147
impl Default for AppSettings {
148
fn default() -> Self {
149
let vignette_default = Vignette::default();
150
Self {
151
selected: 0,
152
chromatic_aberration_intensity: ChromaticAberration::default().intensity,
153
vignette_intensity: vignette_default.intensity,
154
vignette_radius: vignette_default.radius,
155
vignette_smoothness: vignette_default.smoothness,
156
vignette_roundness: vignette_default.roundness,
157
vignette_edge_compensation: vignette_default.edge_compensation,
158
}
159
}
160
}
161
162
/// Handles requests from the user to change the chromatic aberration intensity.
163
fn handle_keyboard_input(mut app_settings: ResMut<AppSettings>, input: Res<ButtonInput<KeyCode>>) {
164
if input.just_pressed(KeyCode::ArrowUp) && app_settings.selected > 0 {
165
app_settings.selected -= 1;
166
} else if input.just_pressed(KeyCode::ArrowDown) && app_settings.selected < 5 {
167
app_settings.selected += 1;
168
}
169
170
let mut delta = 0.0;
171
if input.pressed(KeyCode::ArrowLeft) {
172
delta -= ADJUSTMENT_SPEED;
173
} else if input.pressed(KeyCode::ArrowRight) {
174
delta += ADJUSTMENT_SPEED;
175
}
176
177
// If no arrow key was pressed, just bail out.
178
if delta == 0.0 {
179
return;
180
}
181
182
match app_settings.selected {
183
0 => {
184
app_settings.chromatic_aberration_intensity =
185
(app_settings.chromatic_aberration_intensity + delta)
186
.clamp(0.0, MAX_CHROMATIC_ABERRATION_INTENSITY);
187
}
188
1 => {
189
app_settings.vignette_intensity =
190
(app_settings.vignette_intensity + delta).clamp(0.0, 1.0);
191
}
192
2 => app_settings.vignette_radius = (app_settings.vignette_radius + delta).clamp(0.0, 2.0),
193
3 => {
194
app_settings.vignette_smoothness = (app_settings.vignette_smoothness + delta).max(0.01);
195
}
196
4 => app_settings.vignette_roundness = (app_settings.vignette_roundness + delta).max(0.01),
197
5 => {
198
app_settings.vignette_edge_compensation =
199
(app_settings.vignette_edge_compensation + delta).clamp(0.0, 1.0);
200
}
201
_ => {}
202
}
203
}
204
205
/// Updates the [`ChromaticAberration`] settings per the [`AppSettings`].
206
fn update_chromatic_aberration_settings(
207
mut chromatic_aberration: Query<&mut ChromaticAberration>,
208
mut vignette: Query<&mut Vignette>,
209
app_settings: Res<AppSettings>,
210
) {
211
let intensity = app_settings.chromatic_aberration_intensity;
212
213
// Pick a reasonable maximum sample size for the intensity to avoid an
214
// artifact whereby the individual samples appear instead of producing
215
// smooth streaks of color.
216
//
217
// Don't take this formula too seriously; it hasn't been heavily tuned.
218
let max_samples = ((intensity - 0.02) / (0.20 - 0.02) * 56.0 + 8.0)
219
.clamp(8.0, 64.0)
220
.round() as u32;
221
222
for mut chromatic_aberration in &mut chromatic_aberration {
223
chromatic_aberration.intensity = intensity;
224
chromatic_aberration.max_samples = max_samples;
225
}
226
227
for mut vignette in &mut vignette {
228
vignette.intensity = app_settings.vignette_intensity;
229
vignette.radius = app_settings.vignette_radius;
230
vignette.smoothness = app_settings.vignette_smoothness;
231
vignette.roundness = app_settings.vignette_roundness;
232
vignette.edge_compensation = app_settings.vignette_edge_compensation;
233
}
234
}
235
236
/// Updates the help text at the bottom of the screen to reflect the current
237
/// [`AppSettings`].
238
fn update_help_text(mut text: Single<&mut Text>, app_settings: Res<AppSettings>) {
239
text.clear();
240
let text_list = [
241
format!(
242
"Chromatic aberration intensity: {:.2}\n",
243
app_settings.chromatic_aberration_intensity
244
),
245
format!(
246
"Vignette intensity: {:.2}\n",
247
app_settings.vignette_intensity
248
),
249
format!("Vignette radius: {:.2}\n", app_settings.vignette_radius),
250
format!(
251
"Vignette smoothness: {:.2}\n",
252
app_settings.vignette_smoothness
253
),
254
format!(
255
"Vignette roundness: {:.2}\n",
256
app_settings.vignette_roundness
257
),
258
format!(
259
"Vignette edge_compensation: {:.2}\n",
260
app_settings.vignette_edge_compensation
261
),
262
];
263
for (i, val) in text_list.iter().enumerate() {
264
if i == app_settings.selected {
265
text.push_str("> ");
266
}
267
text.push_str(val);
268
}
269
text.push_str("\n(Press Up or Down to select)\n(Press Left or Right to change)");
270
}
271
272