-
-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathgame_of_life.rs
215 lines (190 loc) · 6.46 KB
/
game_of_life.rs
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
#![allow(deprecated)]
use std::sync::Mutex;
use bevy::{
diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin},
image::ImageSampler,
prelude::*,
reflect::Reflect,
render::{
render_asset::RenderAssetUsages,
render_resource::{Extent3d, TextureDimension, TextureFormat},
},
window::{PrimaryWindow, WindowResized},
};
use bevy_mod_scripting::prelude::*;
#[derive(Debug, Default, Clone, Reflect, Component, LuaProxy)]
#[reflect(Component, LuaProxyable)]
pub struct LifeState {
pub cells: Vec<u8>,
}
#[derive(Default)]
pub struct LifeAPI;
impl APIProvider for LifeAPI {
type APITarget = Mutex<Lua>;
type ScriptContext = Mutex<Lua>;
type DocTarget = LuaDocFragment;
fn attach_api(&mut self, _: &mut Self::APITarget) -> Result<(), ScriptError> {
// we don't actually provide anything global
Ok(())
}
fn register_with_app(&self, app: &mut App) {
// this will register the `LuaProxyable` typedata since we derived it
// this will resolve retrievals of this component to our custom lua object
app.register_type::<LifeState>();
app.register_type::<Settings>();
}
}
#[derive(Reflect, Resource)]
#[reflect(Resource)]
pub struct Settings {
physical_grid_dimensions: (u32, u32),
display_grid_dimensions: (u32, u32),
border_thickness: u32,
live_color: u8,
dead_color: u8,
}
impl Default for Settings {
fn default() -> Self {
Self {
border_thickness: 1,
live_color: 255u8,
dead_color: 0u8,
physical_grid_dimensions: (88, 50),
display_grid_dimensions: (0, 0),
}
}
}
pub fn setup(
mut commands: Commands,
mut assets: ResMut<Assets<Image>>,
asset_server: Res<AssetServer>,
settings: Res<Settings>,
) {
let mut image = Image::new_fill(
Extent3d {
width: settings.physical_grid_dimensions.0,
height: settings.physical_grid_dimensions.1,
depth_or_array_layers: 1,
},
TextureDimension::D2,
&[0u8],
TextureFormat::R8Unorm,
RenderAssetUsages::RENDER_WORLD | RenderAssetUsages::MAIN_WORLD,
);
image.sampler = ImageSampler::nearest();
let script_path = bevy_mod_scripting_lua::lua_path!("game_of_life");
commands.spawn(Camera2d);
commands
.spawn(Sprite {
image: assets.add(image),
custom_size: Some(Vec2::new(
settings.display_grid_dimensions.0 as f32,
settings.display_grid_dimensions.1 as f32,
)),
color: Color::srgb(1.0, 0.388, 0.278), // TOMATO
..Default::default()
})
.insert(LifeState {
cells: vec![
0u8;
(settings.physical_grid_dimensions.0 * settings.physical_grid_dimensions.1)
as usize
],
})
.insert(ScriptCollection::<LuaFile> {
scripts: vec![Script::new(
script_path.to_owned(),
asset_server.load(script_path),
)],
});
}
pub fn sync_window_size(
mut resize_event: EventReader<WindowResized>,
mut settings: ResMut<Settings>,
mut query: Query<&mut Sprite, With<LifeState>>,
primary_windows: Query<&Window, With<PrimaryWindow>>,
) {
if let Some(e) = resize_event
.read()
.filter(|e| primary_windows.get(e.window).is_ok())
.last()
{
let primary_window = primary_windows.get(e.window).unwrap();
settings.display_grid_dimensions = (
primary_window.physical_width(),
primary_window.physical_height(),
);
// resize all game's of life, retain aspect ratio and fit the entire game in the window
for mut sprite in query.iter_mut() {
let scale = if settings.physical_grid_dimensions.0 > settings.physical_grid_dimensions.1
{
// horizontal is longer
settings.display_grid_dimensions.1 as f32
/ settings.physical_grid_dimensions.1 as f32
} else {
// vertical is longer
settings.display_grid_dimensions.0 as f32
/ settings.physical_grid_dimensions.0 as f32
};
sprite.custom_size = Some(Vec2::new(
(settings.physical_grid_dimensions.0 as f32) * scale,
(settings.physical_grid_dimensions.1 as f32) * scale,
));
}
}
}
/// Runs after LifeState components are updated, updates their rendered representation
pub fn update_rendered_state(
mut assets: ResMut<Assets<Image>>,
query: Query<(&LifeState, &Sprite)>,
) {
for (new_state, old_rendered_state) in query.iter() {
let old_rendered_state = assets
.get_mut(&old_rendered_state.image)
.expect("World is not setup correctly");
old_rendered_state.data = new_state.cells.clone();
}
}
/// Sends events allowing scripts to drive update logic
pub fn send_on_update(mut events: PriorityEventWriter<LuaEvent<()>>) {
events.send(
LuaEvent {
hook_name: "on_update".to_owned(),
args: (),
recipients: Recipients::All,
},
1,
)
}
/// Sends initialization event
pub fn send_init(mut events: PriorityEventWriter<LuaEvent<()>>) {
events.send(
LuaEvent {
hook_name: "init".to_owned(),
args: (),
recipients: Recipients::All,
},
0,
)
}
const UPDATE_FREQUENCY: f32 = 1.0 / 60.0;
fn main() -> std::io::Result<()> {
let mut app = App::new();
app.add_plugins(DefaultPlugins)
.insert_resource(Time::<Fixed>::from_seconds(UPDATE_FREQUENCY.into()))
.add_plugins(LogDiagnosticsPlugin::default())
.add_plugins(FrameTimeDiagnosticsPlugin)
.add_plugins(ScriptingPlugin)
.init_resource::<Settings>()
.add_systems(Startup, setup)
.add_systems(Startup, send_init)
.add_systems(Update, sync_window_size)
.add_systems(FixedUpdate, update_rendered_state.after(sync_window_size))
.add_systems(FixedUpdate, send_on_update.after(update_rendered_state))
.add_systems(FixedUpdate, script_event_handler::<LuaScriptHost<()>, 0, 1>)
.add_script_host::<LuaScriptHost<()>>(PostUpdate)
.add_api_provider::<LuaScriptHost<()>>(Box::new(LuaCoreBevyAPIProvider))
.add_api_provider::<LuaScriptHost<()>>(Box::new(LifeAPI));
app.run();
Ok(())
}