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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
//! # patterns.rs
//!
//! ## Module Overview
//!
//! Defines the DanmakuPerformance asset and related data structures for
//! the timeline-based danmaku system.
//!
//! 定义基于时间轴的弹幕系统的 DanmakuPerformance 资产和相关数据结构。

use bevy::prelude::*;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

// ============================================================================
// Default Value Functions
// ============================================================================

fn default_damage() -> f32 {
    1.0
}

fn default_lifetime() -> f32 {
    5.0
}

fn default_z_index() -> f32 {
    15.0
}

fn default_scale() -> f32 {
    1.0
}

fn default_frame_duration() -> f32 {
    0.05
}

fn default_linear_direction() -> (f32, f32) {
    (0.0, -1.0)
}

fn default_linear_speed() -> f32 {
    100.0
}

fn default_angular_velocity() -> f32 {
    1.0
}

fn default_sine_axis() -> (f32, f32) {
    (1.0, 0.0)
}

fn default_sine_amplitude() -> f32 {
    20.0
}

fn default_sine_frequency() -> f32 {
    2.0
}

fn default_line_spacing() -> f32 {
    20.0
}

fn default_edge_spacing() -> f32 {
    30.0
}

fn default_edge_margin() -> f32 {
    200.0
}

// ============================================================================
// Core Types: DanmakuPerformance (Timeline & Reference Architecture)
// ============================================================================

/// Danmaku Performance asset - defines a complete bullet pattern sequence.
/// Corresponds to a .performance.ron file.
///
/// 弹幕演出资产 - 定义完整的弹幕模式序列。
/// 对应 .performance.ron 文件。
#[derive(Asset, Debug, Clone, Deserialize, Serialize, Reflect)]
#[reflect(Debug)]
pub struct DanmakuPerformance {
    /// Bullet prototypes: ID -> visual/collision/damage data
    #[serde(default)]
    pub prototypes: HashMap<String, BulletPrototype>,

    /// Behavior definitions: ID -> BulletBehavior
    #[serde(default)]
    pub behaviors: HashMap<String, BulletBehavior>,

    /// Timeline: sequence of timed events
    pub timeline: Vec<TimelineEvent>,
}

// ============================================================================
// Bullet Prototype
// ============================================================================

/// Hit behavior preset for RON configuration.
/// Maps to BulletHitBehavior component at runtime.
///
/// RON 配置的命中行为预设。
/// 在运行时映射到 BulletHitBehavior 组件。
#[derive(Debug, Clone, Deserialize, Serialize, Reflect, Default)]
pub enum HitBehaviorPreset {
    /// Default: despawn on hit, damage always (default)
    #[default]
    Default,
    /// Persistent: doesn't despawn on hit, has i-frames
    Persistent,
    /// Blue soul style: damage only when player is moving
    DamageWhenMoving,
    /// Orange soul style: damage only when player is stationary
    DamageWhenStationary,
    /// Custom configuration
    Custom {
        #[serde(default = "default_despawn_on_hit")]
        despawn_on_hit: bool,
        #[serde(default)]
        damage_on_player_moving: bool,
        #[serde(default)]
        damage_on_player_stationary: bool,
        #[serde(default)]
        invincibility_duration: f32,
    },
}

fn default_despawn_on_hit() -> bool {
    true
}

/// Color tint configuration for bullets.
/// Supports hex color strings like "#FCA600".
///
/// 弹幕的颜色叠加配置。
/// 支持十六进制颜色字符串如 "#FCA600"。
#[derive(Debug, Clone, Deserialize, Serialize, Reflect, Default)]
pub struct ColorTint {
    /// Hex color string (e.g., "#FCA600" for orange, "#40FEFE" for blue)
    #[serde(default)]
    pub hex: String,
    /// RGBA values (0.0-1.0), used if hex is empty
    #[serde(default)]
    pub rgba: Option<(f32, f32, f32, f32)>,
}

impl ColorTint {
    /// Convert to Bevy Color
    pub fn to_color(&self) -> Option<Color> {
        if !self.hex.is_empty() {
            parse_hex_color(&self.hex)
        } else if let Some((r, g, b, a)) = self.rgba {
            Some(Color::srgba(r, g, b, a))
        } else {
            None
        }
    }
}

/// Parse hex color string to Color.
/// Supports formats: "#RGB", "#RGBA", "#RRGGBB", "#RRGGBBAA"
fn parse_hex_color(hex: &str) -> Option<Color> {
    let hex = hex.trim_start_matches('#');
    match hex.len() {
        3 => {
            // #RGB
            let r = u8::from_str_radix(&hex[0..1], 16).ok()? * 17;
            let g = u8::from_str_radix(&hex[1..2], 16).ok()? * 17;
            let b = u8::from_str_radix(&hex[2..3], 16).ok()? * 17;
            Some(Color::srgb_u8(r, g, b))
        }
        4 => {
            // #RGBA
            let r = u8::from_str_radix(&hex[0..1], 16).ok()? * 17;
            let g = u8::from_str_radix(&hex[1..2], 16).ok()? * 17;
            let b = u8::from_str_radix(&hex[2..3], 16).ok()? * 17;
            let a = u8::from_str_radix(&hex[3..4], 16).ok()? * 17;
            Some(Color::srgba_u8(r, g, b, a))
        }
        6 => {
            // #RRGGBB
            let r = u8::from_str_radix(&hex[0..2], 16).ok()?;
            let g = u8::from_str_radix(&hex[2..4], 16).ok()?;
            let b = u8::from_str_radix(&hex[4..6], 16).ok()?;
            Some(Color::srgb_u8(r, g, b))
        }
        8 => {
            // #RRGGBBAA
            let r = u8::from_str_radix(&hex[0..2], 16).ok()?;
            let g = u8::from_str_radix(&hex[2..4], 16).ok()?;
            let b = u8::from_str_radix(&hex[4..6], 16).ok()?;
            let a = u8::from_str_radix(&hex[6..8], 16).ok()?;
            Some(Color::srgba_u8(r, g, b, a))
        }
        _ => None,
    }
}

/// Bullet prototype - defines the appearance and collision of a bullet type.
///
/// 弹幕原型 - 定义弹幕类型的外观和碰撞。
#[derive(Debug, Clone, Deserialize, Serialize, Reflect)]
pub struct BulletPrototype {
    /// Visual representation
    pub visual: BulletVisual,

    /// Collision shape
    #[serde(default)]
    pub collider: ColliderShape,

    /// Base damage
    #[serde(default = "default_damage")]
    pub damage: f32,

    /// Lifetime in seconds
    #[serde(default = "default_lifetime")]
    pub lifetime: f32,

    /// Z-index for rendering order
    #[serde(default = "default_z_index")]
    pub z_index: f32,

    /// Scale factor (default: 1.0)
    #[serde(default = "default_scale")]
    pub scale: f32,

    /// Hit behavior configuration (default: despawn on hit)
    #[serde(default)]
    pub hit_behavior: HitBehaviorPreset,

    /// Color tint overlay (for blue/orange soul bullets)
    /// Empty hex string means no tint
    #[serde(default)]
    pub color_tint: ColorTint,
}

/// Visual representation of a bullet.
///
/// 弹幕的视觉表现。
#[derive(Debug, Clone, Deserialize, Serialize, Reflect)]
pub enum BulletVisual {
    /// Static sprite image by direct path (legacy)
    Sprite { path: String },
    /// Static sprite by reference to config.toml sprite name
    SpriteRef { module: String, name: String },
    /// Animated sprite (references animation name in config.toml)
    Animation {
        module: String,
        name: String,
        #[serde(default = "default_frame_duration")]
        frame_duration: f32,
    },
}

/// Collider shape for hit detection.
///
/// 碰撞形状用于命中检测。
#[derive(Debug, Clone, Deserialize, Serialize, Reflect)]
pub enum ColliderShape {
    CircleCollider(f32),
    BoxCollider(f32, f32),
}

impl Default for ColliderShape {
    fn default() -> Self {
        ColliderShape::CircleCollider(4.0)
    }
}

// ============================================================================
// Bullet Behavior
// ============================================================================

/// Bullet behavior definition.
/// Supports both built-in algorithms and custom FFI algorithms.
///
/// 弹幕行为定义。
/// 同时支持内置算法和自定义 FFI 算法。
#[derive(Debug, Clone, Deserialize, Serialize, Reflect)]
pub enum BulletBehavior {
    // === Built-in Behaviors (内置行为) ===
    /// Linear motion in a direction
    Linear(LinearConfig),

    /// Tween animation (opacity, scale, position, etc.)
    Tween(TweenConfig),

    /// Orbital motion around spawn center (rotation + radial movement)
    Orbital(OrbitalConfig),

    /// Sinusoidal oscillation
    Sine(SineConfig),

    // === Custom Behavior (自定义行为) ===
    /// Algorithm loaded from mod system via FFI
    Custom {
        /// Algorithm ID registered in DanmakuRegistry
        id: String,
        /// Properties passed to the algorithm
        #[serde(default)]
        props: HashMap<String, f32>,
    },
}

/// Linear motion configuration.
#[derive(Debug, Clone, Deserialize, Serialize, Reflect)]
pub struct LinearConfig {
    #[serde(default = "default_linear_direction")]
    pub dir: (f32, f32),
    #[serde(default = "default_linear_speed")]
    pub speed: f32,
}

impl Default for LinearConfig {
    fn default() -> Self {
        Self {
            dir: default_linear_direction(),
            speed: default_linear_speed(),
        }
    }
}

/// Orbital motion configuration (rotation around spawn center).
///
/// 轨道运动配置(围绕生成中心旋转)。
#[derive(Debug, Clone, Deserialize, Serialize, Reflect)]
pub struct OrbitalConfig {
    #[serde(default = "default_angular_velocity")]
    pub angular_velocity: f32,
    #[serde(default)]
    pub radial_velocity: f32,
}

impl Default for OrbitalConfig {
    fn default() -> Self {
        Self {
            angular_velocity: default_angular_velocity(),
            radial_velocity: 0.0,
        }
    }
}

/// Sine wave configuration.
#[derive(Debug, Clone, Deserialize, Serialize, Reflect)]
pub struct SineConfig {
    #[serde(default = "default_sine_axis")]
    pub axis: (f32, f32),
    #[serde(default = "default_sine_amplitude")]
    pub amplitude: f32,
    #[serde(default = "default_sine_frequency")]
    pub frequency: f32,
    #[serde(default)]
    pub phase: f32,
}

impl Default for SineConfig {
    fn default() -> Self {
        Self {
            axis: default_sine_axis(),
            amplitude: default_sine_amplitude(),
            frequency: default_sine_frequency(),
            phase: 0.0,
        }
    }
}

/// Tween animation configuration.
#[derive(Debug, Clone, Deserialize, Serialize, Reflect)]
pub struct TweenConfig {
    /// Target property to animate
    pub target: TweenTarget,
    /// Duration in seconds
    pub duration: f32,
    /// Easing function
    #[serde(default)]
    pub ease: Easing,
    /// Value range (start, end)
    pub range: (f32, f32),
    /// Delay before starting
    #[serde(default)]
    pub delay: f32,
}

/// Tween target properties.
#[derive(Debug, Clone, Copy, Deserialize, Serialize, Reflect, Default)]
pub enum TweenTarget {
    #[default]
    Opacity,
    Scale,
    ScaleX,
    ScaleY,
    PositionX,
    PositionY,
    Rotation,
}

/// Easing functions for interpolation.
#[derive(Debug, Clone, Copy, Deserialize, Serialize, Default, Reflect)]
pub enum Easing {
    #[default]
    Linear,
    QuadIn,
    QuadOut,
    QuadInOut,
    CubicIn,
    CubicOut,
    CubicInOut,
    SineIn,
    SineOut,
    SineInOut,
}

impl Easing {
    pub fn apply(self, t: f32) -> f32 {
        match self {
            Easing::Linear => t,
            Easing::QuadIn => t * t,
            Easing::QuadOut => 1.0 - (1.0 - t) * (1.0 - t),
            Easing::QuadInOut => {
                if t < 0.5 {
                    2.0 * t * t
                } else {
                    1.0 - (-2.0 * t + 2.0).powi(2) / 2.0
                }
            }
            Easing::CubicIn => t * t * t,
            Easing::CubicOut => 1.0 - (1.0 - t).powi(3),
            Easing::CubicInOut => {
                if t < 0.5 {
                    4.0 * t * t * t
                } else {
                    1.0 - (-2.0 * t + 2.0).powi(3) / 2.0
                }
            }
            Easing::SineIn => 1.0 - (t * std::f32::consts::FRAC_PI_2).cos(),
            Easing::SineOut => (t * std::f32::consts::FRAC_PI_2).sin(),
            Easing::SineInOut => -(t * std::f32::consts::PI).cos() / 2.0 + 0.5,
        }
    }
}

// ============================================================================
// Timeline Event
// ============================================================================

/// Timeline event - describes what happens at a specific time.
///
/// 时间轴事件 - 描述在特定时间发生的事情。
#[derive(Debug, Clone, Deserialize, Serialize, Reflect)]
pub struct TimelineEvent {
    /// Time in seconds from performance start.
    /// By default this is relative time (delta from previous event).
    /// Set `absolute: true` to use absolute time from performance start.
    ///
    /// 距演出开始的时间(秒)。
    /// 默认为相对时间(与上一事件的时间差)。
    /// 设置 `absolute: true` 使用距演出开始的绝对时间。
    pub t: f32,

    /// Whether t is absolute time (from performance start) or relative (from previous event).
    /// Default is false (relative time).
    ///
    /// t 是否为绝对时间(从演出开始)还是相对时间(从上一事件)。
    /// 默认为 false(相对时间)。
    #[serde(default)]
    pub absolute: bool,

    /// Prototype ID to spawn
    pub spawn: String,

    /// Spawn pattern (built-in geometric patterns)
    #[serde(default)]
    pub pattern: SpawnPattern,

    /// List of behavior IDs to apply (references to `behaviors` map)
    #[serde(default)]
    pub apply: Vec<String>,

    /// Inline behavior definitions (applied after referenced behaviors)
    /// Use this for one-off behaviors that don't need to be reused.
    ///
    /// 内联行为定义(在引用行为之后应用)
    /// 用于不需要复用的一次性行为。
    #[serde(default)]
    pub behaviors: Vec<BulletBehavior>,
}

/// Spawn pattern for timeline events.
/// Built-in geometric patterns for bullet arrangement.
///
/// 时间轴事件的生成模式。
/// 内置的几何图案用于弹幕排列。
#[derive(Debug, Clone, Deserialize, Serialize, Reflect, Default)]
pub enum SpawnPattern {
    /// Spawn a single bullet at center
    #[default]
    Single,

    /// Spawn bullets in a ring/circle
    RingGenerator {
        count: usize,
        #[serde(default)]
        radius: f32,
        #[serde(default)]
        start_angle: f32,
    },

    /// Spawn bullets in a line
    LineGenerator {
        count: usize,
        #[serde(default = "default_line_spacing")]
        spacing: f32,
        #[serde(default = "default_linear_direction")]
        direction: (f32, f32),
    },

    /// Spawn bullets from a screen edge
    EdgeGenerator {
        count: usize,
        #[serde(default)]
        side: EdgeSide,
        #[serde(default = "default_edge_spacing")]
        spacing: f32,
        #[serde(default = "default_edge_margin")]
        margin: f32,
    },

    /// Custom spawn pattern from mod system
    CustomGenerator {
        id: String,
        #[serde(default)]
        params: HashMap<String, f32>,
    },
}

/// Which screen edge to spawn from.
#[derive(Debug, Clone, Copy, Deserialize, Serialize, Default, Reflect)]
pub enum EdgeSide {
    #[default]
    Left,
    Right,
    Top,
    Bottom,
}

impl EdgeSide {
    pub fn to_direction(self) -> Vec2 {
        match self {
            EdgeSide::Left => Vec2::new(1.0, 0.0),
            EdgeSide::Right => Vec2::new(-1.0, 0.0),
            EdgeSide::Top => Vec2::new(0.0, -1.0),
            EdgeSide::Bottom => Vec2::new(0.0, 1.0),
        }
    }

    pub fn to_offset(self, margin: f32) -> Vec2 {
        match self {
            EdgeSide::Left => Vec2::new(-margin, 0.0),
            EdgeSide::Right => Vec2::new(margin, 0.0),
            EdgeSide::Top => Vec2::new(0.0, margin),
            EdgeSide::Bottom => Vec2::new(0.0, -margin),
        }
    }
}

// ============================================================================
// Runtime Resources and Events
// ============================================================================

/// Resource tracking pending performance loads.
#[derive(Resource, Default)]
pub struct PendingPerformanceLoads {
    pub pending: Vec<(Handle<DanmakuPerformance>, PlayPerformanceEvent)>,
}

/// Event to play a danmaku performance.
///
/// 播放弹幕演出的事件。
#[derive(bevy::ecs::message::Message, Clone)]
pub struct PlayPerformanceEvent {
    /// Path to the .performance.ron file
    pub performance_path: String,
    /// Center position for the performance
    pub position: Vec2,
}

impl PlayPerformanceEvent {
    pub fn new(performance_path: impl Into<String>) -> Self {
        Self {
            performance_path: performance_path.into(),
            position: Vec2::ZERO,
        }
    }

    pub fn at_position(mut self, position: Vec2) -> Self {
        self.position = position;
        self
    }
}