File: playercommand.cc

package info (click to toggle)
widelands 1:19+repack-3
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 370,608 kB
  • ctags: 20,609
  • sloc: cpp: 108,404; ansic: 18,695; python: 5,155; sh: 487; xml: 460; makefile: 233
file content (1763 lines) | stat: -rw-r--r-- 60,638 bytes parent folder | download | duplicates (2)
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
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
/*
 * Copyright (C) 2004, 2007-2011, 2013 by the Widelands Development Team
 *
 * 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.
 *
 */

#include "logic/playercommand.h"

#include "base/log.h"
#include "base/macros.h"
#include "base/wexception.h"
#include "economy/economy.h"
#include "economy/wares_queue.h"
#include "io/fileread.h"
#include "io/filewrite.h"
#include "io/streamwrite.h"
#include "logic/game.h"
#include "logic/map_objects/map_object.h"
#include "logic/map_objects/tribes/militarysite.h"
#include "logic/map_objects/tribes/ship.h"
#include "logic/map_objects/tribes/soldier.h"
#include "logic/map_objects/tribes/tribe_descr.h"
#include "logic/player.h"
#include "logic/widelands_geometry_io.h"
#include "map_io/map_object_loader.h"
#include "map_io/map_object_saver.h"

namespace Widelands {

namespace {

// Returns the serial number of the object with the given "object_index" as
// registered by the mol. If object_index is zero (because the object that was
// saved to the file did no longer exist on saving) zero will be returned. That
// means that get_object will always return nullptr and all upcasts will fail -
// so the commands will never do anything when executed.
template <typename T>
Serial get_object_serial_or_zero(uint32_t object_index, MapObjectLoader& mol) {
	if (!object_index)
		return 0;
	return mol.get<T>(object_index).serial();
}

}  // namespace

// NOTE keep numbers of existing entries as they are to ensure backward compatible savegame loading
enum {
	PLCMD_UNUSED = 0,
	PLCMD_BULLDOZE = 1,
	PLCMD_BUILD = 2,
	PLCMD_BUILDFLAG = 3,
	PLCMD_BUILDROAD = 4,
	PLCMD_FLAGACTION = 5,
	PLCMD_STARTSTOPBUILDING = 6,
	PLCMD_ENHANCEBUILDING = 7,
	PLCMD_CHANGETRAININGOPTIONS = 8,
	PLCMD_DROPSOLDIER = 9,
	PLCMD_CHANGESOLDIERCAPACITY = 10,
	PLCMD_ENEMYFLAGACTION = 11,
	PLCMD_SETWAREPRIORITY = 12,
	PLCMD_SETWARETARGETQUANTITY = 13,
	PLCMD_RESETWARETARGETQUANTITY = 14,
	PLCMD_SETWORKERTARGETQUANTITY = 15,
	PLCMD_RESETWORKERTARGETQUANTITY = 16,
	// Used to be PLCMD_CHANGEMILITARYCONFIG
	PLCMD_MESSAGESETSTATUSREAD = 18,
	PLCMD_MESSAGESETSTATUSARCHIVED = 19,
	PLCMD_SETSTOCKPOLICY = 20,
	PLCMD_SETWAREMAXFILL = 21,
	PLCMD_DISMANTLEBUILDING = 22,
	PLCMD_EVICTWORKER = 23,
	PLCMD_MILITARYSITESETSOLDIERPREFERENCE = 24,
	PLCMD_SHIP_EXPEDITION = 25,
	PLCMD_SHIP_SCOUT = 26,
	PLCMD_SHIP_EXPLORE = 27,
	PLCMD_SHIP_CONSTRUCT = 28,
	PLCMD_SHIP_SINK = 29,
	PLCMD_SHIP_CANCELEXPEDITION = 30
};

/*** class PlayerCommand ***/

PlayerCommand::PlayerCommand(const uint32_t time, const PlayerNumber s)
   : GameLogicCommand(time), sender_(s), cmdserial_(0) {
}

PlayerCommand* PlayerCommand::deserialize(StreamRead& des) {
	switch (des.unsigned_8()) {
	case PLCMD_BULLDOZE:
		return new CmdBulldoze(des);
	case PLCMD_BUILD:
		return new CmdBuild(des);
	case PLCMD_BUILDFLAG:
		return new CmdBuildFlag(des);
	case PLCMD_BUILDROAD:
		return new CmdBuildRoad(des);
	case PLCMD_FLAGACTION:
		return new CmdFlagAction(des);
	case PLCMD_STARTSTOPBUILDING:
		return new CmdStartStopBuilding(des);
	case PLCMD_SHIP_EXPEDITION:
		return new CmdStartOrCancelExpedition(des);
	case PLCMD_SHIP_SCOUT:
		return new CmdShipScoutDirection(des);
	case PLCMD_SHIP_EXPLORE:
		return new CmdShipExploreIsland(des);
	case PLCMD_SHIP_CONSTRUCT:
		return new CmdShipConstructPort(des);
	case PLCMD_SHIP_SINK:
		return new CmdShipSink(des);
	case PLCMD_SHIP_CANCELEXPEDITION:
		return new CmdShipCancelExpedition(des);
	case PLCMD_ENHANCEBUILDING:
		return new CmdEnhanceBuilding(des);
	case PLCMD_CHANGETRAININGOPTIONS:
		return new CmdChangeTrainingOptions(des);
	case PLCMD_DROPSOLDIER:
		return new CmdDropSoldier(des);
	case PLCMD_CHANGESOLDIERCAPACITY:
		return new CmdChangeSoldierCapacity(des);
	case PLCMD_ENEMYFLAGACTION:
		return new CmdEnemyFlagAction(des);
	case PLCMD_SETWAREPRIORITY:
		return new CmdSetWarePriority(des);
	case PLCMD_SETWARETARGETQUANTITY:
		return new CmdSetWareTargetQuantity(des);
	case PLCMD_RESETWARETARGETQUANTITY:
		return new CmdResetWareTargetQuantity(des);
	case PLCMD_SETWORKERTARGETQUANTITY:
		return new CmdSetWorkerTargetQuantity(des);
	case PLCMD_RESETWORKERTARGETQUANTITY:
		return new CmdResetWorkerTargetQuantity(des);
	case PLCMD_MESSAGESETSTATUSREAD:
		return new CmdMessageSetStatusRead(des);
	case PLCMD_MESSAGESETSTATUSARCHIVED:
		return new CmdMessageSetStatusArchived(des);
	case PLCMD_SETSTOCKPOLICY:
		return new CmdSetStockPolicy(des);
	case PLCMD_SETWAREMAXFILL:
		return new CmdSetWareMaxFill(des);
	case PLCMD_DISMANTLEBUILDING:
		return new CmdDismantleBuilding(des);
	case PLCMD_EVICTWORKER:
		return new CmdEvictWorker(des);
	case PLCMD_MILITARYSITESETSOLDIERPREFERENCE:
		return new CmdMilitarySiteSetSoldierPreference(des);
	default:
		throw wexception("PlayerCommand::deserialize(): Invalid command id encountered");
	}
}

/**
 * Write this player command to a file. Call this from base classes
 */
constexpr uint16_t kCurrentPacketVersionPlayerCommand = 2;

void PlayerCommand::write(FileWrite& fw, EditorGameBase& egbase, MapObjectSaver& mos) {
	// First, write version
	fw.unsigned_16(kCurrentPacketVersionPlayerCommand);

	GameLogicCommand::write(fw, egbase, mos);
	// Now sender
	fw.unsigned_8(sender());
	fw.unsigned_32(cmdserial());
}

void PlayerCommand::read(FileRead& fr, EditorGameBase& egbase, MapObjectLoader& mol) {
	try {
		const uint16_t packet_version = fr.unsigned_16();
		if (packet_version == kCurrentPacketVersionPlayerCommand) {
			GameLogicCommand::read(fr, egbase, mol);
			sender_ = fr.unsigned_8();
			if (!egbase.get_player(sender_))
				throw GameDataError("player %u does not exist", sender_);
			cmdserial_ = fr.unsigned_32();
		} else {
			throw UnhandledVersionError(
			   "PlayerCommand", packet_version, kCurrentPacketVersionPlayerCommand);
		}
	} catch (const WException& e) {
		throw GameDataError("player command: %s", e.what());
	}
}

/*** class Cmd_Bulldoze ***/

CmdBulldoze::CmdBulldoze(StreamRead& des)
   : PlayerCommand(0, des.unsigned_8()), serial(des.unsigned_32()), recurse(des.unsigned_8()) {
}

void CmdBulldoze::execute(Game& game) {
	if (upcast(PlayerImmovable, pimm, game.objects().get_object(serial)))
		game.player(sender()).bulldoze(*pimm, recurse);
}

void CmdBulldoze::serialize(StreamWrite& ser) {
	ser.unsigned_8(PLCMD_BULLDOZE);
	ser.unsigned_8(sender());
	ser.unsigned_32(serial);
	ser.unsigned_8(recurse);
}

constexpr uint16_t kCurrentPacketVersionCmdBulldoze = 2;

void CmdBulldoze::read(FileRead& fr, EditorGameBase& egbase, MapObjectLoader& mol) {
	try {
		const uint16_t packet_version = fr.unsigned_16();
		if (packet_version == kCurrentPacketVersionCmdBulldoze) {
			PlayerCommand::read(fr, egbase, mol);
			serial = get_object_serial_or_zero<PlayerImmovable>(fr.unsigned_32(), mol);
			recurse = 2 <= packet_version ? fr.unsigned_8() : false;
		} else {
			throw UnhandledVersionError(
			   "CmdBulldoze", packet_version, kCurrentPacketVersionCmdBulldoze);
		}
	} catch (const WException& e) {
		throw GameDataError("bulldoze: %s", e.what());
	}
}
void CmdBulldoze::write(FileWrite& fw, EditorGameBase& egbase, MapObjectSaver& mos) {
	// First, write version
	fw.unsigned_16(kCurrentPacketVersionCmdBulldoze);
	// Write base classes
	PlayerCommand::write(fw, egbase, mos);
	// Now serial
	fw.unsigned_32(mos.get_object_file_index_or_zero(egbase.objects().get_object(serial)));
	fw.unsigned_8(recurse);
}

/*** class Cmd_Build ***/

CmdBuild::CmdBuild(StreamRead& des) : PlayerCommand(0, des.unsigned_8()) {
	bi = des.signed_16();
	coords = read_coords_32(&des);
}

void CmdBuild::execute(Game& game) {
	// Empty former vector since its a new csite.
	Building::FormerBuildings former_buildings;
	game.player(sender()).build(coords, bi, true, former_buildings);
}

void CmdBuild::serialize(StreamWrite& ser) {
	ser.unsigned_8(PLCMD_BUILD);
	ser.unsigned_8(sender());
	ser.signed_16(bi);
	write_coords_32(&ser, coords);
}

constexpr uint16_t kCurrentPacketVersionCmdBuild = 1;

void CmdBuild::read(FileRead& fr, EditorGameBase& egbase, MapObjectLoader& mol) {
	try {
		const uint16_t packet_version = fr.unsigned_16();
		if (packet_version == kCurrentPacketVersionCmdBuild) {
			PlayerCommand::read(fr, egbase, mol);
			bi = fr.unsigned_16();
			coords = read_coords_32(&fr, egbase.map().extent());
		} else {
			throw UnhandledVersionError("CmdBuild", packet_version, kCurrentPacketVersionCmdBuild);
		}

	} catch (const WException& e) {
		throw GameDataError("build: %s", e.what());
	}
}

void CmdBuild::write(FileWrite& fw, EditorGameBase& egbase, MapObjectSaver& mos) {
	// First, write version
	fw.unsigned_16(kCurrentPacketVersionCmdBuild);
	// Write base classes
	PlayerCommand::write(fw, egbase, mos);
	fw.unsigned_16(bi);
	write_coords_32(&fw, coords);
}

/*** class Cmd_BuildFlag ***/

CmdBuildFlag::CmdBuildFlag(StreamRead& des)
   : PlayerCommand(0, des.unsigned_8()), coords(read_coords_32(&des)) {
}

void CmdBuildFlag::execute(Game& game) {
	game.player(sender()).build_flag(coords);
}

void CmdBuildFlag::serialize(StreamWrite& ser) {
	ser.unsigned_8(PLCMD_BUILDFLAG);
	ser.unsigned_8(sender());
	write_coords_32(&ser, coords);
}

constexpr uint16_t kCurrentPacketVersionCmdBuildFlag = 1;

void CmdBuildFlag::read(FileRead& fr, EditorGameBase& egbase, MapObjectLoader& mol) {
	try {
		const uint16_t packet_version = fr.unsigned_16();
		if (packet_version == kCurrentPacketVersionCmdBuildFlag) {
			PlayerCommand::read(fr, egbase, mol);
			coords = read_coords_32(&fr, egbase.map().extent());
		} else {
			throw UnhandledVersionError(
			   "CmdBuildFlag", packet_version, kCurrentPacketVersionCmdBuildFlag);
		}
	} catch (const WException& e) {
		throw GameDataError("build flag: %s", e.what());
	}
}
void CmdBuildFlag::write(FileWrite& fw, EditorGameBase& egbase, MapObjectSaver& mos) {
	// First, write version
	fw.unsigned_16(kCurrentPacketVersionCmdBuildFlag);
	// Write base classes
	PlayerCommand::write(fw, egbase, mos);
	write_coords_32(&fw, coords);
}

/*** class Cmd_BuildRoad ***/

CmdBuildRoad::CmdBuildRoad(uint32_t t, int32_t p, Path& pa)
   : PlayerCommand(t, p),
     path(&pa),
     start(pa.get_start()),
     nsteps(pa.get_nsteps()),
     steps(nullptr) {
}

CmdBuildRoad::CmdBuildRoad(StreamRead& des)
   : PlayerCommand(0, des.unsigned_8()),
     // We cannot completely deserialize the path here because we don't have a Map
     path(nullptr),
     start(read_coords_32(&des)),
     nsteps(des.unsigned_16()),
     steps(new char[nsteps]) {
	for (Path::StepVector::size_type i = 0; i < nsteps; ++i) {
		steps[i] = des.unsigned_8();
	}
}

CmdBuildRoad::~CmdBuildRoad() {
	delete path;

	delete[] steps;
}

void CmdBuildRoad::execute(Game& game) {
	if (path == nullptr) {
		assert(steps);

		path = new Path(start);
		for (Path::StepVector::size_type i = 0; i < nsteps; ++i)
			path->append(game.map(), steps[i]);
	}

	game.player(sender()).build_road(*path);
}

void CmdBuildRoad::serialize(StreamWrite& ser) {
	ser.unsigned_8(PLCMD_BUILDROAD);
	ser.unsigned_8(sender());
	write_coords_32(&ser, start);
	ser.unsigned_16(nsteps);

	assert(path || steps);

	for (Path::StepVector::size_type i = 0; i < nsteps; ++i)
		ser.unsigned_8(path ? (*path)[i] : steps[i]);
}

constexpr uint16_t kCurrentPacketVersionCmdBuildRoad = 1;

void CmdBuildRoad::read(FileRead& fr, EditorGameBase& egbase, MapObjectLoader& mol) {
	try {
		const uint16_t packet_version = fr.unsigned_16();
		if (packet_version == kCurrentPacketVersionCmdBuildRoad) {
			PlayerCommand::read(fr, egbase, mol);
			start = read_coords_32(&fr, egbase.map().extent());
			nsteps = fr.unsigned_16();
			path = nullptr;
			steps = new char[nsteps];
			for (Path::StepVector::size_type i = 0; i < nsteps; ++i)
				steps[i] = fr.unsigned_8();
		} else {
			throw UnhandledVersionError(
			   "CmdBuildRoad", packet_version, kCurrentPacketVersionCmdBuildRoad);
		}
	} catch (const WException& e) {
		throw GameDataError("build road: %s", e.what());
	}
}
void CmdBuildRoad::write(FileWrite& fw, EditorGameBase& egbase, MapObjectSaver& mos) {
	// First, write version
	fw.unsigned_16(kCurrentPacketVersionCmdBuildRoad);
	// Write base classes
	PlayerCommand::write(fw, egbase, mos);
	write_coords_32(&fw, start);
	fw.unsigned_16(nsteps);
	for (Path::StepVector::size_type i = 0; i < nsteps; ++i)
		fw.unsigned_8(path ? (*path)[i] : steps[i]);
}

/*** Cmd_FlagAction ***/
CmdFlagAction::CmdFlagAction(StreamRead& des) : PlayerCommand(0, des.unsigned_8()) {
	des.unsigned_8();
	serial = des.unsigned_32();
}

void CmdFlagAction::execute(Game& game) {
	Player& player = game.player(sender());
	if (upcast(Flag, flag, game.objects().get_object(serial)))
		if (&flag->owner() == &player)
			player.flagaction(*flag);
}

void CmdFlagAction::serialize(StreamWrite& ser) {
	ser.unsigned_8(PLCMD_FLAGACTION);
	ser.unsigned_8(sender());
	ser.unsigned_8(0);
	ser.unsigned_32(serial);
}

constexpr uint16_t kCurrentPacketVersionCmdFlagAction = 1;

void CmdFlagAction::read(FileRead& fr, EditorGameBase& egbase, MapObjectLoader& mol) {
	try {
		const uint16_t packet_version = fr.unsigned_16();
		if (packet_version == kCurrentPacketVersionCmdFlagAction) {
			PlayerCommand::read(fr, egbase, mol);
			fr.unsigned_8();
			serial = get_object_serial_or_zero<Flag>(fr.unsigned_32(), mol);
		} else {
			throw UnhandledVersionError(
			   "CmdFlagAction", packet_version, kCurrentPacketVersionCmdFlagAction);
		}
	} catch (const WException& e) {
		throw GameDataError("flag action: %s", e.what());
	}
}
void CmdFlagAction::write(FileWrite& fw, EditorGameBase& egbase, MapObjectSaver& mos) {
	// First, write version
	fw.unsigned_16(kCurrentPacketVersionCmdFlagAction);
	// Write base classes
	PlayerCommand::write(fw, egbase, mos);
	// Now action
	fw.unsigned_8(0);

	// Now serial
	fw.unsigned_32(mos.get_object_file_index_or_zero(egbase.objects().get_object(serial)));
}

/*** Cmd_StartStopBuilding ***/

CmdStartStopBuilding::CmdStartStopBuilding(StreamRead& des) : PlayerCommand(0, des.unsigned_8()) {
	serial = des.unsigned_32();
}

void CmdStartStopBuilding::execute(Game& game) {
	if (upcast(Building, building, game.objects().get_object(serial)))
		game.player(sender()).start_stop_building(*building);
}

void CmdStartStopBuilding::serialize(StreamWrite& ser) {
	ser.unsigned_8(PLCMD_STARTSTOPBUILDING);
	ser.unsigned_8(sender());
	ser.unsigned_32(serial);
}

constexpr uint16_t kCurrentPacketVersionCmdStartStopBuilding = 1;

void CmdStartStopBuilding::read(FileRead& fr, EditorGameBase& egbase, MapObjectLoader& mol) {
	try {
		const uint16_t packet_version = fr.unsigned_16();
		if (packet_version == kCurrentPacketVersionCmdStartStopBuilding) {
			PlayerCommand::read(fr, egbase, mol);
			serial = get_object_serial_or_zero<Building>(fr.unsigned_32(), mol);
		} else {
			throw UnhandledVersionError(
			   "CmdStartStopBuilding", packet_version, kCurrentPacketVersionCmdStartStopBuilding);
		}
	} catch (const WException& e) {
		throw GameDataError("start/stop building: %s", e.what());
	}
}
void CmdStartStopBuilding::write(FileWrite& fw, EditorGameBase& egbase, MapObjectSaver& mos) {
	// First, write version
	fw.unsigned_16(kCurrentPacketVersionCmdStartStopBuilding);
	// Write base classes
	PlayerCommand::write(fw, egbase, mos);

	// Now serial
	fw.unsigned_32(mos.get_object_file_index_or_zero(egbase.objects().get_object(serial)));
}

CmdMilitarySiteSetSoldierPreference::CmdMilitarySiteSetSoldierPreference(StreamRead& des)
   : PlayerCommand(0, des.unsigned_8()) {
	serial = des.unsigned_32();
	preference = des.unsigned_8();
}

void CmdMilitarySiteSetSoldierPreference::serialize(StreamWrite& ser) {
	ser.unsigned_8(PLCMD_MILITARYSITESETSOLDIERPREFERENCE);
	ser.unsigned_8(sender());
	ser.unsigned_32(serial);
	ser.unsigned_8(preference);
}

void CmdMilitarySiteSetSoldierPreference::execute(Game& game) {
	if (upcast(MilitarySite, building, game.objects().get_object(serial)))
		game.player(sender()).military_site_set_soldier_preference(*building, preference);
}

constexpr uint16_t kCurrentPacketVersionSoldierPreference = 1;

void CmdMilitarySiteSetSoldierPreference::write(FileWrite& fw,
                                                EditorGameBase& egbase,
                                                MapObjectSaver& mos) {
	// First, write version
	fw.unsigned_16(kCurrentPacketVersionSoldierPreference);
	// Write base classes
	PlayerCommand::write(fw, egbase, mos);

	fw.unsigned_8(preference);

	// Now serial.
	fw.unsigned_32(mos.get_object_file_index_or_zero(egbase.objects().get_object(serial)));
}

void CmdMilitarySiteSetSoldierPreference::read(FileRead& fr,
                                               EditorGameBase& egbase,
                                               MapObjectLoader& mol) {
	try {
		const uint16_t packet_version = fr.unsigned_16();
		if (packet_version == kCurrentPacketVersionSoldierPreference) {
			PlayerCommand::read(fr, egbase, mol);
			preference = fr.unsigned_8();
			serial = get_object_serial_or_zero<MilitarySite>(fr.unsigned_32(), mol);
		} else {
			throw UnhandledVersionError("CmdMilitarySiteSetSoldierPreference", packet_version,
			                            kCurrentPacketVersionSoldierPreference);
		}
	} catch (const WException& e) {
		throw GameDataError("start/stop building: %s", e.what());
	}
}

/*** Cmd_StartOrCancelExpedition ***/

CmdStartOrCancelExpedition::CmdStartOrCancelExpedition(StreamRead& des)
   : PlayerCommand(0, des.unsigned_8()) {
	serial = des.unsigned_32();
}

void CmdStartOrCancelExpedition::execute(Game& game) {
	if (upcast(Warehouse, warehouse, game.objects().get_object(serial)))
		game.player(sender()).start_or_cancel_expedition(*warehouse);
}

void CmdStartOrCancelExpedition::serialize(StreamWrite& ser) {
	ser.unsigned_8(PLCMD_SHIP_EXPEDITION);
	ser.unsigned_8(sender());
	ser.unsigned_32(serial);
}

constexpr uint16_t kCurrentPacketVersionExpedition = 1;

void CmdStartOrCancelExpedition::read(FileRead& fr, EditorGameBase& egbase, MapObjectLoader& mol) {
	try {
		uint16_t const packet_version = fr.unsigned_16();
		if (packet_version == kCurrentPacketVersionExpedition) {
			PlayerCommand::read(fr, egbase, mol);
			serial = get_object_serial_or_zero<Warehouse>(fr.unsigned_32(), mol);
		} else {
			throw UnhandledVersionError(
			   "CmdStartOrCancelExpedition", packet_version, kCurrentPacketVersionExpedition);
		}
	} catch (const WException& e) {
		throw GameDataError("start/stop building: %s", e.what());
	}
}
void CmdStartOrCancelExpedition::write(FileWrite& fw, EditorGameBase& egbase, MapObjectSaver& mos) {
	// First, write version
	fw.unsigned_16(kCurrentPacketVersionExpedition);
	// Write base classes
	PlayerCommand::write(fw, egbase, mos);

	// Now serial
	fw.unsigned_32(mos.get_object_file_index_or_zero(egbase.objects().get_object(serial)));
}

/*** Cmd_EnhanceBuilding ***/

CmdEnhanceBuilding::CmdEnhanceBuilding(StreamRead& des) : PlayerCommand(0, des.unsigned_8()) {
	serial = des.unsigned_32();
	bi = des.unsigned_16();
}

void CmdEnhanceBuilding::execute(Game& game) {
	if (upcast(Building, building, game.objects().get_object(serial)))
		game.player(sender()).enhance_building(building, bi);
}

void CmdEnhanceBuilding::serialize(StreamWrite& ser) {
	ser.unsigned_8(PLCMD_ENHANCEBUILDING);
	ser.unsigned_8(sender());
	ser.unsigned_32(serial);
	ser.unsigned_16(bi);
}

constexpr uint16_t kCurrentPacketVersionCmdEnhanceBuilding = 1;

void CmdEnhanceBuilding::read(FileRead& fr, EditorGameBase& egbase, MapObjectLoader& mol) {
	try {
		const uint16_t packet_version = fr.unsigned_16();
		if (packet_version == kCurrentPacketVersionCmdEnhanceBuilding) {
			PlayerCommand::read(fr, egbase, mol);
			serial = get_object_serial_or_zero<Building>(fr.unsigned_32(), mol);
			bi = fr.unsigned_16();
		} else {
			throw UnhandledVersionError(
			   "CmdEnhanceBuilding", packet_version, kCurrentPacketVersionCmdEnhanceBuilding);
		}
	} catch (const WException& e) {
		throw GameDataError("enhance building: %s", e.what());
	}
}
void CmdEnhanceBuilding::write(FileWrite& fw, EditorGameBase& egbase, MapObjectSaver& mos) {
	// First, write version
	fw.unsigned_16(kCurrentPacketVersionCmdEnhanceBuilding);
	// Write base classes
	PlayerCommand::write(fw, egbase, mos);

	// Now serial
	fw.unsigned_32(mos.get_object_file_index_or_zero(egbase.objects().get_object(serial)));

	// Now id
	fw.unsigned_16(bi);
}

/*** Cmd_DismantleBuilding ***/
CmdDismantleBuilding::CmdDismantleBuilding(StreamRead& des) : PlayerCommand(0, des.unsigned_8()) {
	serial = des.unsigned_32();
}

void CmdDismantleBuilding::execute(Game& game) {
	if (upcast(Building, building, game.objects().get_object(serial)))
		game.player(sender()).dismantle_building(building);
}

void CmdDismantleBuilding::serialize(StreamWrite& ser) {
	ser.unsigned_8(PLCMD_DISMANTLEBUILDING);
	ser.unsigned_8(sender());
	ser.unsigned_32(serial);
}

constexpr uint16_t kCurrentPacketVersionDismantleBuilding = 1;

void CmdDismantleBuilding::read(FileRead& fr, EditorGameBase& egbase, MapObjectLoader& mol) {
	try {
		const uint16_t packet_version = fr.unsigned_16();
		if (packet_version == kCurrentPacketVersionDismantleBuilding) {
			PlayerCommand::read(fr, egbase, mol);
			serial = get_object_serial_or_zero<Building>(fr.unsigned_32(), mol);
		} else {
			throw UnhandledVersionError(
			   "CmdDismantleBuilding", packet_version, kCurrentPacketVersionDismantleBuilding);
		}
	} catch (const WException& e) {
		throw GameDataError("dismantle building: %s", e.what());
	}
}
void CmdDismantleBuilding::write(FileWrite& fw, EditorGameBase& egbase, MapObjectSaver& mos) {
	// First, write version
	fw.unsigned_16(kCurrentPacketVersionDismantleBuilding);
	// Write base classes
	PlayerCommand::write(fw, egbase, mos);

	// Now serial
	fw.unsigned_32(mos.get_object_file_index_or_zero(egbase.objects().get_object(serial)));
}

/*** Cmd_EvictWorker ***/
CmdEvictWorker::CmdEvictWorker(StreamRead& des) : PlayerCommand(0, des.unsigned_8()) {
	serial = des.unsigned_32();
}

void CmdEvictWorker::execute(Game& game) {
	upcast(Worker, worker, game.objects().get_object(serial));
	if (worker && worker->owner().player_number() == sender()) {
		worker->evict(game);
	}
}

void CmdEvictWorker::serialize(StreamWrite& ser) {
	ser.unsigned_8(PLCMD_EVICTWORKER);
	ser.unsigned_8(sender());
	ser.unsigned_32(serial);
}

constexpr uint16_t kCurrentPacketVersionCmdEvictWorker = 1;

void CmdEvictWorker::read(FileRead& fr, EditorGameBase& egbase, MapObjectLoader& mol) {
	try {
		const uint16_t packet_version = fr.unsigned_16();
		if (packet_version == kCurrentPacketVersionCmdEvictWorker) {
			PlayerCommand::read(fr, egbase, mol);
			serial = get_object_serial_or_zero<Worker>(fr.unsigned_32(), mol);
		} else {
			throw UnhandledVersionError(
			   "CmdEvictWorker", packet_version, kCurrentPacketVersionCmdEvictWorker);
		}
	} catch (const WException& e) {
		throw GameDataError("evict worker: %s", e.what());
	}
}
void CmdEvictWorker::write(FileWrite& fw, EditorGameBase& egbase, MapObjectSaver& mos) {
	// First, write version
	fw.unsigned_16(kCurrentPacketVersionCmdEvictWorker);
	// Write base classes
	PlayerCommand::write(fw, egbase, mos);

	// Now serial
	fw.unsigned_32(mos.get_object_file_index_or_zero(egbase.objects().get_object(serial)));
}

/*** Cmd_ShipScoutDirection ***/
CmdShipScoutDirection::CmdShipScoutDirection(StreamRead& des) : PlayerCommand(0, des.unsigned_8()) {
	serial = des.unsigned_32();
	dir = static_cast<WalkingDir>(des.unsigned_8());
}

void CmdShipScoutDirection::execute(Game& game) {
	upcast(Ship, ship, game.objects().get_object(serial));
	if (ship && ship->get_owner()->player_number() == sender()) {
		if (!(ship->get_ship_state() == Widelands::Ship::ShipStates::kExpeditionWaiting ||
		      ship->get_ship_state() == Widelands::Ship::ShipStates::kExpeditionPortspaceFound ||
		      ship->get_ship_state() == Widelands::Ship::ShipStates::kExpeditionScouting)) {
			log(" %1d:ship on %3dx%3d received scout command but not in "
			    "kExpeditionWaiting or kExpeditionPortspaceFound or kExpeditionScouting status "
			    "(expedition: %s), ignoring...\n",
			    ship->get_owner()->player_number(), ship->get_position().x, ship->get_position().y,
			    (ship->state_is_expedition()) ? "Y" : "N");
			return;
		}
		ship->exp_scouting_direction(game, dir);
	}
}

void CmdShipScoutDirection::serialize(StreamWrite& ser) {
	ser.unsigned_8(PLCMD_SHIP_SCOUT);
	ser.unsigned_8(sender());
	ser.unsigned_32(serial);
	ser.unsigned_8(static_cast<uint8_t>(dir));
}

constexpr uint16_t kCurrentPacketVersionShipScoutDirection = 1;

void CmdShipScoutDirection::read(FileRead& fr, EditorGameBase& egbase, MapObjectLoader& mol) {
	try {
		const uint16_t packet_version = fr.unsigned_16();
		if (packet_version == kCurrentPacketVersionShipScoutDirection) {
			PlayerCommand::read(fr, egbase, mol);
			serial = get_object_serial_or_zero<Ship>(fr.unsigned_32(), mol);
			// direction
			dir = static_cast<WalkingDir>(fr.unsigned_8());
		} else {
			throw UnhandledVersionError(
			   "CmdShipScoutDirection", packet_version, kCurrentPacketVersionShipScoutDirection);
		}
	} catch (const WException& e) {
		throw GameDataError("Ship scout: %s", e.what());
	}
}
void CmdShipScoutDirection::write(FileWrite& fw, EditorGameBase& egbase, MapObjectSaver& mos) {
	// First, write version
	fw.unsigned_16(kCurrentPacketVersionShipScoutDirection);
	// Write base classes
	PlayerCommand::write(fw, egbase, mos);

	// Now serial
	fw.unsigned_32(mos.get_object_file_index_or_zero(egbase.objects().get_object(serial)));

	// direction
	fw.unsigned_8(static_cast<uint8_t>(dir));
}

/*** Cmd_ShipConstructPort ***/
CmdShipConstructPort::CmdShipConstructPort(StreamRead& des) : PlayerCommand(0, des.unsigned_8()) {
	serial = des.unsigned_32();
	coords = read_coords_32(&des);
}

void CmdShipConstructPort::execute(Game& game) {
	upcast(Ship, ship, game.objects().get_object(serial));
	if (ship && ship->get_owner()->player_number() == sender()) {
		if (ship->get_ship_state() != Widelands::Ship::ShipStates::kExpeditionPortspaceFound) {
			log(" %1d:ship on %3dx%3d received build port command but "
			    "not in kExpeditionPortspaceFound status (expedition: %s), ignoring...\n",
			    ship->get_owner()->player_number(), ship->get_position().x, ship->get_position().y,
			    (ship->state_is_expedition()) ? "Y" : "N");
			return;
		}
		ship->exp_construct_port(game, coords);
	}
}

void CmdShipConstructPort::serialize(StreamWrite& ser) {
	ser.unsigned_8(PLCMD_SHIP_CONSTRUCT);
	ser.unsigned_8(sender());
	ser.unsigned_32(serial);
	write_coords_32(&ser, coords);
}

constexpr uint16_t kCurrentPacketVersionShipConstructPort = 1;

void CmdShipConstructPort::read(FileRead& fr, EditorGameBase& egbase, MapObjectLoader& mol) {
	try {
		const uint16_t packet_version = fr.unsigned_16();
		if (packet_version == kCurrentPacketVersionShipConstructPort) {
			PlayerCommand::read(fr, egbase, mol);
			serial = get_object_serial_or_zero<Ship>(fr.unsigned_32(), mol);
			// Coords
			coords = read_coords_32(&fr);
		} else {
			throw UnhandledVersionError(
			   "CmdShipConstructPort", packet_version, kCurrentPacketVersionShipConstructPort);
		}
	} catch (const WException& e) {
		throw GameDataError("Ship construct port: %s", e.what());
	}
}
void CmdShipConstructPort::write(FileWrite& fw, EditorGameBase& egbase, MapObjectSaver& mos) {
	// First, write version
	fw.unsigned_16(kCurrentPacketVersionShipConstructPort);
	// Write base classes
	PlayerCommand::write(fw, egbase, mos);

	// Now serial
	fw.unsigned_32(mos.get_object_file_index_or_zero(egbase.objects().get_object(serial)));

	// Coords
	write_coords_32(&fw, coords);
}

/*** Cmd_ShipExploreIsland ***/
CmdShipExploreIsland::CmdShipExploreIsland(StreamRead& des) : PlayerCommand(0, des.unsigned_8()) {
	serial = des.unsigned_32();
	island_explore_direction = static_cast<IslandExploreDirection>(des.unsigned_8());
}

void CmdShipExploreIsland::execute(Game& game) {
	upcast(Ship, ship, game.objects().get_object(serial));
	if (ship && ship->get_owner()->player_number() == sender()) {
		if (!(ship->get_ship_state() == Widelands::Ship::ShipStates::kExpeditionWaiting ||
		      ship->get_ship_state() == Widelands::Ship::ShipStates::kExpeditionPortspaceFound ||
		      ship->get_ship_state() == Widelands::Ship::ShipStates::kExpeditionScouting)) {
			log(" %1d:ship on %3dx%3d received explore island command "
			    "but not in kExpeditionWaiting or kExpeditionPortspaceFound or kExpeditionScouting "
			    "status (expedition: %s), ignoring...\n",
			    ship->get_owner()->player_number(), ship->get_position().x, ship->get_position().y,
			    (ship->state_is_expedition()) ? "Y" : "N");
			return;
		}
		ship->exp_explore_island(game, island_explore_direction);
	}
}

void CmdShipExploreIsland::serialize(StreamWrite& ser) {
	ser.unsigned_8(PLCMD_SHIP_EXPLORE);
	ser.unsigned_8(sender());
	ser.unsigned_32(serial);
	ser.unsigned_8(static_cast<uint8_t>(island_explore_direction));
}

constexpr uint16_t kCurrentPacketVersionShipExploreIsland = 1;

void CmdShipExploreIsland::read(FileRead& fr, EditorGameBase& egbase, MapObjectLoader& mol) {
	try {
		const uint16_t packet_version = fr.unsigned_16();
		if (packet_version == kCurrentPacketVersionShipExploreIsland) {
			PlayerCommand::read(fr, egbase, mol);
			serial = get_object_serial_or_zero<Ship>(fr.unsigned_32(), mol);
			island_explore_direction = static_cast<IslandExploreDirection>(fr.unsigned_8());
		} else {
			throw UnhandledVersionError(
			   "CmdShipExploreIsland", packet_version, kCurrentPacketVersionShipExploreIsland);
		}
	} catch (const WException& e) {
		throw GameDataError("Ship explore: %s", e.what());
	}
}
void CmdShipExploreIsland::write(FileWrite& fw, EditorGameBase& egbase, MapObjectSaver& mos) {
	// First, write version
	fw.unsigned_16(kCurrentPacketVersionShipExploreIsland);
	// Write base classes
	PlayerCommand::write(fw, egbase, mos);

	// Now serial
	fw.unsigned_32(mos.get_object_file_index_or_zero(egbase.objects().get_object(serial)));

	// Direction of exploration
	fw.unsigned_8(static_cast<uint8_t>(island_explore_direction));
}

/*** Cmd_ShipSink ***/
CmdShipSink::CmdShipSink(StreamRead& des) : PlayerCommand(0, des.unsigned_8()) {
	serial = des.unsigned_32();
}

void CmdShipSink::execute(Game& game) {
	upcast(Ship, ship, game.objects().get_object(serial));
	if (ship && ship->get_owner()->player_number() == sender()) {
		ship->sink_ship(game);
	}
}

void CmdShipSink::serialize(StreamWrite& ser) {
	ser.unsigned_8(PLCMD_SHIP_SINK);
	ser.unsigned_8(sender());
	ser.unsigned_32(serial);
}

constexpr uint16_t kCurrentPacketVersionCmdShipSink = 1;

void CmdShipSink::read(FileRead& fr, EditorGameBase& egbase, MapObjectLoader& mol) {
	try {
		const uint16_t packet_version = fr.unsigned_16();
		if (packet_version == kCurrentPacketVersionCmdShipSink) {
			PlayerCommand::read(fr, egbase, mol);
			serial = get_object_serial_or_zero<Ship>(fr.unsigned_32(), mol);
		} else {
			throw UnhandledVersionError(
			   "CmdShipSink", packet_version, kCurrentPacketVersionCmdShipSink);
		}
	} catch (const WException& e) {
		throw GameDataError("Ship explore: %s", e.what());
	}
}
void CmdShipSink::write(FileWrite& fw, EditorGameBase& egbase, MapObjectSaver& mos) {
	// First, write version
	fw.unsigned_16(kCurrentPacketVersionCmdShipSink);
	// Write base classes
	PlayerCommand::write(fw, egbase, mos);

	// Now serial
	fw.unsigned_32(mos.get_object_file_index_or_zero(egbase.objects().get_object(serial)));
}

/*** Cmd_ShipCancelExpedition ***/
CmdShipCancelExpedition::CmdShipCancelExpedition(StreamRead& des)
   : PlayerCommand(0, des.unsigned_8()) {
	serial = des.unsigned_32();
}

void CmdShipCancelExpedition::execute(Game& game) {
	upcast(Ship, ship, game.objects().get_object(serial));
	if (ship && ship->get_owner()->player_number() == sender()) {
		ship->exp_cancel(game);
	}
}

void CmdShipCancelExpedition::serialize(StreamWrite& ser) {
	ser.unsigned_8(PLCMD_SHIP_CANCELEXPEDITION);
	ser.unsigned_8(sender());
	ser.unsigned_32(serial);
}

constexpr uint16_t kCurrentPacketVersionShipCancelExpedition = 1;

void CmdShipCancelExpedition::read(FileRead& fr, EditorGameBase& egbase, MapObjectLoader& mol) {
	try {
		const uint16_t packet_version = fr.unsigned_16();
		if (packet_version == kCurrentPacketVersionShipCancelExpedition) {
			PlayerCommand::read(fr, egbase, mol);
			serial = get_object_serial_or_zero<Ship>(fr.unsigned_32(), mol);
		} else {
			throw UnhandledVersionError(
			   "CmdShipCancelExpedition", packet_version, kCurrentPacketVersionShipCancelExpedition);
		}
	} catch (const WException& e) {
		throw GameDataError("Ship explore: %s", e.what());
	}
}
void CmdShipCancelExpedition::write(FileWrite& fw, EditorGameBase& egbase, MapObjectSaver& mos) {
	// First, write version
	fw.unsigned_16(kCurrentPacketVersionShipCancelExpedition);
	// Write base classes
	PlayerCommand::write(fw, egbase, mos);

	// Now serial
	fw.unsigned_32(mos.get_object_file_index_or_zero(egbase.objects().get_object(serial)));
}

/*** class Cmd_SetWarePriority ***/
CmdSetWarePriority::CmdSetWarePriority(const uint32_t init_duetime,
                                       const PlayerNumber init_sender,
                                       PlayerImmovable& imm,
                                       const int32_t init_type,
                                       const DescriptionIndex i,
                                       const int32_t init_priority)
   : PlayerCommand(init_duetime, init_sender),
     serial_(imm.serial()),
     type_(init_type),
     index_(i),
     priority_(init_priority) {
}

void CmdSetWarePriority::execute(Game& game) {
	upcast(Building, psite, game.objects().get_object(serial_));

	if (!psite)
		return;
	if (psite->owner().player_number() != sender())
		return;

	psite->set_priority(type_, index_, priority_);
}

constexpr uint16_t kCurrentPacketVersionCmdSetWarePriority = 1;

void CmdSetWarePriority::write(FileWrite& fw, EditorGameBase& egbase, MapObjectSaver& mos) {
	fw.unsigned_16(kCurrentPacketVersionCmdSetWarePriority);

	PlayerCommand::write(fw, egbase, mos);

	fw.unsigned_32(mos.get_object_file_index_or_zero(egbase.objects().get_object(serial_)));
	fw.unsigned_8(type_);
	fw.signed_32(index_);
	fw.signed_32(priority_);
}

void CmdSetWarePriority::read(FileRead& fr, EditorGameBase& egbase, MapObjectLoader& mol) {
	try {
		const uint16_t packet_version = fr.unsigned_16();
		if (packet_version == kCurrentPacketVersionCmdSetWarePriority) {
			PlayerCommand::read(fr, egbase, mol);
			serial_ = get_object_serial_or_zero<Building>(fr.unsigned_32(), mol);
			type_ = fr.unsigned_8();
			index_ = fr.signed_32();
			priority_ = fr.signed_32();
		} else {
			throw UnhandledVersionError(
			   "CmdSetWarePriority", packet_version, kCurrentPacketVersionCmdSetWarePriority);
		}

	} catch (const WException& e) {
		throw GameDataError("set ware priority: %s", e.what());
	}
}

CmdSetWarePriority::CmdSetWarePriority(StreamRead& des)
   : PlayerCommand(0, des.unsigned_8()),
     serial_(des.unsigned_32()),
     type_(des.unsigned_8()),
     index_(des.signed_32()),
     priority_(des.signed_32()) {
}

void CmdSetWarePriority::serialize(StreamWrite& ser) {
	ser.unsigned_8(PLCMD_SETWAREPRIORITY);
	ser.unsigned_8(sender());
	ser.unsigned_32(serial_);
	ser.unsigned_8(type_);
	ser.signed_32(index_);
	ser.signed_32(priority_);
}

/*** class Cmd_SetWareMaxFill ***/
CmdSetWareMaxFill::CmdSetWareMaxFill(const uint32_t init_duetime,
                                     const PlayerNumber init_sender,
                                     PlayerImmovable& imm,
                                     const DescriptionIndex index,
                                     const uint32_t max_fill)
   : PlayerCommand(init_duetime, init_sender),
     serial_(imm.serial()),
     index_(index),
     max_fill_(max_fill) {
}

void CmdSetWareMaxFill::execute(Game& game) {
	upcast(Building, b, game.objects().get_object(serial_));

	if (!b)
		return;
	if (b->owner().player_number() != sender())
		return;

	b->waresqueue(index_).set_max_fill(max_fill_);
}

constexpr uint16_t kCurrentPacketVersionCmdSetWareMaxFill = 1;

void CmdSetWareMaxFill::write(FileWrite& fw, EditorGameBase& egbase, MapObjectSaver& mos) {
	fw.unsigned_16(kCurrentPacketVersionCmdSetWareMaxFill);

	PlayerCommand::write(fw, egbase, mos);

	fw.unsigned_32(mos.get_object_file_index_or_zero(egbase.objects().get_object(serial_)));
	fw.signed_32(index_);
	fw.unsigned_32(max_fill_);
}

void CmdSetWareMaxFill::read(FileRead& fr, EditorGameBase& egbase, MapObjectLoader& mol) {
	try {
		const uint16_t packet_version = fr.unsigned_16();
		if (packet_version == kCurrentPacketVersionCmdSetWareMaxFill) {
			PlayerCommand::read(fr, egbase, mol);
			serial_ = get_object_serial_or_zero<Building>(fr.unsigned_32(), mol);
			index_ = fr.signed_32();
			max_fill_ = fr.unsigned_32();
		} else {
			throw UnhandledVersionError(
			   "CmdSetWareMaxFill", packet_version, kCurrentPacketVersionCmdSetWareMaxFill);
		}
	} catch (const WException& e) {
		throw GameDataError("set ware max fill: %s", e.what());
	}
}

CmdSetWareMaxFill::CmdSetWareMaxFill(StreamRead& des)
   : PlayerCommand(0, des.unsigned_8()),
     serial_(des.unsigned_32()),
     index_(des.signed_32()),
     max_fill_(des.unsigned_32()) {
}

void CmdSetWareMaxFill::serialize(StreamWrite& ser) {
	ser.unsigned_8(PLCMD_SETWAREMAXFILL);
	ser.unsigned_8(sender());
	ser.unsigned_32(serial_);
	ser.signed_32(index_);
	ser.unsigned_32(max_fill_);
}

CmdChangeTargetQuantity::CmdChangeTargetQuantity(const uint32_t init_duetime,
                                                 const PlayerNumber init_sender,
                                                 const uint32_t init_economy,
                                                 const DescriptionIndex init_ware_type)
   : PlayerCommand(init_duetime, init_sender), economy_(init_economy), ware_type_(init_ware_type) {
}

void CmdChangeTargetQuantity::write(FileWrite& fw, EditorGameBase& egbase, MapObjectSaver& mos) {
	PlayerCommand::write(fw, egbase, mos);
	fw.unsigned_32(economy());
	fw.c_string(egbase.player(sender()).tribe().get_ware_descr(ware_type())->name());
}

void CmdChangeTargetQuantity::read(FileRead& fr, EditorGameBase& egbase, MapObjectLoader& mol) {
	try {
		PlayerCommand::read(fr, egbase, mol);
		economy_ = fr.unsigned_32();
		ware_type_ = egbase.player(sender()).tribe().ware_index(fr.c_string());
	} catch (const WException& e) {
		throw GameDataError("change target quantity: %s", e.what());
	}
}

CmdChangeTargetQuantity::CmdChangeTargetQuantity(StreamRead& des)
   : PlayerCommand(0, des.unsigned_8()), economy_(des.unsigned_32()), ware_type_(des.unsigned_8()) {
}

void CmdChangeTargetQuantity::serialize(StreamWrite& ser) {
	ser.unsigned_8(sender());
	ser.unsigned_32(economy());
	ser.unsigned_8(ware_type());
}

CmdSetWareTargetQuantity::CmdSetWareTargetQuantity(const uint32_t init_duetime,
                                                   const PlayerNumber init_sender,
                                                   const uint32_t init_economy,
                                                   const DescriptionIndex init_ware_type,
                                                   const uint32_t init_permanent)
   : CmdChangeTargetQuantity(init_duetime, init_sender, init_economy, init_ware_type),
     permanent_(init_permanent) {
}

void CmdSetWareTargetQuantity::execute(Game& game) {
	Player& player = game.player(sender());
	if (economy() < player.get_nr_economies() && game.tribes().ware_exists(ware_type())) {
		player.get_economy_by_number(economy())->set_ware_target_quantity(
		   ware_type(), permanent_, duetime());
	}
}

constexpr uint16_t kCurrentPacketVersionSetWareTargetQuantity = 2;

void CmdSetWareTargetQuantity::write(FileWrite& fw, EditorGameBase& egbase, MapObjectSaver& mos) {
	fw.unsigned_16(kCurrentPacketVersionSetWareTargetQuantity);
	CmdChangeTargetQuantity::write(fw, egbase, mos);
	fw.unsigned_32(permanent_);
}

void CmdSetWareTargetQuantity::read(FileRead& fr, EditorGameBase& egbase, MapObjectLoader& mol) {
	try {
		const uint16_t packet_version = fr.unsigned_16();
		if (packet_version == kCurrentPacketVersionSetWareTargetQuantity) {
			CmdChangeTargetQuantity::read(fr, egbase, mol);
			permanent_ = fr.unsigned_32();
		} else {
			throw UnhandledVersionError(
			   "CmdSetWareTargetQuantity", packet_version, kCurrentPacketVersionSetWareTargetQuantity);
		}
	} catch (const WException& e) {
		throw GameDataError("set ware target quantity: %s", e.what());
	}
}

CmdSetWareTargetQuantity::CmdSetWareTargetQuantity(StreamRead& des)
   : CmdChangeTargetQuantity(des), permanent_(des.unsigned_32()) {
	if (cmdserial() == 1)
		des.unsigned_32();
}

void CmdSetWareTargetQuantity::serialize(StreamWrite& ser) {
	ser.unsigned_8(PLCMD_SETWARETARGETQUANTITY);
	CmdChangeTargetQuantity::serialize(ser);
	ser.unsigned_32(permanent_);
}

CmdResetWareTargetQuantity::CmdResetWareTargetQuantity(const uint32_t init_duetime,
                                                       const PlayerNumber init_sender,
                                                       const uint32_t init_economy,
                                                       const DescriptionIndex init_ware_type)
   : CmdChangeTargetQuantity(init_duetime, init_sender, init_economy, init_ware_type) {
}

void CmdResetWareTargetQuantity::execute(Game& game) {
	Player& player = game.player(sender());
	const TribeDescr& tribe = player.tribe();
	if (economy() < player.get_nr_economies() && game.tribes().ware_exists(ware_type())) {
		const int count = tribe.get_ware_descr(ware_type())->default_target_quantity(tribe.name());
		player.get_economy_by_number(economy())->set_ware_target_quantity(
		   ware_type(), count, duetime());
	}
}

constexpr uint16_t kCurrentPacketVersionResetWareTargetQuantity = 1;

void CmdResetWareTargetQuantity::write(FileWrite& fw, EditorGameBase& egbase, MapObjectSaver& mos) {
	fw.unsigned_16(kCurrentPacketVersionResetWareTargetQuantity);
	CmdChangeTargetQuantity::write(fw, egbase, mos);
}

void CmdResetWareTargetQuantity::read(FileRead& fr, EditorGameBase& egbase, MapObjectLoader& mol) {
	try {
		const uint16_t packet_version = fr.unsigned_16();
		if (packet_version == kCurrentPacketVersionResetWareTargetQuantity) {
			CmdChangeTargetQuantity::read(fr, egbase, mol);
		} else {
			throw UnhandledVersionError("CmdResetWareTargetQuantity", packet_version,
			                            kCurrentPacketVersionResetWareTargetQuantity);
		}
	} catch (const WException& e) {
		throw GameDataError("reset target quantity: %s", e.what());
	}
}

CmdResetWareTargetQuantity::CmdResetWareTargetQuantity(StreamRead& des)
   : CmdChangeTargetQuantity(des) {
}

void CmdResetWareTargetQuantity::serialize(StreamWrite& ser) {
	ser.unsigned_8(PLCMD_RESETWARETARGETQUANTITY);
	CmdChangeTargetQuantity::serialize(ser);
}

CmdSetWorkerTargetQuantity::CmdSetWorkerTargetQuantity(const uint32_t init_duetime,
                                                       const PlayerNumber init_sender,
                                                       const uint32_t init_economy,
                                                       const DescriptionIndex init_ware_type,
                                                       const uint32_t init_permanent)
   : CmdChangeTargetQuantity(init_duetime, init_sender, init_economy, init_ware_type),
     permanent_(init_permanent) {
}

void CmdSetWorkerTargetQuantity::execute(Game& game) {
	Player& player = game.player(sender());
	if (economy() < player.get_nr_economies() && game.tribes().ware_exists(ware_type())) {
		player.get_economy_by_number(economy())->set_worker_target_quantity(
		   ware_type(), permanent_, duetime());
	}
}

constexpr uint16_t kCurrentPacketVersionSetWorkerTargetQuantity = 2;

void CmdSetWorkerTargetQuantity::write(FileWrite& fw, EditorGameBase& egbase, MapObjectSaver& mos) {
	fw.unsigned_16(kCurrentPacketVersionSetWorkerTargetQuantity);
	CmdChangeTargetQuantity::write(fw, egbase, mos);
	fw.unsigned_32(permanent_);
}

void CmdSetWorkerTargetQuantity::read(FileRead& fr, EditorGameBase& egbase, MapObjectLoader& mol) {
	try {
		const uint16_t packet_version = fr.unsigned_16();
		if (packet_version == kCurrentPacketVersionSetWorkerTargetQuantity) {
			CmdChangeTargetQuantity::read(fr, egbase, mol);
			permanent_ = fr.unsigned_32();
		} else {
			throw UnhandledVersionError("CmdSetWorkerTargetQuantity", packet_version,
			                            kCurrentPacketVersionSetWorkerTargetQuantity);
		}
	} catch (const WException& e) {
		throw GameDataError("set worker target quantity: %s", e.what());
	}
}

CmdSetWorkerTargetQuantity::CmdSetWorkerTargetQuantity(StreamRead& des)
   : CmdChangeTargetQuantity(des), permanent_(des.unsigned_32()) {
	if (cmdserial() == 1)
		des.unsigned_32();
}

void CmdSetWorkerTargetQuantity::serialize(StreamWrite& ser) {
	ser.unsigned_8(PLCMD_SETWORKERTARGETQUANTITY);
	CmdChangeTargetQuantity::serialize(ser);
	ser.unsigned_32(permanent_);
}

CmdResetWorkerTargetQuantity::CmdResetWorkerTargetQuantity(const uint32_t init_duetime,
                                                           const PlayerNumber init_sender,
                                                           const uint32_t init_economy,
                                                           const DescriptionIndex init_ware_type)
   : CmdChangeTargetQuantity(init_duetime, init_sender, init_economy, init_ware_type) {
}

void CmdResetWorkerTargetQuantity::execute(Game& game) {
	Player& player = game.player(sender());
	const TribeDescr& tribe = player.tribe();
	if (economy() < player.get_nr_economies() && game.tribes().ware_exists(ware_type())) {
		const int count = tribe.get_ware_descr(ware_type())->default_target_quantity(tribe.name());
		player.get_economy_by_number(economy())->set_worker_target_quantity(
		   ware_type(), count, duetime());
	}
}

constexpr uint16_t kCurrentPacketVersionResetWorkerTargetQuantity = 1;

void CmdResetWorkerTargetQuantity::write(FileWrite& fw,
                                         EditorGameBase& egbase,
                                         MapObjectSaver& mos) {
	fw.unsigned_16(kCurrentPacketVersionResetWorkerTargetQuantity);
	CmdChangeTargetQuantity::write(fw, egbase, mos);
}

void CmdResetWorkerTargetQuantity::read(FileRead& fr,
                                        EditorGameBase& egbase,
                                        MapObjectLoader& mol) {
	try {
		const uint16_t packet_version = fr.unsigned_16();
		if (packet_version == kCurrentPacketVersionResetWorkerTargetQuantity) {
			CmdChangeTargetQuantity::read(fr, egbase, mol);
		} else {
			throw UnhandledVersionError("CmdResetWorkerTargetQuantity", packet_version,
			                            kCurrentPacketVersionResetWorkerTargetQuantity);
		}
	} catch (const WException& e) {
		throw GameDataError("reset worker target quantity: %s", e.what());
	}
}

CmdResetWorkerTargetQuantity::CmdResetWorkerTargetQuantity(StreamRead& des)
   : CmdChangeTargetQuantity(des) {
}

void CmdResetWorkerTargetQuantity::serialize(StreamWrite& ser) {
	ser.unsigned_8(PLCMD_RESETWORKERTARGETQUANTITY);
	CmdChangeTargetQuantity::serialize(ser);
}

/*** class Cmd_ChangeTrainingOptions ***/
CmdChangeTrainingOptions::CmdChangeTrainingOptions(StreamRead& des)
   : PlayerCommand(0, des.unsigned_8()) {
	serial = des.unsigned_32();                                    //  Serial of the building
	attribute = static_cast<TrainingAttribute>(des.unsigned_8());  //  Attribute to modify
	value = des.unsigned_16();                                     //  New vale
}

void CmdChangeTrainingOptions::execute(Game& game) {
	if (upcast(TrainingSite, trainingsite, game.objects().get_object(serial)))
		game.player(sender()).change_training_options(*trainingsite, attribute, value);
}

void CmdChangeTrainingOptions::serialize(StreamWrite& ser) {
	ser.unsigned_8(PLCMD_CHANGETRAININGOPTIONS);
	ser.unsigned_8(sender());
	ser.unsigned_32(serial);
	ser.unsigned_8(static_cast<uint8_t>(attribute));
	ser.unsigned_16(value);
}

constexpr uint16_t kCurrentPacketVersionChangeTrainingOptions = 2;

void CmdChangeTrainingOptions::read(FileRead& fr, EditorGameBase& egbase, MapObjectLoader& mol) {
	try {
		const uint16_t packet_version = fr.unsigned_16();
		if (packet_version == kCurrentPacketVersionChangeTrainingOptions) {
			PlayerCommand::read(fr, egbase, mol);
			serial = get_object_serial_or_zero<TrainingSite>(fr.unsigned_32(), mol);
			attribute = static_cast<TrainingAttribute>(fr.unsigned_8());
			value = fr.unsigned_16();
		} else {
			throw UnhandledVersionError(
			   "CmdChangeTrainingOptions", packet_version, kCurrentPacketVersionChangeTrainingOptions);
		}
	} catch (const WException& e) {
		throw GameDataError("change training options: %s", e.what());
	}
}

void CmdChangeTrainingOptions::write(FileWrite& fw, EditorGameBase& egbase, MapObjectSaver& mos) {
	// First, write version
	fw.unsigned_16(kCurrentPacketVersionChangeTrainingOptions);
	// Write base classes
	PlayerCommand::write(fw, egbase, mos);

	// Now serial
	fw.unsigned_32(mos.get_object_file_index_or_zero(egbase.objects().get_object(serial)));

	fw.unsigned_8(static_cast<uint8_t>(attribute));
	fw.unsigned_16(value);
}

/*** class Cmd_DropSoldier ***/

CmdDropSoldier::CmdDropSoldier(StreamRead& des) : PlayerCommand(0, des.unsigned_8()) {
	serial = des.unsigned_32();   //  Serial of the building
	soldier = des.unsigned_32();  //  Serial of soldier
}

void CmdDropSoldier::execute(Game& game) {
	if (upcast(PlayerImmovable, player_imm, game.objects().get_object(serial)))
		if (upcast(Soldier, s, game.objects().get_object(soldier)))
			game.player(sender()).drop_soldier(*player_imm, *s);
}

void CmdDropSoldier::serialize(StreamWrite& ser) {
	ser.unsigned_8(PLCMD_DROPSOLDIER);
	ser.unsigned_8(sender());
	ser.unsigned_32(serial);
	ser.unsigned_32(soldier);
}

constexpr uint16_t kCurrentPacketVersionCmdDropSoldier = 1;

void CmdDropSoldier::read(FileRead& fr, EditorGameBase& egbase, MapObjectLoader& mol) {
	try {
		const uint16_t packet_version = fr.unsigned_16();
		if (packet_version == kCurrentPacketVersionCmdDropSoldier) {
			PlayerCommand::read(fr, egbase, mol);
			serial = get_object_serial_or_zero<PlayerImmovable>(fr.unsigned_32(), mol);
			soldier = get_object_serial_or_zero<Soldier>(fr.unsigned_32(), mol);
		} else {
			throw UnhandledVersionError(
			   "CmdDropSoldier", packet_version, kCurrentPacketVersionCmdDropSoldier);
		}
	} catch (const WException& e) {
		throw GameDataError("drop soldier: %s", e.what());
	}
}

void CmdDropSoldier::write(FileWrite& fw, EditorGameBase& egbase, MapObjectSaver& mos) {
	// First, write version
	fw.unsigned_16(kCurrentPacketVersionCmdDropSoldier);
	// Write base classes
	PlayerCommand::write(fw, egbase, mos);

	//  site serial
	fw.unsigned_32(mos.get_object_file_index_or_zero(egbase.objects().get_object(serial)));

	//  soldier serial
	fw.unsigned_32(mos.get_object_file_index_or_zero(egbase.objects().get_object(soldier)));
}

/*** Cmd_ChangeSoldierCapacity ***/

CmdChangeSoldierCapacity::CmdChangeSoldierCapacity(StreamRead& des)
   : PlayerCommand(0, des.unsigned_8()) {
	serial = des.unsigned_32();
	val = des.signed_16();
}

void CmdChangeSoldierCapacity::execute(Game& game) {
	if (upcast(Building, building, game.objects().get_object(serial)))
		if (&building->owner() == game.get_player(sender()))
			if (upcast(SoldierControl, ctrl, building))
				ctrl->changeSoldierCapacity(val);
}

void CmdChangeSoldierCapacity::serialize(StreamWrite& ser) {
	ser.unsigned_8(PLCMD_CHANGESOLDIERCAPACITY);
	ser.unsigned_8(sender());
	ser.unsigned_32(serial);
	ser.signed_16(val);
}

constexpr uint16_t kCurrentPacketVersionChangeSoldierCapacity = 1;

void CmdChangeSoldierCapacity::read(FileRead& fr, EditorGameBase& egbase, MapObjectLoader& mol) {
	try {
		const uint16_t packet_version = fr.unsigned_16();
		if (packet_version == kCurrentPacketVersionChangeSoldierCapacity) {
			PlayerCommand::read(fr, egbase, mol);
			serial = get_object_serial_or_zero<Building>(fr.unsigned_32(), mol);
			val = fr.signed_16();
		} else {
			throw UnhandledVersionError(
			   "CmdChangeSoldierCapacity", packet_version, kCurrentPacketVersionChangeSoldierCapacity);
		}
	} catch (const WException& e) {
		throw GameDataError("change soldier capacity: %s", e.what());
	}
}

void CmdChangeSoldierCapacity::write(FileWrite& fw, EditorGameBase& egbase, MapObjectSaver& mos) {
	// First, write version
	fw.unsigned_16(kCurrentPacketVersionChangeSoldierCapacity);
	// Write base classes
	PlayerCommand::write(fw, egbase, mos);

	// Now serial
	fw.unsigned_32(mos.get_object_file_index_or_zero(egbase.objects().get_object(serial)));

	// Now capacity
	fw.signed_16(val);
}

/*** Cmd_EnemyFlagAction ***/

CmdEnemyFlagAction::CmdEnemyFlagAction(StreamRead& des) : PlayerCommand(0, des.unsigned_8()) {
	des.unsigned_8();
	serial = des.unsigned_32();
	des.unsigned_8();
	number = des.unsigned_8();
}

void CmdEnemyFlagAction::execute(Game& game) {
	Player& player = game.player(sender());

	if (upcast(Flag, flag, game.objects().get_object(serial))) {
		log("Cmd_EnemyFlagAction::execute player(%u): flag->owner(%d) "
		    "number=%u\n",
		    player.player_number(), flag->owner().player_number(), number);

		if (const Building* const building = flag->get_building()) {
			if (player.is_hostile(flag->owner()) &&
			    1 < player.vision(Map::get_index(building->get_position(), game.map().get_width())))
				player.enemyflagaction(*flag, sender(), number);
			else
				log("Cmd_EnemyFlagAction::execute: ERROR: wrong player target not "
				    "seen or not hostile.\n");
		}
	}
}

void CmdEnemyFlagAction::serialize(StreamWrite& ser) {
	ser.unsigned_8(PLCMD_ENEMYFLAGACTION);
	ser.unsigned_8(sender());
	ser.unsigned_8(1);
	ser.unsigned_32(serial);
	ser.unsigned_8(sender());
	ser.unsigned_8(number);
}

constexpr uint16_t kCurrentPacketVersionCmdEnemyFlagAction = 3;

void CmdEnemyFlagAction::read(FileRead& fr, EditorGameBase& egbase, MapObjectLoader& mol) {
	try {
		const uint16_t packet_version = fr.unsigned_16();
		if (packet_version == kCurrentPacketVersionCmdEnemyFlagAction) {
			PlayerCommand::read(fr, egbase, mol);
			fr.unsigned_8();
			serial = get_object_serial_or_zero<Flag>(fr.unsigned_32(), mol);
			fr.unsigned_8();
			number = fr.unsigned_8();
		} else {
			throw UnhandledVersionError(
			   "CmdEnemyFlagAction", packet_version, kCurrentPacketVersionCmdEnemyFlagAction);
		}
	} catch (const WException& e) {
		throw GameDataError("enemy flag action: %s", e.what());
	}
}

void CmdEnemyFlagAction::write(FileWrite& fw, EditorGameBase& egbase, MapObjectSaver& mos) {
	// First, write version
	fw.unsigned_16(kCurrentPacketVersionCmdEnemyFlagAction);
	// Write base classes
	PlayerCommand::write(fw, egbase, mos);
	// Now action
	fw.unsigned_8(0);

	// Now serial
	fw.unsigned_32(mos.get_object_file_index_or_zero(egbase.objects().get_object(serial)));

	// Now param
	fw.unsigned_8(sender());
	fw.unsigned_8(number);
}

/*** struct PlayerMessageCommand ***/

PlayerMessageCommand::PlayerMessageCommand(StreamRead& des)
   : PlayerCommand(0, des.unsigned_8()), message_id_(des.unsigned_32()) {
}

constexpr uint16_t kCurrentPacketVersionPlayerMessageCommand = 1;

void PlayerMessageCommand::read(FileRead& fr, EditorGameBase& egbase, MapObjectLoader& mol) {
	try {
		const uint16_t packet_version = fr.unsigned_16();
		if (packet_version == kCurrentPacketVersionPlayerMessageCommand) {
			PlayerCommand::read(fr, egbase, mol);
			message_id_ = MessageId(fr.unsigned_32());
			if (!message_id_)
				throw GameDataError("(player %u): message id is null", sender());
		} else {
			throw UnhandledVersionError(
			   "PlayerMessageCommand", packet_version, kCurrentPacketVersionPlayerMessageCommand);
		}
	} catch (const WException& e) {
		throw GameDataError("player message: %s", e.what());
	}
}

void PlayerMessageCommand::write(FileWrite& fw, EditorGameBase& egbase, MapObjectSaver& mos) {
	fw.unsigned_16(kCurrentPacketVersionPlayerMessageCommand);
	PlayerCommand::write(fw, egbase, mos);
	fw.unsigned_32(mos.message_savers[sender() - 1][message_id()].value());
}

/*** struct Cmd_MessageSetStatusRead ***/

void CmdMessageSetStatusRead::execute(Game& game) {
	game.player(sender()).messages().set_message_status(message_id(), Message::Status::kRead);
}

void CmdMessageSetStatusRead::serialize(StreamWrite& ser) {
	ser.unsigned_8(PLCMD_MESSAGESETSTATUSREAD);
	ser.unsigned_8(sender());
	ser.unsigned_32(message_id().value());
}

/*** struct Cmd_MessageSetStatusArchived ***/

void CmdMessageSetStatusArchived::execute(Game& game) {
	game.player(sender()).messages().set_message_status(message_id(), Message::Status::kArchived);
}

void CmdMessageSetStatusArchived::serialize(StreamWrite& ser) {
	ser.unsigned_8(PLCMD_MESSAGESETSTATUSARCHIVED);
	ser.unsigned_8(sender());
	ser.unsigned_32(message_id().value());
}

/*** struct Cmd_SetStockPolicy ***/
CmdSetStockPolicy::CmdSetStockPolicy(uint32_t time,
                                     PlayerNumber p,
                                     Warehouse& wh,
                                     bool isworker,
                                     DescriptionIndex ware,
                                     Warehouse::StockPolicy policy)
   : PlayerCommand(time, p) {
	warehouse_ = wh.serial();
	isworker_ = isworker;
	ware_ = ware;
	policy_ = policy;
}

CmdSetStockPolicy::CmdSetStockPolicy()
   : PlayerCommand(), warehouse_(0), isworker_(false), policy_() {
}

void CmdSetStockPolicy::execute(Game& game) {
	// Sanitize data that could have come from the network
	if (Player* plr = game.get_player(sender())) {
		if (upcast(Warehouse, warehouse, game.objects().get_object(warehouse_))) {
			if (&warehouse->owner() != plr) {
				log("Cmd_SetStockPolicy: sender %u, but warehouse owner %u\n", sender(),
				    warehouse->owner().player_number());
				return;
			}

			switch (policy_) {
			case Warehouse::SP_Normal:
			case Warehouse::SP_Prefer:
			case Warehouse::SP_DontStock:
			case Warehouse::SP_Remove:
				break;
			}

			if (isworker_) {
				if (!(game.tribes().worker_exists(ware_))) {
					log("Cmd_SetStockPolicy: sender %u, worker %u does not exist\n", sender(), ware_);
					return;
				}
				warehouse->set_worker_policy(ware_, policy_);
			} else {
				if (!(game.tribes().ware_exists(ware_))) {
					log("Cmd_SetStockPolicy: sender %u, ware %u does not exist\n", sender(), ware_);
					return;
				}
				warehouse->set_ware_policy(ware_, policy_);
			}
		}
	}
}

CmdSetStockPolicy::CmdSetStockPolicy(StreamRead& des) : PlayerCommand(0, des.unsigned_8()) {
	warehouse_ = des.unsigned_32();
	isworker_ = des.unsigned_8();
	ware_ = DescriptionIndex(des.unsigned_8());
	policy_ = static_cast<Warehouse::StockPolicy>(des.unsigned_8());
}

void CmdSetStockPolicy::serialize(StreamWrite& ser) {
	ser.unsigned_8(PLCMD_SETSTOCKPOLICY);
	ser.unsigned_8(sender());
	ser.unsigned_32(warehouse_);
	ser.unsigned_8(isworker_);
	ser.unsigned_8(ware_);
	ser.unsigned_8(policy_);
}

constexpr uint8_t kCurrentPacketVersionCmdSetStockPolicy = 1;

void CmdSetStockPolicy::read(FileRead& fr, EditorGameBase& egbase, MapObjectLoader& mol) {
	try {
		uint8_t packet_version = fr.unsigned_8();
		if (packet_version == kCurrentPacketVersionCmdSetStockPolicy) {
			PlayerCommand::read(fr, egbase, mol);
			warehouse_ = fr.unsigned_32();
			isworker_ = fr.unsigned_8();
			ware_ = DescriptionIndex(fr.unsigned_8());
			policy_ = static_cast<Warehouse::StockPolicy>(fr.unsigned_8());
		} else {
			throw UnhandledVersionError(
			   "CmdSetStockPolicy", packet_version, kCurrentPacketVersionCmdSetStockPolicy);
		}
	} catch (const std::exception& e) {
		throw GameDataError("Cmd_SetStockPolicy: %s", e.what());
	}
}

void CmdSetStockPolicy::write(FileWrite& fw, EditorGameBase& egbase, MapObjectSaver& mos) {
	fw.unsigned_8(kCurrentPacketVersionCmdSetStockPolicy);
	PlayerCommand::write(fw, egbase, mos);
	fw.unsigned_32(warehouse_);
	fw.unsigned_8(isworker_);
	fw.unsigned_8(ware_);
	fw.unsigned_8(policy_);
}
}