bevy/examples/stress_tests/many_buttons.rs
Carter Anderson 1bb751cb8d Plugins own their settings. Rework PluginGroup trait. (#6336)
# Objective

Fixes #5884 #2879
Alternative to #2988 #5885 #2886

"Immutable" Plugin settings are currently represented as normal ECS resources, which are read as part of plugin init. This presents a number of problems:

1. If a user inserts the plugin settings resource after the plugin is initialized, it will be silently ignored (and use the defaults instead)
2. Users can modify the plugin settings resource after the plugin has been initialized. This creates a false sense of control over settings that can no longer be changed.

(1) and (2) are especially problematic and confusing for the `WindowDescriptor` resource, but this is a general problem.

## Solution

Immutable Plugin settings now live on each Plugin struct (ex: `WindowPlugin`). PluginGroups have been reworked to support overriding plugin values. This also removes the need for the `add_plugins_with` api, as the `add_plugins` api can use the builder pattern directly. Settings that can be used at runtime continue to be represented as ECS resources.

Plugins are now configured like this:

```rust
app.add_plugin(AssetPlugin {
  watch_for_changes: true,
  ..default()
})
```

PluginGroups are now configured like this:

```rust
app.add_plugins(DefaultPlugins
  .set(AssetPlugin {
    watch_for_changes: true,
    ..default()
  })
)
```

This is an alternative to #2988, which is similar. But I personally prefer this solution for a couple of reasons:
* ~~#2988 doesn't solve (1)~~ #2988 does solve (1) and will panic in that case. I was wrong!
* This PR directly ties plugin settings to Plugin types in a 1:1 relationship, rather than a loose "setup resource" <-> plugin coupling (where the setup resource is consumed by the first plugin that uses it).
* I'm not a huge fan of overloading the ECS resource concept and implementation for something that has very different use cases and constraints.

## Changelog

- PluginGroups can now be configured directly using the builder pattern. Individual plugin values can be overridden by using `plugin_group.set(SomePlugin {})`, which enables overriding default plugin values.  
- `WindowDescriptor` plugin settings have been moved to `WindowPlugin` and `AssetServerSettings` have been moved to `AssetPlugin`
- `app.add_plugins_with` has been replaced by using `add_plugins` with the builder pattern.

## Migration Guide

The `WindowDescriptor` settings have been moved from a resource to `WindowPlugin::window`:

```rust
// Old (Bevy 0.8)
app
  .insert_resource(WindowDescriptor {
    width: 400.0,
    ..default()
  })
  .add_plugins(DefaultPlugins)

// New (Bevy 0.9)
app.add_plugins(DefaultPlugins.set(WindowPlugin {
  window: WindowDescriptor {
    width: 400.0,
    ..default()
  },
  ..default()
}))
```


The `AssetServerSettings` resource has been removed in favor of direct `AssetPlugin` configuration:

```rust
// Old (Bevy 0.8)
app
  .insert_resource(AssetServerSettings {
    watch_for_changes: true,
    ..default()
  })
  .add_plugins(DefaultPlugins)

// New (Bevy 0.9)
app.add_plugins(DefaultPlugins.set(AssetPlugin {
  watch_for_changes: true,
  ..default()
}))
```

`add_plugins_with` has been replaced by `add_plugins` in combination with the builder pattern:

```rust
// Old (Bevy 0.8)
app.add_plugins_with(DefaultPlugins, |group| group.disable::<AssetPlugin>());

// New (Bevy 0.9)
app.add_plugins(DefaultPlugins.build().disable::<AssetPlugin>());
```
2022-10-24 21:20:33 +00:00

118 lines
3.4 KiB
Rust

use bevy::{
diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin},
prelude::*,
window::PresentMode,
};
// For a total of 110 * 110 = 12100 buttons with text
const ROW_COLUMN_COUNT: usize = 110;
const FONT_SIZE: f32 = 7.0;
/// This example shows what happens when there is a lot of buttons on screen.
fn main() {
App::new()
.add_plugins(DefaultPlugins.set(WindowPlugin {
window: WindowDescriptor {
present_mode: PresentMode::Immediate,
..default()
},
..default()
}))
.add_plugin(FrameTimeDiagnosticsPlugin::default())
.add_plugin(LogDiagnosticsPlugin::default())
.init_resource::<UiFont>()
.add_startup_system(setup)
.add_system(button_system)
.run();
}
#[derive(Component)]
struct IdleColor(BackgroundColor);
fn button_system(
mut interaction_query: Query<
(&Interaction, &mut BackgroundColor, &IdleColor),
Changed<Interaction>,
>,
) {
for (interaction, mut material, IdleColor(idle_color)) in interaction_query.iter_mut() {
if matches!(interaction, Interaction::Hovered) {
*material = Color::ORANGE_RED.into();
} else {
*material = *idle_color;
}
}
}
#[derive(Resource)]
struct UiFont(Handle<Font>);
impl FromWorld for UiFont {
fn from_world(world: &mut World) -> Self {
let asset_server = world.resource::<AssetServer>();
UiFont(asset_server.load("fonts/FiraSans-Bold.ttf"))
}
}
fn setup(mut commands: Commands, font: Res<UiFont>) {
let count = ROW_COLUMN_COUNT;
let count_f = count as f32;
let as_rainbow = |i: usize| Color::hsl((i as f32 / count_f) * 360.0, 0.9, 0.8);
commands.spawn(Camera2dBundle::default());
commands
.spawn(NodeBundle {
style: Style {
size: Size::new(Val::Percent(100.0), Val::Percent(100.0)),
..default()
},
..default()
})
.with_children(|commands| {
for i in 0..count {
for j in 0..count {
let color = as_rainbow(j % i.max(1)).into();
spawn_button(commands, font.0.clone_weak(), color, count_f, i, j);
}
}
});
}
fn spawn_button(
commands: &mut ChildBuilder,
font: Handle<Font>,
color: BackgroundColor,
total: f32,
i: usize,
j: usize,
) {
let width = 90.0 / total;
commands
.spawn((
ButtonBundle {
style: Style {
size: Size::new(Val::Percent(width), Val::Percent(width)),
position: UiRect {
bottom: Val::Percent(100.0 / total * i as f32),
left: Val::Percent(100.0 / total * j as f32),
..default()
},
align_items: AlignItems::Center,
position_type: PositionType::Absolute,
..default()
},
background_color: color,
..default()
},
IdleColor(color),
))
.with_children(|commands| {
commands.spawn(TextBundle::from_section(
format!("{i}, {j}"),
TextStyle {
font,
font_size: FONT_SIZE,
color: Color::rgb(0.2, 0.2, 0.2),
},
));
});
}