Skip to main content

manabrew_engine/replacement/
replace_moved.rs

1//! Replacement logic for `Event$ Moved`.
2//!
3//! Mirrors Java `ReplaceMoved.java` in `forge/game/replacement/`.
4
5use std::collections::HashMap;
6
7use forge_foundation::ZoneType;
8
9use crate::ability::effects::{self, EffectContext};
10use crate::agent::{PassAgent, PlayerAgent};
11use crate::card::Card;
12use crate::game::GameState;
13use crate::game_rng::ThreadRngAdapter;
14use crate::ids::CardId;
15use crate::mana::ManaPool;
16use crate::spellability::build_spell_ability;
17use crate::trigger::TriggerHandler;
18
19use super::replacement_effect::{zone_matches, ReplacementEffect};
20use super::replacement_handler::{ReplacementEvent, ReplacementRuntime};
21use super::replacement_result::ReplacementResult;
22use super::replacement_type::ReplacementType;
23use crate::card_trait_base::CardTrait;
24
25/// Mirrors Java `ReplaceMoved.canReplace()`.
26pub fn can_replace(
27    effect: &ReplacementEffect,
28    event: &ReplacementEvent,
29    game: &GameState,
30    source_card: &Card,
31) -> bool {
32    if effect.event != ReplacementType::Moved {
33        return false;
34    }
35    let (moving_id, origin, destination, is_discard) = match event {
36        ReplacementEvent::Moved {
37            card,
38            origin,
39            destination,
40            is_discard,
41            ..
42        } => (*card, *origin, *destination, *is_discard),
43        _ => return false,
44    };
45    // Discard$ True — only match when the move is from a discard action.
46    // Mirrors Java ReplaceMoved.canReplace() Discard$ check.
47    if let Some(requires_discard) = effect.ir.discard {
48        if requires_discard != is_discard {
49            return false;
50        }
51    }
52    if let Some(dest) = effect.ir.destination_text.as_deref() {
53        if !zone_matches(dest, destination) {
54            return false;
55        }
56    }
57    if let Some(exclude) = effect.ir.exclude_destination_text.as_deref() {
58        if zone_matches(exclude, destination) {
59            return false;
60        }
61    }
62    if let Some(orig) = effect.ir.origin_text.as_deref() {
63        if !zone_matches(orig, origin) {
64            return false;
65        }
66    }
67    let moving_card = &game.cards[moving_id.index()];
68    if let Some(fizzle) = effect.ir.fizzle {
69        if game.stack.resolving_fizzle(moving_id) != Some(fizzle) {
70            return false;
71        }
72    }
73    if let Some(valid) = effect.ir.valid_stack_sa_text.as_deref() {
74        if !moving_card.cast_sa.as_deref().is_some_and(|sa| {
75            crate::spellability::matches_valid_sa(valid, sa, source_card, Some(moving_card))
76        }) {
77            return false;
78        }
79    }
80    if let Some(valid) = effect.ir.valid_card_selector.as_ref() {
81        if !effect.matches_compiled_valid_card(valid, moving_card, source_card) {
82            return false;
83        }
84    }
85    // FlashbackCast$ True — only match when the card was cast via Flashback.
86    if effect.ir.flashback_cast == Some(true) && !moving_card.cast_with_flashback {
87        return false;
88    }
89    // HarmonizeCast$ True — only match when the card was cast via Harmonize.
90    if effect.ir.harmonize_cast == Some(true) && !moving_card.cast_with_harmonize {
91        return false;
92    }
93    if let Some(valid_lki) = effect.ir.valid_lki_text.as_deref() {
94        if !effect.matches_valid_card(valid_lki, moving_card, source_card) {
95            return false;
96        }
97    }
98    // Mirrors Java `ReplaceMoved.canReplace()` L103: only gate ETB chains.
99    destination != ZoneType::Battlefield || effect.can_replace_etb(source_card, moving_card)
100}
101
102/// Mirrors Java `ReplacementHandler.executeReplacement()` for Moved.
103pub fn execute(
104    effect: &ReplacementEffect,
105    event: &mut ReplacementEvent,
106    game: &mut GameState,
107    source_card_id: CardId,
108    agents: Option<&mut [Box<dyn PlayerAgent>]>,
109    runtime: Option<&mut ReplacementRuntime<'_>>,
110) -> ReplacementResult {
111    let (moving_id, _destination) = match event {
112        ReplacementEvent::Moved {
113            card, destination, ..
114        } => (*card, destination),
115        _ => return ReplacementResult::NotReplaced,
116    };
117    // Check NewDestination$ first (explicit redirect), then ReplaceWith$ (common alias).
118    // Rest in Peace uses "ReplaceWith$ Exile", while other cards use "NewDestination$ Exile".
119    let redirect = effect
120        .ir
121        .new_destination_text
122        .as_deref()
123        .or(effect.replace_with());
124
125    if let Some(new_dest) = redirect {
126        let new_zone = match new_dest.trim() {
127            "Exile" => Some(ZoneType::Exile),
128            "Graveyard" => Some(ZoneType::Graveyard),
129            "Hand" => Some(ZoneType::Hand),
130            "Library" => Some(ZoneType::Library),
131            "Battlefield" => Some(ZoneType::Battlefield),
132            "Command" => Some(ZoneType::Command),
133            _ => None,
134        };
135        if let Some(z) = new_zone {
136            if let ReplacementEvent::Moved { destination, .. } = event {
137                *destination = z;
138            }
139            if effect.ir.valid_stack_sa_text.as_deref() == Some("Spell.Adventure")
140                && z == ZoneType::Exile
141                && !game.card(moving_id).is_token
142            {
143                game.card_mut(moving_id).on_adventure = true;
144            }
145            if z == ZoneType::Exile && effect.ir.exiled_with_effect_source {
146                let exile_source = game
147                    .card(source_card_id)
148                    .effect_source
149                    .unwrap_or(source_card_id);
150                game.card_mut(moving_id).set_exiled_by(Some(exile_source));
151                game.card_mut(exile_source).add_remembered_card(moving_id);
152            }
153            return ReplacementResult::Updated;
154        }
155    }
156    // If the redirect value wasn't a zone name, try executing it as an SVar spell ability.
157    if let Some(replace_with_key) = effect.replace_with() {
158        let succeeded = execute_replace_with(
159            effect,
160            replace_with_key,
161            game,
162            source_card_id,
163            event,
164            agents,
165            runtime,
166        );
167        if !succeeded {
168            return ReplacementResult::NotReplaced;
169        }
170    }
171    if let Some(result) = effect.ir.replacement_result.as_deref() {
172        return match result {
173            "Updated" => ReplacementResult::Updated,
174            "Replaced" => ReplacementResult::Replaced,
175            "Skipped" => ReplacementResult::Skipped,
176            "Prevented" => ReplacementResult::Prevented,
177            _ => ReplacementResult::Replaced,
178        };
179    }
180    ReplacementResult::Replaced
181}
182
183fn execute_replace_with(
184    effect: &ReplacementEffect,
185    replace_with: &str,
186    game: &mut GameState,
187    source_card_id: CardId,
188    event: &ReplacementEvent,
189    agents: Option<&mut [Box<dyn PlayerAgent>]>,
190    mut runtime: Option<&mut ReplacementRuntime<'_>>,
191) -> bool {
192    let Some(raw) = game.card(source_card_id).svars.get(replace_with).cloned() else {
193        return false;
194    };
195    let controller = game.card(source_card_id).controller;
196    let mut sa = build_spell_ability(game, source_card_id, &raw, controller);
197    effect.set_replacing_objects(event, &mut sa);
198
199    // `local_agents_storage` keeps the fallback Vec alive when the caller
200    // didn't provide agents; we hand back a borrow into it.
201    #[allow(unused_assignments)]
202    let mut local_agents_storage: Option<Vec<Box<dyn PlayerAgent>>> = None;
203    let agents: &mut [Box<dyn PlayerAgent>] = if let Some(agents) = agents {
204        agents
205    } else {
206        local_agents_storage = Some(
207            (0..game.players.len())
208                .map(|_| Box::new(PassAgent) as Box<dyn PlayerAgent>)
209                .collect(),
210        );
211        local_agents_storage.as_mut().unwrap().as_mut_slice()
212    };
213
214    let mut local_mana_pools: Vec<ManaPool> =
215        (0..game.players.len()).map(|_| ManaPool::new()).collect();
216    let mana_pools_for_targets: &[ManaPool] = if let Some(rt) = runtime.as_ref() {
217        rt.mana_pools.as_slice()
218    } else {
219        local_mana_pools.as_slice()
220    };
221    if sa.uses_targeting() && !sa.setup_targets(game, agents, mana_pools_for_targets) {
222        return false;
223    }
224
225    let mut local_trigger_handler = TriggerHandler::new();
226    let local_token_templates: HashMap<String, Card> = HashMap::new();
227    let local_token_art_variants: HashMap<(String, String), usize> = HashMap::new();
228    let local_token_fallback: HashMap<String, String> = HashMap::new();
229    let local_edition_dates: HashMap<String, String> = HashMap::new();
230    let mut local_rng = ThreadRngAdapter;
231
232    let mut parent_target_card: Option<CardId> = None;
233    let mut parent_target_player = None;
234    let mut current_sa: Option<&crate::spellability::SpellAbility> = Some(&sa);
235    while let Some(cur) = current_sa {
236        let mut sa_with_ctx;
237        let sa_ref = if parent_target_player.is_some() && cur.target_chosen.target_player.is_none()
238        {
239            sa_with_ctx = cur.clone();
240            sa_with_ctx.target_chosen.target_player = parent_target_player;
241            &sa_with_ctx
242        } else {
243            cur
244        };
245
246        let (
247            trigger_handler_ref,
248            token_templates_ref,
249            token_art_ref,
250            token_fb_ref,
251            edition_dates_ref,
252            mana_pools_ref,
253            rng_ref,
254        ): (
255            &mut TriggerHandler,
256            &HashMap<String, Card>,
257            &HashMap<(String, String), usize>,
258            &HashMap<String, String>,
259            &HashMap<String, String>,
260            &mut Vec<ManaPool>,
261            &mut dyn crate::game_rng::GameRng,
262        ) = if let Some(rt) = runtime.as_deref_mut() {
263            (
264                rt.trigger_handler,
265                rt.token_templates,
266                rt.token_art_variants,
267                rt.token_fallback,
268                rt.edition_dates,
269                rt.mana_pools,
270                rt.rng,
271            )
272        } else {
273            (
274                &mut local_trigger_handler,
275                &local_token_templates,
276                &local_token_art_variants,
277                &local_token_fallback,
278                &local_edition_dates,
279                &mut local_mana_pools,
280                &mut local_rng,
281            )
282        };
283
284        let mut ctx = EffectContext {
285            game,
286            combat: None,
287            agents,
288            trigger_handler: trigger_handler_ref,
289            token_templates: token_templates_ref,
290            token_art_variants: token_art_ref,
291            token_fallback: token_fb_ref,
292            edition_dates: edition_dates_ref,
293            mana_pools: mana_pools_ref,
294            parent_target_card,
295            rng: rng_ref,
296        };
297        effects::resolve_effect(&mut ctx, sa_ref);
298        parent_target_card = sa_ref.target_chosen.target_card;
299        parent_target_player = sa_ref.target_chosen.target_player;
300        current_sa = cur.get_sub_ability();
301    }
302    true
303}
304
305// `set_replacing_objects_for_moved` was inlined into the cross-event
306// `ReplacementEffect::set_replacing_objects` dispatcher in `replacement_effect.rs`
307// to mirror Java's polymorphic `setReplacingObjects` hook.