souprune 0.5.1

A game framework designed specifically for Deltarune / Undertale fangames.
Documentation
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
//! # sequencer.rs
//!
//! # sequencer.rs 文件
//!
//! ## Module Overview
//!
//! ## 模块概述
//!
//! Sequencer is the linear sequence manager for the battle system.
//! It is responsible for managing and executing Chapters in the battle,
//! ensuring they proceed in order.
//!
//! Sequencer 是战斗系统的线性序列管理器。
//! 它负责管理和执行战斗中的章节(Chapter),确保它们按顺序进行。

/// Module for the battle sequencer.
///
/// 战斗系统的线性序列管理器。
pub(crate) struct SequencerPlugin;

impl Plugin for SequencerPlugin {
    fn build(&self, app: &mut App) {
        app.init_resource::<BattleContext>()
            .add_systems(OnEnter(AppState::Battle), load_default_chapter_system)
            .add_systems(
                Update,
                (
                    advance_battle_flow_system,
                    process_player_action_system,
                    process_camera_action_system,
                    process_ui_action_system,
                    process_danmaku_performance_system,
                    process_am_performance_system,
                    process_player_spawn_requests,
                    process_wait_chapter_system,
                    process_am_wait_chapter_system,
                    process_parallel_chapter_system,
                    cleanup_finished_chapters_system,
                    sync_battle_flow_system,
                )
                    .chain()
                    .in_set(BattleUpdate),
            );
    }
}

use super::am_integration::{AmPerformanceState, PlayAmPerformanceEvent};
use super::chapter::{Chapter, PlayerAction};
use super::danmaku::PlayPerformanceEvent;
use crate::app_state::AppState;
use crate::app_state::battle::config::BattlePlayerConfig;
use crate::app_state::battle::{BattleAsset, BattleUpdate};
use crate::core::danmaku::BulletTarget;
use crate::core::mod_system::{BehaviorParams, BehaviorVelocity};
use bevy::prelude::*;

#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
pub enum BattleExecutionState {
    #[default]
    Idle,
    Processing,
    Waiting,
}

/// [Resource] includes the queue of Chapters that have not yet occurred
///
/// [Resource] 存放还没发生的章节队列
#[derive(Resource, Default)]
pub struct BattleContext {
    pub chapters: Vec<Chapter>,
    pub state: BattleExecutionState,
}

#[derive(Component)]
struct ActiveChapter {
    chapter: Chapter,
    parent: Option<Entity>,
}

#[derive(Component)]
struct WaitTimer(Timer);

#[derive(Component)]
struct ParallelTracker {
    pending_count: usize,
}

#[derive(Resource)]
struct CurrentBattleFlow(Handle<BattleAsset>);

/// System to load the default chapter resource.
///
/// 加载默认章节资源的系统。
fn load_default_chapter_system(
    mut commands: Commands,
    asset_server: Res<AssetServer>,
    souprune_config: Res<crate::config::SoupruneConfig>,
) {
    let chapter_path = &souprune_config.game.initial_battle_path;
    let handle = asset_server.load::<BattleAsset>(chapter_path);
    commands.insert_resource(CurrentBattleFlow(handle));
    info!("Loading default battle flow: {}", chapter_path);
}

fn sync_battle_flow_system(
    mut commands: Commands,
    flow_handle: Option<Res<CurrentBattleFlow>>,
    mut context: ResMut<BattleContext>,
    assets: Res<Assets<BattleAsset>>,
) {
    if let Some(handle) = flow_handle
        && let Some(asset) = assets.get(&handle.0)
        && context.chapters.is_empty()
    {
        info!(
            "Battle flow loaded. Pushing {} chapters to queue.",
            asset.0.len()
        );
        context.chapters.extend(asset.0.clone());
        commands.remove_resource::<CurrentBattleFlow>();
    }
}

// Helper to spawn chapters
fn spawn_chapter(commands: &mut Commands, chapter: Chapter, parent: Option<Entity>) {
    let entity = commands
        .spawn(ActiveChapter {
            chapter: chapter.clone(),
            parent,
        })
        .id();

    match chapter {
        Chapter::Wait(secs) => {
            commands
                .entity(entity)
                .insert(WaitTimer(Timer::from_seconds(secs, TimerMode::Once)));
        }
        Chapter::Parallel(children) => {
            commands.entity(entity).insert(ParallelTracker {
                pending_count: children.len(),
            });
            for child in children {
                spawn_chapter(commands, child, Some(entity));
            }
        }
        Chapter::Sequence(children) => {
            if parent.is_some() {
                warn!("Nested Sequence not fully implemented yet, treating as Parallel for now");
                commands.entity(entity).insert(ParallelTracker {
                    pending_count: children.len(),
                });
                for child in children {
                    spawn_chapter(commands, child, Some(entity));
                }
            }
        }
        _ => {}
    }
}

/// System to advance the battle flow.
///
/// 推进战斗流程系统。
fn advance_battle_flow_system(
    mut commands: Commands,
    mut context: ResMut<BattleContext>,
    active_chapters: Query<&ActiveChapter>,
) {
    // Check if any root-level chapter is active
    // 检查是否有任何根级章节处于活动状态
    for chapter in active_chapters.iter() {
        if chapter.parent.is_none() {
            return;
        }
    }

    if context.chapters.is_empty() {
        return;
    }

    let next_chapter = context.chapters.remove(0);

    match next_chapter {
        Chapter::Sequence(sub_chapters) => {
            // Unpack sequence to the front of the queue
            let mut new_queue = sub_chapters;
            new_queue.append(&mut context.chapters);
            context.chapters = new_queue;
            // Loop again next frame to pick up the first item
        }
        _ => {
            info!("Starting Root Chapter: {:?}", next_chapter);
            spawn_chapter(&mut commands, next_chapter, None);
        }
    }
}

fn process_parallel_chapter_system(
    _commands: Commands,
    _parents: Query<(Entity, &mut ParallelTracker)>,
) {
    // Placeholder to keep the system chain happy if needed, or remove it.
    // Logic moved to cleanup_finished_chapters_system
}

#[derive(Component)]
struct ChapterFinished;

fn cleanup_finished_chapters_system(
    mut commands: Commands,
    finished_query: Query<(Entity, &ActiveChapter), With<ChapterFinished>>,
    mut parallel_parents: Query<&mut ParallelTracker>,
) {
    for (entity, chapter) in finished_query.iter() {
        if let Some(parent_entity) = chapter.parent
            && let Ok(mut tracker) = parallel_parents.get_mut(parent_entity)
        {
            tracker.pending_count = tracker.pending_count.saturating_sub(1);
            if tracker.pending_count == 0 {
                // Parent finished!
                commands.entity(parent_entity).insert(ChapterFinished);
            }
        }

        // Use despawn_recursive from Bevy's hierarchy extension
        // Since I cannot easily import it here without changing prelude usage,
        // and despawn_recursive is a trait method on EntityCommands.
        // It requires `bevy::hierarchy::DespawnRecursiveExt`.
        //
        // However, a simpler way in standard Bevy usage is usually commands.entity(e).despawn_recursive().
        // If it's not found, maybe I should just use despawn() if I don't expect children?
        // But Parallel chapters have children (though children despawn themselves).
        // The Parallel parent itself doesn't "own" children in ECS hierarchy (Transform parent),
        // it just tracks them via Entity ID.
        // So despawn() is fine.
        commands.entity(entity).despawn();
    }
}

fn process_wait_chapter_system(
    mut commands: Commands,
    mut query: Query<(Entity, &mut WaitTimer), Without<ChapterFinished>>,
    time: Res<Time>,
) {
    for (entity, mut timer) in query.iter_mut() {
        timer.0.tick(time.delta());
        if timer.0.is_finished() {
            commands.entity(entity).insert(ChapterFinished);
            info!("Wait Chapter finished.");
        }
    }
}

fn process_camera_action_system(
    mut commands: Commands,
    query: Query<(Entity, &ActiveChapter), (Without<WaitTimer>, Without<ChapterFinished>)>,
    mut camera_query: Query<
        (Entity, &mut Transform, &mut Projection),
        With<crate::app_state::battle::BattleCamera>,
    >,
    resolution_scale: Res<crate::app_state::app_setup::ResolutionScale>,
) {
    for (entity, active_chapter) in query.iter() {
        if let Chapter::SetCamera(action) = &active_chapter.chapter {
            for (_cam_entity, mut transform, mut proj) in camera_query.iter_mut() {
                match action {
                    super::chapter::CameraAction::SetPosition(pos) => {
                        transform.translation = pos.extend(transform.translation.z);
                    }
                    super::chapter::CameraAction::SetZoom(zoom) => {
                        if let Projection::Orthographic(ortho) = &mut *proj {
                            // Apply zoom relative to base resolution scale
                            // 相对于基础分辨率缩放应用缩放
                            ortho.scale = *zoom / resolution_scale.get() as f32;
                            info!(
                                "[Battle] SetZoom: requested={}, actual={}",
                                zoom, ortho.scale
                            );
                        }
                    }
                    _ => {
                        warn!("Camera action {:?} not implemented yet", action);
                    }
                }
            }
            commands.entity(entity).insert(ChapterFinished);
        }
    }
}

fn process_ui_action_system(
    mut commands: Commands,
    query: Query<(Entity, &ActiveChapter), (Without<WaitTimer>, Without<ChapterFinished>)>,
    asset_server: Res<AssetServer>,
) {
    for (entity, active_chapter) in query.iter() {
        if let Chapter::SetUI(action) = &active_chapter.chapter {
            match action {
                super::chapter::UIAction::LoadLayout(path) => {
                    let handle = asset_server.load(path);
                    commands.insert_resource(crate::core::ui::UILayoutHandle {
                        handle,
                        last_modified: None,
                    });
                    commands.spawn((
                        crate::core::ui::components::RonUI::new(
                            crate::core::ui::components::UILayer::BACKPACK_MENU,
                            0,
                        ),
                        Transform::default(),
                        GlobalTransform::default(),
                        Visibility::default(),
                        InheritedVisibility::default(),
                        ViewVisibility::default(),
                        crate::app_state::battle::BattleEntity,
                        Name::new("BattleUI Root"),
                    ));
                    commands.init_resource::<crate::core::ui::UILayoutWatcher>();
                }
                _ => {
                    warn!("UI action {:?} not fully implemented yet", action);
                }
            }
            commands.entity(entity).insert(ChapterFinished);
        } else if let Chapter::UIInteraction { ui_layout } = &active_chapter.chapter {
            info!("[Battle] Loading UI layout for battle: {}", ui_layout);
            let handle = asset_server.load(ui_layout);
            commands.insert_resource(crate::core::ui::UILayoutHandle {
                handle,
                last_modified: None,
            });
            commands.spawn((
                crate::core::ui::components::RonUI::new(
                    crate::core::ui::components::UILayer::BACKPACK_MENU,
                    0,
                ),
                Transform::default(),
                GlobalTransform::default(),
                Visibility::default(),
                InheritedVisibility::default(),
                ViewVisibility::default(),
                crate::app_state::battle::BattleEntity,
                Name::new("BattleUI Root"),
            ));
            commands.entity(entity).insert(ChapterFinished);
        }
    }
}

/// System to process DanmakuPerformance chapters.
///
/// 处理弹幕演出章节的系统。
fn process_danmaku_performance_system(
    mut commands: Commands,
    query: Query<(Entity, &ActiveChapter), (Without<WaitTimer>, Without<ChapterFinished>)>,
    mut performance_events: bevy::ecs::message::MessageWriter<PlayPerformanceEvent>,
) {
    for (entity, active_chapter) in query.iter() {
        if let Chapter::DanmakuPerformance {
            performance,
            position,
        } = &active_chapter.chapter
        {
            info!(
                "[Battle] Starting danmaku performance from: {}",
                performance
            );
            let mut event = PlayPerformanceEvent::new(performance.clone());
            if let Some((x, y)) = position {
                event = event.at_position(Vec2::new(*x, *y));
            }
            performance_events.write(event);
            commands.entity(entity).insert(ChapterFinished);
        }
    }
}

fn process_player_action_system(
    mut commands: Commands,
    query: Query<(Entity, &ActiveChapter), (Without<WaitTimer>, Without<ChapterFinished>)>,
    asset_server: Res<AssetServer>,
    mut player_query: Query<
        &mut Transform,
        (
            With<BehaviorParams>,
            With<crate::app_state::battle::BattleEntity>,
        ),
    >,
) {
    for (entity, active_chapter) in query.iter() {
        if let Chapter::SetPlayer(action) = &active_chapter.chapter {
            match action {
                PlayerAction::Spawn {
                    config_path,
                    position,
                } => {
                    let handle = asset_server.load::<BattlePlayerConfig>(config_path);
                    commands.spawn((
                        PlayerSpawnRequest {
                            config_handle: handle,
                            position: *position,
                        },
                        crate::app_state::battle::BattleEntity,
                    ));
                }
                PlayerAction::Teleport(pos) => {
                    for mut transform in player_query.iter_mut() {
                        transform.translation = pos.extend(0.0);
                        info!("Player teleported to {}", pos);
                    }
                }
                _ => {}
            }
            commands.entity(entity).insert(ChapterFinished);
        }
    }
}

#[derive(Component)]
struct PlayerSpawnRequest {
    config_handle: Handle<BattlePlayerConfig>,
    position: Vec2,
}

fn process_player_spawn_requests(
    mut commands: Commands,
    query: Query<(Entity, &PlayerSpawnRequest)>,
    configs: Res<Assets<BattlePlayerConfig>>,
    asset_server: Res<AssetServer>,
) {
    for (entity, req) in query.iter() {
        if let Some(config) = configs.get(&req.config_handle) {
            info!("Config loaded. Spawning player...");

            let physics_collider = match &config.physics_collider.shape {
                crate::app_state::battle::config::ColliderShape::Circle { radius } => {
                    crate::core::collision::PhysicsCollider::Circle { radius: *radius }
                }
                crate::app_state::battle::config::ColliderShape::Box { half_size } => {
                    crate::core::collision::PhysicsCollider::Box {
                        half_size: *half_size,
                    }
                }
            };

            let damage_trigger = match &config.damage_trigger.shape {
                crate::app_state::battle::config::ColliderShape::Circle { radius } => {
                    crate::core::collision::TriggerCollider::Circle { radius: *radius }
                }
                crate::app_state::battle::config::ColliderShape::Box { half_size } => {
                    crate::core::collision::TriggerCollider::Box {
                        half_size: *half_size,
                    }
                }
            };

            commands.spawn((
                Sprite {
                    image: asset_server.load(&config.sprite_path),
                    color: config.color,
                    ..default()
                },
                Transform::from_translation(req.position.extend(config.z_position)),
                physics_collider.clone(),
                damage_trigger.clone(),
                BehaviorParams {
                    mode_id: config.default_mode_id.clone(),
                },
                BehaviorVelocity::default(),
                BulletTarget::new(),
                crate::app_state::battle::BattleEntity,
                Name::new("BattlePlayer"),
            ));

            info!(
                "Spawned player with physics collider: {:?}, damage trigger: {:?}, at z: {}",
                physics_collider, damage_trigger, config.z_position
            );

            commands.entity(entity).despawn();
        }
    }
}

/// Marker component for AM performance chapter tracking
#[derive(Component)]
struct AmPerformanceTracker {
    wait_for_completion: bool,
    /// Whether we've seen the performance start (is_playing became true)
    started: bool,
}

/// System to process AmPerformance chapters.
///
/// 处理 AM 演出章节的系统。
fn process_am_performance_system(
    mut commands: Commands,
    query: Query<
        (Entity, &ActiveChapter),
        (
            Without<WaitTimer>,
            Without<ChapterFinished>,
            Without<AmPerformanceTracker>,
        ),
    >,
    mut performance_events: bevy::ecs::message::MessageWriter<PlayAmPerformanceEvent>,
) {
    for (entity, active_chapter) in query.iter() {
        if let Chapter::AmPerformance {
            amproj_path,
            wait_for_completion,
        } = &active_chapter.chapter
        {
            info!("[Battle] Starting AM performance from: {}", amproj_path);

            // Send event to start the AM performance
            performance_events.write(PlayAmPerformanceEvent::new(amproj_path.clone()));

            if *wait_for_completion {
                // Add tracker component to wait for completion
                commands.entity(entity).insert(AmPerformanceTracker {
                    wait_for_completion: true,
                    started: false,
                });
            } else {
                // Not waiting, mark as finished immediately
                commands.entity(entity).insert(ChapterFinished);
            }
        }
    }
}

/// System to check if AM performance has completed and finish the chapter.
///
/// 检查 AM 演出是否完成并结束章节的系统。
fn process_am_wait_chapter_system(
    mut commands: Commands,
    mut query: Query<(Entity, &mut AmPerformanceTracker), Without<ChapterFinished>>,
    am_state: Res<AmPerformanceState>,
) {
    for (entity, mut tracker) in query.iter_mut() {
        if !tracker.wait_for_completion {
            continue;
        }

        // Wait for performance to start first
        if am_state.is_playing {
            tracker.started = true;
        }

        // Only mark finished after performance has started and then stopped
        if tracker.started && !am_state.is_playing {
            info!("[Battle] AM performance chapter finished");
            commands.entity(entity).insert(ChapterFinished);
        }
    }
}