1use std::{
2 fmt::Debug,
3 mem,
4 sync::Arc,
5 thread,
6 time::{Duration, Instant},
7};
8
9use azalea_core::tick::GameTick;
10use azalea_entity::{
11 EntityUpdateSystems, PlayerAbilities, indexing::EntityIdIndex, inventory::Inventory,
12};
13use azalea_physics::client_movement::ClientMovementState;
14use azalea_world::Worlds;
15use bevy_app::{App, AppExit, Plugin, PluginsState, SubApp, Update};
16use bevy_ecs::{
17 message::MessageCursor,
18 prelude::*,
19 schedule::{InternedScheduleLabel, LogLevel, ScheduleBuildSettings},
20};
21use parking_lot::RwLock;
22use tokio::{sync::oneshot, time};
23use tracing::{info, warn};
24
25use crate::{
26 attack,
27 block_update::QueuedServerBlockUpdates,
28 chunks::ChunkBatchInfo,
29 connection::RawConnection,
30 cookies::ServerCookies,
31 interact::BlockStatePredictionHandler,
32 local_player::{Experience, Hunger, PermissionLevel, TabList, TabListResource, WorldHolder},
33 mining,
34 movement::LastSentLookDirection,
35 player::retroactively_add_game_profile_component,
36};
37#[derive(Bundle)]
43pub struct LocalPlayerBundle {
44 pub raw_connection: RawConnection,
45 pub world_holder: WorldHolder,
46
47 pub metadata: azalea_entity::metadata::PlayerMetadataBundle,
48}
49
50#[derive(Bundle, Default)]
57pub struct JoinedClientBundle {
58 pub physics_state: ClientMovementState,
61 pub inventory: Inventory,
62 pub tab_list: TabList,
63 pub block_state_prediction_handler: BlockStatePredictionHandler,
64 pub queued_server_block_updates: QueuedServerBlockUpdates,
65 pub last_sent_direction: LastSentLookDirection,
66 pub abilities: PlayerAbilities,
67 pub permission_level: PermissionLevel,
68 pub chunk_batch_info: ChunkBatchInfo,
69 pub hunger: Hunger,
70 pub experience: Experience,
71 pub cookies: ServerCookies,
72
73 pub entity_id_index: EntityIdIndex,
74
75 pub mining: mining::MineBundle,
76 pub attack: attack::AttackBundle,
77
78 pub in_game_state: InGameState,
79}
80
81#[derive(Clone, Component, Debug, Default)]
84pub struct InGameState;
85#[derive(Clone, Component, Debug, Default)]
88pub struct InConfigState;
89
90pub struct AzaleaPlugin;
91impl Plugin for AzaleaPlugin {
92 fn build(&self, app: &mut App) {
93 app.add_systems(
94 Update,
95 (
96 retroactively_add_game_profile_component
98 .after(EntityUpdateSystems::Index)
99 .after(crate::join::handle_start_join_server_event),
100 ),
101 )
102 .init_resource::<Worlds>()
103 .init_resource::<TabListResource>();
104 }
105}
106
107#[doc(hidden)]
120pub fn start_ecs_runner(
121 app: &mut SubApp,
122) -> (
123 Arc<RwLock<World>>,
124 impl FnOnce(),
125 oneshot::Receiver<AppExit>,
126) {
127 if app.plugins_state() != PluginsState::Cleaned {
130 if app.plugins_state() == PluginsState::Adding {
132 info!("Waiting for plugins to load ...");
133 while app.plugins_state() == PluginsState::Adding {
134 thread::yield_now();
135 }
136 }
137 app.finish();
139 app.cleanup();
140 }
141
142 let ecs = Arc::new(RwLock::new(mem::take(app.world_mut())));
145
146 let ecs_clone = ecs.clone();
147 let outer_schedule_label = *app.update_schedule.as_ref().unwrap();
148
149 let (appexit_tx, appexit_rx) = oneshot::channel();
150 let start_running_systems = move || {
151 tokio::task::spawn_local(async move {
152 let appexit = run_schedule_loop(ecs_clone, outer_schedule_label).await;
153 appexit_tx.send(appexit)
154 });
155 };
156
157 (ecs, start_running_systems, appexit_rx)
158}
159
160async fn run_schedule_loop(
165 ecs: Arc<RwLock<World>>,
166 outer_schedule_label: InternedScheduleLabel,
167) -> AppExit {
168 let mut last_update: Option<Instant> = None;
169 let mut last_tick: Option<Instant> = None;
170
171 const UPDATE_DURATION_TARGET: Duration = Duration::from_micros(1_000_000 / 60);
175 const GAME_TICK_DURATION_TARGET: Duration = Duration::from_micros(1_000_000 / 20);
177
178 loop {
179 let now = Instant::now();
181 if let Some(last_update) = last_update {
182 let elapsed = now.duration_since(last_update);
183 if elapsed < UPDATE_DURATION_TARGET {
184 time::sleep(UPDATE_DURATION_TARGET - elapsed).await;
185 }
186 }
187 last_update = Some(now);
188
189 let mut ecs = ecs.write();
190
191 ecs.run_schedule(outer_schedule_label);
193 if last_tick
194 .map(|last_tick| last_tick.elapsed() > GAME_TICK_DURATION_TARGET)
195 .unwrap_or(true)
196 {
197 if let Some(last_tick) = &mut last_tick {
198 *last_tick += GAME_TICK_DURATION_TARGET;
199
200 if (now - *last_tick) > GAME_TICK_DURATION_TARGET * 10 {
204 warn!(
205 "GameTick is more than 10 ticks behind, skipping ticks so we don't have to burst too much"
206 );
207 *last_tick = now;
208 }
209 } else {
210 last_tick = Some(now);
211 }
212 ecs.run_schedule(GameTick);
213 }
214
215 ecs.clear_trackers();
216 if let Some(exit) = should_exit(&mut ecs) {
217 ecs.clear_all();
220 return exit;
225 }
226 }
227}
228
229fn should_exit(ecs: &mut World) -> Option<AppExit> {
233 let mut reader = MessageCursor::default();
234
235 let events = ecs.get_resource::<Messages<AppExit>>()?;
236 let mut events = reader.read(events);
237
238 if events.len() != 0 {
239 return Some(
240 events
241 .find(|exit| exit.is_error())
242 .cloned()
243 .unwrap_or(AppExit::Success),
244 );
245 }
246
247 None
248}
249
250pub struct AmbiguityLoggerPlugin;
251impl Plugin for AmbiguityLoggerPlugin {
252 fn build(&self, app: &mut App) {
253 app.edit_schedule(Update, |schedule| {
254 schedule.set_build_settings(ScheduleBuildSettings {
255 ambiguity_detection: LogLevel::Warn,
256 ..Default::default()
257 });
258 });
259 app.edit_schedule(GameTick, |schedule| {
260 schedule.set_build_settings(ScheduleBuildSettings {
261 ambiguity_detection: LogLevel::Warn,
262 ..Default::default()
263 });
264 });
265 }
266}