Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/examples/stress_tests/many_lights.rs
6592 views
1
//! Simple benchmark to test rendering many point lights.
2
//! Run with `WGPU_SETTINGS_PRIO=webgl2` to restrict to uniform buffers and max 256 lights.
3
4
use std::f64::consts::PI;
5
6
use bevy::{
7
camera::ScalingMode,
8
color::palettes::css::DEEP_PINK,
9
diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin},
10
math::{DVec2, DVec3},
11
pbr::{ExtractedPointLight, GlobalClusterableObjectMeta},
12
prelude::*,
13
render::{Render, RenderApp, RenderSystems},
14
window::{PresentMode, WindowResolution},
15
winit::{UpdateMode, WinitSettings},
16
};
17
use rand::{rng, Rng};
18
19
fn main() {
20
App::new()
21
.add_plugins((
22
DefaultPlugins.set(WindowPlugin {
23
primary_window: Some(Window {
24
resolution: WindowResolution::new(1920, 1080).with_scale_factor_override(1.0),
25
title: "many_lights".into(),
26
present_mode: PresentMode::AutoNoVsync,
27
..default()
28
}),
29
..default()
30
}),
31
FrameTimeDiagnosticsPlugin::default(),
32
LogDiagnosticsPlugin::default(),
33
LogVisibleLights,
34
))
35
.insert_resource(WinitSettings {
36
focused_mode: UpdateMode::Continuous,
37
unfocused_mode: UpdateMode::Continuous,
38
})
39
.add_systems(Startup, setup)
40
.add_systems(Update, (move_camera, print_light_count))
41
.run();
42
}
43
44
fn setup(
45
mut commands: Commands,
46
mut meshes: ResMut<Assets<Mesh>>,
47
mut materials: ResMut<Assets<StandardMaterial>>,
48
) {
49
warn!(include_str!("warning_string.txt"));
50
51
const LIGHT_RADIUS: f32 = 0.3;
52
const LIGHT_INTENSITY: f32 = 1000.0;
53
const RADIUS: f32 = 50.0;
54
const N_LIGHTS: usize = 100_000;
55
56
commands.spawn((
57
Mesh3d(meshes.add(Sphere::new(RADIUS).mesh().ico(9).unwrap())),
58
MeshMaterial3d(materials.add(Color::WHITE)),
59
Transform::from_scale(Vec3::NEG_ONE),
60
));
61
62
let mesh = meshes.add(Cuboid::default());
63
let material = materials.add(StandardMaterial {
64
base_color: DEEP_PINK.into(),
65
..default()
66
});
67
68
// NOTE: This pattern is good for testing performance of culling as it provides roughly
69
// the same number of visible meshes regardless of the viewing angle.
70
// NOTE: f64 is used to avoid precision issues that produce visual artifacts in the distribution
71
let golden_ratio = 0.5f64 * (1.0f64 + 5.0f64.sqrt());
72
73
// Spawn N_LIGHTS many lights
74
commands.spawn_batch((0..N_LIGHTS).map(move |i| {
75
let mut rng = rng();
76
77
let spherical_polar_theta_phi = fibonacci_spiral_on_sphere(golden_ratio, i, N_LIGHTS);
78
let unit_sphere_p = spherical_polar_to_cartesian(spherical_polar_theta_phi);
79
80
(
81
PointLight {
82
range: LIGHT_RADIUS,
83
intensity: LIGHT_INTENSITY,
84
color: Color::hsl(rng.random_range(0.0..360.0), 1.0, 0.5),
85
..default()
86
},
87
Transform::from_translation((RADIUS as f64 * unit_sphere_p).as_vec3()),
88
)
89
}));
90
91
// camera
92
match std::env::args().nth(1).as_deref() {
93
Some("orthographic") => commands.spawn((
94
Camera3d::default(),
95
Projection::from(OrthographicProjection {
96
scaling_mode: ScalingMode::FixedHorizontal {
97
viewport_width: 20.0,
98
},
99
..OrthographicProjection::default_3d()
100
}),
101
)),
102
_ => commands.spawn(Camera3d::default()),
103
};
104
105
// add one cube, the only one with strong handles
106
// also serves as a reference point during rotation
107
commands.spawn((
108
Mesh3d(mesh),
109
MeshMaterial3d(material),
110
Transform {
111
translation: Vec3::new(0.0, RADIUS, 0.0),
112
scale: Vec3::splat(5.0),
113
..default()
114
},
115
));
116
}
117
118
// NOTE: This epsilon value is apparently optimal for optimizing for the average
119
// nearest-neighbor distance. See:
120
// http://extremelearning.com.au/how-to-evenly-distribute-points-on-a-sphere-more-effectively-than-the-canonical-fibonacci-lattice/
121
// for details.
122
const EPSILON: f64 = 0.36;
123
fn fibonacci_spiral_on_sphere(golden_ratio: f64, i: usize, n: usize) -> DVec2 {
124
DVec2::new(
125
PI * 2. * (i as f64 / golden_ratio),
126
ops::acos((1.0 - 2.0 * (i as f64 + EPSILON) / (n as f64 - 1.0 + 2.0 * EPSILON)) as f32)
127
as f64,
128
)
129
}
130
131
fn spherical_polar_to_cartesian(p: DVec2) -> DVec3 {
132
let (sin_theta, cos_theta) = p.x.sin_cos();
133
let (sin_phi, cos_phi) = p.y.sin_cos();
134
DVec3::new(cos_theta * sin_phi, sin_theta * sin_phi, cos_phi)
135
}
136
137
// System for rotating the camera
138
fn move_camera(time: Res<Time>, mut camera_transform: Single<&mut Transform, With<Camera>>) {
139
let delta = time.delta_secs() * 0.15;
140
camera_transform.rotate_z(delta);
141
camera_transform.rotate_x(delta);
142
}
143
144
// System for printing the number of meshes on every tick of the timer
145
fn print_light_count(time: Res<Time>, mut timer: Local<PrintingTimer>, lights: Query<&PointLight>) {
146
timer.0.tick(time.delta());
147
148
if timer.0.just_finished() {
149
info!("Lights: {}", lights.iter().len());
150
}
151
}
152
153
struct LogVisibleLights;
154
155
impl Plugin for LogVisibleLights {
156
fn build(&self, app: &mut App) {
157
let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
158
return;
159
};
160
161
render_app.add_systems(
162
Render,
163
print_visible_light_count.in_set(RenderSystems::Prepare),
164
);
165
}
166
}
167
168
// System for printing the number of meshes on every tick of the timer
169
fn print_visible_light_count(
170
time: Res<Time>,
171
mut timer: Local<PrintingTimer>,
172
visible: Query<&ExtractedPointLight>,
173
global_light_meta: Res<GlobalClusterableObjectMeta>,
174
) {
175
timer.0.tick(time.delta());
176
177
if timer.0.just_finished() {
178
info!(
179
"Visible Lights: {}, Rendered Lights: {}",
180
visible.iter().len(),
181
global_light_meta.entity_to_index.len()
182
);
183
}
184
}
185
186
struct PrintingTimer(Timer);
187
188
impl Default for PrintingTimer {
189
fn default() -> Self {
190
Self(Timer::from_seconds(1.0, TimerMode::Repeating))
191
}
192
}
193
194