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