Skip to main content

sim_logic/application/
transition.rs

1//! No-payload World replacement helpers and deterministic arbitration.
2
3use bevy_ecs::prelude::{Res, Resource};
4
5use crate::{
6    commands::{CommandEnqueueError, LogicCommands},
7    identity::{TransitionIntentToken, WorldFactoryId},
8    input::{Action, FixedInput},
9};
10
11/// One World-owned route from a fixed input press to World replacement.
12///
13/// The descriptor is inert until
14/// [`crate::app::Application::add_world_replacement_on_press_system`] is
15/// registered. That adapter observes every matching press occurrence in
16/// FixedUpdate and forwards the occurrence's runtime-issued causal token to
17/// the ordinary deferred World-replacement command path. Physical key binding
18/// remains separate application configuration.
19///
20/// A route belongs only to the World containing this Resource and disappears
21/// when that World is replaced. Applications needing conditional navigation,
22/// multiple destinations, payloads, or FrameUpdate timing should use an
23/// ordinary System instead.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Resource)]
25pub struct WorldReplacementOnPress<A: Action> {
26    action: A,
27    target: WorldFactoryId,
28}
29
30impl<A: Action> WorldReplacementOnPress<A> {
31    /// Creates one infallible action-to-factory route.
32    ///
33    /// Factory provenance is checked by the existing transition runtime only
34    /// when a matching press requests replacement. Replace the complete Copy
35    /// Resource through `ResMut` when an earlier System must change both route
36    /// fields atomically.
37    pub const fn new(action: A, target: WorldFactoryId) -> Self {
38        Self { action, target }
39    }
40
41    /// Returns the logical action whose press occurrences request replacement.
42    pub const fn action(&self) -> A {
43        self.action
44    }
45
46    /// Returns the opaque registered World factory selected by this route.
47    pub const fn target(&self) -> WorldFactoryId {
48        self.target
49    }
50}
51
52pub(crate) fn replace_world_on_press<A: Action>(
53    input: FixedInput<A>,
54    route: Option<Res<WorldReplacementOnPress<A>>>,
55    mut commands: LogicCommands,
56) -> Result<(), CommandEnqueueError> {
57    let Some(route) = route else {
58        return Ok(());
59    };
60    for edge in input.pressed(route.action) {
61        commands.replace_world(edge.intent(), route.target)?;
62    }
63    Ok(())
64}
65
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub(crate) struct TransitionRequest {
68    intent: TransitionIntentToken,
69    target: WorldFactoryId,
70}
71
72impl TransitionRequest {
73    pub(crate) const fn new(intent: TransitionIntentToken, target: WorldFactoryId) -> Self {
74        Self { intent, target }
75    }
76
77    pub(crate) const fn intent(self) -> TransitionIntentToken {
78        self.intent
79    }
80
81    pub(crate) const fn target(self) -> WorldFactoryId {
82        self.target
83    }
84}
85
86/// Diagnostic emitted when independent causes converge on the same World.
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub struct ConvergentTransitionWarning {
89    distinct_intents: usize,
90}
91
92impl ConvergentTransitionWarning {
93    /// Returns the number of distinct causal tokens that requested the target.
94    pub const fn distinct_intents(self) -> usize {
95        self.distinct_intents
96    }
97}
98
99/// Reason an otherwise well-formed transition batch did not select a target.
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub enum TransitionRejection {
102    /// One causal token was reused for different targets.
103    MalformedIntent,
104    /// Independent causal tokens selected different targets.
105    Conflict,
106}
107
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109pub(crate) enum TransitionArbitration {
110    None,
111    Replace {
112        target: WorldFactoryId,
113        warning: Option<ConvergentTransitionWarning>,
114    },
115    Rejected(TransitionRejection),
116}
117
118pub(crate) fn arbitrate(requests: &[TransitionRequest]) -> TransitionArbitration {
119    let Some(first) = requests.first().copied() else {
120        return TransitionArbitration::None;
121    };
122
123    for (index, request) in requests.iter().enumerate() {
124        if requests[..index]
125            .iter()
126            .any(|earlier| earlier.intent == request.intent && earlier.target != request.target)
127        {
128            return TransitionArbitration::Rejected(TransitionRejection::MalformedIntent);
129        }
130    }
131
132    if requests
133        .iter()
134        .any(|request| request.target != first.target)
135    {
136        return TransitionArbitration::Rejected(TransitionRejection::Conflict);
137    }
138
139    let distinct_intents = requests
140        .iter()
141        .enumerate()
142        .filter(|(index, request)| {
143            !requests[..*index]
144                .iter()
145                .any(|earlier| earlier.intent == request.intent)
146        })
147        .count();
148
149    TransitionArbitration::Replace {
150        target: first.target,
151        warning: (distinct_intents > 1).then_some(ConvergentTransitionWarning { distinct_intents }),
152    }
153}
154
155#[cfg(test)]
156mod tests {
157    use crate::identity::{ApplicationId, WorldGeneration};
158
159    use super::*;
160
161    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
162    enum TestAction {
163        Continue,
164    }
165
166    fn factory(application: ApplicationId, slot: u32) -> WorldFactoryId {
167        WorldFactoryId::new(application, slot, 1)
168    }
169
170    fn intent(application: ApplicationId, occurrence: u64) -> TransitionIntentToken {
171        TransitionIntentToken::direct(
172            application,
173            WorldGeneration::new(application, 1),
174            9,
175            occurrence,
176        )
177    }
178
179    #[test]
180    fn replacement_on_press_preserves_its_action_and_opaque_target() {
181        let application = ApplicationId::from_raw(1);
182        let target = factory(application, 3);
183        let route = WorldReplacementOnPress::new(TestAction::Continue, target);
184
185        assert_eq!(route.action(), TestAction::Continue);
186        assert_eq!(route.target(), target);
187        assert_eq!(route, route);
188        let copied = route;
189        assert_eq!(copied, route);
190    }
191
192    #[test]
193    fn same_intent_and_target_coalesce() {
194        let application = ApplicationId::from_raw(1);
195        let target = factory(application, 0);
196        let intent = intent(application, 1);
197        let requests = [
198            TransitionRequest::new(intent, target),
199            TransitionRequest::new(intent, target),
200        ];
201
202        assert_eq!(
203            arbitrate(&requests),
204            TransitionArbitration::Replace {
205                target,
206                warning: None,
207            }
208        );
209    }
210
211    #[test]
212    fn same_intent_with_different_targets_is_malformed() {
213        let application = ApplicationId::from_raw(1);
214        let intent = intent(application, 1);
215        let requests = [
216            TransitionRequest::new(intent, factory(application, 0)),
217            TransitionRequest::new(intent, factory(application, 1)),
218        ];
219
220        assert_eq!(
221            arbitrate(&requests),
222            TransitionArbitration::Rejected(TransitionRejection::MalformedIntent)
223        );
224    }
225
226    #[test]
227    fn different_intents_with_same_target_converge() {
228        let application = ApplicationId::from_raw(1);
229        let target = factory(application, 0);
230        let requests = [
231            TransitionRequest::new(intent(application, 1), target),
232            TransitionRequest::new(intent(application, 2), target),
233        ];
234
235        assert_eq!(
236            arbitrate(&requests),
237            TransitionArbitration::Replace {
238                target,
239                warning: Some(ConvergentTransitionWarning {
240                    distinct_intents: 2,
241                }),
242            }
243        );
244    }
245
246    #[test]
247    fn different_intents_with_different_targets_conflict() {
248        let application = ApplicationId::from_raw(1);
249        let requests = [
250            TransitionRequest::new(intent(application, 1), factory(application, 0)),
251            TransitionRequest::new(intent(application, 2), factory(application, 1)),
252        ];
253
254        assert_eq!(
255            arbitrate(&requests),
256            TransitionArbitration::Rejected(TransitionRejection::Conflict)
257        );
258    }
259}