Statistics
| Branch: | Revision:

scoutos / scout / scoutsim / src / sim_frame.cpp @ a224a762

History | View | Annotate | Download (27.8 KB)

1
/**
2
 * The code in this package was developed using the structure of Willow
3
 * Garage's turtlesim package.  It was modified by the CMU Robotics Club
4
 * to be used as a simulator for the Colony Scout robot.
5
 *
6
 * All redistribution of this code is limited to the terms of Willow Garage's
7
 * licensing terms, as well as under permission from the CMU Robotics Club.
8
 * 
9
 * Copyright (c) 2011 Colony Project
10
 * 
11
 * Permission is hereby granted, free of charge, to any person
12
 * obtaining a copy of this software and associated documentation
13
 * files (the "Software"), to deal in the Software without
14
 * restriction, including without limitation the rights to use,
15
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
16
 * copies of the Software, and to permit persons to whom the
17
 * Software is furnished to do so, subject to the following
18
 * conditions:
19
 * 
20
 * The above copyright notice and this permission notice shall be
21
 * included in all copies or substantial portions of the Software.
22
 * 
23
 * Copyright (c) 2009, Willow Garage, Inc.
24
 * All rights reserved.
25
 * 
26
 * Redistribution and use in source and binary forms, with or without
27
 * modification, are permitted provided that the following conditions are met:
28
 * 
29
 *    Redistributions of source code must retain the above copyright
30
 *       notice, this list of conditions and the following disclaimer.
31
 *    Redistributions in binary form must reproduce the above copyright
32
 *       notice, this list of conditions and the following disclaimer in the
33
 *       documentation and/or other materials provided with the distribution.
34
 *    Neither the name of the Willow Garage, Inc. nor the names of its
35
 *       contributors may be used to endorse or promote products derived from
36
 *       this software without specific prior written permission.
37
 * 
38
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
39
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
40
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
41
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
42
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
43
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
44
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
45
 * OTHER DEALINGS IN THE SOFTWARE.
46
 */
47

    
48
/**
49
 * @file sim_frame.cpp
50
 *
51
 * @ingroup scoutsim
52
 * @{
53
 */
54

    
55
#include "sim_frame.h"
56

    
57
#include <stdio.h>
58

    
59
#include <ros/package.h>
60
#include <cstdlib>
61
#include <ctime>
62

    
63
using namespace std;
64

    
65
namespace scoutsim
66
{
67
    SimFrame::SimFrame(wxWindow* parent, string map_name)
68
        : wxFrame(parent, wxID_ANY, wxT("ScoutSim"), wxDefaultPosition,
69
                  wxSize(500, 500), wxDEFAULT_FRAME_STYLE & ~wxRESIZE_BORDER)
70
          , frame_count(0)
71
          , id_counter(0)
72
          , BOM_counter(0)
73
    {
74
        std::cout << "Constructing sim frame." << std::endl;
75

    
76
        srand(time(NULL));
77

    
78
        update_timer = new wxTimer(this);
79
        update_timer->Start(REAL_TIME_REFRESH_RATE * 1000);
80

    
81
        Connect(update_timer->GetId(), wxEVT_TIMER,
82
                wxTimerEventHandler(SimFrame::onUpdate), NULL, this);
83
        Connect(wxEVT_PAINT, wxPaintEventHandler(SimFrame::onPaint),
84
                NULL, this);
85

    
86
        images_path = ros::package::getPath("scoutsim") + "/images/";
87

    
88
        map_base_name =  ros::package::getPath("scoutsim") + "/maps/" +
89
                           map_name + ".bmp";
90
        map_lines_name = ros::package::getPath("scoutsim") + "/maps/" +
91
                           map_name + "_lines.bmp";
92
        map_walls_name = ros::package::getPath("scoutsim") + "/maps/" +
93
                           map_name + "_walls.bmp";
94
        display_map_name = map_base_name;
95

    
96
        wxBitmap lines_bitmap;
97
        wxBitmap walls_bitmap;
98
        ROS_INFO("Loading map: %s", display_map_name.c_str());
99
        path_bitmap.LoadFile(wxString::FromAscii(display_map_name.c_str()));
100

    
101
        // Try to load the file; if it fails, make a new blank file
102
        if (!lines_bitmap.LoadFile(wxString::FromAscii(map_lines_name.c_str())))
103
        {
104
            lines_bitmap = wxBitmap(path_bitmap.GetWidth(), path_bitmap.GetHeight(), 3);
105
        }
106
        lines_image = lines_bitmap.ConvertToImage();
107

    
108
        // Try to load the file; if it fails, make a new blank file
109
        if (!walls_bitmap.LoadFile(wxString::FromAscii(map_walls_name.c_str())))
110
        {
111
            walls_bitmap = wxBitmap(path_bitmap.GetWidth(), path_bitmap.GetHeight(), 3);
112
        }
113
        walls_image = walls_bitmap.ConvertToImage();
114

    
115
        clear();
116

    
117
        clear_srv = nh.advertiseService("clear",
118
                                        &SimFrame::clearCallback, this);
119
        reset_srv = nh.advertiseService("reset",
120
                                        &SimFrame::resetCallback, this);
121
        spawn_srv = nh.advertiseService("spawn",
122
                                        &SimFrame::spawnCallback, this);
123
        spawn_em_srv = nh.advertiseService("spawn_em",
124
                                        &SimFrame::spawnEmCallback, this);
125
        kill_srv = nh.advertiseService("kill",
126
                                        &SimFrame::killCallback, this);
127
        set_sonar_viz_srv = nh.advertiseService("set_sonar_viz",
128
                                        &SimFrame::setSonarVizCallback, this);
129
        set_ghost_srv = nh.advertiseService("set_ghost",
130
                                        &SimFrame::setGhostCallback, this);
131
        set_teleop_srv = nh.advertiseService("set_teleop",
132
                                        &SimFrame::setTeleopCallback, this);
133

    
134
        // Subscribe and publisher wirless from robots
135
        wireless_receive = nh.advertise< ::messages::WirelessPacket>(
136
            "/wireless/receive", 1000); 
137
        wireless_send = nh.subscribe("/wireless/send", 1000,
138
            &SimFrame::wirelessCallback, this);
139

    
140
        // Teleop
141
        teleop_type = TELEOP_OFF;
142
        teleop_l_speed = 0;
143
        teleop_r_speed = 0;
144
        teleop_scoutname = "scout1";
145

    
146
        //Emitter default values
147
        em_aperture = PI / 3.0;
148
        em_distance = 1.0;
149

    
150

    
151
        teleop_pub = nh.advertise< ::messages::set_motors>("/scout1/set_motors", 1000);
152

    
153
        ROS_INFO("Starting scoutsim with node name %s",
154
                 ros::this_node::getName().c_str()) ;
155

    
156
        wxMenu *menuFile = new wxMenu;
157
        menuFile->Append(ID_ABOUT, _("&About"));
158
        menuFile->AppendSeparator();
159
        menuFile->Append(ID_QUIT, _("E&xit"));
160

    
161
        wxMenu *menuSim = new wxMenu;
162
        menuSim->Append(ID_CLEAR, _("&Clear"));
163

    
164
        wxMenu *menuView = new wxMenu;
165
        menuView->Append(ID_MAP, _("&Map"));
166
        menuView->Append(ID_LINES, _("&Lines"));
167
        menuView->Append(ID_WALLS, _("&Walls"));
168

    
169
        wxMenu *menuTeleop = new wxMenu;
170
        menuTeleop->Append(ID_TELEOP_NONE, _("&None"));
171
        menuTeleop->Append(ID_TELEOP_PRECISE, _("&Precise"));
172
        menuTeleop->Append(ID_TELEOP_FLUID, _("&Fluid"));
173

    
174
        wxMenuBar *menuBar = new wxMenuBar;
175
        menuBar->Append(menuFile, _("&File"));
176
        menuBar->Append(menuSim, _("&Sim"));
177
        menuBar->Append(menuView, _("&View"));
178
        menuBar->Append(menuTeleop, _("&Teleop"));
179

    
180
        SetMenuBar(menuBar);
181

    
182
        width_in_meters = GetSize().GetWidth() / PIX_PER_METER;
183
        height_in_meters = GetSize().GetHeight() / PIX_PER_METER;
184

    
185
        spawnScout("scout1", 1.4, .78, 0);
186
    }
187

    
188
    SimFrame::~SimFrame()
189
    {
190
        delete update_timer;
191
    }
192

    
193
    bool SimFrame::spawnCallback(scoutsim::Spawn::Request  &req,
194
                                 scoutsim::Spawn::Response &res)
195
    {
196
        std::string name = spawnScout(req.name, req.x, req.y, req.theta);
197
        if (name.empty())
198
        {
199
            ROS_WARN("A scout named [%s] already exists", req.name.c_str());
200
            return false;
201
        }
202

    
203
        res.name = name;
204
        return true;
205
    }
206

    
207

    
208
    bool SimFrame::spawnEmCallback(scoutsim::Spawn::Request  &req,
209
                                 scoutsim::Spawn::Response &res)
210
    {
211
        std::string name = spawnEmitter(req.name, req.x, req.y, req.theta);
212
        if (name.empty())
213
        {
214
            ROS_WARN("An emitter named [%s] already exists", req.name.c_str());
215
            return false;
216
        }
217
        res.name = name;
218
        return true;
219
    }
220

    
221
    bool SimFrame::killCallback(scoutsim::Kill::Request& req,
222
                                scoutsim::Kill::Response&)
223
    {
224
        M_Scout::iterator it = scouts.find(req.name);
225
        M_Emitter::iterator m_it = emitters.find(req.name);
226
        if (it == scouts.end())
227
        {
228
            if (m_it == emitters.end()) {
229
                ROS_WARN("Tried to kill scout/emitter [%s], which does not exist",
230
                req.name.c_str());
231
                return false;
232
            }
233
            emitters.erase(m_it);
234
            return true;
235
        }
236

    
237
        scouts.erase(it);
238

    
239
        return true;
240
    }
241

    
242
    bool SimFrame::setSonarVizCallback(SetSonarViz::Request& req,
243
                                       SetSonarViz::Response&)
244
    {
245
        M_Scout::iterator it = scouts.find(req.scout_name);
246
        if (it == scouts.end())
247
        {
248
            ROS_WARN("Tried to set sonar on scout [%s], which does not exist",
249
                     req.scout_name.c_str());
250
            return false;
251
        }
252

    
253
        it->second->set_sonar_visual(req.on);
254
        return true;
255
    }
256

    
257
    bool SimFrame::setGhostCallback(SetGhost::Request& req,
258
                                    SetGhost::Response&)
259
    {
260
        for (unsigned int i=0; i < ghost_scouts.size(); ++i)
261
        {
262
            if (ghost_scouts.at(i)->get_name() == req.scout_name)
263
            {
264
                ghost_scouts.at(i)->set_visible(req.on);
265
                return true;
266
            }
267
        }
268

    
269
        ROS_WARN("Tried to set ghost on scout [%s], which does not exist",
270
                 req.scout_name.c_str());
271
        return false;
272
    }
273

    
274
    bool SimFrame::setTeleopCallback(SetTeleop::Request& req,
275
                                     SetTeleop::Response&)
276
    {
277
        std::stringstream ss;
278
        ss << "/" << req.scout_name << "/set_motors";
279
        teleop_pub = nh.advertise< ::messages::set_motors>(ss.str(), 1000);
280
        teleop_scoutname = req.scout_name.c_str();
281
        ROS_INFO("Teleoping %s...",teleop_scoutname.c_str()); //debug statement
282

    
283
        return true;
284
    }
285

    
286
    bool SimFrame::hasScout(const std::string& name)
287
    {
288
        return scouts.find(name) != scouts.end();
289
    }
290

    
291
    bool SimFrame::hasEmitter(const std::string& name)
292
    {
293
        return emitters.find(name) != emitters.end();
294
    }
295

    
296
    std::string SimFrame::spawnScout(const std::string& name,
297
                                     float x, float y, float angle)
298
    {
299
        std::string real_name = name;
300
        if (real_name.empty())
301
        {
302
            // Generate the name scoutX, where X is an increasing number.
303
            do
304
            {
305
                std::stringstream ss;
306
                ss << "scout" << ++id_counter;
307
                real_name = ss.str();
308
            }
309
            while (hasScout(real_name));
310
        }
311
        else
312
        {
313
            if (hasScout(real_name))
314
            {
315
                return "";
316
            }
317
        }
318

    
319
        wxImage scout_image;
320

    
321
        // Try to load a name-specific image; if not, load the default scout
322
        string specific_name = images_path + name + ".png";
323
        if (fileExists(specific_name))
324
        {
325
            scout_image.LoadFile(wxString::FromAscii(specific_name.c_str()));
326
            scout_image.SetMask(true);
327
            scout_image.SetMaskColour(255, 255, 255);
328
        }
329
        else
330
        {
331
            scout_image.LoadFile(
332
                wxString::FromAscii((images_path + "scout.png").c_str()));
333
            scout_image.SetMask(true);
334
            scout_image.SetMaskColour(255, 255, 255);
335
        }
336

    
337
        ScoutPtr t(new Scout(ros::NodeHandle(real_name),
338
                   scout_image, Vector2(x, y), &path_bitmap, angle));
339
        scouts[real_name] = t;
340

    
341
        ghost_scouts.push_back(new GhostScout(ros::NodeHandle(real_name),
342
                scout_image, Vector2(x, y), &path_bitmap, angle, name));
343

    
344
        ROS_INFO("Spawning scout [%s] at x=[%f], y=[%f], theta=[%f]",
345
                 real_name.c_str(), x, y, angle);
346

    
347
        return real_name;
348
    }
349

    
350

    
351
    std::string SimFrame::spawnEmitter(const std::string& name,
352
                                     float x, float y, float angle)
353
    {
354
        std::string real_name = name;
355
        if (real_name.empty())
356
        {
357
            // Generate the name emitterX, where X is an increasing number.
358
            do
359
            {
360
                std::stringstream ss;
361
                ss << "emitter_" << ++BOM_counter;
362
                real_name = ss.str();
363
            }
364
            while (hasEmitter(real_name));
365
        }
366
        else
367
        {
368
            if (hasEmitter(real_name))
369
            {
370
                return "";
371
            }
372
        }
373

    
374
        wxImage emitter_image;
375

    
376
        // Try to load a name-specific image; if not, load the default emitter
377
        string specific_name = images_path + name + ".png";
378
        if (fileExists(specific_name))
379
        {
380
            emitter_image.LoadFile(wxString::FromAscii(specific_name.c_str()));
381
            emitter_image.SetMask(true);
382
            emitter_image.SetMaskColour(255, 255, 255);
383
        }
384
        else
385
        {
386
            ROS_INFO("LOADED EMITTER IMAGE");
387
            emitter_image.LoadFile(
388
                wxString::FromAscii((images_path + "emitter.png").c_str()));
389
            emitter_image.SetMask(true);
390
            emitter_image.SetMaskColour(255, 255, 255);
391
        }
392

    
393
        EmitterPtr t(new Emitter(ros::NodeHandle(real_name),
394
                   emitter_image, Vector2(x, y), &path_bitmap, 
395
                   angle, em_aperture, em_distance));
396
        emitters[real_name] = t;
397

    
398
        ROS_INFO("Spawning emitter [%s] at x=[%f], y=[%f], theta=[%f]",
399
                 real_name.c_str(), x, y, angle);
400

    
401
        return real_name;
402
    }
403

    
404

    
405
    void SimFrame::onQuit(wxCommandEvent& WXUNUSED(event))
406
    {
407
        Close(true);
408
    }
409

    
410
    void SimFrame::onAbout(wxCommandEvent& WXUNUSED(event))
411
    {
412
        wxMessageBox(_("Scoutsim is the simulator the Colony Project's scout robot.\n"
413
                       "\nThe Colony Project is a part of the Carnegie Mellon\n"
414
                       "Robotics Club. Our goal is to use cooperative low-cost\n"
415
                       "robots to solve challenging problems."),
416
                     _("About Scoutsim"),
417
                     wxOK | wxICON_INFORMATION, this );
418
    }
419

    
420
    void SimFrame::onClear(wxCommandEvent& WXUNUSED(event))
421
    {
422
        clear();
423
    }
424

    
425
    void SimFrame::showMap(wxCommandEvent& WXUNUSED(event))
426
    {
427
        display_map_name = map_base_name;
428
        clear();
429
    }
430

    
431
    void SimFrame::showLines(wxCommandEvent& WXUNUSED(event))
432
    {
433
        display_map_name = map_lines_name;
434
        clear();
435
    }
436
    
437
    void SimFrame::showWalls(wxCommandEvent& WXUNUSED(event))
438
    {
439
        display_map_name = map_walls_name;
440
        clear();
441
    }
442

    
443
    void SimFrame::clear()
444
    {
445
        path_dc.SetBackground(wxBrush(wxColour(100, 100, 100)));
446
        path_dc.Clear();
447

    
448
        sonar_dc.SetBackground(wxBrush(wxColour(255, 0, 0)));
449
        sonar_dc.Clear();
450

    
451
        sonar_dc.SelectObject(path_bitmap);
452

    
453
        path_bitmap.LoadFile(wxString::FromAscii(display_map_name.c_str()));
454
        path_dc.SelectObject(path_bitmap);
455
        SetSize(wxSize(path_bitmap.GetWidth(), path_bitmap.GetHeight()));
456
    }
457

    
458
    // Runs every REAL_TIME_REFRESH_RATE.
459
    void SimFrame::onUpdate(wxTimerEvent& evt)
460
    {
461
        ros::spinOnce();
462

    
463
        teleop();
464

    
465
        updateScouts();
466

    
467
        if (!ros::ok())
468
        {
469
            Close();
470
        }
471

    
472
        frame_count++;
473
    }
474

    
475
    void SimFrame::onPaint(wxPaintEvent& evt)
476
    {
477
        wxPaintDC dc(this);
478

    
479
        dc.DrawBitmap(path_bitmap, 0, 0, true);
480

    
481
        M_Scout::iterator it = scouts.begin();
482
        M_Scout::iterator end = scouts.end();
483
        for (; it != end; ++it)
484
        {
485
            it->second->paint(dc);
486
        }
487

    
488

    
489
        M_Emitter::iterator m_it = emitters.begin();
490
        M_Emitter::iterator m_end = emitters.end();
491
        for (; m_it != m_end; ++m_it)
492
        {
493
            m_it->second->paint(dc);
494
        }
495

    
496
        for (unsigned int i=0; i < ghost_scouts.size(); ++i)
497
        {
498
            ghost_scouts.at(i)->paint(dc);
499
        }
500
    }
501

    
502
    bool SimFrame::fileExists(const std::string& filename)
503
    {
504
        struct stat buf;
505
        if (stat(filename.c_str(), &buf) != -1)
506
        {
507
            return true;
508
        }
509
        return false;
510
    }
511

    
512
    void SimFrame::stopTeleop(wxCommandEvent& event)
513
    {
514
        teleop_type = TELEOP_OFF;
515
        teleop_l_speed = 0;
516
        teleop_r_speed = 0;
517
    }
518

    
519
    void SimFrame::startTeleopPrecise(wxCommandEvent& event)
520
    {
521
        teleop_type = TELEOP_PRECISE;
522
        teleop_l_speed = 0;
523
        teleop_r_speed = 0;
524
    }
525

    
526
    void SimFrame::startTeleopFluid(wxCommandEvent& event)
527
    {
528
        teleop_type = TELEOP_FLUID;
529
        teleop_l_speed = 0;
530
        teleop_r_speed = 0;
531
        teleop_fluid_speed = 0;
532
        teleop_fluid_omega = 0;
533
    }
534

    
535
    void SimFrame::teleop_move_precise()
536
    {
537
        // Default to stop
538
        teleop_l_speed = 0;
539
        teleop_r_speed = 0;
540

    
541
        if (wxGetKeyState(WXK_UP))
542
        {
543
            teleop_l_speed = TELEOP_PRECISE_SPEED;
544
            teleop_r_speed = TELEOP_PRECISE_SPEED;
545
        }
546
        else if (wxGetKeyState(WXK_DOWN))
547
        {
548
            teleop_l_speed = -TELEOP_PRECISE_SPEED;
549
            teleop_r_speed = -TELEOP_PRECISE_SPEED;
550
        }
551
        else if (wxGetKeyState(WXK_LEFT))
552
        {
553
            teleop_l_speed = -TELEOP_PRECISE_TURN_SPEED;
554
            teleop_r_speed = TELEOP_PRECISE_TURN_SPEED;
555
        }
556
        else if (wxGetKeyState(WXK_RIGHT))
557
        {
558
            teleop_l_speed = TELEOP_PRECISE_TURN_SPEED;
559
            teleop_r_speed = -TELEOP_PRECISE_TURN_SPEED;
560
        }
561
    }
562

    
563
    void SimFrame::teleop_move_fluid()
564
    {
565
        if (wxGetKeyState(WXK_UP))
566
        {
567
            teleop_fluid_speed += TELEOP_FLUID_INC * 2;
568
        }
569
        else if (wxGetKeyState(WXK_DOWN))
570
        {
571
            teleop_fluid_speed -= TELEOP_FLUID_INC * 2;
572
        }
573
        else if (teleop_fluid_speed > TELEOP_FLUID_INC)
574
        {
575
            teleop_fluid_speed -= TELEOP_FLUID_INC;
576
        }
577
        else if (teleop_fluid_speed < -TELEOP_FLUID_INC)
578
        {
579
            teleop_fluid_speed += TELEOP_FLUID_INC;
580
        }
581
        else
582
        {
583
            teleop_fluid_speed = 0;
584
        }
585

    
586
        if (wxGetKeyState(WXK_LEFT))
587
        {
588
            teleop_fluid_omega -= TELEOP_FLUID_INC * 2;
589
        }
590
        else if (wxGetKeyState(WXK_RIGHT))
591
        {
592
            teleop_fluid_omega += TELEOP_FLUID_INC * 2;
593
        }
594
        else
595
        {
596
            teleop_fluid_omega = 0;
597
        }
598

    
599
        if (teleop_fluid_speed > TELEOP_FLUID_MAX_SPEED)
600
        {
601
            teleop_fluid_speed = TELEOP_FLUID_MAX_SPEED;
602
        }
603
        else if (teleop_fluid_speed < -TELEOP_FLUID_MAX_SPEED)
604
        {
605
            teleop_fluid_speed = -TELEOP_FLUID_MAX_SPEED;
606
        }
607
        if (teleop_fluid_omega > TELEOP_FLUID_MAX_SPEED)
608
        {
609
            teleop_fluid_omega = TELEOP_FLUID_MAX_SPEED;
610
        }
611
        else if (teleop_fluid_omega < -TELEOP_FLUID_MAX_SPEED)
612
        {
613
            teleop_fluid_omega = -TELEOP_FLUID_MAX_SPEED;
614
        }
615

    
616
        int l_speed = teleop_fluid_speed + teleop_fluid_omega;
617
        int r_speed = teleop_fluid_speed - teleop_fluid_omega;
618

    
619
        teleop_l_speed = max(MIN_ABSOLUTE_SPEED,
620
                             min(MAX_ABSOLUTE_SPEED, l_speed));
621
        teleop_r_speed = max(MIN_ABSOLUTE_SPEED,
622
                             min(MAX_ABSOLUTE_SPEED, r_speed));
623
    }
624

    
625
    void SimFrame::teleop()
626
    {
627
        switch (teleop_type)
628
        {
629
            case TELEOP_OFF:
630
                return;
631
            case TELEOP_PRECISE:
632
                teleop_move_precise();
633
                break;
634
            case TELEOP_FLUID:
635
                teleop_move_fluid();
636
                break;
637
        }
638

    
639
        ::messages::set_motors msg;
640
        msg.fl_set = true;
641
        msg.fr_set = true;
642
        msg.bl_set = true;
643
        msg.br_set = true;
644
        msg.teleop_ON = true;
645

    
646
        msg.fl_speed = teleop_l_speed;
647
        msg.fr_speed = teleop_r_speed;
648
        msg.bl_speed = teleop_l_speed;
649
        msg.br_speed = teleop_r_speed;
650

    
651
        teleop_pub.publish(msg);
652
    }
653

    
654
    void SimFrame::updateScouts()
655
    {
656

    
657
        if (last_scout_update.isZero())
658
        {
659
            last_scout_update = ros::WallTime::now();
660
            return;
661
        }
662

    
663
        path_image = path_bitmap.ConvertToImage();
664
        Refresh();
665

    
666
        M_Scout::iterator it = scouts.begin();
667
        M_Scout::iterator end = scouts.end();
668

    
669
        M_Emitter::iterator m_it = emitters.begin();
670
        M_Emitter::iterator m_end = emitters.end();
671

    
672
        world_state state;
673
        state.canvas_width = width_in_meters;
674
        state.canvas_height = height_in_meters;
675

    
676

    
677
        for (; m_it != m_end; ++m_it)
678
        {
679

    
680
            m_it->second->update(SIM_TIME_REFRESH_RATE,
681
                               path_dc,
682
                               path_image, lines_image, walls_image,
683
                               path_dc.GetBackground().GetColour(),
684
                               state);
685
        }
686

    
687

    
688
        for (; it != end; ++it)
689
        {
690
            //ROS_INFO(it->second);
691
            geometry_msgs::Pose2D scout_pos;
692
            scout_pos = it->second->update(SIM_TIME_REFRESH_RATE,
693
                               path_dc, sonar_dc,
694
                               path_image, lines_image, walls_image,
695
                               path_dc.GetBackground().GetColour(),
696
                               sonar_dc.GetBackground().GetColour(),
697
                               state);
698

    
699
            checkBOM(scout_pos, it);            
700
        }
701

    
702

    
703
        for (unsigned int i = 0; i < ghost_scouts.size(); ++i)
704
        {
705
            ghost_scouts.at(i)->update(SIM_TIME_REFRESH_RATE, path_dc, sonar_dc,
706
                path_dc.GetBackground().GetColour(), state);
707
        }
708

    
709

    
710
        frame_count++;
711
    }
712

    
713

    
714
    void SimFrame::checkBOM(geometry_msgs::Pose2D scout_pos, 
715
                            M_Scout::iterator it)
716
     {
717

    
718
        M_Emitter::iterator m_it = emitters.begin();
719
        M_Emitter::iterator m_end = emitters.end();
720

    
721
        //Emitter default values
722
        double bom_aperture = PI / 3.0;
723
        double bom_distance = 1.0;
724
    
725
            //iterate over Emitters:
726
       for (; m_it != m_end; ++m_it)
727
        {
728
            geometry_msgs::Pose2D emitter_pos;
729
            emitter_pos = m_it->second->get_pos();
730
            if (is_inrange(scout_pos, emitter_pos, em_aperture, em_distance)) { 
731
            //if scout is within emitter range
732
            //check if emitter is within each BOM range
733
            double x_offset;
734
            double y_offset;    
735
            double offset_angle;
736
            double diag_dis = pow((pow((SCOUT_W/2.0),2) + 
737
                              pow((SCOUT_H/2.0),2)),(0.5));
738

    
739
                for (int i = 0; i<10; i++) {
740
                geometry_msgs::Pose2D bom_pos;
741
                
742
                if (i == 2) { //middle left
743
                    offset_angle = PI/2.0;
744
                    bom_pos.theta = scout_pos.theta + PI/2.0;
745
                }
746
                else if (i == 7) { //middle right
747
                    offset_angle = 3*PI/2.0;
748
                    bom_pos.theta = scout_pos.theta + 3.0*PI/2.0;
749
                }
750
                else if (i < 2) { //top left
751
                    offset_angle =  atan(abs((SCOUT_W/2.0)/(SCOUT_H/2.0)));
752
                    bom_pos.theta = scout_pos.theta + PI/2.0 * i;
753
                }
754
                else if (i >= 2 && i <5) { //bottom left
755
                    offset_angle =  PI - atan(abs((SCOUT_W/2.0)/(SCOUT_H/2.0)));
756
                    bom_pos.theta = scout_pos.theta + PI/2.0 + PI/2.0 * (i/4);
757
                }
758
                else if (i >= 5 && i < 8) { //bottom right
759
                    offset_angle =  PI + atan(abs((SCOUT_W/2.0)/(SCOUT_H/2.0)));
760
                    bom_pos.theta = scout_pos.theta + PI + PI/2.0 * (i/6);
761
                }
762
                else { //top right
763
                    offset_angle =  2*PI - atan(abs((SCOUT_W/2.0)/(SCOUT_H/2.0)));
764
                    bom_pos.theta = scout_pos.theta + 3*PI/2.0 + PI/2.0 * (i/9);
765
                }
766
                offset_angle += scout_pos.theta;
767
                
768
                if (i == 2 || i == 7) {
769
                    x_offset = (SCOUT_W/2.0)*cos(offset_angle);
770
                    y_offset = (SCOUT_W/2.0)*sin(offset_angle);
771
                }
772
                else {
773
                    x_offset = diag_dis*cos(offset_angle);
774
                    y_offset = diag_dis*sin(offset_angle);
775
                }
776

    
777
                bom_pos.x = scout_pos.x + x_offset;
778
                bom_pos.y = scout_pos.y - y_offset;  
779

    
780
                if (bom_pos.theta > 2*PI) {
781
                    bom_pos.theta -= 2*PI;
782
                }  
783
                else if (bom_pos.theta < 0) {
784
                    bom_pos.theta += 2*PI;
785
                }
786

    
787
                if(is_inrange(emitter_pos, bom_pos, bom_aperture, bom_distance)) {
788
                    string em_id_str = m_it->first.substr(m_it->first.find("_")+1);
789
                    int emitter_id = atoi(em_id_str.c_str());
790
                    it->second->update_BOM(i, 1, emitter_id);
791
                }
792
                else {
793
                    it->second->update_BOM(i, 0, 0);
794
                }
795
                }
796
            }
797
        }
798

    
799
    }
800

    
801

    
802
    bool SimFrame::clearCallback(std_srvs::Empty::Request&,
803
                                 std_srvs::Empty::Response&)
804
    {
805
        ROS_INFO("Clearing scoutsim.");
806
        clear();
807
        return true;
808
    }
809

    
810
    bool SimFrame::resetCallback(std_srvs::Empty::Request&,
811
                                 std_srvs::Empty::Response&)
812
    {
813
        ROS_INFO("Resetting scoutsim.");
814
        scouts.clear();
815
        id_counter = 0;
816
        BOM_counter = 0;
817

    
818
        spawnScout("", width_in_meters / 2.0, height_in_meters / 2.0, 0);
819
        clear();
820
        return true;
821
    }
822

    
823
    void SimFrame::wirelessCallback(const ::messages::WirelessPacket::ConstPtr& msg)
824
    {
825
        wireless_receive.publish(msg);
826
    }
827

    
828

    
829
    bool SimFrame::is_inrange(geometry_msgs::Pose2D scout_pos,
830
                           geometry_msgs::Pose2D emitter_pos,
831
                           double aperture, double distance)
832
                           
833
    {
834
        //ROS_INFO("SCOUT: %f %f %f ", scout_pos.x, scout_pos.x, scout_pos.theta);
835
        //ROS_INFO("EMITTER: %f %f %f ", emitter_pos.x, emitter_pos.x, emitter_pos.theta);
836
        double se_distance = pow((pow((scout_pos.x - emitter_pos.x),2) + 
837
                              pow((scout_pos.y - emitter_pos.y),2)),(0.5));
838
        double se_angle = atan((scout_pos.x - emitter_pos.x)/(scout_pos.y - emitter_pos.y));
839
        if (scout_pos.y < emitter_pos.y)
840
        {
841
            se_angle = se_angle + PI/2;
842
        }        
843
        else 
844
        {
845
            se_angle = se_angle + PI*3/2;
846
        }
847
        double emitter_orient = emitter_pos.theta;
848
        
849
        //ROS_INFO("distance: %f, angle: %f, orient: %f", se_distance, se_angle, emitter_orient);
850

    
851
        if ((se_distance <= distance)) { //distance check
852

    
853
            double upper_limit = (emitter_orient + aperture/2);
854
            double lower_limit = (emitter_orient - aperture/2);
855

    
856
            //ROS_INFO("upper: %f, lower: %f", upper_limit, lower_limit+2*PI);
857

    
858
            if (upper_limit > 2*PI) {
859
               if (((se_angle < 2*PI) && (se_angle > (lower_limit))) ||
860
                   ((se_angle < upper_limit-2*PI) && (se_angle >= 0))) {
861
                return true;
862
                }
863
                
864
            }
865
            else if (lower_limit < 0) {
866
                if (((se_angle < 2*PI) && (se_angle > (lower_limit+2*PI))) ||
867
                   ((se_angle < upper_limit) && (se_angle >= 0))) {
868
                return true;
869
                }
870

    
871

    
872
            }
873
            else {
874
                if ((se_angle < upper_limit) && //angle check 
875
                    (se_angle > lower_limit)) {
876
                return true;
877
                }   
878
            }
879
        }
880
        return false;
881
            
882
    }
883

    
884
}
885

    
886
/** @} */