-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathswarm_simulation.rs
More file actions
169 lines (148 loc) Β· 4.92 KB
/
swarm_simulation.rs
File metadata and controls
169 lines (148 loc) Β· 4.92 KB
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
//! Swarm simulation with realβtime visualization.
use offline_first_autonomy::agent_core::Agent;
use offline_first_autonomy::mesh_transport::{MeshTransport, MeshTransportConfig};
use offline_first_autonomy::state_sync::CrdtMap;
use common::types::AgentId;
use std::collections::HashMap;
use std::time::{Duration, Instant};
use tokio::time;
use crossterm::{
cursor, execute,
style::{Color, Print, ResetColor, SetForegroundColor},
terminal::{Clear, ClearType},
};
use std::io::{stdout, Write};
/// A simple 2D position for visualization.
#[derive(Clone, Debug)]
struct Position {
x: f32,
y: f32,
}
/// Simulated agent with position and state.
struct SimAgent {
id: AgentId,
agent: Agent,
position: Position,
velocity: (f32, f32),
color: Color,
}
impl SimAgent {
fn new(id: u64, config: MeshTransportConfig) -> Self {
let agent = Agent::new(AgentId(id), config).expect("Failed to create agent");
Self {
id: AgentId(id),
agent,
position: Position { x: 0.0, y: 0.0 },
velocity: (0.0, 0.0),
color: match id % 5 {
0 => Color::Red,
1 => Color::Green,
2 => Color::Yellow,
3 => Color::Blue,
4 => Color::Magenta,
_ => Color::Cyan,
},
}
}
async fn update(&mut self, delta_time: f32) {
// Simple random walk
use rand::Rng;
let mut rng = rand::thread_rng();
self.velocity.0 += rng.gen_range(-1.0..1.0);
self.velocity.1 += rng.gen_range(-1.0..1.0);
// Damping
self.velocity.0 *= 0.9;
self.velocity.1 *= 0.9;
// Update position
self.position.x += self.velocity.0 * delta_time;
self.position.y += self.velocity.1 * delta_time;
// Keep within bounds
self.position.x = self.position.x.clamp(-10.0, 10.0);
self.position.y = self.position.y.clamp(-10.0, 10.0);
// Update CRDT with position
let key = format!("agent/{}/position", self.id.0);
let value = serde_json::json!({
"x": self.position.x,
"y": self.position.y,
"timestamp": std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs(),
});
self.agent.set_value(&key, value).expect("Set failed");
}
fn draw(&self, grid: &mut Vec<Vec<char>>, offset_x: usize, offset_y: usize) {
let grid_x = ((self.position.x + 10.0) * 2.0).round() as usize;
let grid_y = ((self.position.y + 10.0) * 2.0).round() as usize;
if grid_x < 40 && grid_y < 40 {
grid[grid_y + offset_y][grid_x + offset_x] = '@';
}
}
}
/// Render the swarm in a terminal grid.
fn render_grid(agents: &[SimAgent]) {
let width = 80;
let height = 24;
let mut grid = vec![vec![' '; width]; height];
// Draw axes
let center_x = width / 2;
let center_y = height / 2;
for y in 0..height {
grid[y][center_x] = '|';
}
for x in 0..width {
grid[center_y][x] = '-';
}
grid[center_y][center_x] = '+';
// Draw each agent
for agent in agents {
agent.draw(&mut grid, center_x, center_y);
}
// Output to terminal
let mut stdout = stdout();
execute!(stdout, Clear(ClearType::All), cursor::MoveTo(0, 0)).unwrap();
for row in grid {
let line: String = row.iter().collect();
execute!(stdout, Print(line), Print("\r\n")).unwrap();
}
execute!(stdout, ResetColor).unwrap();
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("Starting swarm simulation with 5 agents...");
// Create agents with inβmemory transport (so they can communicate)
let mut agents = Vec::new();
for i in 0..5 {
let config = MeshTransportConfig::in_memory();
let mut sim_agent = SimAgent::new(i, config);
sim_agent.agent.start().expect("Agent start failed");
agents.push(sim_agent);
}
let start = Instant::now();
let mut last_render = Instant::now();
let render_interval = Duration::from_millis(100);
loop {
let elapsed = start.elapsed();
let delta_time = 0.1; // fixed time step for simplicity
// Update each agent
for agent in &mut agents {
agent.update(delta_time).await;
}
// Broadcast changes (simulate sync)
for agent in &mut agents {
let _ = agent.agent.broadcast_changes().await;
}
// Render if enough time has passed
if last_render.elapsed() >= render_interval {
render_grid(&agents);
last_render = Instant::now();
}
// Break after some time
if elapsed >= Duration::from_secs(30) {
break;
}
time::sleep(Duration::from_millis(50)).await;
}
println!("Simulation finished.");
Ok(())
}