Files
smart-rgb/crates/borders-core/src/ui/plugin.rs
2025-10-25 16:15:50 -05:00

58 lines
2.4 KiB
Rust

//! Frontend plugin for UI/rendering integration
//!
//! This module provides the FrontendPlugin which handles all frontend communication
//! including rendering, input, and UI updates.
use crate::app::{App, Plugin, Update};
use crate::game::TerritoryManager;
use crate::ui::protocol::{BackendMessage, FrontendMessage};
use crate::ui::transport::{FrontendTransport, RenderBridge, emit_backend_messages_system, ingest_frontend_messages_system, send_initial_render_data, stream_spawn_preview_deltas, stream_territory_deltas};
use bevy_ecs::prelude::*;
/// Plugin to add frontend communication and UI systems to Bevy
pub struct FrontendPlugin<T: FrontendTransport> {
transport: T,
}
impl<T: FrontendTransport> FrontendPlugin<T> {
pub fn new(transport: T) -> Self {
Self { transport }
}
}
impl<T: FrontendTransport> Plugin for FrontendPlugin<T> {
fn build(&self, app: &mut App) {
let _guard = tracing::trace_span!("frontend_plugin_build").entered();
// Register message event types
app.add_message::<BackendMessage>();
app.add_message::<FrontendMessage>();
// Insert the bridge resource
app.insert_resource(RenderBridge::new(self.transport.clone()));
// Add render systems - must run AFTER turn execution to capture changes
app.add_systems(
Update,
(send_initial_render_data::<T>, stream_territory_deltas::<T>, stream_spawn_preview_deltas::<T>)
.chain()
// Ensure territory changes are processed before rendering
// (Both systems have early returns for their respective phases)
.after(crate::game::systems::update_player_borders_system),
);
// Add communication systems
app.add_systems(Update, (emit_backend_messages_system::<T>, ingest_frontend_messages_system::<T>, reset_bridge_on_quit_system::<T>));
}
}
/// System to reset the render bridge when a game is quit
/// This ensures fresh initialization data is sent when starting a new game
fn reset_bridge_on_quit_system<T: FrontendTransport>(territory_manager: Option<Res<TerritoryManager>>, mut bridge: ResMut<RenderBridge<T>>) {
// If TerritoryManager doesn't exist but bridge is initialized, reset it
if territory_manager.is_none() && bridge.initialized {
bridge.reset();
tracing::debug!("RenderBridge reset - ready for next game initialization");
}
}