File: Character.cpp

package info (click to toggle)
cyphesis-cpp 0.5.16-1
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 5,084 kB
  • ctags: 3,627
  • sloc: cpp: 30,418; python: 4,812; xml: 4,674; sh: 4,118; makefile: 902; ansic: 617
file content (1751 lines) | stat: -rw-r--r-- 58,698 bytes parent folder | download
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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
// Cyphesis Online RPG Server and AI Engine
// Copyright (C) 2000,2001 Alistair Riddoch
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

// $Id: Character.cpp,v 1.323 2008-05-28 19:42:36 alriddoch Exp $

#include "Character.h"

#include "Pedestrian.h"
#include "MindFactory.h"
#include "BaseMind.h"
#include "Script.h"
#include "World.h"
#include "Task.h"
#include "StatisticsProperty.h"
#include "EntityProperty.h"
#include "OutfitProperty.h"

#include "common/op_switch.h"
#include "common/const.h"
#include "common/debug.h"
#include "common/globals.h"
#include "common/log.h"
#include "common/TypeNode.h"
#include "common/serialno.h"
#include "common/compose.hpp"
#include "common/PropertyManager.h"

#include "common/Actuate.h"
#include "common/Attack.h"
#include "common/Eat.h"
#include "common/Nourish.h"
#include "common/Setup.h"
#include "common/Tick.h"
#include "common/Unseen.h"
#include "common/Update.h"

#include <wfmath/atlasconv.h>

#include <Atlas/Objects/Operation.h>
#include <Atlas/Objects/Anonymous.h>

#include <cassert>

using Atlas::Message::Element;
using Atlas::Message::ListType;
using Atlas::Message::MapType;
using Atlas::Objects::Root;
using Atlas::Objects::Operation::Set;
using Atlas::Objects::Operation::Sight;
using Atlas::Objects::Operation::Sound;
using Atlas::Objects::Operation::Tick;
using Atlas::Objects::Operation::Look;
using Atlas::Objects::Operation::Move;
using Atlas::Objects::Operation::Setup;
using Atlas::Objects::Operation::Action;
using Atlas::Objects::Operation::Unseen;
using Atlas::Objects::Operation::Nourish;
using Atlas::Objects::Operation::Appearance;
using Atlas::Objects::Operation::Update;
using Atlas::Objects::Operation::Wield;
using Atlas::Objects::Entity::Anonymous;
using Atlas::Objects::Entity::RootEntity;

using Atlas::Objects::smart_dynamic_cast;

static const bool debug_flag = false;

// This figure is calculated to allow a character to live for 4 weeks
// without food, during which time they will lose 40% of their mass
// before starving.
const double Character::energyConsumption = 0.0001;

// Food consumption is fast, to keep Acorn playable
const double Character::foodConsumption = 0.1;

// When the character is starving, they start to lose weight. During
// the latter 2 and a half weeks, they lose about 40% of their mass.
// Bad players who do not feed their characters will be punished.
const double Character::weightConsumption = 0.00002;

// Ammount of evergy turned into weight by metabolism when Character
// is well fed.
const double Character::energyLaidDown = 0.1;

// Ammount of weight gained as a result. High for Acorn.
const double Character::weightGain = 0.5;

static const std::string RIGHT_HAND_WIELD = "right_hand_wield";
static const std::string OUTFIT = "outfit";

/// \brief Calculate how the Characters metabolism has affected it in the
/// last tick
///
/// This function is called every 90 seconds. It does one of three things.
/// If energy is very high, it loses some, and gains some weight. Otherwise
/// it loses some energy, unless energy is very low, in which case loss
/// is slower, as weight is used to compensate.
/// A fully healthy Character should take about a week to starve to death.
/// So 10080 / 90 = 6720 ticks.
/// @param res Any result of changes is returned here.
/// @param ammount Time scale factor, currently not used.
void Character::metabolise(OpVector & res, double ammount)
{
    bool stamina_changed = false,
         mass_changed = false;

    // Currently handles energy
    // We should probably call this whenever the entity performs a movement.

    PropertyBase * status_prop = getProperty("status");
    if (status_prop == 0) {
        status_prop = PropertyManager::instance()->addProperty(this, "status");
        if (status_prop == 0) {
            log(ERROR, "Unable to get a STATUS property.");
            return;
        }
        m_properties["status"] = status_prop;
        status_prop->set(1.f);
    }
    Element value;
    status_prop->get(value);
    assert(value.isFloat());
    float status = value.asFloat();

    Anonymous update_arg;
    update_arg->setId(getId());

    PropertyBase * food_prop = getProperty("food");
    // DIGEST
    if (food_prop != 0 && food_prop->get(value) && value.isFloat()) {
        float food = value.Float();
        if (food >= foodConsumption && status < 2) {
            // It is important that the metabolise bit is done next, as this
            // handles the status change
            status += foodConsumption;
            food -= foodConsumption;
            food_prop->set(food);

            update_arg->setAttr("food", food);
        }
    }

    PropertyBase * mass_prop = getProperty("mass");
    float mass = 0.f;
    if (mass_prop != 0 && mass_prop->get(value) && value.isFloat()) {
        mass = value.Float();
    }
    // If status is very high, we gain weight
    if (status > (1.5 + energyLaidDown) && mass < m_maxMass) {
        status -= energyLaidDown;
        mass += weightGain;
        mass_changed = true;
    } else {
        // If status is relatively is not very high, then energy is burned
        double energy_used = energyConsumption * ammount;
        double weight_used = weightConsumption * mass * ammount;
        if (status <= 0.5 && mass > weight_used) {
            // Drain away a little energy and lose some weight
            // This ensures there is a long term penalty to allowing something
            // to starve
            status -= (energy_used / 2);
            mass -= weight_used;
            mass_changed = true;
        } else {
            // Just drain away a little energy
            status -= energy_used;
        }
    }
    if (m_stamina < 1. && m_task == 0 && !m_movement.updateNeeded(m_location)) {
        m_stamina = 1.;
        stamina_changed = true;
    }

    status_prop->set(status);
    update_arg->setAttr("status", status);

    if (mass_changed && mass_prop != 0) {
        mass_prop->set(mass);
        update_arg->setAttr("mass", mass);
    }
    if (stamina_changed) {
        update_arg->setAttr("stamina", m_stamina);
    }

    Update update;
    update->setTo(getId());
    update->setArgs1(update_arg);

    res.push_back(update);
}

/// \brief Hooked to the Entity::containered signal of the wielded entity
/// to indicate a change of location
///
/// This function responds by removing it as a wielded entity.
void Character::wieldDropped()
{
    Wield wield;
    wield->setTo(getId());
    sendWorld(wield);
}

/// \brief Search for an entity in an entities contents
///
/// Recursive function the finds an entity by ID in another entities
/// contains list.
/// @param ent Entity to search in
/// @param id Identifier of entity to search for
LocatedEntity * Character::findInContains(LocatedEntity * ent,
                                          const std::string & id)
{
    if (ent->m_contains == 0) {
        return 0;
    }
    LocatedEntitySet::const_iterator I = ent->m_contains->begin();
    LocatedEntitySet::const_iterator Iend = ent->m_contains->end();
    for (; I != Iend; ++I) {
        LocatedEntity * child = *I;
        if (child->getId() == id) {
            return *I;
        }
        if (child->m_contains != 0 && !child->m_contains->empty()) {
            LocatedEntity * found = findInContains(child, id);
            if (found != 0) {
                return found;
            }
        }
    }
    return 0;
}

/// \brief Search for an entity in the Character's inventory
///
/// Implemented using the recursive function findInContains.
/// @param id Identifier of entity to search for
LocatedEntity * Character::findInInventory(const std::string & id)
{
    return findInContains(this, id);
}

/// \brief Character constructor
///
/// @param id String identifier
/// @param intId Integer identifier
Character::Character(const std::string & id, long intId) :
           Identified(id, intId),
           Character_parent(id, intId),
               m_statistics(*this),
               m_movement(*new Pedestrian(*this)),
               m_task(0), m_isAlive(true),
               m_stamina(1.),
               m_maxMass(100),
               m_mind(0), m_externalMind(0)
{
    m_location.setBBox(BBox(WFMath::Point<3>(-0.25, -0.25, 0),
                            WFMath::Point<3>(0.25, 0.25, 2)));

    m_properties["stamina"] = new Property<double>(m_stamina, 0);
    m_properties["statistics"] = new StatisticsProperty(m_statistics, 0);
    m_properties[RIGHT_HAND_WIELD] = new EntityProperty;
}

Character::~Character()
{
    delete &m_movement;
    if (m_mind != 0) {
        delete m_mind;
    }
    if (m_externalMind != 0) {
        delete m_externalMind;
    }
}

/// \brief Set a new task as the one being performed by the Character
///
/// The old one is cleared and deleted if present
/// @param task The new task to be assigned to the Character
void Character::setTask(Task * task)
{
    if (m_task != 0) {
        clearTask();
    }
    m_task = task;
    task->incRef();

    updateTask();
}

/// \brief Update the visible representation of the current task
///
/// Generate a Set operation which modifies the Characters task property
/// to reflect the current status of the task.
void Character::updateTask()
{
    if (m_task == 0) {
        log(ERROR, "Character::updateTask called when no task running");
    }

    Anonymous set_arg;
    m_task->addToEntity(set_arg);
    set_arg->setId(getId());

    Set set;
    set->setArgs1(set_arg);
    set->setTo(getId());
    
    sendWorld(set);
}

/// \brief Clean up and remove the task currently being executed
///
/// Remove the task, and send an operation indicating that no tasks
/// are now present.
void Character::clearTask()
{
    if (m_task == 0) {
        log(ERROR, "Character.clearTask: No task currently set");
        return;
    }
    m_task->decRef();
    m_task = 0;

    Anonymous set_arg;
    set_arg->setAttr("tasks", ListType());
    set_arg->setId(getId());

    Set set;
    set->setArgs1(set_arg);
    set->setTo(getId());
    
    sendWorld(set);
}

void Character::ImaginaryOperation(const Operation & op, OpVector & res)
{
    Sight s;
    s->setArgs1(op);
    res.push_back(s);
}

void Character::SetupOperation(const Operation & op, OpVector & res)
{
    debug( std::cout << "CHaracter::SetupOperation()" << std::endl
                     << std::flush;);

    if (!op->getArgs().empty()) {
        debug( std::cout << __func__ << " Setup op is for subsystem" << std::endl << std::flush;);
        return;
    }

    if (0 == m_externalMind) {
        // This ensures that newly created player characters don't get
        // bogged down with an NPC mind. In the short term this
        // takes away PC programmability.
        // FIXME Characters restored from the database will still get
        // AI minds, so  we need to handle them somehow differently.
        // Perhaps the Restore op (different from Setup op) is needed?

        m_mind = MindFactory::instance()->newMind(getId(), getIntId(), m_type);

        Operation s(op.copy());
        Anonymous setup_arg;
        setup_arg->setName("mind");
        s->setArgs1(setup_arg);
        res.push_back(s);

        Look l;
        l->setTo(getId());
        res.push_back(l);
    }

    Tick tick;
    tick->setTo(getId());
    res.push_back(tick);
}

void Character::TickOperation(const Operation & op, OpVector & res)
{
    debug(std::cout << "================================" << std::endl
                    << std::flush;);
    const std::vector<Root> & args = op->getArgs();
    if (!args.empty()) {
        const Root & arg = args.front();
        if (arg->getName() == "move") {
            // Deal with movement.
            Element serialno;
            if (arg->copyAttr("serialno", serialno) == 0 && (serialno.isInt())) {
                if (serialno.asInt() < m_movement.serialno()) {
                    debug(std::cout << "Old tick" << std::endl << std::flush;);
                    return;
                }
            } else {
                log(ERROR, "Character::TickOperation: No serialno in tick arg");
            }
            Location return_location;
            if (m_movement.getUpdatedLocation(return_location)) {
                return;
            }
            res.push_back(m_movement.generateMove(return_location));
            Anonymous tick_arg;
            tick_arg->setName("move");
            tick_arg->setAttr("serialno", m_movement.serialno());
            Tick tickOp;
            tickOp->setTo(getId());
            tickOp->setFutureSeconds(m_movement.getTickAddition(return_location.pos(), return_location.velocity()));
            tickOp->setArgs1(tick_arg);
            res.push_back(tickOp);
        } else if (arg->getName() == "task") {
            // Deal with task iteration
            if (m_task == 0) {
                return;
            }
            Element serialno;
            if (arg->copyAttr("serialno", serialno) == 0 && (serialno.isInt())) {
                if (serialno.asInt() != m_task->serialno()) {
                    debug(std::cout << "Old tick" << std::endl << std::flush;);
                    return;
                }
            } else {
                log(ERROR, "Character::TickOperation: No serialno in tick arg");
                return;
            }
            m_task->TickOperation(op, res);
            assert(m_task != 0);
            if (m_task->obsolete()) {
                clearTask();
            } else {
                updateTask();
            }
        } else if (arg->getName() == "mind") {
            // Do nothing. Passed to mind.
        } else {
            debug(std::cout << "Tick to unknown subsystem " << arg->getName()
                            << " arrived" << std::endl << std::flush;);
        }
    } else {
        // METABOLISE
        metabolise(res);
        
        // TICK
        Tick tickOp;
        tickOp->setTo(getId());
        tickOp->setFutureSeconds(consts::basic_tick * 30);
        res.push_back(tickOp);
    }
}

void Character::TalkOperation(const Operation & op, OpVector & res)
{
    debug( std::cout << "Character::OPeration(Talk)" << std::endl<<std::flush;);
    Sound s;
    s->setArgs1(op);
    res.push_back(s);
}

void Character::NourishOperation(const Operation & op, OpVector & res)
{
    if (op->getArgs().empty()) {
        error(op, "Nourish has no argument", res, getId());
        return;
    }
    const Root & arg = op->getArgs().front();
    Element mass_attr;
    if (arg->copyAttr("mass", mass_attr) != 0 || !mass_attr.isNum()) {
        return;
    }

    PropertyBase * food_property = getProperty("food");
    if (food_property == 0) {
        food_property = PropertyManager::instance()->addProperty(this, "food");
        if (food_property == 0) {
            log(ERROR, "Unable to set a FOOD property.");
            return;
        }
        m_properties["food"] = food_property;
    }
    Element value;
    food_property->get(value);
    assert(value.isFloat());
    float food = value.Float();
    food = food + mass_attr.asNum();
    food_property->set(food);

    Anonymous food_ent;
    food_ent->setId(getId());
    food_ent->setAttr("food", food);

    Set s;
    s->setArgs1(food_ent);
    // FIXME FROM, SECONDS?

    Sight si;
    si->setTo(getId());
    si->setArgs1(s);
    res.push_back(si);
}

void Character::WieldOperation(const Operation & op, OpVector & res)
{
    if (op->getArgs().empty()) {
        EntityProperty * rhw = getSpecificProperty<EntityProperty>(RIGHT_HAND_WIELD);
        if (rhw == 0) {
            return;
        }

        rhw->data() = EntityRef(0);
        // FIXME Remove the property?

        // FIXME Make sure we stop wielding if the container changes,
        // but connections are cleared, and don't build up.
        // if (m_rightHandWieldConnection.connected()) {
            // m_rightHandWieldConnection.disconnect();
        // }

        Update update;
        update->setTo(getId());
        Anonymous update_arg;
        update_arg->setId(getId());
        update_arg->setAttr(RIGHT_HAND_WIELD, "");
        update->setArgs1(update_arg);
        res.push_back(update);

        return;
    }
    const Root & arg = op->getArgs().front();
    if (!arg->hasAttrFlag(Atlas::Objects::ID_FLAG)) {
        error(op, "Wield arg has no ID", res, getId());
        return;
    }
    const std::string & id = arg->getId();
    Entity * item = BaseWorld::instance().getEntity(id);
    if (item == 0) {
        error(op, "Wield arg does not exist", res, getId());
        return;
    }

    if (m_contains == 0 || m_contains->find(item) == m_contains->end()) {
        error(op, "Wield arg is not in inventory", res, getId());
        return;
    }

    Anonymous update_arg;
    update_arg->setId(getId());

    Element worn_attr;
    if (item->getAttr("worn", worn_attr)) {
        debug(std::cout << "Got wield for a garment" << std::endl << std::flush;);
        
        if (worn_attr.isString()) {
            OutfitProperty * outfit = requireSpecificProperty<OutfitProperty>(OUTFIT);
            outfit->wear(this, worn_attr.String(), item);
            outfit->cleanUp();

            update_arg->setAttr(OUTFIT, MapType());
        } else {
            log(WARNING, "Got clothing with non-string worn attribute.");
        }
        // FIXME Implement adding stuff to the outfit propert, as efficiently
        // as possible
        // Must make sure that we can install the entity we have already
        // looked up here, and fix the GuiseProperty code so it does not
        // need a repeat lookup
    } else {
        debug(std::cout << "Got wield for a tool" << std::endl << std::flush;);

        EntityProperty * rhw = requireSpecificProperty<EntityProperty>(RIGHT_HAND_WIELD);
        // FIXME Make sure we don't stay linked to the previous wielded
        // tool.
        // if (m_rightHandWieldConnection.connected()) {
            // m_rightHandWieldConnection.disconnect();
        // }

        // The value is ignored by the update handler, but should be the
        // right type.
        update_arg->setAttr(RIGHT_HAND_WIELD, item->getId());
        rhw->data() = EntityRef(item);

        item->containered.connect(sigc::mem_fun(this, &Character::wieldDropped));

        debug(std::cout << "Wielding " << item->getId() << std::endl << std::flush;);
    }

    Update update;
    update->setTo(getId());
    update->setArgs1(update_arg);
    res.push_back(update);
}

void Character::AttackOperation(const Operation & op, OpVector & res)
{
    const std::string & from = op->getFrom();
    if (from == getId()) {
        return;
    }

    Entity * attack_ent = BaseWorld::instance().getEntity(op->getFrom());
    if (attack_ent == 0) {
        log(ERROR, "AttackOperation: Attack op from non-existant ID");
        return;
    }

    Character * attacker = dynamic_cast<Character *>(attack_ent);

    if (attacker == 0) {
        log(ERROR, "AttackOperation: Attack op from non-character entity");
        return;
    }

    if (attacker->m_task != 0) {
        log(ERROR, String::compose("AttackOperation: Attack op aborted "
                                   "because attacker %1(%2) busy.",
                                   attacker->getId(), attacker->getType()));
        return;
    }

    if (m_task != 0) {
        log(ERROR, String::compose("AttackOperation: Attack op aborted "
                                   "because defender %1(%2) busy.",
                                   getId(), getType()));
        return;
    }

    Task * combat = BaseWorld::instance().newTask("combat", *this);

    if (combat == 0) {
        log(ERROR, "Character::AttackOperation: Unable to create combat task");
        return;
    }

    setTask(combat);
    m_task->initTask(op, res);
    if (m_task->obsolete()) {
        clearTask();
        return;
    }

    combat = BaseWorld::instance().newTask("combat", *attacker);

    if (combat == 0) {
        log(ERROR, "Character::AttackOperation: Unable to create combat task");
        return;
    }

    attacker->setTask(combat);
    attacker->m_task->initTask(op, res);
    if (attacker->m_task->obsolete()) {
        attacker->clearTask();
        clearTask();
        return;
    }
}

/// \brief Filter an Actuate operation coming from the mind
///
/// @param op The operation to be filtered.
/// @param res The filtered result is returned here.
void Character::mindActuateOperation(const Operation & op, OpVector & res)
{
    debug(std::cout << "Got Acuate op from mind" << std::endl << std::flush;);

    const std::vector<Root> & args = op->getArgs();
    if (args.empty()) {
        error(op, "Character::mindActuateOp No arg.", res, getId());
        return;
    }


    RootEntity entity_arg(0);

    assert(!entity_arg.isValid());

    std::string op_type;

    // Look at Actuate args. If arg is an entity, this is the target.
    // If arg is an operation, this is the operation to be used, and the
    // sub op arg may be an entity specifying target. If op to be used is
    // specified, this is checked against the ops permitted by this tool.
    const Root & arg = args.front();
    const std::string & argtype = arg->getObjtype();
    if (argtype == "op") {
        if (!arg->hasAttrFlag(Atlas::Objects::PARENTS_FLAG) ||
            (arg->getParents().empty())) {
            error(op, "Use arg op has malformed parents", res, getId());
            return;
        }
        op_type = arg->getParents().front();
        debug(std::cout << "Got op type " << op_type << " from arg"
                        << std::endl << std::flush;);
        // Check against valid ops
        Operation arg_op = smart_dynamic_cast<Operation>(arg);
        if (!arg_op.isValid()) {
            error(op, "Use op arg is a malformed op", res, getId());
            return;
        }

        const std::vector<Root> & arg_op_args = arg_op->getArgs();
        if (!arg_op_args.empty()) {
            entity_arg = smart_dynamic_cast<RootEntity>(arg_op_args.front());
            if (!entity_arg.isValid()) {
                error(op, "Use op target is malformed", res, getId());
                return;
            }
        }
    } else if (argtype == "obj") {
        entity_arg = smart_dynamic_cast<RootEntity>(arg);
        if (!entity_arg.isValid()) {
            error(op, "Use target is malformed", res, getId());
            return;
        }
    } else {
        error(op, "Use arg has unknown objtype", res, getId());
        return;
    }

    if (!entity_arg.isValid()) {
        error(op, "Character::mindActuateOperation No target specified", res, getId());
        return;
    }

    if (!entity_arg->hasAttrFlag(Atlas::Objects::ID_FLAG)) {
        error(op, "Character::mindActuateOperation Target entity has no ID", res, getId());
        return;
    }

    if (op_type.empty()) {
        error(op, "Character::mindActuateOperation Unable to determine op type for tool", res, getId());
        return;
    }

    Entity * device = BaseWorld::instance().getEntity(entity_arg->getId());

    Element deviceOpAttr;
    std::set<std::string> deviceOps;

    // Determine the actions this device supports
    if (!device->getAttr("actions", deviceOpAttr)) {
        log(NOTICE, "Character::mindActuateOp Attempt to actuate something not a device");
        return;
    }

    if (!deviceOpAttr.isList()) {
        log(ERROR, "Character::mindActuateOp device has non list operations list");
        return;
    }
    const ListType & deviceOpList = deviceOpAttr.asList();
    if (deviceOpList.empty()) {
        log(ERROR, "Character::mindActuateOp device operation list is empty");
        return;
    }
    ListType::const_iterator J = deviceOpList.begin();
    ListType::const_iterator Jend = deviceOpList.end();
    assert(J != Jend);

    for (; J != Jend; ++J) {
        if (!(*J).isString()) {
            log(ERROR, "Character::mindActuateOp device has non string in operations list");
        } else {
            deviceOps.insert((*J).String());
        }
    }

    if (op_type.empty()) {
        op_type = deviceOpList.front().asString();
    } else if (deviceOps.find(op_type) == deviceOps.end()) {
        error(op, "Actuate op is not permitted by device", res, getId());
        return;
    }

    debug(std::cout << "Actuating device " << device->getType()
                    << " with " << op_type << " action."
                    << std::endl << std::flush;);

    Root obj = Atlas::Objects::Factories::instance()->createObject(op_type);
    if (!obj.isValid()) {
        log(ERROR,
            String::compose("Character::mindActuateOperation Unknown op type "
                            "\"%1\" requested by \"%2\" device.",
                            op_type, device->getType()));
        return;
    }
    Operation rop = smart_dynamic_cast<Operation>(obj);
    if (!rop.isValid()) {
        log(ERROR, String::compose("Character::mindActuateOperation Op type "
                                   "\"%1\" requested by %2 device, "
                                   "but it is not an operation type",
                                   op_type, device->getType()));
        // FIXME Think hard about how this error is reported. Would the error
        // make it back to the client if we made an error response?
        return;
    }

    rop->setTo(device->getId());

    res.push_back(rop);

    // Sight sight;
    // sight->setArgs1(rop);
    // res.push_back(sight);
}

/// \brief Filter a Attack operation coming from the mind
///
/// @param op The operation to be filtered.
/// @param res The filtered result is returned here.
void Character::mindAttackOperation(const Operation & op, OpVector & res)
{
    const std::vector<Root> & args = op->getArgs();
    if (args.empty()) {
        log(ERROR, "mindAttackOperation: attack op has no argument");
        return;
    }
    const Root & arg = args.front();
    if (!arg->hasAttrFlag(Atlas::Objects::ID_FLAG)) {
        log(ERROR, "mindAttackOperation: attack op arg has no ID");
        return;
    }
    const std::string & id = arg->getId();

    op->setTo(id);
    res.push_back(op);
}

/// \brief Filter a Setup operation coming from the mind
///
/// @param op The operation to be filtered.
/// @param res The filtered result is returned here.
void Character::mindSetupOperation(const Operation & op, OpVector & res)
{
    Anonymous setup_arg;
    setup_arg->setName("mind");
    op->setArgs1(setup_arg);
    op->setTo(getId());
    res.push_back(op);
}

/// \brief Filter a Use operation coming from the mind
///
/// @param op The operation to be filtered.
/// @param res The filtered result is returned here.
void Character::mindUseOperation(const Operation & op, OpVector & res)
{
    debug(std::cout << "Got Use op from mind" << std::endl << std::flush;);

    const std::vector<Root> & args = op->getArgs();
    if (args.empty()) {
        if (m_task != 0) {
            if (!m_task->obsolete()) {
                m_task->irrelevant();
            }
            assert(m_task->obsolete());
            clearTask();
        }
        return;
    }

    EntityProperty * rhw = getSpecificProperty<EntityProperty>(RIGHT_HAND_WIELD);
    if (rhw == 0) {
        error(op, "Character::mindUseOp No tool wielded.", res, getId());
        return;
    }

    Entity * tool = rhw->data().get();
    if (tool == 0) {
        error(op, "Character::mindUseOp No tool wielded.", res, getId());
        return;
    }
    // FIXME Get a tool id from the op attributes?

    Element toolOpAttr;
    std::set<std::string> toolOps;
    std::string op_type;

    // Determine the operations this tool supports
    if (!tool->getAttr("operations", toolOpAttr)) {
        log(NOTICE, "Character::mindUseOp Attempt to use something not a tool");
        return;
    }

    if (!toolOpAttr.isList()) {
        log(ERROR, "Character::mindUseOp Tool has non list operations list");
        return;
    }
    const ListType & toolOpList = toolOpAttr.asList();
    if (toolOpList.empty()) {
        log(ERROR, "Character::mindUseOp Tool operation list is empty");
        return;
    }
    ListType::const_iterator J = toolOpList.begin();
    ListType::const_iterator Jend = toolOpList.end();
    assert(J != Jend);
    if (!(*J).isString()) {
        log(ERROR, "Character::mindUseOp Tool operation list is malformed");
        return;
    }
    op_type = (*J).String();
    debug(std::cout << "default tool op is " << op_type << std::endl
                                                        << std::flush;);
    for (; J != Jend; ++J) {
        if (!(*J).isString()) {
            log(ERROR, "Character::mindUseOp Tool has non string in operations list");
        } else {
            toolOps.insert((*J).String());
        }
    }


    RootEntity entity_arg(0);

    assert(!entity_arg.isValid());

    // Look at Use args. If arg is an entity, this is the target.
    // If arg is an operation, this is the operation to be used, and the
    // sub op arg may be an entity specifying target. If op to be used is
    // specified, this is checked against the ops permitted by this tool.
    const Root & arg = args.front();
    const std::string & argtype = arg->getObjtype();
    if (argtype == "op") {
        if (!arg->hasAttrFlag(Atlas::Objects::PARENTS_FLAG) ||
            (arg->getParents().empty())) {
            error(op, "Use arg op has malformed parents", res, getId());
            return;
        }
        op_type = arg->getParents().front();
        debug(std::cout << "Got op type " << op_type << " from arg"
                        << std::endl << std::flush;);
        if (toolOps.find(op_type) == toolOps.end()) {
            error(op, "Use op is not permitted by tool", res, getId());
            return;
        }
        // Check against valid ops
        Operation arg_op = smart_dynamic_cast<Operation>(arg);
        if (!arg_op.isValid()) {
            error(op, "Use op arg is a malformed op", res, getId());
            return;
        }

        const std::vector<Root> & arg_op_args = arg_op->getArgs();
        if (!arg_op_args.empty()) {
            entity_arg = smart_dynamic_cast<RootEntity>(arg_op_args.front());
            if (!entity_arg.isValid()) {
                error(op, "Use op target is malformed", res, getId());
                return;
            }
        }
    } else if (argtype == "obj") {
        entity_arg = smart_dynamic_cast<RootEntity>(arg);
        if (!entity_arg.isValid()) {
            error(op, "Use target is malformed", res, getId());
            return;
        }
    } else {
        error(op, "Use arg has unknown objtype", res, getId());
        return;
    }

    Anonymous target;
    if (!entity_arg.isValid()) {
        error(op, "Character::mindUseOperation No target specified", res, getId());
        return;
    }

    if (!entity_arg->hasAttrFlag(Atlas::Objects::ID_FLAG)) {
        error(op, "Character::mindUseOperation Target entity has no ID", res, getId());
        return;
    }
    target->setId(entity_arg->getId());

    if (entity_arg->hasAttrFlag(Atlas::Objects::Entity::POS_FLAG)) {
        target->setPos(entity_arg->getPos());
    }

    if (op_type.empty()) {
        error(op, "Character::mindUseOperation Unable to determine op type for tool", res, getId());
        return;
    }

    debug(std::cout << "Using tool " << tool->getType() << " on "
                    << target->getId()
                    << " with " << op_type << " action."
                    << std::endl << std::flush;);

    Root obj = Atlas::Objects::Factories::instance()->createObject(op_type);
    if (!obj.isValid()) {
        log(ERROR,
            String::compose("Character::mindUseOperation Unknown op type "
                            "\"%1\" requested by \"%2\" tool.",
                            op_type, tool->getType()));
        return;
    }
    Operation rop = smart_dynamic_cast<Operation>(obj);
    if (!rop.isValid()) {
        log(ERROR, String::compose("Character::mindUseOperation Op type "
                                   "\"%1\" requested by %2 tool, "
                                   "but it is not an operation type",
                                   op_type, tool->getType()));
        // FIXME Think hard about how this error is reported. Would the error
        // make it back to the client if we made an error response?
        return;
    } else if (!target->hasAttrFlag(Atlas::Objects::ID_FLAG)) {
        debug(std::cout << "No target" << std::endl << std::flush;);
    } else {
        rop->setArgs1(target);
    }

    rop->setTo(tool->getId());

    Entity * target_ent = BaseWorld::instance().getEntity(entity_arg->getId());
    if (target_ent == 0) {
        error(op, "Character::mindUseOperation Target does not exist", res, getId());
        return;
    }

    Task * task = BaseWorld::instance().activateTask(tool->getType()->name(),
                                                     op_type,
                                                     target_ent->getType()->name(),
                                                     *this);
    if (task != NULL) {
        setTask(task);
        assert(res.empty());
        m_task->initTask(rop, res);
        if (m_task->obsolete()) {
            clearTask();
        } else if (res.empty()) {
            // If initialising the task did not result in any operation at all
            // then the task cannot work correctly. In this case all we can
            // do is flag an error, and get rid of the task.
            log(ERROR, String::compose("Character::mindUseOperation Op type "
                                       "\"%1\" of tool \"%2\" activated a task,"
                                       " but it did not initialise",
                                       op_type, tool->getType()));
            m_task->irrelevant();
            clearTask();
        }
        return;
    }

    res.push_back(rop);

    Sight sight;
    sight->setArgs1(rop);
    res.push_back(sight);
}

/// \brief Filter a Update operation coming from the mind
///
/// @param op The operation to be filtered.
/// @param res The filtered result is returned here.
void Character::mindUpdateOperation(const Operation & op, OpVector & res)
{
}

/// \brief Filter a Wield operation coming from the mind
///
/// @param op The operation to be filtered.
/// @param res The filtered result is returned here.
void Character::mindWieldOperation(const Operation & op, OpVector & res)
{
    debug(std::cout << "Got Wield op from mind" << std::endl << std::flush;);
    op->setTo(getId());
    res.push_back(op);
}

/// \brief Filter a Tick operation coming from the mind
///
/// @param op The operation to be filtered.
/// @param res The filtered result is returned here.
void Character::mindTickOperation(const Operation & op, OpVector & res)
{
    Anonymous tick_arg;
    tick_arg->setName("mind");
    op->setArgs1(tick_arg);
    op->setTo(getId());
    res.push_back(op);
}

/// \brief Filter a Move operation coming from the mind
///
/// @param op The operation to be filtered.
/// @param res The filtered result is returned here.
void Character::mindMoveOperation(const Operation & op, OpVector & res)
{
    debug( std::cout << "Character::mind_move_op" << std::endl << std::flush;);
    const std::vector<Root> & args = op->getArgs();
    if (args.empty()) {
        log(ERROR, "mindMoveOperation: move op has no argument");
        return;
    }
    const RootEntity arg = smart_dynamic_cast<RootEntity>(args.front());
    if (!arg.isValid()) {
        log(ERROR, "mindMoveOperation: Arg is not an entity");
        return;
    }
    if (!arg->hasAttrFlag(Atlas::Objects::ID_FLAG)) {
        log(ERROR, "mindMoveOperation: Arg has no ID");
        return;
    }
    if (getStamina() <= 0.f) {
        // Character is immobilised.
        return;
    }
    const std::string & other_id = arg->getId();
    if (other_id != getId()) {
        debug( std::cout << "Moving something else. " << other_id << std::endl << std::flush;);
        Entity * other = BaseWorld::instance().getEntity(other_id);
        if (other == 0) {
            Unseen u;

            Anonymous unseen_arg;
            unseen_arg->setId(other_id);
            u->setArgs1(unseen_arg);

            u->setTo(getId());
            res.push_back(u);
            return;
        }
        Element mass;
        if (!other->getAttr("mass", mass) || !mass.isFloat() ||
            mass.Float() > m_statistics.get("strength")) {
            debug( std::cout << "We can't move this. Just too heavy" << std::endl << std::flush;);
            return;
        }
        op->setTo(other_id);
        res.push_back(op);
        return;
    }
    std::string new_loc;
    if (arg->hasAttrFlag(Atlas::Objects::Entity::LOC_FLAG)) {
        new_loc = arg->getLoc();
    } else {
        debug( std::cout << "Parent not set" << std::endl << std::flush;);
    }
    Point3D new_pos;
    Vector3D new_velocity;
    Quaternion new_orientation;
    try {
        if (arg->hasAttrFlag(Atlas::Objects::Entity::POS_FLAG)) {
            fromStdVector(new_pos, arg->getPos());
            debug( std::cout << "pos set to " << new_pos << std::endl << std::flush;);
        }

        if (arg->hasAttrFlag(Atlas::Objects::Entity::VELOCITY_FLAG)) {
            fromStdVector(new_velocity, arg->getVelocity());
            debug( std::cout << "vel set to " << new_velocity
                             << std::endl << std::flush;);
        }

        Element orientation_attr;
        if (arg->copyAttr("orientation", orientation_attr) == 0) {
            new_orientation.fromAtlas(orientation_attr);
            debug( std::cout << "ori set to " << new_orientation << std::endl << std::flush;);
            if (!new_orientation.isValid()) {
                log(ERROR, "Invalid orientation from client. Ignoring");
            }
        }
    }
    catch (Atlas::Message::WrongTypeException&) {
        log(ERROR, "EXCEPTION: mindMoveOperation: Malformed move operation");
        return;
    }
    catch (...) {
        log(ERROR, "EXCEPTION: mindMoveOperation: Unknown exception thrown");
        return;
    }

    debug( std::cout << ":" << new_loc << ":" << m_location.m_loc->getId()
                     << ":" << std::endl << std::flush;);
    if (!new_loc.empty() && (new_loc != m_location.m_loc->getId())) {
        debug(std::cout << "Changing loc" << std::endl << std::flush;);
        Entity * target_loc = BaseWorld::instance().getEntity(new_loc);
        if (target_loc == 0) {
            Unseen u;

            Anonymous unseen_arg;
            unseen_arg->setId(new_loc);
            u->setArgs1(unseen_arg);

            u->setTo(getId());
            res.push_back(u);
            return;
        }

        if (new_pos.isValid()) {
            Location target(target_loc, new_pos);
            Vector3D distance = distanceTo(m_location, target);
            assert(distance.isValid());
            // Convert target into our current frame of reference.
            new_pos = m_location.pos() + distance;
        } else {
            log(WARNING, "mindMoveOperation: Argument changes LOC, but no POS specified. Not sure this makes any sense");
        }
    }
    // Movement within current loc. Work out the speed and stuff and
    // use movement object to track movement.

    Location ret_location;
    int ret = m_movement.getUpdatedLocation(ret_location);
    if (ret) {
        ret_location = m_location;
    }

    // FIXME THis here?
    m_movement.reset();

    Vector3D direction;
    if (new_pos.isValid()) {
        direction = new_pos - ret_location.pos();
    } else if (new_velocity.isValid()) {
        direction = new_velocity;
    }
    if (direction.isValid() && (direction.mag() > 0)) {
        direction.normalize();
        debug( std::cout << "Direction: " << direction << std::endl
                         << std::flush;);
        if (!new_orientation.isValid()) {
            // This is a character walking, so it should stap upright
            Vector3D upright_direction = direction;
            upright_direction[cZ] = 0;
            if (upright_direction.mag() > 0) {
                upright_direction.normalize();
                new_orientation = quaternionFromTo(Vector3D(1,0,0),
                                                   upright_direction);
                debug( std::cout << "Orientation: " << new_orientation
                                 << std::endl << std::flush;);
            }
        }
    }

    double vel_mag;
    if (new_velocity.isValid()) {
        vel_mag = std::min(new_velocity.mag(), consts::base_velocity);
    } else {
        vel_mag = consts::base_velocity;
    }

    // Need to add the arguments to this op before we return it
    // direction is already a unit vector
    if (new_pos.isValid()) {
        m_movement.setTarget(new_pos);
        debug(std::cout << "Target" << new_pos
                        << std::endl << std::flush;);
    }
    if (direction.isValid()) {
        ret_location.m_velocity = direction;
        ret_location.m_velocity *= vel_mag;
        debug(std::cout << "Velocity" << ret_location.velocity()
                        << std::endl << std::flush;);
    }
    ret_location.m_orientation = new_orientation;
    debug(std::cout << "Orientation" << ret_location.orientation()
                    << std::endl << std::flush;);

    Operation move_op = m_movement.generateMove(ret_location);
    assert(move_op.isValid());
    res.push_back(move_op);

    if (m_movement.hasTarget() &&
        ret_location.velocity().isValid() &&
        ret_location.velocity() != Vector3D(0,0,0)) {

        Tick tickOp;
        Anonymous tick_arg;
        tick_arg->setAttr("serialno", m_movement.serialno());
        tick_arg->setName("move");
        tickOp->setArgs1(tick_arg);
        tickOp->setTo(getId());
        tickOp->setFutureSeconds(m_movement.getTickAddition(ret_location.pos(),
                                                     ret_location.velocity()));

        res.push_back(tickOp);
    }

}

/// \brief Filter a Set operation coming from the mind
///
/// Currently any Set op is permitted. In the future this will be locked
/// down to only allow mutable things to be changed. For example, for
/// inventory items with no name can have their name set from the client.
/// @param op The operation to be filtered.
/// @param res The filtered result is returned here.
void Character::mindSetOperation(const Operation & op, OpVector & res)
{
    log(WARNING, "Set op from mind");
    const std::vector<Root> & args = op->getArgs();
    if (args.empty()) {
        log(ERROR, "mindSetOperation: set op has no argument");
        return;
    }
    const Root & arg = args.front();
    if (arg->hasAttrFlag(Atlas::Objects::ID_FLAG)) {
        op->setTo(arg->getId());
    } else {
        op->setTo(getId());
    }
    res.push_back(op);
}

/// \brief Filter a Combine operation coming from the mind
///
/// @param op The operation to be filtered.
/// @param res The filtered result is returned here.
void Character::mindCombineOperation(const Operation & op, OpVector & res)
{
    std::cout << "mindCombineOperation" << std::endl << std::flush;
    const std::vector<Root> & args = op->getArgs();
    if (args.empty()) {
        log(ERROR, "mindCombineOperation: combine op has no argument");
        return;
    }
    std::vector<Root>::const_iterator I = args.begin();
    const Root & arg1 = *I;
    op->setTo(arg1->getId());
    std::vector<Root>::const_iterator Iend = args.end();
    for (; I != Iend; ++I) {
        const Root & arg = *I;
        if (!arg->hasAttrFlag(Atlas::Objects::ID_FLAG)) {
            error(op, "Character::mindCombineOp No ID.", res, getId());
            return;
        }
        // FIXME Check item to be combined is in inventory
        // and then also check stackable and the same type.
    }
    res.push_back(op);
}

/// \brief Filter a Create operation coming from the mind
///
/// @param op The operation to be filtered.
/// @param res The filtered result is returned here.
void Character::mindCreateOperation(const Operation & op, OpVector & res)
{
    op->setTo(getId());
    res.push_back(op);
}

/// \brief Filter a Delete operation coming from the mind
///
/// @param op The operation to be filtered.
/// @param res The filtered result is returned here.
void Character::mindDeleteOperation(const Operation & op, OpVector & res)
{
    op->setTo(getId());
    res.push_back(op);
}

/// \brief Filter a Divide operation coming from the mind
///
/// @param op The operation to be filtered.
/// @param res The filtered result is returned here.
void Character::mindDivideOperation(const Operation & op, OpVector & res)
{
    const std::vector<Root> & args = op->getArgs();
    if (args.empty()) {
        log(ERROR, "mindDivideOperation: op has no argument");
        return;
    }
    std::vector<Root>::const_iterator I = args.begin();
    const Root & arg1 = *I;
    if (!arg1->hasAttrFlag(Atlas::Objects::ID_FLAG)) {
        error(op, "Character::mindDivideOp arg 1 has no ID.", res, getId());
        return;
    }
    // FIXME Check entity to be divided is in inventory
    op->setTo(arg1->getId());
    ++I;
    std::vector<Root>::const_iterator Iend = args.end();
    for (; I != Iend; ++I) {
        const Root & arg = *I;
        if (arg->hasAttrFlag(Atlas::Objects::ID_FLAG)) {
            error(op, "Character::mindDivideOp arg has ID.", res, getId());
            return;
        }
        // Check the same type?
    }
    res.push_back(op);
}

/// \brief Filter a Imaginary operation coming from the mind
///
/// @param op The operation to be filtered.
/// @param res The filtered result is returned here.
void Character::mindImaginaryOperation(const Operation & op, OpVector & res)
{
    op->setTo(getId());
    res.push_back(op);
}

/// \brief Filter a Talk operation coming from the mind
///
/// @param op The operation to be filtered.
/// @param res The filtered result is returned here.
void Character::mindTalkOperation(const Operation & op, OpVector & res)
{
    debug( std::cout << "Character::mindTalkOperation"
                     << std::endl << std::flush;);
    op->setTo(getId());
    res.push_back(op);
}

/// \brief Filter a Look operation coming from the mind
///
/// @param op The operation to be filtered.
/// @param res The filtered result is returned here.
void Character::mindLookOperation(const Operation & op, OpVector & res)
{
    debug(std::cout << "Got look up from mind from [" << op->getFrom()
               << "] to [" << op->getTo() << "]" << std::endl << std::flush;);
    m_perceptive = true;
    const std::vector<Root> & args = op->getArgs();
    if (args.empty()) {
        op->setTo(BaseWorld::instance().m_gameWorld.getId());
    } else {
        const Root & arg = args.front();
        if (!arg->hasAttrFlag(Atlas::Objects::ID_FLAG)) {
            log(ERROR, "mindLookOperation: Op has no ID");
            return;
        }
        op->setTo(arg->getId());
    }
    debug( std::cout <<"  now to ["<<op->getTo()<<"]"<<std::endl<<std::flush;);
    res.push_back(op);
}

/// \brief Filter a Eat operation coming from the mind
///
/// @param op The operation to be filtered.
/// @param res The filtered result is returned here.
void Character::mindEatOperation(const Operation & op, OpVector & res)
{
    const std::vector<Root> & args = op->getArgs();
    if (args.empty()) {
        log(ERROR, "mindEatOperation: Op has no ARGS");
        return;
    }
    const Root & arg = args.front();
    if (!arg->hasAttrFlag(Atlas::Objects::ID_FLAG)) {
        log(ERROR, "mindEatOperation: Arg has no ID");
        return;
    }
    op->setTo(arg->getId());
    res.push_back(op);
}

/// \brief Filter a Touch operation coming from the mind
///
/// @param op The operation to be filtered.
/// @param res The filtered result is returned here.
void Character::mindTouchOperation(const Operation & op, OpVector & res)
{
    // Work out what is being touched.
    const std::vector<Root> & args = op->getArgs();
    if (args.empty()) {
        log(ERROR, "mindTouchOperation: Op has no ARGS");
        return;
    }
    const Root & arg = args.front();
    if (!arg->hasAttrFlag(Atlas::Objects::ID_FLAG)) {
        log(ERROR, "mindTouchOperation: Op has no ID");
        return;
    }
    // Pass the modified touch operation on to target.
    op->setTo(arg->getId());
    res.push_back(op);
    // Send sight of touch
    Sight s;
    s->setArgs1(op);
    res.push_back(s);
}

/// \brief Filter any other operation coming from the mind
///
/// @param op The operation to be filtered.
/// @param res The filtered result is returned here.
void Character::mindOtherOperation(const Operation & op, OpVector & res)
{
    log(WARNING, String::compose("Passing %1 op from mind through to world.", op->getParents().front()));
    op->setTo(getId());
    res.push_back(op);
}

/// \brief Filter a Appearance operation coming from the world to the mind
///
/// @param op The operation to be filtered.
/// @return true if the operation should be passed.
bool Character::w2mAppearanceOperation(const Operation & op)
{
    return true;
}

/// \brief Filter a Disappearance operation coming from the world to the mind
///
/// @param op The operation to be filtered.
/// @return true if the operation should be passed.
bool Character::w2mDisappearanceOperation(const Operation & op)
{
    return true;
}

/// \brief Filter a Error operation coming from the world to the mind
///
/// @param op The operation to be filtered.
/// @return true if the operation should be passed.
bool Character::w2mErrorOperation(const Operation & op)
{
    return true;
}

/// \brief Filter a Setup operation coming from the world to the mind
///
/// @param op The operation to be filtered.
/// @return true if the operation should be passed.
bool Character::w2mSetupOperation(const Operation & op)
{
    if (!op->getArgs().empty()) {
        if (op->getArgs().front()->getName() == "mind") {
            return true;
        }
    }
    return false;
}

/// \brief Filter a Tick operation coming from the world to the mind
///
/// @param op The operation to be filtered.
/// @return true if the operation should be passed.
bool Character::w2mTickOperation(const Operation & op)
{
    if (!op->getArgs().empty()) {
        if (op->getArgs().front()->getName() == "mind") {
            return true;
        }
    }
    return false;
}

/// \brief Filter a Unseen operation coming from the world to the mind
///
/// @param op The operation to be filtered.
/// @return true if the operation should be passed.
bool Character::w2mUnseenOperation(const Operation & op)
{
    return true;
}

/// \brief Filter a Sight operation coming from the world to the mind
///
/// @param op The operation to be filtered.
/// @return true if the operation should be passed.
bool Character::w2mSightOperation(const Operation & op)
{
    return true;
}

/// \brief Filter a Sound operation coming from the world to the mind
///
/// @param op The operation to be filtered.
/// @return true if the operation should be passed.
bool Character::w2mSoundOperation(const Operation & op)
{
    return true;
}

/// \brief Filter a Touch operation coming from the world to the mind
///
/// @param op The operation to be filtered.
/// @return true if the operation should be passed.
bool Character::w2mTouchOperation(const Operation & op)
{
    return true;
}

/// \brief Send an operation to the current active part of the mind
///
/// The operation can potentially go to an external mind if one is
/// currently one attached to this Character. This is normally a player
/// client, but could be a remote AI agent. Additionally the operation
/// can go to an internal AI mind. The result from the AI mind is
/// discarded if an external mind is connected.
/// @param op Operation to be processed.
/// @param res The result of the operation is returned here.
void Character::sendMind(const Operation & op, OpVector & res)
{
    debug( std::cout << "Character::sendMind(" << op->getParents().front() << ")" << std::endl << std::flush;);

    if (0 != m_externalMind) {
        if (0 != m_mind) {
            OpVector mindRes;
            m_mind->operation(op, mindRes);
            // Discard all the local results
        }
        debug(std::cout << "Sending to external mind" << std::endl
                         << std::flush;);
        m_externalMind->operation(op, res);
    } else {
        debug(std::cout << "Using ops from local mind"
                        << std::endl << std::flush;);
        if (0 != m_mind) {
            m_mind->operation(op, res);
        }
    }
}

/// \brief Filter operations from the mind destined for the body.
///
/// Operations from the character's mind which is either an NPC mind,
/// or a remote client are passed in here for pre-processing and filtering
/// before they are valid to be processed as internal ops. The operation
/// may be modified and re-used so operations passed to this function have
/// their ownership passed in, and caller should not modify the operation,
/// make assumptions that it has not been modified after calling mind2body.
/// @param op The operation to be processed.
/// @param res The result of the operation is returned here.
void Character::mind2body(const Operation & op, OpVector & res)
{
    debug( std::cout << "Character::mind2body(" << std::endl << std::flush;);

    if (!op->isDefaultTo()) {
        log(ERROR, String::compose("Operation \"%1\" from mind with TO set.",
                                   op->getParents().front()));
        return;
    }
    if (!op->isDefaultFutureSeconds() && op->getClassNo() != Atlas::Objects::Operation::TICK_NO) {
        log(ERROR, String::compose("Operation \"%1\" from mind with "
                                   "FUTURE_SECONDS set.",
                                   op->getParents().front()));
    }
    OpNo op_no = op->getClassNo();
    switch (op_no) {
        case Atlas::Objects::Operation::COMBINE_NO:
            mindCombineOperation(op, res);
            break;
        case Atlas::Objects::Operation::CREATE_NO:
            mindCreateOperation(op, res);
            break;
        case Atlas::Objects::Operation::DELETE_NO:
            mindDeleteOperation(op, res);
            break;
        case Atlas::Objects::Operation::DIVIDE_NO:
            mindDivideOperation(op, res);
            break;
        case Atlas::Objects::Operation::IMAGINARY_NO:
            mindImaginaryOperation(op, res);
            break;
        case Atlas::Objects::Operation::LOOK_NO:
            mindLookOperation(op, res);
            break;
        case Atlas::Objects::Operation::MOVE_NO:
            mindMoveOperation(op, res);
            break;
        case Atlas::Objects::Operation::SET_NO:
            mindSetOperation(op, res);
            break;
        case Atlas::Objects::Operation::TALK_NO:
            mindTalkOperation(op, res);
            break;
        case Atlas::Objects::Operation::TOUCH_NO:
            mindTouchOperation(op, res);
            break;
        case Atlas::Objects::Operation::USE_NO:
            mindUseOperation(op, res);
            break;
        case Atlas::Objects::Operation::WIELD_NO:
            mindWieldOperation(op, res);
            break;
        default:
            if (op_no == Atlas::Objects::Operation::ACTUATE_NO) {
                mindActuateOperation(op, res);
            } else if (op_no == Atlas::Objects::Operation::ATTACK_NO) {
                mindAttackOperation(op, res);
            } else if (op_no == Atlas::Objects::Operation::EAT_NO) {
                mindEatOperation(op, res);
            } else if (op_no == Atlas::Objects::Operation::SETUP_NO) {
                mindSetupOperation(op, res);
            } else if (op_no == Atlas::Objects::Operation::TICK_NO) {
                mindTickOperation(op, res);
            } else if (op_no == Atlas::Objects::Operation::UPDATE_NO) {
                mindUpdateOperation(op, res);
            } else {
                mindOtherOperation(op, res);
            }
            break;
    }
}

/// \brief Filter operations from the world to the mind
///
/// Operations from the world are checked here to see if they are suitable
/// to send to the mind. Some operations should not go to the mind as they
/// leak information. Others are just not necessary as they provide no
/// useful information.
bool Character::world2mind(const Operation & op)
{
    debug( std::cout << "Character::world2mind(" << op->getParents().front() << ")" << std::endl << std::flush;);
    OpNo otype = op->getClassNo();
    POLL_OP_SWITCH(op, otype, w2m)
    return false;
}

void Character::operation(const Operation & op, OpVector & res)
{
    debug( std::cout << "Character::operation(" << op->getParents().front() << ")" << std::endl << std::flush;);
    Entity::operation(op, res);
    // set refno on result?
    if (!m_isAlive) {
        return;
    }
    if (world2mind(op)) {
        debug( std::cout << "Character::operation(" << op->getParents().front() << ") passed to mind" << std::endl << std::flush;);
        OpVector mres;
        sendMind(op, mres);
        OpVector::const_iterator Iend = mres.end();
        for (OpVector::const_iterator I = mres.begin(); I != Iend; ++I) {
            externalOperation(*I);
        }
    }
}

void Character::externalOperation(const Operation & op)
{
    debug( std::cout << "Character::externalOperation(" << op->getParents().front() << ")" << std::endl << std::flush;);
    OpVector mres;
    mind2body(op, mres);
    
    OpVector::const_iterator I = mres.begin();
    OpVector::const_iterator Iend = mres.end();

    // If the original op had a serial no, we assume the first consequence
    // of that is effectively the same operation.
    // FIXME Can this be guaranteed by the mind2body phase?
    if (!op->isDefaultSerialno() && I != Iend) {
        (*I)->setSerialno(op->getSerialno());
    }

    for (; I != Iend; ++I) {
        sendWorld(*I);
    }
}