-
-
Notifications
You must be signed in to change notification settings - Fork 988
/
terrain_builder.cpp
1203 lines (994 loc) · 33.4 KB
/
terrain_builder.cpp
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
/*
Copyright (C) 2004 - 2016 by Philippe Plantier <ayin@anathas.org>
Part of the Battle for Wesnoth Project http://www.wesnoth.org
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.
See the COPYING file for more details.
*/
/**
* @file
* Terrain builder.
*/
#include "terrain_builder.hpp"
#include "game_preferences.hpp"
#include "image.hpp"
#include "loadscreen.hpp"
#include "log.hpp"
#include "map.hpp"
#include "serialization/string_utils.hpp"
#include <boost/foreach.hpp>
static lg::log_domain log_engine("engine");
#define ERR_NG LOG_STREAM(err, log_engine)
#define WRN_NG LOG_STREAM(warn, log_engine)
/**
*
* These legacy map_location functions moved here from map_location.?pp.
* We have refactored them out of everything but this class. Hopefully
* the end is near...
*
// Adds an absolute location to a "delta" location
// This is not the mathematically correct behavior, it is neither
// commutative nor associative. Negative coordinates may give strange
// results. It is retained because terrain builder code relies in this
// broken behavior. Best avoid.
map_location legacy_negation() const;
map_location legacy_sum(const map_location &a) const;
map_location& legacy_sum_assign(const map_location &a);
map_location legacy_difference(const map_location &a) const;
*
*/
static map_location legacy_negation(const map_location & me)
{
return map_location(-me.x, -me.y);
}
static map_location& legacy_sum_assign(map_location & me, const map_location &a)
{
bool parity = (me.x & 1) != 0;
me.x += a.x;
me.y += a.y;
if((a.x > 0) && (a.x % 2) && parity)
me.y++;
if((a.x < 0) && (a.x % 2) && !parity)
me.y--;
return me;
}
static map_location legacy_sum(const map_location & me, const map_location& a)
{
map_location ret(me);
legacy_sum_assign(ret,a);
return ret;
}
static map_location legacy_difference(const map_location & me, const map_location &a)
{
return legacy_sum(me,legacy_negation(a));
}
/**
*
* This file holds the terrain_builder implementation.
*
*/
terrain_builder::building_ruleset terrain_builder::building_rules_;
const config* terrain_builder::rules_cfg_ = NULL;
terrain_builder::rule_image::rule_image(int layer, int x, int y, bool global_image, int cx, int cy, bool is_water) :
layer(layer),
basex(x),
basey(y),
variants(),
global_image(global_image),
center_x(cx),
center_y(cy),
is_water(is_water)
{}
terrain_builder::tile::tile() :
flags(),
images(),
images_foreground(),
images_background(),
last_tod("invalid_tod"),
sorted_images(false)
{}
void terrain_builder::tile::rebuild_cache(const std::string& tod, logs* log)
{
images_background.clear();
images_foreground.clear();
if(!sorted_images){
//sort images by their layer (and basey)
//but use stable to keep the insertion order in equal cases
std::stable_sort(images.begin(), images.end());
sorted_images = true;
}
BOOST_FOREACH(const rule_image_rand& ri, images){
bool is_background = ri->is_background();
bool animate = (!ri.ri->is_water || preferences::animate_water());
imagelist& img_list = is_background ? images_background : images_foreground;
BOOST_FOREACH(const rule_image_variant& variant, ri->variants){
if(!variant.has_flag.empty()) {
bool has_flag_match = true;
BOOST_FOREACH(const std::string& s, variant.has_flag) {
// If a flag listed in "has_flag" is not present, this variant does not match
if(flags.find(s) == flags.end()) {
has_flag_match = false;
break;
}
}
if(!has_flag_match) {
continue;
}
}
if(!variant.tods.empty() && variant.tods.find(tod) == variant.tods.end())
continue;
//need to break parity pattern in RNG
/** @todo improve this */
unsigned int rnd = ri.rand / 7919; //just the 1000th prime
const animated<image::locator>& anim = variant.images[rnd % variant.images.size()];
bool is_empty = true;
for(size_t i = 0; i < anim.get_frames_count(); ++i) {
if(!image::is_empty_hex(anim.get_frame(i))) {
is_empty = false;
break;
}
}
if(is_empty)
continue;
img_list.push_back(anim);
if(variant.random_start)
img_list.back().set_animation_time(ri.rand % img_list.back().get_animation_duration());
if (!animate) {
img_list.back().pause_animation();
}
if(log) {
log->push_back(std::make_pair(&ri, &variant));
}
break; // found a matching variant
}
}
}
void terrain_builder::tile::clear()
{
flags.clear();
images.clear();
sorted_images = false;
images_foreground.clear();
images_background.clear();
last_tod = "invalid_tod";
}
static unsigned int get_noise(const map_location& loc, unsigned int index){
unsigned int a = (loc.x + 92872973) ^ 918273;
unsigned int b = (loc.y + 1672517) ^ 128123;
unsigned int c = (index + 127390) ^ 13923787;
unsigned int abc = a*b*c + a*b + b*c + a*c + a + b + c;
return abc*abc;
}
void terrain_builder::tilemap::reset()
{
for(std::vector<tile>::iterator it = tiles_.begin(); it != tiles_.end(); ++it)
it->clear();
}
void terrain_builder::tilemap::reload(int x, int y)
{
x_ = x;
y_ = y;
std::vector<terrain_builder::tile> new_tiles((x + 4) * (y + 4));
tiles_.swap(new_tiles);
reset();
}
bool terrain_builder::tilemap::on_map(const map_location &loc) const
{
if(loc.x < -2 || loc.y < -2 || loc.x > (x_ + 1) || loc.y > (y_ + 1)) {
return false;
}
return true;
}
terrain_builder::tile& terrain_builder::tilemap::operator[](const map_location &loc)
{
assert(on_map(loc));
return tiles_[(loc.x + 2) + (loc.y + 2) * (x_ + 4)];
}
const terrain_builder::tile& terrain_builder::tilemap::operator[] (const map_location &loc) const
{
assert(on_map(loc));
return tiles_[(loc.x + 2) + (loc.y + 2) * (x_ + 4)];
}
terrain_builder::terrain_builder(const config& level,
const gamemap* m, const std::string& offmap_image) :
tilewidth_(game_config::tile_size),
map_(m),
tile_map_(m ? map().w() : 0, m ? map().h() :0),
terrain_by_type_()
{
image::precache_file_existence("terrain/");
if(building_rules_.empty() && rules_cfg_){
//off_map first to prevent some default rule seems to block it
add_off_map_rule(offmap_image);
// parse global terrain rules
parse_global_config(*rules_cfg_);
} else {
// use cached global rules but clear local rules
flush_local_rules();
}
// parse local rules
parse_config(level);
if (m)
build_terrains();
}
void terrain_builder::rebuild_cache_all()
{
for(int x = -2; x <= map().w(); ++x) {
for(int y = -2; y <= map().h(); ++y) {
tile_map_[map_location(x,y)].rebuild_cache("");
}
}
}
void terrain_builder::flush_local_rules()
{
building_ruleset::iterator i = building_rules_.begin();
for(; i != building_rules_.end();){
if (i->local)
building_rules_.erase(i++);
else
++i;
}
}
void terrain_builder::set_terrain_rules_cfg(const config& cfg)
{
rules_cfg_ = &cfg;
// use the swap trick to clear the rules cache and get a fresh one.
// because simple clear() seems to cause some progressive memory degradation.
building_ruleset empty;
std::swap(building_rules_, empty);
}
void terrain_builder::reload_map()
{
tile_map_.reload(map().w(), map().h());
terrain_by_type_.clear();
build_terrains();
}
void terrain_builder::change_map(const gamemap* m)
{
map_ = m;
reload_map();
}
const terrain_builder::imagelist *terrain_builder::get_terrain_at(const map_location &loc,
const std::string &tod, const TERRAIN_TYPE terrain_type)
{
if(!tile_map_.on_map(loc))
return NULL;
tile& tile_at = tile_map_[loc];
if(tod != tile_at.last_tod) {
tile_at.rebuild_cache(tod);
tile_at.last_tod = tod;
}
const imagelist& img_list = (terrain_type == BACKGROUND) ?
tile_at.images_background : tile_at.images_foreground;
if(!img_list.empty()) {
return &img_list;
}
return NULL;
}
bool terrain_builder::update_animation(const map_location &loc)
{
if(!tile_map_.on_map(loc))
return false;
bool changed = false;
tile& btile = tile_map_[loc];
BOOST_FOREACH(animated<image::locator>& a, btile.images_background) {
if(a.need_update())
changed = true;
a.update_last_draw_time();
}
BOOST_FOREACH(animated<image::locator>& a, btile.images_foreground) {
if(a.need_update())
changed = true;
a.update_last_draw_time();
}
return changed;
}
/** @todo TODO: rename this function */
void terrain_builder::rebuild_terrain(const map_location &loc)
{
if (tile_map_.on_map(loc)) {
tile& btile = tile_map_[loc];
// btile.images.clear();
btile.images_foreground.clear();
btile.images_background.clear();
const std::string filename =
map().get_terrain_info(loc).minimap_image();
if(!filename.empty()) {
animated<image::locator> img_loc;
img_loc.add_frame(100,image::locator("terrain/" + filename + ".png"));
img_loc.start_animation(0, true);
btile.images_background.push_back(img_loc);
}
//Combine base and overlay image if necessary
if(map().get_terrain_info(loc).is_combined()) {
const std::string filename_ovl =
map().get_terrain_info(loc).minimap_image_overlay();
if(!filename_ovl.empty()) {
animated<image::locator> img_loc_ovl;
img_loc_ovl.add_frame(100,image::locator("terrain/" + filename_ovl + ".png"));
img_loc_ovl.start_animation(0, true);
btile.images_background.push_back(img_loc_ovl);
}
}
}
}
void terrain_builder::rebuild_all()
{
tile_map_.reset();
terrain_by_type_.clear();
build_terrains();
}
static bool image_exists(const std::string& name)
{
bool precached = name.find("..") == std::string::npos;
if(precached && image::precached_file_exists(name)) {
return true;
} else if(image::exists(name)) {
return true;
}
return false;
}
static std::vector<std::string> get_variations(const std::string& base, const std::string& variations)
{
/** @todo optimize this function */
std::vector<std::string> res;
if(variations.empty()){
res.push_back(base);
return res;
}
std::string::size_type pos = base.find("@V", 0);
if(pos == std::string::npos) {
res.push_back(base);
return res;
}
std::vector<std::string> vars = utils::split(variations, ';', 0);
BOOST_FOREACH(const std::string& v, vars){
res.push_back(base);
std::string::size_type pos = 0;
while ((pos = res.back().find("@V", pos)) != std::string::npos) {
res.back().replace(pos, 2, v);
pos += v.size();
}
}
return res;
}
bool terrain_builder::load_images(building_rule &rule)
{
// If the rule has no constraints, it is invalid
if(rule.constraints.empty())
return false;
// Parse images and animations data
// If one is not valid, return false.
BOOST_FOREACH(terrain_constraint &constraint, rule.constraints)
{
BOOST_FOREACH(rule_image& ri, constraint.images)
{
BOOST_FOREACH(rule_image_variant& variant, ri.variants)
{
std::vector<std::string> var_strings = get_variations(variant.image_string, variant.variations);
BOOST_FOREACH(const std::string& var, var_strings)
{
/** @todo improve this, 99% of terrains are not animated. */
std::vector<std::string> frames = utils::square_parenthetical_split(var,',');
animated<image::locator> res;
BOOST_FOREACH(const std::string& frame, frames)
{
const std::vector<std::string> items = utils::split(frame, ':');
const std::string& str = items.front();
const size_t tilde = str.find('~');
bool has_tilde = tilde != std::string::npos;
const std::string filename = "terrain/" + (has_tilde ? str.substr(0,tilde) : str);
if(!image_exists(filename)){
continue; // ignore missing frames
}
const std::string modif = (has_tilde ? str.substr(tilde+1) : "");
int time = 100;
if(items.size() > 1) {
time = atoi(items.back().c_str());
}
image::locator locator;
if(ri.global_image) {
locator = image::locator(filename, constraint.loc, ri.center_x, ri.center_y, modif);
} else {
locator = image::locator(filename, modif);
}
res.add_frame(time, locator);
}
if(res.get_frames_count() == 0)
break; // no valid images, don't register it
res.start_animation(0, true);
variant.images.push_back(res);
}
if(variant.images.empty())
return false; //no valid images, rule is invalid
}
}
}
return true;
}
void terrain_builder::rotate(terrain_constraint &ret, int angle)
{
static const struct { int ii; int ij; int ji; int jj; } rotations[6] =
{ { 1, 0, 0, 1 }, { 1, 1, -1, 0 }, { 0, 1, -1, -1 },
{ -1, 0, 0, -1 }, { -1, -1, 1, 0 }, { 0, -1, 1, 1 } };
// The following array of matrices is intended to rotate the (x,y)
// coordinates of a point in a wesnoth hex (and wesnoth hexes are not
// regular hexes :) ).
// The base matrix for a 1-step rotation with the wesnoth tile shape
// is:
//
// r = s^-1 * t * s
//
// with s = [[ 1 0 ]
// [ 0 -sqrt(3)/2 ]]
//
// and t = [[ -1/2 sqrt(3)/2 ]
// [ -sqrt(3)/2 1/2 ]]
//
// With t being the rotation matrix (pi/3 rotation), and s a matrix
// that transforms the coordinates of the wesnoth hex to make them
// those of a regular hex.
//
// (demonstration left as an exercise for the reader)
//
// So we have
//
// r = [[ 1/2 -3/4 ]
// [ 1 1/2 ]]
//
// And the following array contains I(2), r, r^2, r^3, r^4, r^5
// (with r^3 == -I(2)), which are the successive rotations.
static const struct {
double xx;
double xy;
double yx;
double yy;
} xyrotations[6] = {
{ 1., 0., 0., 1. },
{ 1./2. , -3./4., 1., 1./2. },
{ -1./2., -3./4., 1, -1./2.},
{ -1. , 0., 0., -1. },
{ -1./2., 3./4., -1., -1./2.},
{ 1./2. , 3./4., -1., 1./2. },
};
assert(angle >= 0);
angle %= 6;
// Vector i is going from n to s, vector j is going from ne to sw.
int vi = ret.loc.y - ret.loc.x/2;
int vj = ret.loc.x;
int ri = rotations[angle].ii * vi + rotations[angle].ij * vj;
int rj = rotations[angle].ji * vi + rotations[angle].jj * vj;
ret.loc.x = rj;
ret.loc.y = ri + (rj >= 0 ? rj/2 : (rj-1)/2);
for (rule_imagelist::iterator itor = ret.images.begin();
itor != ret.images.end(); ++itor) {
double vx, vy, rx, ry;
vx = double(itor->basex) - double(tilewidth_)/2;
vy = double(itor->basey) - double(tilewidth_)/2;
rx = xyrotations[angle].xx * vx + xyrotations[angle].xy * vy;
ry = xyrotations[angle].yx * vx + xyrotations[angle].yy * vy;
itor->basex = int(rx + tilewidth_/2);
itor->basey = int(ry + tilewidth_/2);
//std::cerr << "Rotation: from " << vx << ", " << vy << " to " << itor->basex <<
// ", " << itor->basey << "\n";
}
}
void terrain_builder::replace_rotate_tokens(std::string &s, int angle,
const std::vector<std::string> &replacement)
{
std::string::size_type pos = 0;
while ((pos = s.find("@R", pos)) != std::string::npos) {
if (pos + 2 >= s.size()) return;
unsigned i = s[pos + 2] - '0' + angle;
if (i >= 6) i -= 6;
if (i >= 6) { pos += 2; continue; }
const std::string &r = replacement[i];
s.replace(pos, 3, r);
pos += r.size();
}
}
void terrain_builder::replace_rotate_tokens(rule_image &image, int angle,
const std::vector<std::string> &replacement)
{
BOOST_FOREACH(rule_image_variant& variant, image.variants) {
replace_rotate_tokens(variant, angle, replacement);
}
}
void terrain_builder::replace_rotate_tokens(rule_imagelist &list, int angle,
const std::vector<std::string> &replacement)
{
BOOST_FOREACH(rule_image &img, list) {
replace_rotate_tokens(img, angle, replacement);
}
}
void terrain_builder::replace_rotate_tokens(building_rule &rule, int angle,
const std::vector<std::string> &replacement)
{
BOOST_FOREACH(terrain_constraint &cons, rule.constraints)
{
// Transforms attributes
BOOST_FOREACH(std::string &flag, cons.set_flag) {
replace_rotate_tokens(flag, angle, replacement);
}
BOOST_FOREACH(std::string &flag, cons.no_flag) {
replace_rotate_tokens(flag, angle, replacement);
}
BOOST_FOREACH(std::string &flag, cons.has_flag) {
replace_rotate_tokens(flag, angle, replacement);
}
replace_rotate_tokens(cons.images, angle, replacement);
}
//replace_rotate_tokens(rule.images, angle, replacement);
}
void terrain_builder::rotate_rule(building_rule &ret, int angle,
const std::vector<std::string> &rot)
{
if (rot.size() != 6) {
ERR_NG << "invalid rotations" << std::endl;
return;
}
BOOST_FOREACH(terrain_constraint &cons, ret.constraints) {
rotate(cons, angle);
}
// Normalize the rotation, so that it starts on a positive location
int minx = INT_MAX;
int miny = INT_MAX;
BOOST_FOREACH(const terrain_constraint &cons, ret.constraints) {
minx = std::min<int>(cons.loc.x, minx);
miny = std::min<int>(2 * cons.loc.y + (cons.loc.x & 1), miny);
}
if((miny & 1) && (minx & 1) && (minx < 0))
miny += 2;
if(!(miny & 1) && (minx & 1) && (minx > 0))
miny -= 2;
BOOST_FOREACH(terrain_constraint &cons, ret.constraints) {
legacy_sum_assign(cons.loc,map_location(-minx, -((miny - 1) / 2)));
}
replace_rotate_tokens(ret, angle, rot);
}
terrain_builder::rule_image_variant::rule_image_variant(const std::string &image_string, const std::string& variations, const std::string& tod, const std::string& has_flag, bool random_start) :
image_string(image_string),
variations(variations),
images(),
tods(),
has_flag(),
random_start(random_start)
{
if(!has_flag.empty()) {
this->has_flag = utils::split(has_flag);
}
if(!tod.empty()) {
const std::vector<std::string> tod_list = utils::split(tod);
tods.insert(tod_list.begin(), tod_list.end());
}
}
void terrain_builder::add_images_from_config(rule_imagelist& images, const config &cfg, bool global, int dx, int dy)
{
BOOST_FOREACH(const config &img, cfg.child_range("image"))
{
int layer = img["layer"];
int basex = tilewidth_ / 2 + dx, basey = tilewidth_ / 2 + dy;
if (const config::attribute_value *base_ = img.get("base")) {
std::vector<std::string> base = utils::split(*base_);
if(base.size() >= 2) {
basex = atoi(base[0].c_str());
basey = atoi(base[1].c_str());
}
}
int center_x = -1, center_y = -1;
if (const config::attribute_value *center_ = img.get("center")) {
std::vector<std::string> center = utils::split(*center_);
if(center.size() >= 2) {
center_x = atoi(center[0].c_str());
center_y = atoi(center[1].c_str());
}
}
bool is_water = img["is_water"].to_bool();
images.push_back(rule_image(layer, basex - dx, basey - dy, global, center_x, center_y, is_water));
// Adds the other variants of the image
BOOST_FOREACH(const config &variant, img.child_range("variant"))
{
const std::string &name = variant["name"];
const std::string &variations = img["variations"];
const std::string &tod = variant["tod"];
const std::string &has_flag = variant["has_flag"];
bool random_start = variant["random_start"].to_bool(true);
images.back().variants.push_back(rule_image_variant(name, variations, tod, has_flag, random_start));
}
// Adds the main (default) variant of the image at the end,
// (will be used only if previous variants don't match)
const std::string &name = img["name"];
const std::string &variations = img["variations"];
bool random_start = img["random_start"].to_bool(true);
images.back().variants.push_back(rule_image_variant(name, variations, random_start));
}
}
terrain_builder::terrain_constraint &terrain_builder::add_constraints(
terrain_builder::constraint_set& constraints,
const map_location& loc,
const t_translation::t_match& type, const config& global_images)
{
terrain_constraint *cons = NULL;
BOOST_FOREACH(terrain_constraint &c, constraints) {
if (c.loc == loc) {
cons = &c;
break;
}
}
if (!cons) {
// The terrain at the current location did not exist, so create it
constraints.push_back(terrain_constraint(loc));
cons = &constraints.back();
}
if(!type.terrain.empty()) {
cons->terrain_types_match = type;
}
int x = loc.x * tilewidth_ * 3 / 4;
int y = loc.y * tilewidth_ + (loc.x % 2) * tilewidth_ / 2;
add_images_from_config(cons->images, global_images, true, x, y);
return *cons;
}
void terrain_builder::add_constraints(terrain_builder::constraint_set &constraints,
const map_location& loc, const config& cfg, const config& global_images)
{
terrain_constraint& constraint = add_constraints(constraints, loc,
t_translation::t_match(cfg["type"], t_translation::WILDCARD), global_images);
std::vector<std::string> item_string = utils::square_parenthetical_split(cfg["set_flag"],',',"[","]");
constraint.set_flag.insert(constraint.set_flag.end(),
item_string.begin(), item_string.end());
item_string = utils::square_parenthetical_split(cfg["has_flag"],',',"[","]");
constraint.has_flag.insert(constraint.has_flag.end(),
item_string.begin(), item_string.end());
item_string = utils::square_parenthetical_split(cfg["no_flag"],',',"[","]");
constraint.no_flag.insert(constraint.no_flag.end(),
item_string.begin(), item_string.end());
item_string = utils::square_parenthetical_split(cfg["set_no_flag"],',',"[","]");
constraint.set_flag.insert(constraint.set_flag.end(),
item_string.begin(), item_string.end());
constraint.no_flag.insert(constraint.no_flag.end(),
item_string.begin(), item_string.end());
add_images_from_config(constraint.images, cfg, false);
}
void terrain_builder::parse_mapstring(const std::string &mapstring,
struct building_rule &br, anchormap& anchors,
const config& global_images)
{
const t_translation::t_map map = t_translation::read_builder_map(mapstring);
// If there is an empty map leave directly.
// Determine after conversion, since a
// non-empty string can return an empty map.
if(map.empty()) {
return;
}
int lineno = (map[0][0] == t_translation::NONE_TERRAIN) ? 1 : 0;
int x = lineno;
int y = 0;
for(size_t y_off = 0; y_off < map.size(); ++y_off) {
for(size_t x_off = x; x_off < map[y_off].size(); ++x_off) {
const t_translation::t_terrain terrain = map[y_off][x_off];
if(terrain.base == t_translation::TB_DOT) {
// Dots are simple placeholders,
// which do not represent actual terrains.
} else if (terrain.overlay != 0 ) {
anchors.insert(std::pair<int, map_location>(terrain.overlay, map_location(x, y)));
} else if (terrain.base == t_translation::TB_STAR) {
add_constraints(br.constraints, map_location(x, y), t_translation::STAR, global_images);
} else {
ERR_NG << "Invalid terrain (" << t_translation::write_terrain_code(terrain) << ") in builder map" << std::endl;
assert(false);
return;
}
x += 2;
}
if(lineno % 2 == 1) {
++y;
x = 0;
} else {
x = 1;
}
++lineno;
}
}
void terrain_builder::add_rule(building_ruleset &rules, building_rule &rule)
{
if(load_images(rule)) {
rules.insert(rule);
}
}
void terrain_builder::add_rotated_rules(building_ruleset &rules, building_rule &tpl,
const std::string &rotations)
{
if(rotations.empty()) {
// Adds the parsed built terrain to the list
add_rule(rules, tpl);
} else {
const std::vector<std::string>& rot = utils::split(rotations, ',');
for(size_t angle = 0; angle < rot.size(); ++angle) {
/* Only 5% of the rules have valid images, so most of
them will be discarded. If the ratio was higher,
it would be more efficient to insert a copy of the
template rule into the ruleset, modify it in place,
and remove it if invalid. But since the ratio is so
low, the speedup is not worth the extra multiset
manipulations. */
building_rule rule = tpl;
rotate_rule(rule, angle, rot);
add_rule(rules, rule);
}
}
}
void terrain_builder::parse_config(const config &cfg, bool local)
{
log_scope("terrain_builder::parse_config");
// Parses the list of building rules (BRs)
BOOST_FOREACH(const config &br, cfg.child_range("terrain_graphics"))
{
building_rule pbr; // Parsed Building rule
pbr.local = local;
// add_images_from_config(pbr.images, **br);
pbr.location_constraints =
map_location(br["x"].to_int() - 1, br["y"].to_int() - 1);
pbr.modulo_constraints =
map_location(br["mod_x"].to_int(), br["mod_y"].to_int());
pbr.probability = br["probability"].to_int(100);
// Mapping anchor indices to anchor locations.
anchormap anchors;
// Parse the map= , if there is one (and fill the anchors list)
parse_mapstring(br["map"], pbr, anchors, br);
// Parses the terrain constraints (TCs)
BOOST_FOREACH(const config &tc, br.child_range("tile"))
{
// Adds the terrain constraint to the current built terrain's list
// of terrain constraints, if it does not exist.
map_location loc;
if (const config::attribute_value *v = tc.get("x")) {
loc.x = *v;
}
if (const config::attribute_value *v = tc.get("y")) {
loc.y = *v;
}
if(loc.valid()) {
add_constraints(pbr.constraints, loc, tc, br);
}
if (const config::attribute_value *v = tc.get("pos")) {
int pos = *v;
if(anchors.find(pos) == anchors.end()) {
WRN_NG << "Invalid anchor!" << std::endl;
continue;
}
std::pair<anchormap::const_iterator, anchormap::const_iterator> range =
anchors.equal_range(pos);
for(; range.first != range.second; ++range.first) {
loc = range.first->second;
add_constraints(pbr.constraints, loc, tc, br);
}
}
}
const std::vector<std::string> global_set_flag = utils::split(br["set_flag"]);
const std::vector<std::string> global_no_flag = utils::split(br["no_flag"]);
const std::vector<std::string> global_has_flag = utils::split(br["has_flag"]);
const std::vector<std::string> global_set_no_flag = utils::split(br["set_no_flag"]);
BOOST_FOREACH(terrain_constraint &constraint, pbr.constraints)
{
constraint.set_flag.insert(constraint.set_flag.end(),
global_set_flag.begin(), global_set_flag.end());
constraint.no_flag.insert(constraint.no_flag.end(),
global_no_flag.begin(), global_no_flag.end());
constraint.has_flag.insert(constraint.has_flag.end(),
global_has_flag.begin(), global_has_flag.end());
constraint.set_flag.insert(constraint.set_flag.end(),
global_set_no_flag.begin(), global_set_no_flag.end());
constraint.no_flag.insert(constraint.no_flag.end(),
global_set_no_flag.begin(), global_set_no_flag.end());
}
// Handles rotations
const std::string &rotations = br["rotations"];
pbr.precedence = br["precedence"];
add_rotated_rules(building_rules_, pbr, rotations);
loadscreen::increment_progress();
}
// Debug output for the terrain rules
#if 0
std::cerr << "Built terrain rules: \n";
building_ruleset::const_iterator rule;
for(rule = building_rules_.begin(); rule != building_rules_.end(); ++rule) {
std::cerr << ">> New rule: image_background = "
<< "\n>> Location " << rule->second.location_constraints
<< "\n>> Probability " << rule->second.probability
for(constraint_set::const_iterator constraint = rule->second.constraints.begin();
constraint != rule->second.constraints.end(); ++constraint) {
std::cerr << ">>>> New constraint: location = (" << constraint->second.loc
<< "), terrain types = '" << t_translation::write_list(constraint->second.terrain_types_match.terrain) << "'\n";
std::vector<std::string>::const_iterator flag;
for(flag = constraint->second.set_flag.begin(); flag != constraint->second.set_flag.end(); ++flag) {
std::cerr << ">>>>>> Set_flag: " << *flag << "\n";
}
for(flag = constraint->second.no_flag.begin(); flag != constraint->second.no_flag.end(); ++flag) {
std::cerr << ">>>>>> No_flag: " << *flag << "\n";
}
}
}
#endif
}
void terrain_builder::add_off_map_rule(const std::string& image)
{
// Build a config object
config cfg;
config &item = cfg.add_child("terrain_graphics");
config &tile = item.add_child("tile");
tile["x"] = 0;
tile["y"] = 0;
tile["type"] = t_translation::write_terrain_code(t_translation::OFF_MAP_USER);
config &tile_image = tile.add_child("image");
tile_image["layer"] = -1000;
tile_image["name"] = image;