File: CMapEditManager.cpp

package info (click to toggle)
vcmi 0.99%2Bdfsg%2Bgit20190113.f06c8a87-2
  • links: PTS, VCS
  • area: contrib
  • in suites: bullseye
  • size: 11,136 kB
  • sloc: cpp: 142,615; sh: 315; objc: 248; makefile: 32; ansic: 28; python: 13
file content (1106 lines) | stat: -rw-r--r-- 29,330 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
/*
 * CMapEditManager.cpp, part of VCMI engine
 *
 * Authors: listed in file AUTHORS in main folder
 *
 * License: GNU General Public License v2.0 or later
 * Full text of license available in license.txt file, in main folder
 *
 */
#include "StdInc.h"
#include "CMapEditManager.h"

#include "../JsonNode.h"
#include "../filesystem/Filesystem.h"
#include "../mapObjects/CObjectClassesHandler.h"
#include "../mapObjects/CGHeroInstance.h"
#include "../VCMI_Lib.h"
#include "CDrawRoadsOperation.h"
#include "../mapping/CMap.h"

MapRect::MapRect() : x(0), y(0), z(0), width(0), height(0)
{

}

MapRect::MapRect(int3 pos, si32 width, si32 height) : x(pos.x), y(pos.y), z(pos.z), width(width), height(height)
{

}

MapRect MapRect::operator&(const MapRect & rect) const
{
	bool intersect = right() > rect.left() && rect.right() > left() &&
			bottom() > rect.top() && rect.bottom() > top() &&
			z == rect.z;
	if(intersect)
	{
		MapRect ret;
		ret.x = std::max(left(), rect.left());
		ret.y = std::max(top(), rect.top());
		ret.z = rect.z;
		ret.width = std::min(right(), rect.right()) - ret.x;
		ret.height = std::min(bottom(), rect.bottom()) - ret.y;
		return ret;
	}
	else
	{
		return MapRect();
	}
}

si32 MapRect::left() const
{
	return x;
}

si32 MapRect::right() const
{
	return x + width;
}

si32 MapRect::top() const
{
	return y;
}

si32 MapRect::bottom() const
{
	return y + height;
}

int3 MapRect::topLeft() const
{
	return int3(x, y, z);
}

int3 MapRect::topRight() const
{
	return int3(right(), y, z);
}

int3 MapRect::bottomLeft() const
{
	return int3(x, bottom(), z);
}

int3 MapRect::bottomRight() const
{
	return int3(right(), bottom(), z);
}

CTerrainSelection::CTerrainSelection(CMap * map) : CMapSelection(map)
{

}

void CTerrainSelection::selectRange(const MapRect & rect)
{
	rect.forEach([this](const int3 pos)
	{
		this->select(pos);
	});
}

void CTerrainSelection::deselectRange(const MapRect & rect)
{
	rect.forEach([this](const int3 pos)
	{
		this->deselect(pos);
	});
}

void CTerrainSelection::setSelection(std::vector<int3> & vec)
{
	for (auto pos : vec)
		this->select(pos);
}

void CTerrainSelection::selectAll()
{
	selectRange(MapRect(int3(0, 0, 0), getMap()->width, getMap()->height));
	selectRange(MapRect(int3(0, 0, 1), getMap()->width, getMap()->height));
}

void CTerrainSelection::clearSelection()
{
	deselectRange(MapRect(int3(0, 0, 0), getMap()->width, getMap()->height));
	deselectRange(MapRect(int3(0, 0, 1), getMap()->width, getMap()->height));
}

CObjectSelection::CObjectSelection(CMap * map) : CMapSelection(map)
{

}

CMapOperation::CMapOperation(CMap * map) : map(map)
{

}

std::string CMapOperation::getLabel() const
{
	return "";
}


MapRect CMapOperation::extendTileAround(const int3 & centerPos) const
{
	return MapRect(int3(centerPos.x - 1, centerPos.y - 1, centerPos.z), 3, 3);
}

MapRect CMapOperation::extendTileAroundSafely(const int3 & centerPos) const
{
	return extendTileAround(centerPos) & MapRect(int3(0, 0, centerPos.z), map->width, map->height);
}


CMapUndoManager::CMapUndoManager() : undoRedoLimit(10)
{

}

void CMapUndoManager::undo()
{
	doOperation(undoStack, redoStack, true);
}

void CMapUndoManager::redo()
{
	doOperation(redoStack, undoStack, false);
}

void CMapUndoManager::clearAll()
{
	undoStack.clear();
	redoStack.clear();
}

int CMapUndoManager::getUndoRedoLimit() const
{
	return undoRedoLimit;
}

void CMapUndoManager::setUndoRedoLimit(int value)
{
	assert(value >= 0);
	undoStack.resize(std::min(undoStack.size(), static_cast<TStack::size_type>(value)));
	redoStack.resize(std::min(redoStack.size(), static_cast<TStack::size_type>(value)));
}

const CMapOperation * CMapUndoManager::peekRedo() const
{
	return peek(redoStack);
}

const CMapOperation * CMapUndoManager::peekUndo() const
{
	return peek(undoStack);
}

void CMapUndoManager::addOperation(std::unique_ptr<CMapOperation> && operation)
{
	undoStack.push_front(std::move(operation));
	if(undoStack.size() > undoRedoLimit) undoStack.pop_back();
	redoStack.clear();
}

void CMapUndoManager::doOperation(TStack & fromStack, TStack & toStack, bool doUndo)
{
	if(fromStack.empty()) return;
	auto & operation = fromStack.front();
	if(doUndo)
	{
		operation->undo();
	}
	else
	{
		operation->redo();
	}
	toStack.push_front(std::move(operation));
	fromStack.pop_front();
}

const CMapOperation * CMapUndoManager::peek(const TStack & stack) const
{
	if(stack.empty()) return nullptr;
	return stack.front().get();
}

CMapEditManager::CMapEditManager(CMap * map)
	: map(map), terrainSel(map), objectSel(map)
{

}

CMap * CMapEditManager::getMap()
{
	return map;
}

void CMapEditManager::clearTerrain(CRandomGenerator * gen)
{
	execute(make_unique<CClearTerrainOperation>(map, gen ? gen : &(this->gen)));
}

void CMapEditManager::drawTerrain(ETerrainType terType, CRandomGenerator * gen)
{
	execute(make_unique<CDrawTerrainOperation>(map, terrainSel, terType, gen ? gen : &(this->gen)));
	terrainSel.clearSelection();
}

void CMapEditManager::drawRoad(ERoadType::ERoadType roadType, CRandomGenerator* gen)
{
	execute(make_unique<CDrawRoadsOperation>(map, terrainSel, roadType, gen ? gen : &(this->gen)));
	terrainSel.clearSelection();
}


void CMapEditManager::insertObject(CGObjectInstance * obj)
{
	execute(make_unique<CInsertObjectOperation>(map, obj));
}

void CMapEditManager::execute(std::unique_ptr<CMapOperation> && operation)
{
	operation->execute();
	undoManager.addOperation(std::move(operation));
}

CTerrainSelection & CMapEditManager::getTerrainSelection()
{
	return terrainSel;
}

CObjectSelection & CMapEditManager::getObjectSelection()
{
	return objectSel;
}

CMapUndoManager & CMapEditManager::getUndoManager()
{
	return undoManager;
}

CComposedOperation::CComposedOperation(CMap * map) : CMapOperation(map)
{

}

void CComposedOperation::execute()
{
	for(auto & operation : operations)
	{
		operation->execute();
	}
}

void CComposedOperation::undo()
{
	for(auto & operation : operations)
	{
		operation->undo();
	}
}

void CComposedOperation::redo()
{
	for(auto & operation : operations)
	{
		operation->redo();
	}
}

void CComposedOperation::addOperation(std::unique_ptr<CMapOperation> && operation)
{
	operations.push_back(std::move(operation));
}

const std::string TerrainViewPattern::FLIP_MODE_DIFF_IMAGES = "D";

const std::string TerrainViewPattern::RULE_DIRT = "D";
const std::string TerrainViewPattern::RULE_SAND = "S";
const std::string TerrainViewPattern::RULE_TRANSITION = "T";
const std::string TerrainViewPattern::RULE_NATIVE = "N";
const std::string TerrainViewPattern::RULE_NATIVE_STRONG = "N!";
const std::string TerrainViewPattern::RULE_ANY = "?";

TerrainViewPattern::TerrainViewPattern() : diffImages(false), rotationTypesCount(0), minPoints(0)
{
	maxPoints = std::numeric_limits<int>::max();
}

TerrainViewPattern::WeightedRule::WeightedRule(std::string &Name) : points(0), name(Name)
{
	standardRule = (TerrainViewPattern::RULE_ANY == Name || TerrainViewPattern::RULE_DIRT == Name
		|| TerrainViewPattern::RULE_NATIVE == Name || TerrainViewPattern::RULE_SAND == Name
		|| TerrainViewPattern::RULE_TRANSITION == Name || TerrainViewPattern::RULE_NATIVE_STRONG == Name);
	anyRule = (Name == TerrainViewPattern::RULE_ANY);
	dirtRule = (Name == TerrainViewPattern::RULE_DIRT);
	sandRule = (Name == TerrainViewPattern::RULE_SAND);
	transitionRule = (Name == TerrainViewPattern::RULE_TRANSITION);
	nativeStrongRule = (Name == TerrainViewPattern::RULE_NATIVE_STRONG);
	nativeRule = (Name == TerrainViewPattern::RULE_NATIVE);
}

void TerrainViewPattern::WeightedRule::setNative()
{
	nativeRule = true;
	standardRule = true;
	//TODO: would look better as a bitfield
	dirtRule = sandRule = transitionRule = nativeStrongRule = anyRule = false; //no idea what they mean, but look mutually exclusive
}

CTerrainViewPatternConfig::CTerrainViewPatternConfig()
{
	const JsonNode config(ResourceID("config/terrainViewPatterns.json"));
	static const std::string patternTypes[] = { "terrainView", "terrainType" };
	for(int i = 0; i < ARRAY_COUNT(patternTypes); ++i)
	{
		const auto & patternsVec = config[patternTypes[i]].Vector();
		for(const auto & ptrnNode : patternsVec)
		{
			TerrainViewPattern pattern;

			// Read pattern data
			const JsonVector & data = ptrnNode["data"].Vector();
			assert(data.size() == 9);
			for(int j = 0; j < data.size(); ++j)
			{
				std::string cell = data[j].String();
				boost::algorithm::erase_all(cell, " ");
				std::vector<std::string> rules;
				boost::split(rules, cell, boost::is_any_of(","));
				for(std::string ruleStr : rules)
				{
					std::vector<std::string> ruleParts;
					boost::split(ruleParts, ruleStr, boost::is_any_of("-"));
					TerrainViewPattern::WeightedRule rule(ruleParts[0]);
					assert(!rule.name.empty());
					if(ruleParts.size() > 1)
					{
						rule.points = boost::lexical_cast<int>(ruleParts[1]);
					}
					pattern.data[j].push_back(rule);
				}
			}

			// Read various properties
			pattern.id = ptrnNode["id"].String();
			assert(!pattern.id.empty());
			pattern.minPoints = static_cast<int>(ptrnNode["minPoints"].Float());
			pattern.maxPoints = static_cast<int>(ptrnNode["maxPoints"].Float());
			if(pattern.maxPoints == 0) pattern.maxPoints = std::numeric_limits<int>::max();

			// Read mapping
			if(i == 0)
			{
				const auto & mappingStruct = ptrnNode["mapping"].Struct();
				for(const auto & mappingPair : mappingStruct)
				{
					TerrainViewPattern terGroupPattern = pattern;
					auto mappingStr = mappingPair.second.String();
					boost::algorithm::erase_all(mappingStr, " ");
					auto colonIndex = mappingStr.find_first_of(":");
					const auto & flipMode = mappingStr.substr(0, colonIndex);
					terGroupPattern.diffImages = TerrainViewPattern::FLIP_MODE_DIFF_IMAGES == &(flipMode[flipMode.length() - 1]);
					if(terGroupPattern.diffImages)
					{
						terGroupPattern.rotationTypesCount = boost::lexical_cast<int>(flipMode.substr(0, flipMode.length() - 1));
						assert(terGroupPattern.rotationTypesCount == 2 || terGroupPattern.rotationTypesCount == 4);
					}
					mappingStr = mappingStr.substr(colonIndex + 1);
					std::vector<std::string> mappings;
					boost::split(mappings, mappingStr, boost::is_any_of(","));
					for(std::string mapping : mappings)
					{
						std::vector<std::string> range;
						boost::split(range, mapping, boost::is_any_of("-"));
						terGroupPattern.mapping.push_back(std::make_pair(boost::lexical_cast<int>(range[0]),
							boost::lexical_cast<int>(range.size() > 1 ? range[1] : range[0])));
					}

					// Add pattern to the patterns map
					const auto & terGroup = getTerrainGroup(mappingPair.first);
					std::vector<TerrainViewPattern> terrainViewPatternFlips;
					terrainViewPatternFlips.push_back(terGroupPattern);

					for (int i = 1; i < 4; ++i)
					{
						//auto p = terGroupPattern;
						flipPattern(terGroupPattern, i); //FIXME: we flip in place - doesn't make much sense now, but used to work
						terrainViewPatternFlips.push_back(terGroupPattern);
					}
					terrainViewPatterns[terGroup].push_back(terrainViewPatternFlips);
				}
			}
			else if(i == 1)
			{
				terrainTypePatterns[pattern.id].push_back(pattern);
				for (int i = 1; i < 4; ++i)
				{
					//auto p = pattern;
					flipPattern(pattern, i); ///FIXME: we flip in place - doesn't make much sense now
					terrainTypePatterns[pattern.id].push_back(pattern);
				}
			}
		}
	}
}

CTerrainViewPatternConfig::~CTerrainViewPatternConfig()
{

}

ETerrainGroup::ETerrainGroup CTerrainViewPatternConfig::getTerrainGroup(const std::string & terGroup) const
{
	static const std::map<std::string, ETerrainGroup::ETerrainGroup> terGroups =
	{
		{"normal", ETerrainGroup::NORMAL},
		{"dirt", ETerrainGroup::DIRT},
		{"sand", ETerrainGroup::SAND},
		{"water", ETerrainGroup::WATER},
		{"rock", ETerrainGroup::ROCK},
	};
	auto it = terGroups.find(terGroup);
	if(it == terGroups.end()) throw std::runtime_error(boost::str(boost::format("Terrain group '%s' does not exist.") % terGroup));
	return it->second;
}

const std::vector<CTerrainViewPatternConfig::TVPVector> & CTerrainViewPatternConfig::getTerrainViewPatternsForGroup(ETerrainGroup::ETerrainGroup terGroup) const
{
	return terrainViewPatterns.find(terGroup)->second;
}

boost::optional<const TerrainViewPattern &> CTerrainViewPatternConfig::getTerrainViewPatternById(ETerrainGroup::ETerrainGroup terGroup, const std::string & id) const
{
	const std::vector<TVPVector> & groupPatterns = getTerrainViewPatternsForGroup(terGroup);
	for (const TVPVector & patternFlips : groupPatterns)
	{
		const TerrainViewPattern & pattern = patternFlips.front();
		if(id == pattern.id)
		{
			return boost::optional<const TerrainViewPattern &>(pattern);
		}
	}
	return boost::optional<const TerrainViewPattern &>();
}
boost::optional<const CTerrainViewPatternConfig::TVPVector &> CTerrainViewPatternConfig::getTerrainViewPatternsById(ETerrainGroup::ETerrainGroup terGroup, const std::string & id) const
{
	const std::vector<TVPVector> & groupPatterns = getTerrainViewPatternsForGroup(terGroup);
	for (const TVPVector & patternFlips : groupPatterns)
	{
		const TerrainViewPattern & pattern = patternFlips.front();
		if (id == pattern.id)
		{
			return boost::optional<const TVPVector &>(patternFlips);
		}
	}
	return boost::optional<const TVPVector &>();
}


const CTerrainViewPatternConfig::TVPVector * CTerrainViewPatternConfig::getTerrainTypePatternById(const std::string & id) const
{
	auto it = terrainTypePatterns.find(id);
	assert(it != terrainTypePatterns.end());
	return &(it->second);
}

void CTerrainViewPatternConfig::flipPattern(TerrainViewPattern & pattern, int flip) const
{
	//flip in place to avoid expensive constructor. Seriously.

	if (flip == 0)
	{
		return;
	}

	//always flip horizontal
	for (int i = 0; i < 3; ++i)
	{
		int y = i * 3;
		std::swap(pattern.data[y], pattern.data[y + 2]);
	}
	//flip vertical only at 2nd step
	if (flip == CMapOperation::FLIP_PATTERN_VERTICAL)
	{
		for (int i = 0; i < 3; ++i)
		{
			std::swap(pattern.data[i], pattern.data[6 + i]);
		}
	}
}


CDrawTerrainOperation::CDrawTerrainOperation(CMap * map, const CTerrainSelection & terrainSel, ETerrainType terType, CRandomGenerator * gen)
	: CMapOperation(map), terrainSel(terrainSel), terType(terType), gen(gen)
{

}

void CDrawTerrainOperation::execute()
{
	for(const auto & pos : terrainSel.getSelectedItems())
	{
		auto & tile = map->getTile(pos);
		tile.terType = terType;
		invalidateTerrainViews(pos);
	}

	updateTerrainTypes();
	updateTerrainViews();
}

void CDrawTerrainOperation::undo()
{
	//TODO
}

void CDrawTerrainOperation::redo()
{
	//TODO
}

std::string CDrawTerrainOperation::getLabel() const
{
	return "Draw Terrain";
}

void CDrawTerrainOperation::updateTerrainTypes()
{
	auto positions = terrainSel.getSelectedItems();
	while(!positions.empty())
	{
		const auto & centerPos = *(positions.begin());
		auto centerTile = map->getTile(centerPos);
		//logGlobal->debug("Set terrain tile at pos '%s' to type '%s'", centerPos, centerTile.terType);
		auto tiles = getInvalidTiles(centerPos);
		auto updateTerrainType = [&](const int3 & pos)
		{
			map->getTile(pos).terType = centerTile.terType;
			positions.insert(pos);
			invalidateTerrainViews(pos);
			//logGlobal->debug("Set additional terrain tile at pos '%s' to type '%s'", pos, centerTile.terType);
		};

		// Fill foreign invalid tiles
		for(const auto & tile : tiles.foreignTiles)
		{
			updateTerrainType(tile);
		}

		tiles = getInvalidTiles(centerPos);
		if(tiles.nativeTiles.find(centerPos) != tiles.nativeTiles.end())
		{
			// Blow up
			auto rect = extendTileAroundSafely(centerPos);
			std::set<int3> suitableTiles;
			int invalidForeignTilesCnt = std::numeric_limits<int>::max(), invalidNativeTilesCnt = 0;
			bool centerPosValid = false;
			rect.forEach([&](const int3 & posToTest)
			{
				auto & terrainTile = map->getTile(posToTest);
				if(centerTile.terType != terrainTile.terType)
				{
					auto formerTerType = terrainTile.terType;
					terrainTile.terType = centerTile.terType;
					auto testTile = getInvalidTiles(posToTest);

					int nativeTilesCntNorm = testTile.nativeTiles.empty() ? std::numeric_limits<int>::max() : testTile.nativeTiles.size();

					bool putSuitableTile = false;
					bool addToSuitableTiles = false;
					if(testTile.centerPosValid)
					{
						if (!centerPosValid)
						{
							centerPosValid = true;
							putSuitableTile = true;
						}
						else
						{
							if(testTile.foreignTiles.size() < invalidForeignTilesCnt)
							{
								putSuitableTile = true;
							}
							else
							{
								addToSuitableTiles = true;
							}
						}
					}
					else if (!centerPosValid)
					{
						if((nativeTilesCntNorm > invalidNativeTilesCnt) ||
								(nativeTilesCntNorm == invalidNativeTilesCnt && testTile.foreignTiles.size() < invalidForeignTilesCnt))
						{
							putSuitableTile = true;
						}
						else if(nativeTilesCntNorm == invalidNativeTilesCnt && testTile.foreignTiles.size() == invalidForeignTilesCnt)
						{
							addToSuitableTiles = true;
						}
					}

					if (putSuitableTile)
					{
						//if(!suitableTiles.empty())
						//{
						//	logGlobal->debug("Clear suitables tiles.");
						//}

						invalidNativeTilesCnt = nativeTilesCntNorm;
						invalidForeignTilesCnt = testTile.foreignTiles.size();
						suitableTiles.clear();
						addToSuitableTiles = true;
					}

					if (addToSuitableTiles)
					{
						suitableTiles.insert(posToTest);
					}

					terrainTile.terType = formerTerType;
				}
			});

			if(suitableTiles.size() == 1)
			{
				updateTerrainType(*suitableTiles.begin());
			}
			else
			{
				static const int3 directions[] = { int3(0, -1, 0), int3(-1, 0, 0), int3(0, 1, 0), int3(1, 0, 0),
											int3(-1, -1, 0), int3(-1, 1, 0), int3(1, 1, 0), int3(1, -1, 0)};
				for(auto & direction : directions)
				{
					auto it = suitableTiles.find(centerPos + direction);
					if(it != suitableTiles.end())
					{
						updateTerrainType(*it);
						break;
					}
				}
			}
		}
		else
		{
			// add invalid native tiles which are not in the positions list
			for(const auto & nativeTile : tiles.nativeTiles)
			{
				if(positions.find(nativeTile) == positions.end())
				{
					positions.insert(nativeTile);
				}
			}

			positions.erase(centerPos);
		}
	}
}

void CDrawTerrainOperation::updateTerrainViews()
{
	for(const auto & pos : invalidatedTerViews)
	{
		const auto & patterns = VLC->terviewh->getTerrainViewPatternsForGroup(getTerrainGroup(map->getTile(pos).terType));

		// Detect a pattern which fits best
		int bestPattern = -1;
		ValidationResult valRslt(false);
		for(int k = 0; k < patterns.size(); ++k)
		{
			const auto & pattern = patterns[k];
			//(ETerrainGroup::ETerrainGroup terGroup, const std::string & id)
			valRslt = validateTerrainView(pos, &pattern);
			if(valRslt.result)
			{
				bestPattern = k;
				break;
			}
		}
		//assert(bestPattern != -1);
		if(bestPattern == -1)
		{
			// This shouldn't be the case
			logGlobal->warn("No pattern detected at pos '%s'.", pos.toString());
			CTerrainViewPatternUtils::printDebuggingInfoAboutTile(map, pos);
			continue;
		}

		// Get mapping
		const TerrainViewPattern & pattern = patterns[bestPattern][valRslt.flip];
		std::pair<int, int> mapping;
		if(valRslt.transitionReplacement.empty())
		{
			mapping = pattern.mapping[0];
		}
		else
		{
			mapping = valRslt.transitionReplacement == TerrainViewPattern::RULE_DIRT ? pattern.mapping[0] : pattern.mapping[1];
		}

		// Set terrain view
		auto & tile = map->getTile(pos);
		if(!pattern.diffImages)
		{
			tile.terView = gen->nextInt(mapping.first, mapping.second);
			tile.extTileFlags = valRslt.flip;
		}
		else
		{
			const int framesPerRot = (mapping.second - mapping.first + 1) / pattern.rotationTypesCount;
			int flip = (pattern.rotationTypesCount == 2 && valRslt.flip == 2) ? 1 : valRslt.flip;
			int firstFrame = mapping.first + flip * framesPerRot;
			tile.terView = gen->nextInt(firstFrame, firstFrame + framesPerRot - 1);
			tile.extTileFlags =	0;
		}
	}
}

ETerrainGroup::ETerrainGroup CDrawTerrainOperation::getTerrainGroup(ETerrainType terType) const
{
	switch(terType)
	{
	case ETerrainType::DIRT:
		return ETerrainGroup::DIRT;
	case ETerrainType::SAND:
		return ETerrainGroup::SAND;
	case ETerrainType::WATER:
		return ETerrainGroup::WATER;
	case ETerrainType::ROCK:
		return ETerrainGroup::ROCK;
	default:
		return ETerrainGroup::NORMAL;
	}
}

CDrawTerrainOperation::ValidationResult CDrawTerrainOperation::validateTerrainView(const int3 & pos, const std::vector<TerrainViewPattern> * pattern, int recDepth) const
{
	for(int flip = 0; flip < 4; ++flip)
	{
		auto valRslt = validateTerrainViewInner(pos, pattern->at(flip), recDepth);
		if(valRslt.result)
		{
			valRslt.flip = flip;
			return valRslt;
		}
	}
	return ValidationResult(false);
}

CDrawTerrainOperation::ValidationResult CDrawTerrainOperation::validateTerrainViewInner(const int3 & pos, const TerrainViewPattern & pattern, int recDepth) const
{
	auto centerTerType = map->getTile(pos).terType;
	auto centerTerGroup = getTerrainGroup(centerTerType);
	int totalPoints = 0;
	std::string transitionReplacement;

	for(int i = 0; i < 9; ++i)
	{
		// The center, middle cell can be skipped
		if(i == 4)
		{
			continue;
		}

		// Get terrain group of the current cell
		int cx = pos.x + (i % 3) - 1;
		int cy = pos.y + (i / 3) - 1;
		int3 currentPos(cx, cy, pos.z);
		bool isAlien = false;
		ETerrainType terType;
		if(!map->isInTheMap(currentPos))
		{
			// position is not in the map, so take the ter type from the neighbor tile
			bool widthTooHigh = currentPos.x >= map->width;
			bool widthTooLess = currentPos.x < 0;
			bool heightTooHigh = currentPos.y >= map->height;
			bool heightTooLess = currentPos.y < 0;

			if ((widthTooHigh && heightTooHigh) || (widthTooHigh && heightTooLess) || (widthTooLess && heightTooHigh) || (widthTooLess && heightTooLess))
			{
				terType = centerTerType;
			}
			else if(widthTooHigh)
			{
				terType = map->getTile(int3(currentPos.x - 1, currentPos.y, currentPos.z)).terType;
			}
			else if(heightTooHigh)
			{
				terType = map->getTile(int3(currentPos.x, currentPos.y - 1, currentPos.z)).terType;
			}
			else if (widthTooLess)
			{
				terType = map->getTile(int3(currentPos.x + 1, currentPos.y, currentPos.z)).terType;
			}
			else if (heightTooLess)
			{
				terType = map->getTile(int3(currentPos.x, currentPos.y + 1, currentPos.z)).terType;
			}
		}
		else
		{
			terType = map->getTile(currentPos).terType;
			if(terType != centerTerType)
			{
				isAlien = true;
			}
		}

		// Validate all rules per cell
		int topPoints = -1;
		for(auto & elem : pattern.data[i])
		{
			TerrainViewPattern::WeightedRule rule = elem;
			if(!rule.isStandardRule())
			{
				if(recDepth == 0 && map->isInTheMap(currentPos))
				{
					if(terType == centerTerType)
					{
						const auto & group = getTerrainGroup(centerTerType);
						const auto & patternForRule = VLC->terviewh->getTerrainViewPatternsById(group, rule.name);
						if(auto p = patternForRule)
						{
							auto rslt = validateTerrainView(currentPos, &(*p), 1);
							if(rslt.result) topPoints = std::max(topPoints, rule.points);
						}
					}
					continue;
				}
				else
				{
					rule.setNative();
				}
			}

			auto applyValidationRslt = [&](bool rslt)
			{
				if(rslt)
				{
					topPoints = std::max(topPoints, rule.points);
				}
			};

			// Validate cell with the ruleset of the pattern
			bool nativeTestOk, nativeTestStrongOk;
			nativeTestOk = nativeTestStrongOk = (rule.isNativeStrong() || rule.isNativeRule()) && !isAlien;
			if(centerTerGroup == ETerrainGroup::NORMAL)
			{
				bool dirtTestOk = (rule.isDirtRule() || rule.isTransition())
						&& isAlien && !isSandType(terType);
				bool sandTestOk = (rule.isSandRule() || rule.isTransition())
						&& isSandType(terType);

				if (transitionReplacement.empty() && rule.isTransition()
						&& (dirtTestOk || sandTestOk))
				{
					transitionReplacement = dirtTestOk ? TerrainViewPattern::RULE_DIRT : TerrainViewPattern::RULE_SAND;
				}
				if (rule.isTransition())
				{
					applyValidationRslt((dirtTestOk && transitionReplacement != TerrainViewPattern::RULE_SAND) ||
							(sandTestOk && transitionReplacement != TerrainViewPattern::RULE_DIRT));
				}
				else
				{
					applyValidationRslt(rule.isAnyRule() || dirtTestOk || sandTestOk || nativeTestOk);
				}
			}
			else if(centerTerGroup == ETerrainGroup::DIRT)
			{
				nativeTestOk = rule.isNativeRule() && !isSandType(terType);
				bool sandTestOk = (rule.isSandRule() || rule.isTransition())
						&& isSandType(terType);
				applyValidationRslt(rule.isAnyRule() || sandTestOk || nativeTestOk || nativeTestStrongOk);
			}
			else if(centerTerGroup == ETerrainGroup::SAND)
			{
				applyValidationRslt(true);
			}
			else if(centerTerGroup == ETerrainGroup::WATER || centerTerGroup == ETerrainGroup::ROCK)
			{
				bool sandTestOk = (rule.isSandRule() || rule.isTransition())
						&& isAlien;
				applyValidationRslt(rule.isAnyRule() || sandTestOk || nativeTestOk);
			}
		}

		if(topPoints == -1)
		{
			return ValidationResult(false);
		}
		else
		{
			totalPoints += topPoints;
		}
	}

	if(totalPoints >= pattern.minPoints && totalPoints <= pattern.maxPoints)
	{
		return ValidationResult(true, transitionReplacement);
	}
	else
	{
		return ValidationResult(false);
	}
}

bool CDrawTerrainOperation::isSandType(ETerrainType terType) const
{
	switch(terType)
	{
	case ETerrainType::WATER:
	case ETerrainType::SAND:
	case ETerrainType::ROCK:
		return true;
	default:
		return false;
	}
}

void CDrawTerrainOperation::invalidateTerrainViews(const int3 & centerPos)
{
	auto rect = extendTileAroundSafely(centerPos);
	rect.forEach([&](const int3 & pos)
	{
		invalidatedTerViews.insert(pos);
	});
}

CDrawTerrainOperation::InvalidTiles CDrawTerrainOperation::getInvalidTiles(const int3 & centerPos) const
{
	//TODO: this is very expensive function for RMG, needs optimization
	InvalidTiles tiles;
	auto centerTerType = map->getTile(centerPos).terType;
	auto rect = extendTileAround(centerPos);
	rect.forEach([&](const int3 & pos)
	{
		if(map->isInTheMap(pos))
		{
			auto ptrConfig = VLC->terviewh;
			auto terType = map->getTile(pos).terType;
			auto valid = validateTerrainView(pos, ptrConfig->getTerrainTypePatternById("n1")).result;

			// Special validity check for rock & water
			if(valid && (terType == ETerrainType::WATER || terType == ETerrainType::ROCK))
			{
				static const std::string patternIds[] = { "s1", "s2" };
				for(auto & patternId : patternIds)
				{
					valid = !validateTerrainView(pos, ptrConfig->getTerrainTypePatternById(patternId)).result;
					if(!valid) break;
				}
			}
			// Additional validity check for non rock OR water
			else if(!valid && (terType != ETerrainType::WATER && terType != ETerrainType::ROCK))
			{
				static const std::string patternIds[] = { "n2", "n3" };
				for(auto & patternId : patternIds)
				{
					valid = validateTerrainView(pos, ptrConfig->getTerrainTypePatternById(patternId)).result;
					if(valid) break;
				}
			}

			if(!valid)
			{
				if(terType == centerTerType) tiles.nativeTiles.insert(pos);
				else tiles.foreignTiles.insert(pos);
			}
			else if(centerPos == pos)
			{
				tiles.centerPosValid = true;
			}
		}
	});
	return tiles;
}

CDrawTerrainOperation::ValidationResult::ValidationResult(bool result, const std::string & transitionReplacement)
	: result(result), transitionReplacement(transitionReplacement), flip(0)
{

}

void CTerrainViewPatternUtils::printDebuggingInfoAboutTile(const CMap * map, int3 pos)
{
	logGlobal->debug("Printing detailed info about nearby map tiles of pos '%s'", pos.toString());
	for(int y = pos.y - 2; y <= pos.y + 2; ++y)
	{
		std::string line;
		const int PADDED_LENGTH = 10;
		for(int x = pos.x - 2; x <= pos.x + 2; ++x)
		{
			auto debugPos = int3(x, y, pos.z);
			if(map->isInTheMap(debugPos))
			{
				auto debugTile = map->getTile(debugPos);

				std::string terType = debugTile.terType.toString().substr(0, 6);
				line += terType;
				line.insert(line.end(), PADDED_LENGTH - terType.size(), ' ');
			}
			else
			{
				line += "X";
				line.insert(line.end(), PADDED_LENGTH - 1, ' ');
			}
		}

		logGlobal->debug(line);
	}
}

CClearTerrainOperation::CClearTerrainOperation(CMap * map, CRandomGenerator * gen) : CComposedOperation(map)
{
	CTerrainSelection terrainSel(map);
	terrainSel.selectRange(MapRect(int3(0, 0, 0), map->width, map->height));
	addOperation(make_unique<CDrawTerrainOperation>(map, terrainSel, ETerrainType::WATER, gen));
	if(map->twoLevel)
	{
		terrainSel.clearSelection();
		terrainSel.selectRange(MapRect(int3(0, 0, 1), map->width, map->height));
		addOperation(make_unique<CDrawTerrainOperation>(map, terrainSel, ETerrainType::ROCK, gen));
	}
}

std::string CClearTerrainOperation::getLabel() const
{
	return "Clear Terrain";
}

CInsertObjectOperation::CInsertObjectOperation(CMap * map, CGObjectInstance * obj)
	: CMapOperation(map), obj(obj)
{

}

void CInsertObjectOperation::execute()
{
	obj->id = ObjectInstanceID(map->objects.size());

	boost::format fmt("%s_%d");
	fmt % obj->typeName % obj->id.getNum();
	obj->instanceName = fmt.str();

	map->addNewObject(obj);
}

void CInsertObjectOperation::undo()
{
	//TODO
}

void CInsertObjectOperation::redo()
{
	execute();
}

std::string CInsertObjectOperation::getLabel() const
{
	return "Insert Object";
}