issun 0.10.0

A mini game engine for logic-focused games - Build games in ISSUN (一寸) of time
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
//! World map system for orchestrating travel

use super::config::WorldMapConfig;
use super::hook::WorldMapHook;
use super::registry::WorldMapRegistry;
use super::service::WorldMapService;
use super::state::WorldMapState;
use super::types::*;
use crate::system::System;
use async_trait::async_trait;
use std::any::Any;
use std::sync::Arc;

/// World map system (event-driven travel orchestration)
#[derive(Clone)]
#[allow(dead_code)]
pub struct WorldMapSystem {
    hook: Arc<dyn WorldMapHook>,
    service: WorldMapService,
}

#[async_trait]
impl System for WorldMapSystem {
    fn name(&self) -> &'static str {
        "issun:worldmap_system"
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
}

impl WorldMapSystem {
    /// Create a new world map system
    pub fn new(hook: Arc<dyn WorldMapHook>) -> Self {
        Self {
            hook,
            service: WorldMapService,
        }
    }

    /// Update all active travels
    ///
    /// # Arguments
    ///
    /// * `state` - World map state
    /// * `registry` - World map registry
    /// * `config` - World map configuration
    /// * `delta_time` - Time elapsed since last update (seconds)
    ///
    /// # Returns
    ///
    /// Vector of travel events
    pub async fn update(
        &mut self,
        state: &mut WorldMapState,
        registry: &WorldMapRegistry,
        config: &WorldMapConfig,
        delta_time: f32,
    ) -> Vec<TravelEvent> {
        let mut events = Vec::new();

        // Update all travels
        let completed = state.update_travels(delta_time);

        // Process completions
        for complete in completed {
            // Notify hook
            self.hook
                .on_travel_completed(&complete.entity_id, &complete.destination)
                .await;

            events.push(TravelEvent::Arrived {
                entity_id: complete.entity_id.clone(),
                location_id: complete.destination.clone(),
            });

            // Discover location (if fog of war enabled)
            if config.enable_fog_of_war {
                events.push(TravelEvent::LocationDiscovered {
                    entity_id: complete.entity_id,
                    location_id: complete.destination,
                });
            }
        }

        // Check for encounters
        let active_travels: Vec<(EntityId, Travel)> = state
            .travels()
            .iter()
            .map(|(id, travel)| (id.clone(), travel.clone()))
            .collect();

        for (entity_id, travel) in active_travels {
            if travel.status != TravelStatus::InProgress {
                continue;
            }

            if let Some(route) = registry.get_route(&travel.route_id) {
                // Check if encounter should trigger
                if self.should_check_encounter(&travel, route, config) {
                    if let Some(encounter) = self
                        .hook
                        .generate_encounter(&entity_id, &travel, route)
                        .await
                    {
                        // Add encounter to travel
                        if let Some(t) = state.get_travel_mut(&entity_id) {
                            t.encounters.push(encounter.id.clone());
                            t.status = TravelStatus::Interrupted;
                        }

                        events.push(TravelEvent::EncounterTriggered {
                            entity_id,
                            encounter,
                        });
                    }
                }
            }
        }

        events
    }

    /// Start a new travel
    ///
    /// # Arguments
    ///
    /// * `state` - World map state
    /// * `registry` - World map registry
    /// * `config` - World map configuration
    /// * `entity_id` - Entity to travel
    /// * `from` - Starting location
    /// * `to` - Destination location
    ///
    /// # Returns
    ///
    /// Travel ID, or error
    pub async fn start_travel(
        &mut self,
        state: &mut WorldMapState,
        registry: &WorldMapRegistry,
        config: &WorldMapConfig,
        entity_id: impl Into<String>,
        from: impl Into<String>,
        to: impl Into<String>,
    ) -> Result<TravelId, TravelError> {
        let entity_id = entity_id.into();
        let from = from.into();
        let to = to.into();

        // Validate with hook
        self.hook
            .can_start_travel(&entity_id, &from, &to)
            .await
            .map_err(|_| TravelError::ValidationFailed)?;

        // Validate locations exist
        let from_loc = registry
            .get_location(&from)
            .ok_or(TravelError::LocationNotFound)?;
        let to_loc = registry
            .get_location(&to)
            .ok_or(TravelError::LocationNotFound)?;

        // Find direct route
        let routes = registry.get_routes_from(&from);
        let route = routes
            .iter()
            .find(|r| r.to == to || (r.bidirectional && r.from == to))
            .ok_or(TravelError::NoRouteExists)?;

        // Calculate distance
        let distance = route
            .distance
            .unwrap_or_else(|| from_loc.position.distance_to(&to_loc.position));

        // Calculate speed
        let base_speed = config.default_travel_speed;
        let terrain_multiplier = if config.enable_terrain_modifiers {
            route.terrain.speed_multiplier()
        } else {
            1.0
        };
        let hook_multiplier = self.hook.calculate_speed_modifier(&entity_id, route).await;
        let speed = base_speed * terrain_multiplier * hook_multiplier;

        if speed <= 0.0 {
            return Err(TravelError::InvalidSpeed);
        }

        // Create travel
        let travel_id = format!(
            "travel_{}_{}",
            entity_id,
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_millis()
        );

        let travel = Travel::new(
            travel_id.clone(),
            entity_id.clone(),
            route.id.clone(),
            from,
            to,
            distance,
            speed,
        );

        // Notify hook
        self.hook.on_travel_started(&entity_id, &travel).await;

        // Register travel
        state.start_travel(travel);

        Ok(travel_id)
    }

    /// Cancel travel
    ///
    /// # Arguments
    ///
    /// * `state` - World map state
    /// * `entity_id` - Entity to cancel travel for
    ///
    /// # Returns
    ///
    /// Cancelled travel, or None if not traveling
    pub async fn cancel_travel(
        &mut self,
        state: &mut WorldMapState,
        entity_id: &str,
    ) -> Option<Travel> {
        if let Some(travel) = state.cancel_travel(&entity_id.to_string()) {
            // Notify hook
            self.hook.on_travel_cancelled(entity_id, &travel).await;
            Some(travel)
        } else {
            None
        }
    }

    /// Pause travel
    ///
    /// # Arguments
    ///
    /// * `state` - World map state
    /// * `entity_id` - Entity to pause travel for
    ///
    /// # Returns
    ///
    /// True if paused, false if not traveling
    pub async fn pause_travel(&mut self, state: &mut WorldMapState, entity_id: &str) -> bool {
        if state.pause_travel(&entity_id.to_string()) {
            if let Some(travel) = state.get_travel(&entity_id.to_string()) {
                self.hook.on_travel_paused(entity_id, travel).await;
            }
            true
        } else {
            false
        }
    }

    /// Resume travel
    ///
    /// # Arguments
    ///
    /// * `state` - World map state
    /// * `entity_id` - Entity to resume travel for
    ///
    /// # Returns
    ///
    /// True if resumed, false if not paused
    pub async fn resume_travel(&mut self, state: &mut WorldMapState, entity_id: &str) -> bool {
        if state.resume_travel(&entity_id.to_string()) {
            if let Some(travel) = state.get_travel(&entity_id.to_string()) {
                self.hook.on_travel_resumed(entity_id, travel).await;
            }
            true
        } else {
            false
        }
    }

    /// Teleport entity to a location
    ///
    /// # Arguments
    ///
    /// * `state` - World map state
    /// * `entity_id` - Entity to teleport
    /// * `location_id` - Destination location
    pub fn teleport(
        &mut self,
        state: &mut WorldMapState,
        entity_id: impl Into<String>,
        location_id: impl Into<String>,
    ) {
        state.set_position(entity_id, location_id);
    }

    /// Check if encounter should be evaluated
    fn should_check_encounter(
        &self,
        travel: &Travel,
        route: &Route,
        config: &WorldMapConfig,
    ) -> bool {
        // Don't check if too early in journey
        if travel.progress < 0.1 {
            return false;
        }

        // Don't check if route is safe
        if route.danger_level <= 0.0 {
            return false;
        }

        // Simple probability check
        // In a real implementation, this would check elapsed time since last encounter
        let encounter_chance = WorldMapService::calculate_encounter_chance(
            travel.progress,
            route.danger_level,
            config.base_encounter_rate,
            config.danger_multiplier,
        );

        // Simple random check (game should inject RNG via Hook)
        use rand::Rng;
        let mut rng = rand::thread_rng();
        rng.gen::<f32>() < encounter_chance * 0.01 // Reduce frequency for testing
    }
}

/// Travel events
#[derive(Clone, Debug)]
pub enum TravelEvent {
    Arrived {
        entity_id: EntityId,
        location_id: LocationId,
    },
    EncounterTriggered {
        entity_id: EntityId,
        encounter: Encounter,
    },
    LocationDiscovered {
        entity_id: EntityId,
        location_id: LocationId,
    },
}

/// Travel errors
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TravelError {
    LocationNotFound,
    NoRouteExists,
    InvalidSpeed,
    ValidationFailed,
}

impl std::fmt::Display for TravelError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TravelError::LocationNotFound => write!(f, "Location not found"),
            TravelError::NoRouteExists => write!(f, "No route exists between locations"),
            TravelError::InvalidSpeed => write!(f, "Invalid travel speed"),
            TravelError::ValidationFailed => write!(f, "Travel validation failed"),
        }
    }
}

impl std::error::Error for TravelError {}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::plugin::worldmap::hook::DefaultWorldMapHook;

    #[tokio::test]
    async fn test_start_travel() {
        let mut registry = WorldMapRegistry::new();
        let mut state = WorldMapState::new();
        let config = WorldMapConfig::default();

        // Setup map
        registry.register_location(
            Location::new("city_a", "City A").with_position(Position::new(0.0, 0.0)),
        );
        registry.register_location(
            Location::new("city_b", "City B").with_position(Position::new(100.0, 0.0)),
        );
        registry.register_route(Route::new("route_1", "city_a", "city_b"));

        let hook = Arc::new(DefaultWorldMapHook);
        let mut system = WorldMapSystem::new(hook);

        let travel_id = system
            .start_travel(
                &mut state, &registry, &config, "player_1", "city_a", "city_b",
            )
            .await
            .unwrap();

        assert!(!travel_id.is_empty());
        assert_eq!(state.active_travel_count(), 1);
    }

    #[tokio::test]
    async fn test_start_travel_no_route() {
        let mut registry = WorldMapRegistry::new();
        let mut state = WorldMapState::new();
        let config = WorldMapConfig::default();

        registry.register_location(Location::new("city_a", "City A"));
        registry.register_location(Location::new("city_b", "City B"));

        let hook = Arc::new(DefaultWorldMapHook);
        let mut system = WorldMapSystem::new(hook);

        let result = system
            .start_travel(
                &mut state, &registry, &config, "player_1", "city_a", "city_b",
            )
            .await;

        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), TravelError::NoRouteExists);
    }

    #[tokio::test]
    async fn test_cancel_travel() {
        let mut registry = WorldMapRegistry::new();
        let mut state = WorldMapState::new();
        let config = WorldMapConfig::default();

        registry.register_location(
            Location::new("city_a", "City A").with_position(Position::new(0.0, 0.0)),
        );
        registry.register_location(
            Location::new("city_b", "City B").with_position(Position::new(100.0, 0.0)),
        );
        registry.register_route(Route::new("route_1", "city_a", "city_b"));

        let hook = Arc::new(DefaultWorldMapHook);
        let mut system = WorldMapSystem::new(hook);

        system
            .start_travel(
                &mut state, &registry, &config, "player_1", "city_a", "city_b",
            )
            .await
            .unwrap();

        let cancelled = system.cancel_travel(&mut state, "player_1").await;
        assert!(cancelled.is_some());
        assert_eq!(state.active_travel_count(), 0);
    }

    #[tokio::test]
    async fn test_update_completes_travel() {
        let mut registry = WorldMapRegistry::new();
        let mut state = WorldMapState::new();
        let config = WorldMapConfig::default();

        registry.register_location(
            Location::new("city_a", "City A").with_position(Position::new(0.0, 0.0)),
        );
        registry.register_location(
            Location::new("city_b", "City B").with_position(Position::new(100.0, 0.0)),
        );
        registry.register_route(Route::new("route_1", "city_a", "city_b"));

        let hook = Arc::new(DefaultWorldMapHook);
        let mut system = WorldMapSystem::new(hook);

        system
            .start_travel(
                &mut state, &registry, &config, "player_1", "city_a", "city_b",
            )
            .await
            .unwrap();

        // Update enough to complete travel (100 distance / 10 speed = 10 seconds)
        let events = system.update(&mut state, &registry, &config, 10.0).await;

        assert_eq!(state.active_travel_count(), 0);
        assert!(!events.is_empty());
    }
}