]> mj.ucw.cz Git - leo.git/blob - labeller.c
61dd53ecbd5913758d9f1b81ed30a8cac1c37530
[leo.git] / labeller.c
1 #include <ucw/lib.h>
2 #include <ucw/conf.h>
3 #include <ucw/gary.h>
4 #include <ucw/mempool.h>
5 #include <ucw/eltpool.h>
6
7 #include "leo.h"
8 #include "sym.h"
9 #include "map.h"
10 #include "labeller.h"
11
12 #define HASH_NODE struct graph_node
13 #define HASH_PREFIX(x) hash_##x
14 #define HASH_KEY_ATOMIC id
15 #define HASH_WANT_FIND
16 #define HASH_WANT_NEW
17 #define HASH_WANT_CLEANUP
18 #include <ucw/hashtable.h>
19
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <math.h>
23 #include <fcntl.h>
24 #include <limits.h>
25
26 #define BLOCK_SIZE 4096
27
28 #define DEBUG(dbg_sec, dbg_lvl, msg, ...) if (dbg_sec >= dbg_lvl) printf(msg, ##__VA_ARGS__)
29
30 static struct request_point *requests_point;
31 static struct request_line *requests_line;
32 static struct request_area *requests_area;
33
34 static struct graph_edge **bfs_queue;
35 static struct longline *longlines;
36 static struct buffer_line *buffer_line;
37 static struct buffer_linelabel *buffer_linelabel;
38
39 struct eltpool *ep_individuals;
40
41 struct individual **population1;
42 struct individual **population2;
43
44 int dbg_segments = VERBOSITY_NONE;
45 int dbg_plan = VERBOSITY_NONE;
46 int dbg_requests = VERBOSITY_NONE;
47 int dbg_graph = VERBOSITY_NONE;
48 int dbg_bfs = VERBOSITY_NONE;
49 int dbg_map_parts = VERBOSITY_NONE;
50 int dbg_movement = VERBOSITY_NONE;
51 int dbg_init = VERBOSITY_NONE;
52 int dbg_overlaps = VERBOSITY_GENERAL;
53 int dbg_rank = VERBOSITY_NONE;
54 int dbg_evolution = VERBOSITY_POPULATION;
55 int dbg_mutation = VERBOSITY_NONE;
56 int dbg_breeding = VERBOSITY_NONE;
57
58 int page_width_int;
59 int page_height_int;
60
61 int num_nodes;
62 int num_edges = 0;
63 int dbg_num_hits = 0;
64
65 int breed_pop_size;
66 int breed_rbest_size;
67
68 int mutate_pop_size;
69 int mutate_rbest_size;
70
71 int elite_pop_size;
72
73
74 int old_best = INT_MAX;
75 int iteration = 0;
76 int pop2_ind;
77
78 // In milimeters
79 int move_min = 0;
80 int move_max = 5;
81
82 int num_requests = 0;
83 int num_placements = 0;
84
85 // In milimeters
86 int conf_map_part_width = 5;
87 int conf_map_part_height = 5;
88
89 uns num_map_parts_row;
90 uns num_map_parts_col;
91 uns num_map_parts;
92
93 int conf_pop_size = 200, conf_fit_size = 1, conf_term_cond = TERM_COND_ITERATIONS;
94
95 double conf_penalty_bound = 100, conf_stagnation_bound = 10;
96 int conf_iteration_limit = 200;
97
98 double conf_breed_pop_size = 0.45, conf_breed_rbest = 1,
99        conf_mutate_children, conf_mutate_children_prob = 0.6,
100        conf_mutate_pop_size = 0.45, conf_mutate_rbest = 1,
101        conf_mutate_move_bound = 0.1, conf_mutate_regen_bound = 0.05, conf_mutate_chvar_bound = 0.1,
102        conf_elite_pop_size = 0.1;
103
104 double conf_max_section_length = 80, conf_max_section_overlay = 10;
105
106 static struct cf_section evolution_cf = {
107   CF_ITEMS {
108     CF_INT("PopSize", &conf_pop_size),
109     CF_INT("FitSize", &conf_fit_size),
110     CF_INT("TermCond", &conf_term_cond),
111     CF_DOUBLE("PenaltyBound", &conf_penalty_bound),
112     CF_DOUBLE("StagnationBound", &conf_stagnation_bound),
113     CF_INT("IterationLimit", &conf_iteration_limit),
114     CF_DOUBLE("BreedPopSize", &conf_breed_pop_size),
115     CF_DOUBLE("BreedNumBest", &conf_breed_rbest),
116     CF_DOUBLE("MutateChild", &conf_mutate_children_prob),
117     CF_DOUBLE("MutatePopSize", &conf_mutate_pop_size),
118     CF_DOUBLE("MutateNumBest", &conf_mutate_rbest),
119     CF_DOUBLE("MutateMoveBound", &conf_mutate_move_bound),
120     CF_DOUBLE("MutateRegenBound", &conf_mutate_regen_bound),
121     CF_DOUBLE("MutateChvarBound", &conf_mutate_chvar_bound),
122     CF_DOUBLE("ElitePopSize", &conf_elite_pop_size),
123     CF_DOUBLE("MaxSectionLenght", &conf_max_section_length),
124     CF_DOUBLE("MaxSectionOverlay", &conf_max_section_overlay),
125     CF_END
126   }
127 };
128
129 void compute_sizes(void);
130
131 void make_population(void);
132 bool shall_terminate(void);
133 void breed(void);
134 void mutate(void);
135 void elite(void);
136 void rank_population(void);
137 void plan_individual(struct individual *individual);
138
139 int overlaps(struct placement *p1, struct placement *p2);
140 int get_overlap(struct placement *p, int **planed_ptr, int iteration);
141 int individual_overlap(struct individual *individual);
142
143 double get_distance(struct placement *p);
144 double individual_distances(struct individual *individual);
145
146 double get_omittment(struct placement *p);
147 double individual_omittment(struct individual *individual);
148
149 struct individual **perform_crossover(struct individual *parent1, struct individual *parent2);
150 void perform_mutation(struct individual *individual);
151 void init_placement(struct placement *p, struct individual *individual, struct request *r);
152 void init_individual(struct individual *i);
153 void copy_individual(struct individual *src, struct individual *dest);
154 int cmp_individual(const void *a, const void *b);
155
156 void clear_individual(struct individual *individual);
157 void clear_population(struct individual **pop);
158
159 void make_bitmap(struct variant *v, struct symbol *sym);
160 void make_bitmap_icon(struct variant *v, struct sym_icon *si);
161 void make_bitmap_point(struct variant *v, struct sym_point *sp);
162 void make_bitmap_label(struct variant *v, struct sym_text *text);
163
164 double gen_movement(void);
165 double gen_movement_uniform(void);
166 void move_symbol(struct placement *p);
167 void move_symbol_point(struct placement *p);
168 void move_symbol_segment(struct placement *p);
169 void hide_segment_labels(struct individual *individual);
170
171 void gen_coords(struct placement *p);
172 void gen_coords_point(struct placement *p);
173 void gen_coords_segment(struct placement *p);
174 void gen_coords_area(struct placement *p);
175
176 struct map_part **get_map_parts(struct placement *p);
177 void update_map_parts(struct placement *p);
178 void update_map_parts_delete(struct placement *p);
179 void update_map_parts_create(struct placement *p);
180 struct placement **get_closure(struct placement *placement);
181 void copy_symbols(struct placement **closure, struct individual *parent, struct individual *child, bool **processed_ptr);
182 struct placement **get_overlapping(struct placement *p);
183 struct placement **filter(struct placement **list, bool **pred_ptr);
184
185
186 void make_graph(void);
187 void label_graph(void);
188 void bfs_wrapper(void);
189 void bfs(uns longline);
190 void bfs_edge(struct graph_edge *e, struct graph_node *node, struct graph_node *anode, enum edge_dir dir);
191 void make_segments(void);
192
193 void cut_edge(struct graph_edge *e, double dist);
194 struct request_line *make_new_line(void);
195 struct request_section *make_new_section(struct request_line *rl);
196 struct request_segment *make_new_segment(struct request_section *rls, struct symbol *sym);
197
198 void dump_bitmaps(struct individual *individual);
199 void dump_graph(void);
200 void dump_longlines(void);
201 void dump_linelabel_requests(void);
202 void dump_individual(struct individual *individual);
203 void dump_label(struct symbol *sym);
204 void dump_penalties(struct individual **population);
205 void dump_placements(struct individual *individual);
206 void dump_placement_links(struct placement *p);
207 void dump_part_links(struct map_part *part);
208 void dump_links(struct individual *individual);
209
210 int randint(int min, int max);
211 int flip(int a, int b);
212 double randdouble(void);
213
214 int max2(int a, int b);
215 int min2(int a, int b);
216 int max4(int a, int b, int c, int d);
217 int min4(int a, int b, int c, int d);
218
219 struct placement dummy_placement;
220
221 int max2(int a, int b)
222 {
223   return (a > b ? a : b);
224 }
225
226 int min2(int a, int b)
227 {
228   return (a < b ? a : b);
229 }
230
231 int max4(int a, int b, int c, int d)
232 {
233   return max2(max2(a, b), max2(c, d));
234 }
235
236 int min4(int a, int b, int c, int d)
237 {
238   return min2(min2(a, b), min2(c, d));
239 }
240
241 void dump_label(struct symbol *sym)
242 {
243   switch (sym->type)
244   {
245     case SYMBOLIZER_TEXT: ;
246       struct sym_text *st = (struct sym_text *) sym;
247       printf("%s\n", osm_val_decode(st->text));
248     default:
249       // FIXME
250       ;
251   }
252 }
253
254 void labeller_conf(void)
255 {
256   cf_declare_section("Evolution", &evolution_cf, 0);
257 }
258
259 void labeller_init(void)
260 {
261   GARY_INIT(requests_point, 0);
262   GARY_INIT(requests_line, 0);
263   GARY_INIT(requests_area, 0);
264   GARY_INIT(buffer_line, 0);
265   GARY_INIT(buffer_linelabel, 0);
266   ep_individuals = ep_new(sizeof(struct individual), 1);
267
268   compute_sizes();
269 }
270
271 void make_bitmap(struct variant *v, struct symbol *sym)
272 {
273   v->offset_x = v->offset_y = 0;
274
275   switch (sym->type)
276   {
277     case SYMBOLIZER_POINT:
278       make_bitmap_point(v, (struct sym_point *) sym);
279       break;
280     case SYMBOLIZER_ICON:
281       make_bitmap_icon(v, (struct sym_icon *) sym);
282       break;
283     case SYMBOLIZER_TEXT:
284       make_bitmap_label(v, (struct sym_text *) sym);
285       break;
286     default:
287       ASSERT(sym->type != SYMBOLIZER_INVALID);
288   }
289 }
290
291 void make_bitmap_icon(struct variant *v, struct sym_icon *si)
292 {
293   v->width = si->sir.width + 1;
294   v->height = si->sir.height + 1;
295   v->bitmap = xmalloc(v->width * v->height * sizeof(bool));
296   for (int i=0; i<v->width*v->height; i++) v->bitmap[i] = 1;
297 }
298
299 void make_bitmap_point(struct variant *v, struct sym_point *sp)
300 {
301   v->width = v->height = sp->size + 1;
302   v->bitmap = xmalloc(v->width * v->height * sizeof(bool));
303   // FIXME: Okay, memset would be much nicer here
304   for (int i=0; i<sp->size*sp->size; i++) v->bitmap[i] = 1;
305 }
306
307 void make_bitmap_label(struct variant *v, struct sym_text *text)
308 {
309   int tw = ceil(text->tw);
310   int th = ceil(text->th);
311
312   double rotate_rad = text->rotate / (-180 / M_PI);
313
314   // Initially, ll = [0; 0], lr = [tw, 0], ul = [0, th], ur = [tw, th]
315   // They could be declared before but should not be initialized in code
316   // as reassigning x-coordinate affects computation of y-cordinate
317   int llx = 0;
318   int lly = 0;
319
320   int lrx = tw * cos(rotate_rad);
321   int lry = tw * sin(rotate_rad);
322
323   int ulx = th * sin(rotate_rad);
324   int uly = th * cos(rotate_rad);
325
326   int urx = tw * cos(rotate_rad) + th * sin(rotate_rad);
327   int ury = tw * sin(rotate_rad) + th * cos(rotate_rad);
328
329   int min_x = min4(llx, lrx, ulx, urx);
330   int min_y = min4(lly, lry, uly, ury);
331   int max_x = max4(llx, lrx, ulx, urx);
332   int max_y = max4(lly, lry, uly, ury);
333
334   v->width = max_x - min_x + 1;
335   v->height = max_y - min_y + 1;
336   v->bitmap = xmalloc(v->width * v->height * sizeof(bool));
337   memset(v->bitmap, 0, v->width * v->height * sizeof(bool));
338
339   for (int i=0; i<th; i++)
340   {
341     for (int j=0; j<tw; j++)
342     {
343       int nx = j*cos(rotate_rad) + i*sin(rotate_rad);
344       int ny = j*sin(rotate_rad) + i*cos(rotate_rad);
345       v->bitmap[(ny-min_y)*v->width + (nx-min_x)] = 1;
346     }
347   }
348 }
349
350 void labeller_add_point(struct symbol *sym, struct osm_object *object, z_index_t zindex)
351 {
352   DEBUG(dbg_requests, VERBOSITY_PLACEMENT, "Adding point\n");
353   if (object->type != OSM_TYPE_NODE)
354   {
355     printf("Warning: Point label requested on non-point object\n");
356     return;
357   }
358
359   struct request_point *r = GARY_PUSH(requests_point);
360
361   r->request.type = REQUEST_POINT;
362   r->request.ind = num_requests++;
363
364   r->sym = sym;
365   r->zindex = zindex;
366
367   r->offset_x = 0;
368   r->offset_y = 0;
369
370   r->num_variants = 1;
371   GARY_INIT(r->request.variants, 0);
372
373   struct variant *v = GARY_PUSH(r->request.variants);
374
375   struct osm_node *n = (struct osm_node *) object; // FIXME: Compiler warning
376   r->x = n->x;
377   r->y = n->y;
378   make_bitmap(v, sym);
379   switch (sym->type)
380   {
381     case SYMBOLIZER_ICON:
382       // FIXME: Really?
383       r->x = ((struct sym_icon *)sym)->sir.x;
384       r->y = ((struct sym_icon *)sym)->sir.y;
385       break;
386     default:
387       // FIXME
388       return;
389   }
390
391   DEBUG(dbg_requests, VERBOSITY_PLACEMENT, "Inited point to [%.2f; %.2f] on %u\n", r->x, r->y, r->zindex);
392 }
393
394 void labeller_add_line(struct symbol *sym, z_index_t zindex)
395 {
396   DEBUG(dbg_requests, VERBOSITY_PLACEMENT, "Adding line on %u\n", zindex);
397   struct buffer_line *b = GARY_PUSH(buffer_line);
398   b->line = (struct sym_line *) sym;
399   b->zindex = zindex;
400   sym_plan(sym, zindex);
401 }
402
403 void labeller_add_linelabel(struct symbol *sym, struct osm_object *o, z_index_t zindex)
404 {
405   if (o->type != OSM_TYPE_WAY)
406   {
407     printf("Linelabel request on object which is not way\n");
408     return;
409   }
410
411   DEBUG(dbg_requests, VERBOSITY_PLACEMENT, "Labelling way %ju on %u\n", o->id, zindex);
412   struct buffer_linelabel *ll = GARY_PUSH(buffer_linelabel);
413   ll->way = (struct osm_way *) o;
414   ll->label = sym;
415   ll->zindex = zindex;
416 }
417
418 void labeller_add_arealabel(struct symbol *sym, struct osm_object *o, z_index_t zindex)
419 {
420   DEBUG(dbg_requests, VERBOSITY_PLACEMENT, "Adding area on %u\n", zindex);
421   struct request_area *r = GARY_PUSH(requests_area);
422
423   r->request.type = REQUEST_AREA;
424   r->request.ind = num_requests++;
425
426   r->o = (struct osm_multipolygon *) o;
427   r->zindex = zindex;
428   r->label = sym;
429
430   osm_obj_center(o, &(r->cx), &(r->cy));
431
432   GARY_INIT(r->request.variants, 0);
433   struct variant *v = GARY_PUSH(r->request.variants);
434   make_bitmap(v, sym);
435 }
436
437 void make_graph(void)
438 {
439   hash_init();
440   struct mempool *mp_edges = mp_new(BLOCK_SIZE);
441
442   DEBUG(dbg_graph, VERBOSITY_GENERAL, "Extracting nodes, will iterate over %zu ways\n", GARY_SIZE(buffer_line));
443   for (uns i=0; i<GARY_SIZE(buffer_line); i++)
444   {
445     struct osm_way *way = (struct osm_way *) buffer_line[i].line->s.o;
446     struct graph_node *g_prev = NULL;
447     struct osm_node *o_prev = NULL;
448
449     CLIST_FOR_EACH(struct osm_ref *, ref, way->nodes)
450     {
451       // FIXME: Shall osm_object's type be checked here?
452       struct osm_node *o_node = (struct osm_node *) ref->o;
453
454       struct graph_node *g_node = hash_find(ref->o->id);
455       if (!g_node)
456       {
457         g_node = hash_new(ref->o->id);
458         GARY_INIT(g_node->edges, 0);
459         g_node->o = o_node;
460         g_node->id = ref->o->id;
461         g_node->num = num_nodes++;
462       }
463
464       if (! g_prev)
465       {
466         g_prev = g_node;
467         o_prev = o_node;
468         continue;
469       }
470
471       struct graph_edge *e = mp_alloc(mp_edges, sizeof(struct graph_edge));
472       e->num = num_edges++;
473       e->id = buffer_line[i].line->s.o->id;
474       e->color = buffer_line[i].line->color;
475       e->length = hypot(abs(o_prev->x - o_node->x), abs(o_prev->y - o_node->y));
476       e->visited = -1;
477       e->prev = NULL;
478       e->next = NULL;
479       e->n1 = g_prev;
480       e->n2 = g_node;
481       e->longline = (uns) -1;
482       e->line = buffer_line[i].line;
483       e->dir = DIR_UNSET;
484       e->label = NULL;
485
486       struct graph_edge **edge = GARY_PUSH(g_prev->edges);
487       *edge = e;
488       edge = GARY_PUSH(g_node->edges);
489       *edge = e;
490
491       g_prev = g_node;
492       o_prev = o_node;
493     }
494   }
495 }
496
497 void dump_graph(void)
498 {
499   HASH_FOR_ALL(hash, node)
500   {
501     printf("* Node: (%d) #%ju [%.2f; %.2f]\n", node->num, node->id, node->o->x, node->o->y);
502     for (uns i=0; i<GARY_SIZE(node->edges); i++)
503     {
504       struct graph_edge *e = node->edges[i];
505       printf("\t edge (%d) #%ju to ", e->num, e->id);
506       if (node->edges[i]->n1->id == node->id)
507         printf("(%d) #%ju [%.2f; %.2f]\n", e->n2->num, e->n2->id, e->n2->o->x, e->n2->o->y);
508       else if (node->edges[i]->n2->id == node->id)
509         printf("(%d) #%ju [%.2f; %.2f]\n", e->n1->num, e->n1->id, e->n1->o->x, e->n1->o->y);
510       else
511       {
512         // This shouldn't ever happen
513         printf("BEWARE! Edge is associated with a node it doesn't belongs to!\n");
514       }
515
516       printf("\t\t");
517
518       if ((node->edges[i]->label) && (node->edges[i]->label->type == SYMBOLIZER_TEXT)) printf(" labelled %s;", osm_val_decode(((struct sym_text *) node->edges[i]->label)->text));
519       else if ((node->edges[i]->label)) printf("Labelled\n");
520
521       printf(" colored %d;", node->edges[i]->color);
522       printf("   length %.2f", node->edges[i]->length);
523       printf("\n");
524     }
525   }
526   HASH_END_FOR;
527 }
528
529 void label_graph(void)
530 {
531   DEBUG(dbg_graph, VERBOSITY_GENERAL, "There are %zu line labels requested\n", GARY_SIZE(buffer_linelabel));
532   for (uns i=0; i<GARY_SIZE(buffer_linelabel); i++)
533   {
534     if (buffer_linelabel[i].label->type == SYMBOLIZER_TEXT)
535     DEBUG(dbg_graph, VERBOSITY_INDIVIDUAL, "Labelling nodes of way %s\n", osm_val_decode(((struct sym_text *) buffer_linelabel[i].label)->text));
536     CLIST_FOR_EACH(struct osm_ref *, ref, buffer_linelabel[i].way->nodes)
537     {
538       DEBUG(dbg_graph, VERBOSITY_PLACEMENT, "Looking for node %ju\n", ref->o->id);
539       struct graph_node *n = hash_find(ref->o->id);
540       if (n == NULL)
541       {
542         printf("BEWARE! Requested node couldn't be found.\n");
543       }
544       else
545       {
546         DEBUG(dbg_graph, VERBOSITY_ALL, "Searching among %zu edges\n", GARY_SIZE(n->edges));
547         for (uns j=0; j<GARY_SIZE(n->edges); j++)
548         {
549           if (n->edges[j]->id == buffer_linelabel[i].way->o.id)
550           {
551             DEBUG(dbg_graph, VERBOSITY_ALL, "Labelling node %ju\n", n->id);
552             n->edges[j]->label = buffer_linelabel[i].label;
553             n->edges[j]->zindex = buffer_linelabel[i].zindex;
554           }
555         }
556       }
557     }
558   }
559 }
560
561 void bfs_edge(struct graph_edge *e, struct graph_node *node, struct graph_node *anode, enum edge_dir dir)
562 {
563   DEBUG(dbg_bfs, VERBOSITY_PLACEMENT, "BFS edge called for edge %d (going %d) in direction %d\n", e->num, e->dir, dir);
564   struct graph_edge *candidate = NULL;
565
566   for (uns i=0; i<GARY_SIZE(node->edges); i++)
567   {
568     struct graph_edge *other = node->edges[i];
569     if ((other->longline != (uns) -1) && (other->longline != e->longline)) continue;
570
571     if ((uns) other->visited != e->longline) {
572     DEBUG(dbg_bfs, VERBOSITY_PLACEMENT, "Pushing new edge %d / %ju\n", other->num, other->id);
573     struct graph_edge **e_ptr = GARY_PUSH(bfs_queue);
574     *e_ptr = other;
575     other->visited = e->longline;
576     }
577
578     if (((other->n1->id == node->id) && (other->n2->id == anode->id)) ||
579         ((other->n2->id == node->id) && (other->n1->id == anode->id)))
580         continue;
581
582     if (((other->n1->id == node->id) || (other->n2->id == node->id)) &&
583         (e->label) && (other->label) &&
584         (e->label->type == SYMBOLIZER_TEXT) && (other->label->type == SYMBOLIZER_TEXT) &&
585         (((struct sym_text *) e->label)->text == ((struct sym_text *) other->label)->text))
586     {
587       if (! candidate || (other->length > candidate->length))
588       candidate = other;
589     }
590   }
591
592   if (candidate)
593   {
594     DEBUG(dbg_bfs, VERBOSITY_PLACEMENT, "New line in longline %u\n", e->longline);
595     struct graph_edge *other = candidate;
596       other->longline = e->longline;
597       other->dir = dir;
598       if (((dir == DIR_BWD) && (other->n1->id == node->id)) ||
599           ((dir == DIR_FWD) && (other->n2->id == node->id)))
600       {
601         struct graph_node *swp = other->n2;
602         other->n2 = other->n1;
603         other->n1 = swp;
604       }
605
606       switch (dir)
607       {
608         case DIR_BWD:
609           e->prev = other;
610           other->next = e;
611           longlines[other->longline].first = other;
612           break;
613         case DIR_FWD:
614           e->next = other;
615           other->prev = e;
616           break;
617         default:
618           printf("Oops\n");
619           ASSERT(0);
620       }
621   }
622 }
623
624 void bfs(uns longline)
625 {
626   DEBUG(dbg_bfs, VERBOSITY_INDIVIDUAL, "BFS called for longline %u\n", longline);
627   DEBUG(dbg_bfs, VERBOSITY_INDIVIDUAL, "%zu longlines exist\n", GARY_SIZE(longlines));
628
629   for (uns i=0; i<GARY_SIZE(bfs_queue); i++)
630   {
631     struct graph_edge *cur = bfs_queue[i];
632     DEBUG(dbg_bfs, VERBOSITY_PLACEMENT, "Exploring new edge %d; %zu remaining\n", cur->num, GARY_SIZE(bfs_queue));
633
634     cur->visited = longline;
635
636     if (cur->longline == (uns) -1)
637       continue;
638
639     if (cur->dir == DIR_UNSET)
640     {
641       cur->dir = DIR_CENTER;
642       bfs_edge(cur, cur->n1, cur->n2, DIR_BWD);
643       bfs_edge(cur, cur->n2, cur->n1, DIR_FWD);
644     }
645     else
646     {
647       switch (cur->dir)
648       {
649         case DIR_BWD:
650           bfs_edge(cur, cur->n1, cur->n2, cur->dir);
651           break;
652         case DIR_FWD:
653           bfs_edge(cur, cur->n2, cur->n1, cur->dir);
654           break;
655         default:
656           // FIXME
657           ;
658       }
659     }
660   }
661 }
662
663 void bfs_wrapper(void)
664 {
665   GARY_INIT(bfs_queue, 0);
666   GARY_INIT(longlines, 0);
667
668   HASH_FOR_ALL(hash, node)
669   {
670     for (uns i=0; i<GARY_SIZE(node->edges); i++)
671     {
672       if ((node->edges[i]->label) && (node->edges[i]->longline == (uns) -1))
673       {
674         GARY_PUSH(longlines);
675         longlines[GARY_SIZE(longlines)-1].first = node->edges[i];
676
677         DEBUG(dbg_bfs, VERBOSITY_INDIVIDUAL, "Running new BFS\n");
678         DEBUG(dbg_bfs, VERBOSITY_INDIVIDUAL, "Creating longline %zu\n", GARY_SIZE(longlines)-1);
679
680         GARY_RESIZE(bfs_queue, 0);
681         struct graph_edge **e = GARY_PUSH(bfs_queue);
682         *e = node->edges[i];
683         node->edges[i]->longline = GARY_SIZE(longlines)-1;
684         bfs(node->edges[i]->longline);
685
686         DEBUG(dbg_bfs, VERBOSITY_INDIVIDUAL, "Joined %d edges\n", dbg_num_hits); dbg_num_hits = 0;
687         DEBUG(dbg_bfs, VERBOSITY_INDIVIDUAL, "Planned %zu edges\n", GARY_SIZE(bfs_queue));
688       }
689     }
690   }
691   HASH_END_FOR;
692
693   GARY_FREE(bfs_queue);
694 }
695
696 void dump_longlines(void)
697 {
698   printf("*** Longlines dump\n");
699   for (uns i=0; i<GARY_SIZE(longlines); i++)
700   {
701     printf("Longline %u:", i);
702     struct graph_edge *e = longlines[i].first;
703     if ((e->label) && (e->label->type == SYMBOLIZER_TEXT))
704       printf(" labelled %s", osm_val_decode(((struct sym_text *) e->label)->text));
705     printf("\n");
706
707     while (e)
708     {
709       printf("\t#%ju (%d): [%.2f; %.2f] -- [%.2f; %.2f] (dir %d)\n",
710              e->id, e->num, e->n1->o->x, e->n1->o->y, e->n2->o->x, e->n2->o->y, e->dir);
711
712       e = e->next;
713     }
714   }
715 }
716
717 struct request_line *make_new_line(void)
718 {
719   struct request_line *rl = GARY_PUSH(requests_line);
720   rl->request.ind = num_requests++;
721   rl->request.type = REQUEST_LINE;
722   GARY_INIT(rl->sections, 0);
723   GARY_INIT(rl->request.variants, 0);
724
725   return rl;
726 }
727
728 struct request_section *make_new_section(struct request_line *rl)
729 {
730   struct request_section *rls = GARY_PUSH(rl->sections);
731   rls->request.ind = num_requests++;
732   rls->request.type = REQUEST_SECTION;
733   rls->num_segments = 0;
734   GARY_INIT(rls->segments, 0);
735   GARY_INIT(rls->request.variants, 0);
736
737   return rls;
738 }
739
740 struct request_segment *make_new_segment(struct request_section *rls, struct symbol *sym)
741 {
742   struct request_segment *rs = GARY_PUSH(rls->segments);
743   rls->num_segments++;
744
745   rs->request.ind = num_requests++;
746   rs->request.type = REQUEST_SEGMENT;
747
748   GARY_INIT(rs->request.variants, 0);
749   if (sym)
750   {
751     struct variant *v = GARY_PUSH(rs->request.variants);
752     make_bitmap(v, sym);
753   }
754
755   return rs;
756 }
757
758 void cut_edge(struct graph_edge *e, double dist)
759 {
760   DEBUG(dbg_segments, VERBOSITY_PLACEMENT, "Cutting [%.2f; %.2f] -- [%.2f; %.2f] to dist %.2f\n", e->n1->o->x, e->n1->o->y, e->n2->o->x, e->n2->o->y, dist);
761
762   struct graph_edge *new = xmalloc(sizeof(struct graph_edge));
763   *new = *e;
764   e->next = new;
765
766   switch (e->label->type)
767   {
768     case SYMBOLIZER_TEXT:
769       new->label = xmalloc(sizeof(struct sym_text));
770       *((struct sym_text *) new->label) = *((struct sym_text *) e->label);
771       break;
772     default:
773       ;
774   }
775
776   struct osm_node *n1 = e->n1->o;
777   struct osm_node *n2 = e->n2->o;
778
779   if ((n1->x == n2->x) && (n1->y == n2->y))
780   {
781     printf("[%.2f; %.2f] -- [%.2f; %.2f]\n", n1->x, n1->y, n2->x, n2->y);
782     DEBUG(dbg_segments, VERBOSITY_PLACEMENT, "Won't cut point\n");
783     return;
784   }
785
786   struct osm_node *n11 = xmalloc(sizeof(struct osm_node));
787   struct graph_node *gn = xmalloc(sizeof(struct graph_node));
788   gn->o = n11;
789   double vsize = hypot(n1->x - n2->x, n1->y - n2->y);
790   n11->x = n1->x + (n2->x - n1->x) / vsize * dist;
791   n11->y = n1->y + (n2->y - n1->y) / vsize * dist;
792
793   e->n2 = new->n1 = gn;
794
795   e->length = hypot(abs(n1->x - n11->x), abs(n1->y - n11->y));
796   new->length = hypot(abs(n11->x - n2->x), abs(n11->y - n2->y));
797   new->visited = 0;
798 }
799
800 void make_segments(void)
801 {
802   for (uns i=0; i<GARY_SIZE(longlines); i++)
803   {
804     // Skip lines which are not labelled
805     if (! (longlines[i].first && longlines[i].first->label))
806       continue;
807
808     struct request_line *request = make_new_line();
809     struct request_section *rls = make_new_section(request);
810     struct request_segment *rs = NULL;
811
812     struct graph_edge *e = longlines[i].first;
813     double cur_length = 0;
814
815     struct sym_text *st = NULL;
816     if (e->label->type == SYMBOLIZER_TEXT)
817     {
818       st = (struct sym_text *) e->label;
819     }
820     else
821     {
822       // FIXME: Should other label types be supported in future?
823       DEBUG(dbg_segments, VERBOSITY_PLACEMENT, "Warning: Skipping line\n");
824       continue;
825     }
826
827     DEBUG(dbg_segments, VERBOSITY_INDIVIDUAL, "New longline\n");
828
829     while (e)
830     {
831       if (e->visited < 0)
832       {
833         DEBUG(dbg_segments, VERBOSITY_PLACEMENT, "BEWARE: Edge cycle\n");
834         break;
835       }
836       e->visited = -1;
837
838       DEBUG(dbg_segments, VERBOSITY_PLACEMENT, "Taking edge from [%.2f; %.2f] to [%.2f; %.2f] of length %.2f\n", e->n1->o->x, e->n1->o->y, e->n2->o->x, e->n2->o->y, e->length);
839
840       if (st && (e->length < st->tw))
841       {
842         e = e->next;
843         DEBUG(dbg_segments, VERBOSITY_PLACEMENT, "Warning: Skipping segment\n");
844         continue;
845       }
846
847       if (cur_length + e->length > conf_max_section_length + conf_max_section_overlay)
848       {
849         DEBUG(dbg_segments, VERBOSITY_PLACEMENT, "Edge too long, length is %.2f; %.2f - %.2f = %.2f\n", e->length, conf_max_section_length, cur_length, conf_max_section_length - cur_length);
850         // HACK to prevent cutting to 0 lenght
851         cut_edge(e, max2(conf_max_section_length - cur_length, 2));
852       }
853
854       rs = make_new_segment(rls, NULL);
855       rs->label = xmalloc(sizeof(struct sym_text));
856       *((struct sym_text *) rs->label) = *((struct sym_text *) e->label);
857
858       rs->x1 = e->n1->o->x;
859       rs->y1 = e->n1->o->y;
860       rs->x2 = e->n2->o->x;
861       rs->y2 = e->n2->o->y;
862
863       rs->slope = (rs->y2 - rs->y1) / (rs->x2 - rs->x1);
864       ((struct sym_text *) rs->label)->rotate = atan(rs->slope) * (-180 / M_PI);
865       struct variant *v = GARY_PUSH(rs->request.variants);
866       make_bitmap(v, rs->label);
867
868       rs->zindex = e->zindex;
869
870       cur_length += e->length;
871       if (cur_length > conf_max_section_length)
872       {
873         DEBUG(dbg_segments, VERBOSITY_PLACEMENT, "Making new section, new length would be %f, allowed is %.2f / %.2f\n", cur_length + e->length, conf_max_section_length, conf_max_section_overlay);
874
875         rls = make_new_section(request);
876         cur_length = 0;
877       }
878
879       e = e->next;
880     }
881
882     if (request->sections[0].num_segments == 0)
883     {
884       DEBUG(dbg_segments, VERBOSITY_INDIVIDUAL, "WARNING: Longline without any segment, skipped\n");
885
886       struct request_section *rls = &request->sections[0];
887       GARY_FREE(rls->segments);
888       GARY_FREE(rls->request.variants);
889
890       struct request_line *rl = &requests_line[GARY_SIZE(requests_line)-1];
891       GARY_FREE(rl->sections);
892       GARY_FREE(rl->request.variants);
893
894       GARY_POP(requests_line);
895       num_requests -= 2;
896     }
897   }
898 }
899
900 void dump_linelabel_requests(void)
901 {
902   for (uns i=0; i<GARY_SIZE(requests_line); i++)
903   {
904     if (requests_line[i].sections[0].num_segments == 0)
905     {
906       DEBUG(dbg_segments, VERBOSITY_INDIVIDUAL, "Beware: Longline without any segment\n");
907       continue;
908     }
909
910     printf("Request for linelabel, %zu sections\n", GARY_SIZE(requests_line[i].sections));
911     dump_label(requests_line[i].sections[0].segments[0].label);
912     for (uns j=0; j<GARY_SIZE(requests_line[i].sections); j++)
913     {
914       printf("%u section, %zu segments [%d]\n", j, GARY_SIZE(requests_line[i].sections[j].segments), requests_line[i].sections[j].request.ind);
915       for (uns k=0; k<GARY_SIZE(requests_line[i].sections[j].segments); k++)
916       {
917         struct request_segment *rs = &requests_line[i].sections[j].segments[k];
918         printf("[%.2f; %.2f] -- [%.2f; %.2f]\t\t[%d]\n", rs->x1, rs->y1, rs->x2, rs->y2, rs->request.ind);
919       }
920     }
921     printf("\n");
922   }
923 }
924
925 void dump_bitmaps(struct individual *individual)
926 {
927   bool *bitmap = xmalloc(page_width_int * page_height_int * sizeof(bool));
928   printf("Bitmap size is %d\n", page_width_int * page_height_int);
929   for (int i=0; i<page_height_int; i++)
930     for (int j=0; j<page_width_int; j++)
931       bitmap[i*page_width_int + j] = 0;
932
933   int total = 0;
934   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
935   {
936     if (individual->placements[i].variant_used == -1) continue;
937
938     struct placement *p = &(individual->placements[i]);
939     struct variant *v = NULL;
940
941     switch (p->request->type)
942     {
943       case REQUEST_SEGMENT: ;
944       case REQUEST_POINT: ;
945       case REQUEST_AREA: ;
946         v = &(p->request->variants[p->variant_used]);
947         break;
948       default:
949         ASSERT(p->request->type != REQUEST_INVALID);
950         continue;
951     }
952
953     int base_x = p->x; int base_y = p->y;
954     for (int dr = max2(0, 0-p->y); dr < v->height; dr++)
955     {
956       for (int dc = max2(0, 0-p->x); dc < v->width; dc++)
957       {
958         if (v->bitmap[dr * v->width + dc])
959         {
960           if (bitmap[(base_y + dr) * page_width_int + (base_x + dc)]) total += 1;
961           bitmap[(base_y + dr) * page_width_int + (base_x + dc)] = 1;
962         }
963       }
964     }
965   }
966   DEBUG(dbg_overlaps, VERBOSITY_GENERAL, "There were %d collisions during bitmap dump\n", total);
967
968   FILE *fd_dump = fopen("dump.pbm", "w");
969   fprintf(fd_dump, "P1\n");
970   fprintf(fd_dump, "%d %d\n", page_width_int, page_height_int);
971   for (int i=0; i<page_height_int; i++)
972   {
973     for (int j=0; j<page_width_int; j++)
974     {
975       fprintf(fd_dump, "%d", bitmap[(int) (i*page_width_int + j)] ? 1 : 0);
976     }
977     fprintf(fd_dump, "\n");
978   }
979   fclose(fd_dump);
980
981   free(bitmap);
982 }
983
984 void dump_individual(struct individual *individual)
985 {
986   printf("*** Individual dump\n");
987   printf("(There are %d requests)\n", num_requests);
988
989   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
990   {
991     struct placement *p = &(individual->placements[i]);
992
993     switch (p->request->type)
994     {
995       case REQUEST_POINT:
996         printf("Point at [%.2f; %.2f] on %u\n", p->x, p->y, ((struct request_point *) p->request)->zindex);
997         break;
998       case REQUEST_LINE: ;
999         struct request_line *rl = (struct request_line *) p->request;
1000         printf("Line: ");
1001         dump_label(rl->sections[0].segments[0].label);
1002         break;
1003       case REQUEST_SECTION: ;
1004         printf("*");
1005         break;
1006       case REQUEST_SEGMENT: ;
1007         if (p->variant_used >= 0)
1008           printf("Segment placed at [%.2f; %.2f] on %u\n", p->x, p->y, ((struct request_segment *) p->request)->zindex);
1009         else
1010           printf("Segment not placed\n");
1011         break;
1012       case REQUEST_AREA: ;
1013         struct request_area *ra = (struct request_area *) p->request;
1014         printf("Area label ");
1015         dump_label(ra->label);
1016         printf(" at [%.2f; %.2f] on %u\n", p->x, p->y, ((struct request_area *) p->request)->zindex);
1017         break;
1018       default:
1019         ASSERT(p->request->type != 0);
1020     }
1021   }
1022   printf("\nTotal penalty: %d\n", individual->penalty);
1023 }
1024
1025 void dump_placements(struct individual *individual)
1026 {
1027   printf("*** Individual placements dump\n");
1028
1029   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
1030   {
1031     struct placement *p = &individual->placements[i];
1032     printf("Placement %d:\tPlacet at [%.2f; %.2f] using variant %d\n", p->ind, p->x, p->y, p->variant_used);
1033   }
1034 }
1035
1036 void plan_individual(struct individual *individual)
1037 {
1038   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
1039   {
1040     struct symbol *s = NULL;
1041     z_index_t zindex = 0;
1042     /**
1043     if (individual->placements[i].variant_used < 0)
1044     {
1045       printf("Skipping placement of request %d\n", individual->placements[i].request->ind);
1046     }
1047     **/
1048     if (individual->placements[i].variant_used < 0) continue;
1049     switch (individual->placements[i].request->type)
1050     {
1051       case REQUEST_POINT: ;
1052         struct request_point *rp = (struct request_point *) individual->placements[i].request;
1053         s = rp->sym;
1054         zindex = rp->zindex;
1055         break;
1056       case REQUEST_SEGMENT: ;
1057         struct request_segment *rs = (struct request_segment *) individual->placements[i].request;
1058         s = rs->label;
1059         zindex = rs->zindex;
1060         break;
1061       case REQUEST_LINE: ;
1062         break;
1063       case REQUEST_AREA: ;
1064         struct request_area *ra = (struct request_area *) individual->placements[i].request;
1065         s = ra->label;
1066         zindex = ra->zindex;
1067         break;
1068       default:
1069         ASSERT(individual->placements[i].request != REQUEST_INVALID);
1070         continue;
1071     }
1072
1073   DEBUG(dbg_plan, VERBOSITY_PLACEMENT, "Will plan symbol of request %d at [%.2f; %.2f] on %u\n", individual->placements[i].request->ind, individual->placements[i].x, individual->placements[i].y, zindex);
1074
1075     if (s) switch (s->type)
1076     {
1077       case SYMBOLIZER_POINT: ;
1078         struct sym_point *sp = (struct sym_point *) s;
1079         sp->x = individual->placements[i].x;
1080         sp->y = individual->placements[i].y;
1081         sym_plan((struct symbol *) sp, zindex);
1082         break;
1083       case SYMBOLIZER_ICON: ;
1084         struct sym_icon *si = (struct sym_icon *) s;
1085         si->sir.x = individual->placements[i].x;
1086         si->sir.y = individual->placements[i].y;
1087         sym_plan((struct symbol *) si, zindex);
1088         break;
1089       case SYMBOLIZER_TEXT: ;
1090         struct sym_text *st = (struct sym_text *) s;
1091         st->x = individual->placements[i].x;
1092         st->y = individual->placements[i].y;
1093         st->next_duplicate = NULL;
1094         DEBUG(dbg_plan, VERBOSITY_PLACEMENT, "Planning text %s at [%.2f; %.2f] on %u, with rotation %.2f\n", osm_val_decode(st->text), st->x, st->y, zindex, st->rotate);
1095         sym_plan((struct symbol *) st, zindex);
1096         break;
1097       default:
1098         ASSERT(s->type != SYMBOLIZER_INVALID);
1099     }
1100   }
1101 }
1102
1103 void dump_penalties(struct individual **population)
1104 {
1105   for (int i=0; i<conf_pop_size; i++)
1106   {
1107     printf("Individual %d has penalty %d\n", i, population[i]->penalty);
1108   }
1109 }
1110
1111 void dump_placement_links(struct placement *p)
1112 {
1113   struct map_placement *mp = p->map_links;
1114
1115   while (mp)
1116   {
1117     printf(" %d", mp->part->ind);
1118     mp = mp->next_in_placement;
1119   }
1120
1121   printf("\n");
1122 }
1123
1124 void dump_part_links(struct map_part *part)
1125 {
1126   struct map_placement *mp = part->placement->next_in_map;
1127
1128   while (mp)
1129   {
1130     printf(" %d", mp->placement->ind);
1131     mp = mp->next_in_map;
1132   }
1133
1134   printf("\n");
1135 }
1136
1137 void dump_links(struct individual *individual)
1138 {
1139   printf("Dumping links in individual\n");
1140   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
1141   {
1142     dump_placement_links(&individual->placements[i]);
1143   }
1144 }
1145
1146 void compute_sizes(void)
1147 {
1148   page_width_int = floor(page_width);
1149   page_height_int = floor(page_height);
1150
1151   num_map_parts_row = (page_width_int + conf_map_part_width) / conf_map_part_width;
1152   num_map_parts_col = (page_height_int + conf_map_part_height) / conf_map_part_height;
1153   num_map_parts = num_map_parts_row * num_map_parts_col;
1154
1155   breed_pop_size = conf_breed_pop_size * conf_pop_size;
1156   breed_rbest_size = conf_breed_rbest * conf_pop_size;
1157   if (dbg_evolution >= VERBOSITY_GENERAL)
1158   {
1159     printf("Breeding parameters:\n");
1160     printf(" %d individuals are created\n", breed_pop_size);
1161     printf(" %d best individuals in old population are considered\n", breed_rbest_size);
1162   }
1163
1164   mutate_pop_size = conf_mutate_pop_size * conf_pop_size;
1165   mutate_rbest_size = conf_mutate_rbest * conf_pop_size;
1166   if (dbg_evolution >= VERBOSITY_GENERAL)
1167   {
1168     printf("Mutation parameters:\n");
1169     printf(" %d individuals are created\n", mutate_pop_size);
1170     printf(" %d best individuals in old population are considered\n", mutate_rbest_size);
1171   }
1172
1173   elite_pop_size = conf_elite_pop_size * conf_pop_size;
1174   if (dbg_evolution >= VERBOSITY_GENERAL)
1175   {
1176     printf("Elitism parameters:\n");
1177     printf(" %d best individuals are copied\n", elite_pop_size);
1178   }
1179
1180   if (breed_pop_size + mutate_pop_size + elite_pop_size != conf_pop_size)
1181   {
1182     if (conf_fit_size)
1183     {
1184       elite_pop_size += conf_pop_size - (breed_pop_size + mutate_pop_size + elite_pop_size);
1185     }
1186     else
1187     {
1188       fprintf(stderr, "Breeding + mutation + elitism won't create correct number of individuals\n");
1189       fprintf(stderr, "Please fix conf_breed_pop_size, conf_mutate_pop_size and conf_elite_pop_size parameters\n");
1190       exit(2);
1191     }
1192   }
1193 }
1194
1195 void labeller_label(void)
1196 {
1197 //srandom(29011992);
1198   make_graph();
1199   label_graph();
1200   bfs_wrapper();
1201   make_segments();
1202
1203   printf("Will deal with %d requests\n", num_requests);
1204
1205   GARY_INIT(population1, conf_pop_size);
1206   GARY_INIT(population2, conf_pop_size);
1207   make_population();
1208   rank_population();
1209   qsort(population1, conf_pop_size, sizeof(struct individual *), cmp_individual);
1210
1211   if (dbg_evolution >= VERBOSITY_GENERAL)
1212   {
1213     printf("Penalties after initialization\n");
1214     dump_penalties(population1);
1215   }
1216
1217   while (! shall_terminate())
1218   {
1219     iteration++;
1220     if (dbg_evolution)
1221       printf("\n*** Iteration %d ***\n", iteration);
1222
1223     breed();
1224     mutate();
1225     elite();
1226
1227     struct individual **swp = population1;
1228     population1 = population2;
1229     population2 = swp;
1230     pop2_ind = 0;
1231     clear_population(population2);
1232
1233     rank_population();
1234
1235     if (dbg_evolution >= VERBOSITY_INDIVIDUAL)
1236     {
1237       printf("Penalties before sort\n");
1238       dump_penalties(population1);
1239     }
1240
1241     DEBUG(dbg_evolution, VERBOSITY_GENERAL, "Sorting population\n");
1242     qsort(population1, conf_pop_size, sizeof(struct individual *), cmp_individual);
1243
1244     if (dbg_evolution >= VERBOSITY_GENERAL)
1245     {
1246       printf("Penalties after sort\n");
1247       dump_penalties(population1);
1248     }
1249
1250     old_best = population1[0]->penalty;
1251   }
1252
1253   if (dbg_overlaps >= VERBOSITY_GENERAL)
1254     dump_bitmaps(population1[0]);
1255
1256   plan_individual(population1[0]);
1257
1258   labeller_cleanup();
1259 }
1260
1261 void labeller_cleanup(void)
1262 {
1263   hash_cleanup();
1264   GARY_FREE(longlines);
1265
1266   GARY_FREE(requests_point);
1267   GARY_FREE(requests_area);
1268
1269   for (uns i=0; i<GARY_SIZE(requests_line); i++)
1270   {
1271     for (uns j=0; j<GARY_SIZE(requests_line[i].sections); j++)
1272     {
1273       GARY_FREE(requests_line[i].sections[j].segments);
1274     }
1275     GARY_FREE(requests_line[i].sections);
1276   }
1277   GARY_FREE(requests_line);
1278 }
1279
1280 void make_population(void)
1281 {
1282   for (int i=0; i<conf_pop_size; i++)
1283   {
1284     num_placements = 0; // FIXME: This IS a terrible HACK
1285     struct individual *i2 = ep_alloc(ep_individuals);
1286     init_individual(i2);
1287     population2[i] = i2;
1288
1289     DEBUG(dbg_init, VERBOSITY_INDIVIDUAL, "Making individual %d\n", i);
1290     struct individual *individual = ep_alloc(ep_individuals); init_individual(individual);
1291     population1[i] = individual;
1292
1293     int p = 0;
1294     for (uns j=0; j<GARY_SIZE(requests_point); j++)
1295     {
1296       init_placement(&(individual->placements[p++]), individual, (struct request *) &requests_point[j]);
1297     }
1298
1299     for (uns j=0; j<GARY_SIZE(requests_line); j++)
1300     {
1301       init_placement(&(individual->placements[p++]), individual, (struct request *) &requests_line[j]);
1302
1303       for (uns k=0; k<GARY_SIZE(requests_line[j].sections); k++)
1304       {
1305         init_placement(&(individual->placements[p++]), individual, (struct request *) &requests_line[j].sections[k]);
1306
1307         for (uns l=0; l<GARY_SIZE(requests_line[j].sections[k].segments); l++)
1308         {
1309           init_placement(&(individual->placements[p++]), individual, (struct request *) &requests_line[j].sections[k].segments[l]);
1310         }
1311       }
1312     }
1313
1314     for (uns j=0; j<GARY_SIZE(requests_area); j++)
1315     {
1316       init_placement(&(individual->placements[p++]), individual, (struct request *) &requests_area[j]);
1317     }
1318
1319     hide_segment_labels(individual);
1320
1321     ASSERT(p == num_requests);
1322   }
1323 }
1324
1325 bool shall_terminate(void)
1326 {
1327   switch (conf_term_cond)
1328   {
1329     case TERM_COND_PENALTY:
1330       return (population1[0]->penalty < conf_penalty_bound);
1331     case TERM_COND_STAGNATION:
1332       return (abs(old_best - population1[0]->penalty) < conf_stagnation_bound);
1333     case TERM_COND_ITERATIONS:
1334       return (iteration >= conf_iteration_limit);
1335     default:
1336       fprintf(stderr, "Warning: No termination condition is set, terminating\n");
1337       return 1;
1338   }
1339 }
1340
1341 void breed(void)
1342 {
1343   int i=0;
1344
1345   struct individual **breed_buffer;
1346   while (i < breed_pop_size)
1347   {
1348     int parent1 = randint(0, breed_rbest_size);
1349     int parent2 = randint(0, breed_rbest_size);
1350     DEBUG(dbg_breeding, VERBOSITY_INDIVIDUAL, "Will breed %d and %d\n", parent1, parent2);
1351
1352     breed_buffer = perform_crossover(population1[parent1], population1[parent2]);
1353     population2[pop2_ind++] = breed_buffer[0];
1354     population2[pop2_ind++] = breed_buffer[1];
1355     free(breed_buffer);
1356     i += 2;
1357   }
1358 }
1359
1360 struct individual **perform_crossover(struct individual *parent1, struct individual *parent2)
1361 {
1362   struct individual **buffer = xmalloc(2*sizeof(struct individual));
1363   struct individual *child1 = ep_alloc(ep_individuals); init_individual(child1);
1364   struct individual *child2 = ep_alloc(ep_individuals); init_individual(child2);
1365
1366   bool *processed;
1367   GARY_INIT_ZERO(processed, GARY_SIZE(parent1->placements));
1368
1369   for (uns i=0; i<GARY_SIZE(parent1->placements); i++)
1370   {
1371     if (! processed[parent1->placements[i].ind])
1372     {
1373       DEBUG(dbg_breeding, VERBOSITY_PLACEMENT, "Creating symbol closure for placement %u\n", i);
1374
1375       struct placement **clos_symbols = get_closure(&(parent1->placements[i]));
1376       int x = randint(0, 2);
1377
1378       if (x == 0)
1379       {
1380         DEBUG(dbg_breeding, VERBOSITY_PLACEMENT, "Copying parent->child 1->1 and 2->2\n");
1381         copy_symbols(clos_symbols, parent1, child1, &processed);
1382         copy_symbols(clos_symbols, parent2, child2, &processed);
1383       }
1384       else
1385       {
1386         DEBUG(dbg_breeding, VERBOSITY_PLACEMENT, "Copying parent->child 2->1 and 1->2\n");
1387         copy_symbols(clos_symbols, parent2, child1, &processed);
1388         copy_symbols(clos_symbols, parent1, child2, &processed);
1389       }
1390
1391       GARY_FREE(clos_symbols);
1392     }
1393   }
1394
1395   GARY_FREE(processed);
1396
1397   if (conf_mutate_children)
1398   {
1399     if (randdouble() < conf_mutate_children_prob) perform_mutation(child1);
1400     else hide_segment_labels(child1);
1401
1402     if (randdouble() < conf_mutate_children_prob) perform_mutation(child2);
1403     else hide_segment_labels(child2);
1404   }
1405
1406   buffer[0] = child1;
1407   buffer[1] = child2;
1408   return buffer;
1409 }
1410
1411 void mutate(void)
1412 {
1413   for (int i=0; i < mutate_pop_size; i++)
1414   {
1415     DEBUG(dbg_mutation, VERBOSITY_INDIVIDUAL, "Creating %d-th individual by mutation\n", i);
1416     int ind = randint(0, mutate_rbest_size);
1417     DEBUG(dbg_mutation, VERBOSITY_INDIVIDUAL, "Mutating %d-th individual of original population\n", ind);
1418     population2[pop2_ind] = ep_alloc(ep_individuals);
1419     copy_individual(population1[ind], population2[pop2_ind]);
1420     DEBUG(dbg_mutation, VERBOSITY_INDIVIDUAL, "Individual %d in pop2 inited from individual %d in pop1\n", pop2_ind, ind);
1421     perform_mutation(population2[pop2_ind]);
1422     pop2_ind++;
1423   }
1424 }
1425
1426 void perform_mutation(struct individual *individual)
1427 {
1428   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
1429   {
1430     double x = randdouble();
1431     double acc = 0;
1432
1433     if (x <= acc + conf_mutate_move_bound)
1434     {
1435       DEBUG(dbg_mutation, VERBOSITY_PLACEMENT, "Mutation: Moving symbol in placement %u\n", i);
1436       move_symbol(&(individual->placements[i]));
1437       continue;
1438     }
1439     acc += conf_mutate_move_bound;
1440
1441     if (x <= acc + conf_mutate_regen_bound)
1442     {
1443       gen_coords(&(individual->placements[i]));
1444       continue;
1445     }
1446     acc += conf_mutate_regen_bound;
1447
1448     if (x <= acc + conf_mutate_chvar_bound)
1449     {
1450       struct placement *p = &(individual->placements[i]);
1451       switch (p->request->type)
1452       {
1453         case REQUEST_POINT:
1454         case REQUEST_AREA:
1455           // Does nothing when there are 0 variants... does it mind?
1456           p->variant_used = randint(-1, GARY_SIZE(p->request->variants));
1457           break;
1458         case REQUEST_SEGMENT:
1459           p->variant_used = randint(0, GARY_SIZE(p->request->variants));
1460           break;
1461         case REQUEST_SECTION:
1462           p->variant_used = randint(0, GARY_SIZE(((struct request_section *) p->request)->segments));
1463           break;
1464         default:
1465           ;
1466       }
1467     }
1468   }
1469
1470   hide_segment_labels(individual);
1471 }
1472
1473 void elite(void)
1474 {
1475   for (int i=0; i<elite_pop_size; i++)
1476   {
1477     DEBUG(dbg_evolution, VERBOSITY_INDIVIDUAL, "Iteration %d: Copying individual #%d from pop 1 to #%d in pop 2\n", iteration, i, pop2_ind);
1478     population2[pop2_ind] = ep_alloc(ep_individuals);
1479     copy_individual(population1[i], population2[pop2_ind++]);
1480   }
1481 }
1482
1483 int overlaps(struct placement *p1, struct placement *p2)
1484 {
1485   if (p1->request->type != REQUEST_POINT &&
1486       p1->request->type != REQUEST_SEGMENT &&
1487       p1->request->type != REQUEST_AREA)
1488     return 0;
1489
1490   if (p2->request->type != REQUEST_POINT &&
1491       p2->request->type != REQUEST_SEGMENT &&
1492       p2->request->type != REQUEST_AREA)
1493     return 0;
1494
1495   if (p1->variant_used == -1 || p2->variant_used == -1)
1496     return 0;
1497
1498   struct variant *v1, *v2;
1499
1500   v1 = &(p1->request->variants[p1->variant_used]);
1501   v2 = &(p2->request->variants[p2->variant_used]);
1502
1503   // FIXME: This doesn't fully respect offset which it probably should
1504   int p1x = p1->x; int p1y = p1->y;
1505   int p2x = p2->x; int p2y = p2->y;
1506
1507   int overlap = 0;
1508   for (int y=max2(0, max2(p1y, p2y)); y<min2(page_height_int, min2(p1y+v1->height, p2y+v2->height)); y++)
1509     for (int x=max2(0, max2(p1x, p2x)); x<min2(page_width_int, min2(p1x+v1->width, p2x+v2->width)); x++)
1510     {
1511       if (v1->bitmap[(y-p1y)*v1->width + (x-p1x)] &&
1512           v2->bitmap[(y-p2y)*v2->width + (x-p2x)])
1513         overlap++;
1514     }
1515
1516   return overlap;
1517 }
1518
1519 int get_overlap(struct placement *p, int **planned_ptr, int iteration)
1520 {
1521   int *planned = *planned_ptr;
1522
1523   if (p->variant_used == -1) return 0;
1524
1525   struct map_part **parts = get_map_parts(p);
1526   if (! parts)
1527   {
1528     DEBUG(dbg_overlaps, VERBOSITY_PLACEMENT, "Placement of request %d seems not to be placed\n", p->request->ind);
1529     return 0;
1530   }
1531
1532   struct placement **others;
1533
1534   planned[p->request->ind] = iteration;
1535   GARY_INIT(others, 0);
1536
1537 //printf("Iterating over parts of placement %d (at [%.2f; %.2f] / %d)\n", p->ind, p->x, p->y, p->variant_used);
1538   for (uns i=0; i<GARY_SIZE(parts); i++)
1539   {
1540   //printf("%d:\t", parts[i]->ind);
1541   //dump_part_links(parts[i]);
1542     struct map_placement *mp = parts[i]->placement->next_in_map;
1543     while (mp)
1544     {
1545       if (planned[mp->placement->request->ind] != iteration)
1546       {
1547         struct placement **p = GARY_PUSH(others);
1548         *p = mp->placement;
1549         planned[mp->placement->request->ind] = iteration;
1550       }
1551       mp = mp->next_in_map;
1552     }
1553   }
1554
1555   int overlap = 0;
1556   for (uns i=0; i<GARY_SIZE(others); i++)
1557   {
1558     overlap += overlaps(p, others[i]);
1559   }
1560
1561   GARY_FREE(parts);
1562   GARY_FREE(others);
1563
1564   if (dbg_overlaps >= VERBOSITY_PLACEMENT)
1565   {
1566     printf("Placement %d (of request %d) add %d to overlaps", p->ind, p->request->ind, overlap);
1567     dump_placement_links(p);
1568   }
1569
1570   if (p->x < 0) overlap += 0 - p->x;
1571   if (p->x + p->request->variants[p->variant_used].width > page_width_int)
1572     overlap += p->x + p->request->variants[p->variant_used].width - page_width_int;
1573
1574   if (p->y < 0) overlap += 0 - p->y;
1575   if (p->y + p->request->variants[p->variant_used].height > page_height_int)
1576     overlap += p->y + p->request->variants[p->variant_used].height - page_height_int;
1577
1578   return overlap;
1579 }
1580
1581 int individual_overlap(struct individual *individual)
1582 {
1583   int overlap = 0;
1584
1585   int *planned;
1586   GARY_INIT_ZERO(planned, GARY_SIZE(individual->placements));
1587
1588   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
1589   {
1590     overlap += get_overlap(&individual->placements[i], &planned, i+1);
1591   }
1592
1593   GARY_FREE(planned);
1594
1595 //  printf("Total overlap is %d\n", overlap);
1596
1597   return overlap;
1598 }
1599
1600 double get_distance(struct placement *p)
1601 {
1602   if (p->variant_used < 0) return 0;
1603   struct variant *v = &p->request->variants[p->variant_used];
1604
1605   double dx, dy, distance;
1606   switch (p->request->type)
1607   {
1608     case REQUEST_POINT: ;
1609       struct request_point *rp = (struct request_point *) p->request;
1610       dx = rp->x + v->offset_x - p->x;
1611       dy = rp->y + v->offset_y - p->y;
1612       distance = hypot(dx, dy);
1613       DEBUG(dbg_rank, VERBOSITY_PLACEMENT, "Point placed at [%.2f; %.2f], expected at [%.2f; %.2f]\n", p->x, p->y, rp->x, rp->y);
1614       break;
1615     case REQUEST_SEGMENT: ;
1616       struct request_segment *rs = (struct request_segment *) p->request;
1617       struct sym_text *st = (struct sym_text *) rs->label;
1618
1619       double width = p->request->variants[p->variant_used].width;
1620       double rotated_x = p->x + width * sin(st->rotate / (-180 / M_PI));
1621       double rotated_y = p->y + width * cos(st->rotate / (-180 / M_PI));
1622
1623       if (rs->x1 < rs->x2)
1624       {
1625         if (p->x < rs->x1)
1626         {
1627           dx = rs->x1 - p->x;
1628           dy = rs->y1 - p->y;
1629         }
1630         else if (rotated_x > rs->x2)
1631         {
1632           dx = rotated_x - rs->x2;
1633           dy = rotated_y - rs->y2;
1634         }
1635         else
1636         {
1637           dx = dy = 0;
1638         }
1639       }
1640       else
1641       {
1642         if (p->x < rs->x2)
1643         {
1644           dx = rs->x2 - p->x;
1645           dy = rs->y2 - p->y;
1646         }
1647         else if (rotated_x > rs->x1)
1648         {
1649           dx = rotated_x - rs->x1;
1650           dy = rotated_y - rs->y1;
1651         }
1652         else
1653         {
1654           dx = dy = 0;
1655         }
1656       }
1657
1658       distance = hypot(dx, dy);
1659       break;
1660     case REQUEST_AREA: ;
1661       struct request_area *ra = (struct request_area *) p->request;
1662       dx = ra->cx + v->offset_x - p->x;
1663       dy = ra->cy + v->offset_y - p->y;
1664       distance = hypot(dx, dy);
1665       DEBUG(dbg_rank, VERBOSITY_PLACEMENT, "Area placed at [%.2f; %.2f], expected at [%.2f; %.2f]\n", p->x, p->y, ra->cx, ra->cy);
1666       break;
1667     default:
1668       return 0;
1669   }
1670
1671   DEBUG(dbg_rank, VERBOSITY_PLACEMENT, "Placement %d has distance %.2f\n", p->ind, distance);
1672   return distance;
1673 }
1674
1675 double individual_distances(struct individual *individual)
1676 {
1677   int distances = 0;
1678
1679   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
1680   {
1681     distances += get_distance(&individual->placements[i]);
1682   }
1683
1684   return distances;
1685 }
1686
1687 double get_omittment(struct placement *p)
1688 {
1689   if (p->variant_used >= 0) return 0;
1690
1691   // FIX ME :)
1692   switch (p->request->type)
1693   {
1694     case REQUEST_POINT:
1695     case REQUEST_AREA:
1696       return 10;
1697       break;
1698     default:
1699       return 0;
1700   }
1701 }
1702
1703 double individual_omittment(struct individual *individual)
1704 {
1705   int omittment = 0;
1706
1707   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
1708   {
1709     omittment += get_omittment(&individual->placements[i]);
1710   }
1711
1712   return omittment;
1713 }
1714
1715 int cmp_individual(const void *a, const void *b)
1716 {
1717   struct individual **ia = (struct individual **) a;
1718   struct individual **ib = (struct individual **) b;
1719
1720   return (*ia)->penalty - (*ib)->penalty;
1721 }
1722
1723 void rank_population(void)
1724 {
1725   int penalty;
1726
1727   for (int i=0; i<conf_pop_size; i++)
1728   {
1729     DEBUG(dbg_rank, VERBOSITY_INDIVIDUAL, "Individual %d\n", i);
1730     population1[i]->penalty = 0;
1731
1732     penalty = individual_omittment(population1[i]);
1733     DEBUG(dbg_rank, VERBOSITY_INDIVIDUAL, "Increasing penalty by %d for omittment\n", penalty);
1734     population1[i]->penalty += penalty;
1735
1736     penalty = individual_overlap(population1[i]);
1737     DEBUG(dbg_rank, VERBOSITY_INDIVIDUAL, "Increasing penalty by %d for overlap\n", penalty);
1738     population1[i]->penalty += penalty;
1739
1740     penalty = individual_distances(population1[i]);
1741     DEBUG(dbg_rank, VERBOSITY_INDIVIDUAL, "Increasing penalty by %d for distances\n", penalty);
1742     population1[i]->penalty += penalty;
1743   }
1744 }
1745
1746 struct map_part **get_map_parts(struct placement *p)
1747 {
1748   if (p->variant_used < 0) return NULL;
1749
1750   struct map_part **buffer;
1751   GARY_INIT(buffer, 0);
1752
1753   DEBUG(dbg_map_parts, VERBOSITY_PLACEMENT, "Looking for map parts containing placement of request %d, placed at [%.2f; %.2f]\n", p->request->ind, p->x, p->y);
1754
1755   struct variant v;
1756   switch (p->request->type)
1757   {
1758     case REQUEST_POINT:
1759     case REQUEST_SEGMENT:
1760     case REQUEST_AREA:
1761       v = p->request->variants[p->variant_used];
1762       break;
1763     default:
1764       DEBUG(dbg_map_parts, VERBOSITY_ALL, "Skipping unsupported request type (%d)\n", p->request->type);
1765       return NULL;
1766   }
1767
1768   DEBUG(dbg_map_parts, VERBOSITY_PLACEMENT, "Bitmap is %d x %d\n", v.width, v.height);
1769
1770   int x_min = max2(0, p->x) / conf_map_part_width;
1771   // CHECK ME: Is rounding needed?
1772   int x_max = min2(page_width_int, (p->x + v.width)) / conf_map_part_width;
1773   int y_min = max2(0, p->y) / conf_map_part_height;
1774   // CHECK ME: Is rounding needed?
1775   int y_max = min2(page_height_int, (p->y + v.height)) / conf_map_part_height;
1776
1777   DEBUG(dbg_map_parts, VERBOSITY_PLACEMENT, "Cells between [%d; %d] and [%d; %d] generated\n", x_min, y_min, x_max, y_max);
1778
1779   for (int y=y_min; y<=y_max; y++)
1780     for (int x=x_min; x<=x_max; x++)
1781     {
1782       struct map_part **m = GARY_PUSH(buffer);
1783       DEBUG(dbg_map_parts, VERBOSITY_ALL, "Asking for %d of %zu\n", y * num_map_parts_row + x, GARY_SIZE(p->individual->map));
1784       *m = p->individual->map[y * num_map_parts_row + x];
1785     }
1786
1787   DEBUG(dbg_map_parts, VERBOSITY_PLACEMENT, "Returning %zu map parts potentially containing the symbol\n", GARY_SIZE(buffer));
1788
1789   return buffer;
1790 }
1791
1792 void update_map_parts_delete(struct placement *p)
1793 {
1794   struct map_placement *mp = p->map_links;
1795   while (mp)
1796   {
1797     mp->prev_in_map->next_in_map = mp->next_in_map;
1798     if (mp->next_in_map)
1799       mp->next_in_map->prev_in_map = mp->prev_in_map;
1800
1801     struct map_placement *tmp = mp;
1802     mp = mp->next_in_placement;
1803     free(tmp);
1804   }
1805   p->map_links = NULL;
1806 }
1807
1808 void update_map_parts_create(struct placement *p)
1809 {
1810   struct map_part **parts = get_map_parts(p);
1811   if (parts == NULL) return;
1812
1813   for (uns i=0; i<GARY_SIZE(parts); i++)
1814   {
1815     struct map_placement *mp = xmalloc(sizeof(struct map_placement));
1816     mp->placement = p;
1817     mp->part = parts[i];
1818
1819     mp->next_in_map = parts[i]->placement->next_in_map;
1820     mp->prev_in_map = parts[i]->placement;
1821     parts[i]->placement->next_in_map = mp;
1822     if (mp->next_in_map) mp->next_in_map->prev_in_map = mp;
1823
1824     mp->next_in_placement = p->map_links;
1825     mp->prev_in_placement = NULL;
1826     p->map_links = mp;
1827   }
1828
1829   GARY_FREE(parts);
1830 }
1831
1832 void update_map_parts(struct placement *p)
1833 {
1834   update_map_parts_delete(p);
1835   update_map_parts_create(p);
1836 }
1837
1838 void gen_coords(struct placement *p)
1839 {
1840   switch(p->request->type)
1841   {
1842     case REQUEST_POINT:
1843       gen_coords_point(p);
1844       break;
1845     case REQUEST_AREA:
1846       gen_coords_area(p);
1847       break;
1848     case REQUEST_SEGMENT:
1849       gen_coords_segment(p);
1850       break;
1851     case REQUEST_LINE:
1852       if (dbg_movement)
1853         printf("Not yet implemented\n");
1854       break;
1855     default:
1856       DEBUG(dbg_movement, VERBOSITY_ALL, "Testing request type\n");
1857       ASSERT(p->request->type != REQUEST_INVALID);
1858   }
1859
1860   update_map_parts(p);
1861 }
1862
1863 double gen_movement(void)
1864 {
1865   double m = (random() % 100000) / 10000;
1866   m = pow(m, 1.0/3) * flip(1, -1);
1867   DEBUG(dbg_movement, VERBOSITY_ALL, "Movement %.2f\n", m);
1868   return m;
1869 }
1870
1871 double gen_movement_uniform(void)
1872 {
1873   return (move_max - move_min) * randdouble() * flip(1, -1);
1874 }
1875
1876 void gen_coords_point(struct placement *p)
1877 {
1878   p->x = p->x + gen_movement();
1879 }
1880
1881 void gen_coords_segment(struct placement *p)
1882 {
1883   struct request_segment *rs = (struct request_segment *) p->request;
1884   p->x = (rs->x1 + rs->x2) / 2;
1885   p->y = (rs->y1 + rs->y2) / 2;
1886 }
1887
1888 void gen_coords_area(struct placement *p)
1889 {
1890   struct request_area *ra = (struct request_area *) p->request;
1891
1892   p->x = p->x + gen_movement();
1893   p->y = p->y + gen_movement();
1894
1895   DEBUG(dbg_movement, VERBOSITY_PLACEMENT, "Moved label to [%.2f; %.2f] from [%.2f; %.2f]\n", p->x, p->y, ra->cx, ra->cy);
1896 }
1897
1898 int randint(int min, int max)
1899 {
1900   if (min == max) return min;
1901   int r = random();
1902   return min + (r % (max - min));
1903 }
1904
1905 struct placement **get_closure(struct placement *placement)
1906 {
1907   struct placement **closure;
1908   GARY_INIT(closure, 0);
1909   bool *chosen = xmalloc(GARY_SIZE(placement->individual->placements) * sizeof(bool));
1910   for (uns i=0; i<GARY_SIZE(placement->individual->placements); i++) { chosen[i] = 0; }
1911   chosen[placement->request->ind] = 1;
1912
1913   struct placement **p = GARY_PUSH(closure); *p = placement;
1914
1915   uns first = 0;
1916   while (first < GARY_SIZE(closure))
1917   {
1918     DEBUG(dbg_breeding, VERBOSITY_ALL, "Iterating, first is %u of current %zu\n", first, GARY_SIZE(closure));
1919     struct placement **overlapping = get_overlapping(placement);
1920     if (! overlapping) { first++; continue; }
1921
1922     struct placement **filtered = filter(overlapping, &chosen);
1923     DEBUG(dbg_breeding, VERBOSITY_ALL, "There are %zu new overlapping symbols\n", GARY_SIZE(filtered));
1924     GARY_FREE(overlapping);
1925     overlapping = filtered;
1926     for (uns j=0; j<GARY_SIZE(overlapping); j++)
1927     {
1928       if (! chosen[overlapping[j]->request->ind])
1929       {
1930         if (overlaps(*p, overlapping[j]))
1931         {
1932           p = GARY_PUSH(closure); *p = overlapping[j];
1933           DEBUG(dbg_breeding, VERBOSITY_ALL, "Adding placement of request %d (in fact at [%.2f; %.2f] of size %d x %d)\n", overlapping[j]->request->ind, overlapping[j]->x, overlapping[j]->y, overlapping[j]->request->variants[overlapping[j]->variant_used].width, overlapping[j]->request->variants[overlapping[j]->variant_used].height);
1934           chosen[overlapping[j]->request->ind] = 1;
1935         }
1936       }
1937     }
1938     GARY_FREE(overlapping);
1939     first++;
1940   }
1941
1942   free(chosen);
1943
1944   return closure;
1945 }
1946
1947 void copy_symbols(struct placement **closure, struct individual *parent, struct individual *child, bool **processed_ptr)
1948 {
1949   bool *processed = *processed_ptr;
1950   DEBUG(dbg_breeding, VERBOSITY_ALL, "Will copy %zu symbols\n", GARY_SIZE(closure));
1951
1952   for (uns i=0; i<GARY_SIZE(closure); i++)
1953   {
1954     processed[closure[i]->ind] = 1;
1955     int ind = closure[i]->ind;
1956     child->placements[ind] = parent->placements[ind];
1957     child->placements[ind].individual = child;
1958     child->placements[ind].processed = 0;
1959     child->placements[ind].map_links = NULL;
1960     update_map_parts(&child->placements[ind]);
1961   }
1962 }
1963
1964 void move_symbol(struct placement *p)
1965 {
1966   switch (p->request->type)
1967   {
1968     case REQUEST_POINT:
1969     case REQUEST_AREA:
1970       move_symbol_point(p);
1971       break;
1972     case REQUEST_SEGMENT:
1973       move_symbol_segment(p);
1974       break;
1975     default:
1976       ASSERT(p->request->type != REQUEST_INVALID);
1977   }
1978 }
1979
1980 void move_symbol_point(struct placement *p)
1981 {
1982   p->x += gen_movement_uniform();
1983   p->y += gen_movement_uniform();
1984 }
1985
1986 void move_symbol_segment(struct placement *p)
1987 {
1988   double m = gen_movement_uniform();
1989   // CHECK ME
1990   p->x += m;
1991   p->y += m * ((struct request_segment *) p->request)->slope;
1992 }
1993
1994 void hide_segment_labels(struct individual *individual)
1995 {
1996   // BEWARE: This fully depends on current genetic encoding
1997
1998   int used = -1, num = -1;
1999   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
2000   {
2001     switch (individual->placements[i].request->type)
2002     {
2003       case REQUEST_SECTION:
2004         used = individual->placements[i].variant_used;
2005         num = 0;
2006         break;
2007       case REQUEST_SEGMENT:
2008         if (num == used)
2009           individual->placements[i].variant_used = 0;
2010         else
2011           individual->placements[i].variant_used = -1;
2012         num++;
2013         break;
2014       default:
2015         ;
2016     }
2017   }
2018 }
2019
2020 void init_placement(struct placement *p, struct individual *individual, struct request *r)
2021 {
2022   p->ind = num_placements++;
2023   p->request = r;
2024   p->processed = 0;
2025   p->x = p->y = 0; // To prevent valgrind from complaining
2026   p->variant_used = 0;
2027   p->map_links = NULL;
2028   p->individual = individual;
2029   switch (r->type)
2030   {
2031     case REQUEST_POINT: ;
2032       struct request_point *rp = (struct request_point *) r;
2033       p->x = rp->x;
2034       p->y = rp->y;
2035       break;
2036     case REQUEST_LINE: ;
2037       break;
2038     case REQUEST_SECTION: ;
2039       struct request_section *rls = (struct request_section *) r;
2040       p->variant_used = randint(0, rls->num_segments);
2041       break;
2042     case REQUEST_SEGMENT: ;
2043       struct request_segment *rs = (struct request_segment *) r;
2044       p->x = rs->x2;
2045       p->y = rs->y2;
2046       break;
2047     case REQUEST_AREA: ;
2048       struct request_area *ra = (struct request_area *) r;
2049       p->x = ra->cx;
2050       p->y = ra->cy;
2051       p->variant_used = 0;
2052       break;
2053     default:
2054       ASSERT(p->request->type != REQUEST_INVALID);
2055   }
2056
2057   gen_coords(p);
2058   DEBUG(dbg_init, VERBOSITY_PLACEMENT, "Inited placement to [%.2f; %.2f]\n", p->x, p->y);
2059 }
2060
2061 /**
2062 void reset_individual_map(struct individual *i)
2063 {
2064   for (uns j=0; j<num_map_parts; j++)
2065   {
2066     struct map_placement *mp = i->map[j]->placement;
2067     while (mp)
2068     {
2069       struct map_placement *tmp = mp;
2070       mp = mp->next_in_map;
2071       free(tmp);
2072     }
2073
2074     free(i->map[j]);
2075     struct map_part *part = xmalloc(sizeof(struct map_part));
2076     part->ind = j;
2077
2078     mp = xmalloc(sizeof(struct map_placement));
2079     part->placement = mp;
2080     mp->placement = &dummy_placement;
2081     mp->next_in_map = mp->prev_in_map = NULL;
2082     mp->next_in_placement = mp->prev_in_placement = NULL;
2083     i->map[j] = part;
2084   }
2085 }
2086 **/
2087
2088 /**
2089 void update_individual(struct individual *individual)
2090 {
2091   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
2092   {
2093     update_map_parts_delete(&individual->placements[i]);
2094   }
2095 }
2096 **/
2097
2098 void clear_individual(struct individual *individual)
2099 {
2100   for (uns j=0; j<num_map_parts; j++)
2101   {
2102     struct map_placement *mp = individual->map[j]->placement;
2103     while (mp)
2104     {
2105       struct map_placement *tmp = mp;
2106       mp = mp->next_in_map;
2107       free(tmp);
2108     }
2109
2110     free(individual->map[j]);
2111   }
2112
2113   GARY_FREE(individual->map);
2114   GARY_FREE(individual->placements);
2115   ep_free(ep_individuals, individual);
2116 }
2117
2118 void clear_population(struct individual **pop)
2119 {
2120   for (uns i=0; i<GARY_SIZE(pop); i++)
2121   {
2122     clear_individual(pop[i]);
2123   }
2124 }
2125
2126 struct placement **get_overlapping(struct placement *p)
2127 {
2128   struct placement **buffer;
2129   GARY_INIT(buffer, 0);
2130
2131   struct map_part **parts = get_map_parts(p);
2132   if (! parts) return NULL;
2133
2134   for (uns i=0; i<GARY_SIZE(parts); i++)
2135   {
2136     struct map_placement *mp = parts[i]->placement->next_in_map;
2137     while (mp)
2138     {
2139       if (p->variant_used >= 0)
2140       {
2141         struct placement **p = GARY_PUSH(buffer);
2142         *p = mp->placement;
2143       }
2144       mp = mp->next_in_map;
2145     }
2146   }
2147   GARY_FREE(parts);
2148
2149   DEBUG(dbg_map_parts, VERBOSITY_PLACEMENT, "Returning %zu potentially overlapping placements\n", GARY_SIZE(buffer));
2150
2151   return buffer;
2152 }
2153
2154 struct placement **filter(struct placement **list, bool **pred_ptr)
2155 {
2156   bool *pred = *pred_ptr; // As GARY can't be passed directly
2157   struct placement **filtered;
2158   GARY_INIT(filtered, 0);
2159
2160   for (uns i=0; i<GARY_SIZE(list); i++)
2161   {
2162     if (pred[list[i]->request->ind])
2163       continue;
2164
2165     struct placement **p = GARY_PUSH(filtered);
2166     *p = list[i];
2167   }
2168
2169   return filtered;
2170 }
2171
2172 int flip(int a, int b)
2173 {
2174   return (random() % 2 ? a : b);
2175 }
2176
2177 double randdouble(void)
2178 {
2179   return ((double) rand() / (double) RAND_MAX);
2180 }
2181
2182 void init_individual(struct individual *individual)
2183 {
2184   GARY_INIT(individual->placements, num_requests);
2185   GARY_INIT(individual->map, 0);
2186   for (uns j=0; j<num_map_parts; j++)
2187   {
2188     GARY_PUSH(individual->map);
2189     struct map_part *part = xmalloc(sizeof(struct map_part));
2190     struct map_placement *mp = xmalloc(sizeof(struct map_placement));
2191     part->placement = mp;
2192     part->ind = j;
2193     mp->placement = &dummy_placement;
2194     mp->next_in_map = mp->prev_in_map = NULL;
2195     mp->next_in_placement = mp->prev_in_placement = NULL;
2196     individual->map[j] = part;
2197   }
2198   individual->penalty = 0;
2199 }
2200
2201 void copy_individual(struct individual *src, struct individual *dest)
2202 {
2203   init_individual(dest);
2204   dest->penalty = src->penalty;
2205
2206   for (uns i=0; i<GARY_SIZE(src->placements); i++)
2207   {
2208     dest->placements[i] = src->placements[i];
2209     dest->placements[i].map_links = NULL;
2210     dest->placements[i].individual = dest;
2211
2212     update_map_parts_create(&dest->placements[i]);
2213   }
2214 }