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
use std::mem;

use futures::prelude::*;
use futures::unsync::{mpsc, oneshot};
use sc2_proto::sc2api;
use tokio_core::reactor;
use url::Url;

use constants::sc2_bug_tag;
use data::{GameSetup, Map, PlayerSetup, Race};
use launcher::GamePorts;
use observer::{Event, EventAck};
use services::action_service::{
    ActionBuilder,
    ActionClient,
    ActionControlClient,
    DebugClient,
};
use services::client_service::{ProtoClient, ProtoClientBuilder};
use services::melee_service::{MeleeCompetitor, MeleeRequest, UpdateScheme};
use services::observer_service::{
    ObserverBuilder,
    ObserverClient,
    ObserverControlClient,
};
use {Error, ErrorKind, IntoProto, Result};

/// Build an agent.
pub struct AgentBuilder {
    client: Option<ProtoClientBuilder>,
    action: Option<ActionBuilder>,
    observer: Option<ObserverBuilder>,

    race: Option<Race>,

    event_tx: Option<mpsc::Sender<(Event, EventAck)>>,
    event_rx: Option<mpsc::Receiver<(Event, EventAck)>>,
}

impl AgentBuilder {
    /// Create a new AgentBuilder with the default settings.
    pub fn new() -> Self {
        let client = ProtoClientBuilder::new();
        let action = ActionBuilder::new().proto_client(client.add_client());
        let observer = ObserverBuilder::new().proto_client(client.add_client());

        let (tx, rx) = mpsc::channel(10);

        Self {
            client: Some(client),
            action: Some(action),
            observer: Some(observer),

            race: None,

            event_tx: Some(tx),
            event_rx: Some(rx),
        }
    }

    /// Set the race of the player.
    pub fn race(self, race: Race) -> Self {
        Self {
            race: Some(race),
            ..self
        }
    }

    /// Add an Observer client to observe the game state.
    pub fn add_observer_client(&self) -> ObserverClient {
        self.observer.as_ref().unwrap().add_client()
    }

    /// Add an Action client to dispatch commands.
    pub fn add_action_client(&self) -> ActionClient {
        self.action
            .as_ref()
            .unwrap()
            .add_action_client()
    }

    /// Add a Debug client to use debugging tools.
    pub fn add_debug_client(&self) -> DebugClient {
        self.action.as_ref().unwrap().add_debug_client()
    }

    /// Take the stream of game events to listen for.
    ///
    /// This should be called only once per builder! Subsequent calls will
    /// return None because Streams should not be shared.
    ///
    /// The stream item is a tuple containing the event, and a promise to be
    /// fulfilled once the user is done with the event.
    pub fn take_event_stream(
        &mut self,
    ) -> Option<mpsc::Receiver<(Event, EventAck)>> {
        mem::replace(&mut self.event_rx, None)
    }
}

impl MeleeCompetitor for AgentBuilder {
    fn spawn(
        &mut self,
        handle: &reactor::Handle,
        rx: mpsc::Receiver<MeleeRequest>,
    ) -> Result<()> {
        let tx = mem::replace(&mut self.event_tx, None).unwrap();

        let agent = Agent::new(
            self.client.as_ref().unwrap().add_client(),
            self.action
                .as_ref()
                .unwrap()
                .add_control_client(),
            self.observer
                .as_ref()
                .unwrap()
                .add_control_client(),
            rx,
            tx,
            mem::replace(&mut self.race, None).unwrap_or(Race::Random),
        );

        mem::replace(&mut self.client, None)
            .unwrap()
            .spawn(handle)?;
        mem::replace(&mut self.action, None)
            .unwrap()
            .spawn(handle)?;
        mem::replace(&mut self.observer, None)
            .unwrap()
            .spawn(handle)?;

        agent.spawn(handle)?;

        Ok(())
    }
}

struct Agent {
    control_rx: Option<mpsc::Receiver<MeleeRequest>>,
    client: ProtoClient,
    observer: ObserverControlClient,
    agent: AgentTerminal,
    action: ActionControlClient,
}

impl Agent {
    fn new(
        client: ProtoClient,
        action: ActionControlClient,
        observer: ObserverControlClient,
        control_rx: mpsc::Receiver<MeleeRequest>,
        events: mpsc::Sender<(Event, EventAck)>,
        race: Race,
    ) -> Agent {
        Self {
            control_rx: Some(control_rx),
            client: client,
            observer: observer,
            agent: AgentTerminal {
                tx: events,
                race: race,
            },
            action: action,
        }
    }

    fn spawn(self, handle: &reactor::Handle) -> Result<()> {
        handle.spawn(self.run().map_err(|e| {
            panic!(
                "{}: AgentService ended unexpectedly {:#?}",
                sc2_bug_tag(),
                e
            )
        }));

        Ok(())
    }

    #[async]
    fn run(mut self) -> Result<()> {
        let control_rx = mem::replace(&mut self.control_rx, None).unwrap();

        #[async]
        for req in control_rx.map_err(|_| -> Error { unreachable!() }) {
            match req {
                MeleeRequest::PlayerSetup(game, tx) => {
                    let setup = await!(self.get_player_setup(game))?;
                    tx.send(setup).map_err(|_| -> Error {
                        unreachable!(
                            "{}: Unable to rsp PlayerSetup",
                            sc2_bug_tag()
                        )
                    })?;
                },
                MeleeRequest::Connect(url, tx) => {
                    await!(self.connect(url))?;
                    tx.send(()).map_err(|_| -> Error {
                        unreachable!("{}: Unable to ack connect", sc2_bug_tag())
                    })?;
                },

                MeleeRequest::CreateGame(game, players, update_scheme, tx) => {
                    await!(self.create_game(game, players, update_scheme))?;
                    tx.send(()).map_err(|_| -> Error {
                        unreachable!("{}: Unable to create game", sc2_bug_tag())
                    })?;
                },
                MeleeRequest::JoinGame(player, ports, tx) => {
                    await!(self.join_game(player, ports))?;
                    tx.send(()).map_err(|_| -> Error {
                        unreachable!("{}: Unable to join game", sc2_bug_tag())
                    })?;
                },
                MeleeRequest::RunGame(update_scheme, tx) => {
                    await!(self.run_game(update_scheme))?;
                    tx.send(()).map_err(|_| -> Error {
                        unreachable!("{}: Unable to run game", sc2_bug_tag())
                    })?;
                },
                MeleeRequest::LeaveGame(tx) => {
                    await!(self.leave_game())?;
                    tx.send(()).map_err(|_| -> Error {
                        unreachable!("{}: Unable to leave game", sc2_bug_tag())
                    })?;
                },

                MeleeRequest::Disconnect(tx) => {
                    await!(self.disconnect())?;
                    tx.send(()).map_err(|_| -> Error {
                        unreachable!("{}: Unable to disconnect", sc2_bug_tag())
                    })?;
                },
            }
        }

        Ok(())
    }

    fn get_player_setup(
        &self,
        game: GameSetup,
    ) -> impl Future<Item = PlayerSetup, Error = Error> {
        let future = self.agent.get_player_setup(game);

        async_block! {
            await!(future)
        }
    }

    fn connect(&self, url: Url) -> impl Future<Item = (), Error = Error> {
        let future = self.client.connect(url);

        async_block! {
            await!(future)
        }
    }

    fn create_game(
        &self,
        settings: GameSetup,
        players: Vec<PlayerSetup>,
        update_scheme: UpdateScheme,
    ) -> impl Future<Item = (), Error = Error> {
        let client = self.client.clone();

        async_block! {
            let mut req = sc2api::Request::new();

            match settings.get_map() {
                &Map::LocalMap(ref path) => {
                    req.mut_create_game()
                        .mut_local_map()
                        .set_map_path(match path.clone()
                            .into_os_string()
                            .into_string()
                        {
                            Ok(s) => s,
                            Err(_) => bail!(ErrorKind::InvalidMapPath(format!(
                                "{:?} cannot be converted to an OS string",
                                *path
                            ))),
                        });
                },
                &Map::BlizzardMap(ref map) => {
                    req.mut_create_game()
                        .set_battlenet_map_name(map.clone());
                },
            };

            for player in players {
                let mut setup = sc2api::PlayerSetup::new();

                match player {
                    PlayerSetup::Computer(race, difficulty) => {
                        setup.set_field_type(sc2api::PlayerType::Computer);

                        setup.set_difficulty(difficulty.to_proto());
                        setup.set_race(race.into_proto()?);
                    },
                    PlayerSetup::Player(race) => {
                        setup.set_field_type(sc2api::PlayerType::Participant);

                        setup.set_race(race.into_proto()?);
                    }, /*PlayerSetup::Observer => {
                        setup.set_field_type(sc2api::PlayerType::Observer);
                    }*/
                }

                req.mut_create_game()
                    .mut_player_setup()
                    .push(setup);
            }

            match update_scheme {
                UpdateScheme::Realtime => {
                    req.mut_create_game().set_realtime(true);
                },
                _ => {
                    req.mut_create_game().set_realtime(false);
                },
            }

            await!(client.request(req))?;

            Ok(())
        }
    }

    fn join_game(
        &self,
        setup: PlayerSetup,
        ports: Option<GamePorts>,
    ) -> impl Future<Item = (), Error = Error> {
        let client = self.client.clone();
        let event_future = self.agent.handle_event(Event::GameLoaded);

        async_block! {
            let mut req = sc2api::Request::new();

            match setup {
                PlayerSetup::Computer(race, _) => {
                    req.mut_join_game().set_race(race.into_proto()?);
                },
                PlayerSetup::Player(race) => {
                    req.mut_join_game().set_race(race.into_proto()?);
                }, //_ => req.mut_join_game().set_race(common::Race::NoRace)
            };

            if let Some(ports) = ports {
                req.mut_join_game()
                    .set_shared_port(ports.shared_port as i32);

                {
                    let s = req.mut_join_game().mut_server_ports();

                    s.set_game_port(ports.server_ports.game_port as i32);
                    s.set_base_port(ports.server_ports.base_port as i32);
                }

                {
                    let client_ports = req.mut_join_game().mut_client_ports();

                    for c in &ports.client_ports {
                        let mut p = sc2api::PortSet::new();

                        p.set_game_port(c.game_port as i32);
                        p.set_base_port(c.base_port as i32);

                        client_ports.push(p);
                    }
                }
            }

            {
                let options = req.mut_join_game().mut_options();

                options.set_raw(true);
                options.set_score(true);
            }

            await!(client.request(req))?;
            await!(event_future)?;

            Ok(())
        }
    }

    fn run_game(
        &self,
        update_scheme: UpdateScheme,
    ) -> impl Future<Item = (), Error = Error> {
        let observer = self.observer.clone();
        let agent = self.agent.clone();
        let action = self.action.clone();
        let client = self.client.clone();

        async_block! {
            await!(observer.clone().reset())?;

            let (initial_events, _) = await!(observer.clone().step())?;

            await!(
                agent
                    .clone()
                    .handle_event(Event::GameStarted)
            )?;
            for e in initial_events {
                await!(agent.clone().handle_event(e))?;
            }

            loop {
                match update_scheme {
                    UpdateScheme::Realtime => (),
                    UpdateScheme::Interval(interval) => {
                        let mut req = sc2api::Request::new();
                        req.mut_step().set_count(interval);

                        await!(client.clone().request(req))?;
                    },
                }

                let (events, game_ended) = await!(observer.clone().step())?;

                for e in events {
                    await!(agent.clone().handle_event(e))?;
                }

                await!(agent.clone().handle_event(Event::Step))?;

                if game_ended {
                    await!(
                        agent
                            .clone()
                            .handle_event(Event::GameEnded)
                    )?;
                    break;
                }

                await!(action.clone().step())?;
            }

            Ok(())
        }
    }

    fn leave_game(&self) -> impl Future<Item = (), Error = Error> {
        let mut req = sc2api::Request::new();
        req.mut_leave_game();

        let future = self.client.request(req);

        async_block! {
            await!(future)?;

            Ok(())
        }
    }

    fn disconnect(&self) -> impl Future<Item = (), Error = Error> {
        let future = self.client.disconnect();

        async_block! {
            await!(future)
        }
    }
}

#[derive(Debug, Clone)]
pub struct AgentTerminal {
    tx: mpsc::Sender<(Event, EventAck)>,
    race: Race,
}

impl AgentTerminal {
    fn get_player_setup(
        &self,
        _game: GameSetup,
    ) -> impl Future<Item = PlayerSetup, Error = Error> {
        let race = self.race;

        async_block! {
            Ok(PlayerSetup::Player(race))
        }
    }

    fn handle_event(
        &self,
        event: Event,
    ) -> impl Future<Item = (), Error = Error> {
        let (tx, rx) = oneshot::channel();
        let sender = self.tx.clone();

        async_block! {
            if let Err(_) = await!(
                sender
                    .send((event, EventAck::wrap(tx)))
            ) {
                // This is not really an error, it just means that the user's
                // event stream has been closed or dropped. For now I'm just
                // dropping the event and continuing.
                //
                // It might be worth adding a warning for this later.
            }

            if let Err(_) = await!(rx) {
                // ACK went out of scope, we can assume this means they are done
                // using the event.
                //
                // It might be worth adding a warning for this later.
            }

            Ok(())
        }
    }
}