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