]> mj.ucw.cz Git - leo.git/blob - labeller.c
97e4714931c266d1668df595cd7042a6980a61aa
[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(requests_point);
1285   GARY_FREE(requests_line);
1286   GARY_FREE(requests_area);
1287 }
1288
1289 void make_population(void)
1290 {
1291   for (int i=0; i<conf_pop_size; i++)
1292   {
1293     num_placements = 0; // FIXME: This IS a terrible HACK
1294     struct individual *i2 = ep_alloc(ep_individuals);
1295     init_individual(i2);
1296     population2[i] = i2;
1297
1298     if (dbg_init >= VERBOSITY_INDIVIDUAL)
1299       printf("Making individual %d\n", i);
1300     struct individual *individual = ep_alloc(ep_individuals); init_individual(individual);
1301     population1[i] = individual;
1302
1303     int p = 0;
1304     for (uns j=0; j<GARY_SIZE(requests_point); j++)
1305     {
1306       init_placement(&(individual->placements[p++]), individual, (struct request *) &requests_point[j]);
1307     }
1308
1309     for (uns j=0; j<GARY_SIZE(requests_line); j++)
1310     {
1311       init_placement(&(individual->placements[p++]), individual, (struct request *) &requests_line[j]);
1312
1313       for (uns k=0; k<GARY_SIZE(requests_line[j].sections); k++)
1314       {
1315         init_placement(&(individual->placements[p++]), individual, (struct request *) &requests_line[j].sections[k]);
1316
1317         for (uns l=0; l<GARY_SIZE(requests_line[j].sections[k].segments); l++)
1318         {
1319           init_placement(&(individual->placements[p++]), individual, (struct request *) &requests_line[j].sections[k].segments[l]);
1320         }
1321       }
1322     }
1323
1324     for (uns j=0; j<GARY_SIZE(requests_area); j++)
1325     {
1326       init_placement(&(individual->placements[p++]), individual, (struct request *) &requests_area[j]);
1327     }
1328
1329     hide_segment_labels(individual);
1330
1331     ASSERT(p == num_requests);
1332   }
1333 }
1334
1335 bool shall_terminate(void)
1336 {
1337   switch (conf_term_cond)
1338   {
1339     case TERM_COND_PENALTY:
1340       return (population1[0]->penalty < conf_penalty_bound);
1341     case TERM_COND_STAGNATION:
1342       return (abs(old_best - population1[0]->penalty) < conf_stagnation_bound);
1343     case TERM_COND_ITERATIONS:
1344       return (iteration >= conf_iteration_limit);
1345     default:
1346       fprintf(stderr, "Warning: No termination condition is set, terminating\n");
1347       return 1;
1348   }
1349 }
1350
1351 void breed(void)
1352 {
1353   int i=0;
1354
1355   struct individual **breed_buffer;
1356   while (i < breed_pop_size)
1357   {
1358     int parent1 = randint(0, breed_rbest_size);
1359     int parent2 = randint(0, breed_rbest_size);
1360     if (dbg_breeding >= VERBOSITY_INDIVIDUAL)
1361       printf("Will breed %d and %d\n", parent1, parent2);
1362
1363     breed_buffer = perform_crossover(population1[parent1], population1[parent2]);
1364     population2[pop2_ind++] = breed_buffer[0];
1365     population2[pop2_ind++] = breed_buffer[1];
1366     free(breed_buffer);
1367     i += 2;
1368   }
1369 }
1370
1371 struct individual **perform_crossover(struct individual *parent1, struct individual *parent2)
1372 {
1373   struct individual **buffer = xmalloc(2*sizeof(struct individual));
1374   struct individual *child1 = ep_alloc(ep_individuals); init_individual(child1);
1375   struct individual *child2 = ep_alloc(ep_individuals); init_individual(child2);
1376
1377   bool *processed;
1378   GARY_INIT_ZERO(processed, GARY_SIZE(parent1->placements));
1379
1380   for (uns i=0; i<GARY_SIZE(parent1->placements); i++)
1381   {
1382     if (! processed[parent1->placements[i].ind])
1383     {
1384       if (dbg_breeding >= VERBOSITY_PLACEMENT)
1385         printf("Creating symbol closure for placement %u\n", i);
1386
1387       struct placement **clos_symbols = get_closure(&(parent1->placements[i]));
1388       int x = randint(0, 2);
1389
1390       if (x == 0)
1391       {
1392         if (dbg_breeding >= VERBOSITY_PLACEMENT)
1393           printf("Copying parent->child 1->1 and 2->2\n");
1394         copy_symbols(clos_symbols, parent1, child1, &processed);
1395         copy_symbols(clos_symbols, parent2, child2, &processed);
1396       }
1397       else
1398       {
1399         if (dbg_breeding >= VERBOSITY_PLACEMENT)
1400           printf("Copying parent->child 2->1 and 1->2\n");
1401         copy_symbols(clos_symbols, parent2, child1, &processed);
1402         copy_symbols(clos_symbols, parent1, child2, &processed);
1403       }
1404
1405       GARY_FREE(clos_symbols);
1406     }
1407   }
1408
1409   GARY_FREE(processed);
1410
1411   if (conf_mutate_children)
1412   {
1413     if (randdouble() < conf_mutate_children_prob) perform_mutation(child1);
1414     else hide_segment_labels(child1);
1415
1416     if (randdouble() < conf_mutate_children_prob) perform_mutation(child2);
1417     else hide_segment_labels(child2);
1418   }
1419
1420   buffer[0] = child1;
1421   buffer[1] = child2;
1422   return buffer;
1423 }
1424
1425 void mutate(void)
1426 {
1427   for (int i=0; i < mutate_pop_size; i++)
1428   {
1429     if (dbg_mutation >= VERBOSITY_INDIVIDUAL)
1430       printf("Creating %d-th individual by mutation\n", i);
1431     int ind = randint(0, mutate_rbest_size);
1432     if (dbg_mutation >= VERBOSITY_INDIVIDUAL)
1433       printf("Mutating %d-th individual of original population\n", ind);
1434     population2[pop2_ind] = ep_alloc(ep_individuals);
1435     copy_individual(population1[ind], population2[pop2_ind]);
1436     if (dbg_mutation >= VERBOSITY_INDIVIDUAL)
1437       printf("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       if (dbg_mutation >= VERBOSITY_PLACEMENT)
1453         printf("Mutation: Moving symbol in placement %u\n", i);
1454       move_symbol(&(individual->placements[i]));
1455       continue;
1456     }
1457     acc += conf_mutate_move_bound;
1458
1459     if (x <= acc + conf_mutate_regen_bound)
1460     {
1461       gen_coords(&(individual->placements[i]));
1462       continue;
1463     }
1464     acc += conf_mutate_regen_bound;
1465
1466     if (x <= acc + conf_mutate_chvar_bound)
1467     {
1468       struct placement *p = &(individual->placements[i]);
1469       switch (p->request->type)
1470       {
1471         case REQUEST_POINT:
1472         case REQUEST_AREA:
1473           // Does nothing when there are 0 variants... does it mind?
1474           p->variant_used = randint(-1, GARY_SIZE(p->request->variants));
1475           break;
1476         case REQUEST_SEGMENT:
1477           p->variant_used = randint(0, GARY_SIZE(p->request->variants));
1478           break;
1479         case REQUEST_SECTION:
1480           p->variant_used = randint(0, GARY_SIZE(((struct request_section *) p->request)->segments));
1481           break;
1482         default:
1483           ;
1484       }
1485     }
1486   }
1487
1488   hide_segment_labels(individual);
1489 }
1490
1491 void elite(void)
1492 {
1493   for (int i=0; i<elite_pop_size; i++)
1494   {
1495     if (dbg_evolution >= VERBOSITY_INDIVIDUAL)
1496     {
1497       printf("Iteration %d: Copying individual #%d from pop 1 to #%d in pop 2\n", iteration, i, pop2_ind);
1498     }
1499     population2[pop2_ind] = ep_alloc(ep_individuals);
1500     copy_individual(population1[i], population2[pop2_ind++]);
1501   }
1502 }
1503
1504 int overlaps(struct placement *p1, struct placement *p2)
1505 {
1506   if (p1->request->type != REQUEST_POINT &&
1507       p1->request->type != REQUEST_SEGMENT &&
1508       p1->request->type != REQUEST_AREA)
1509     return 0;
1510
1511   if (p2->request->type != REQUEST_POINT &&
1512       p2->request->type != REQUEST_SEGMENT &&
1513       p2->request->type != REQUEST_AREA)
1514     return 0;
1515
1516   if (p1->variant_used == -1 || p2->variant_used == -1)
1517     return 0;
1518
1519   struct variant *v1, *v2;
1520
1521   v1 = &(p1->request->variants[p1->variant_used]);
1522   v2 = &(p2->request->variants[p2->variant_used]);
1523
1524   // FIXME: This doesn't fully respect offset which it probably should
1525   int p1x = p1->x; int p1y = p1->y;
1526   int p2x = p2->x; int p2y = p2->y;
1527
1528   int overlap = 0;
1529   for (int y=max2(0, max2(p1y, p2y)); y<min2(page_height_int, min2(p1y+v1->height, p2y+v2->height)); y++)
1530     for (int x=max2(0, max2(p1x, p2x)); x<min2(page_width_int, min2(p1x+v1->width, p2x+v2->width)); x++)
1531     {
1532       if (v1->bitmap[(y-p1y)*v1->width + (x-p1x)] &&
1533           v2->bitmap[(y-p2y)*v2->width + (x-p2x)])
1534         overlap++;
1535     }
1536
1537   return overlap;
1538 }
1539
1540 int get_overlap(struct placement *p, int **planned_ptr, int iteration)
1541 {
1542   int *planned = *planned_ptr;
1543
1544   if (p->variant_used == -1) return 0;
1545
1546   struct map_part **parts = get_map_parts(p);
1547   if (! parts)
1548   {
1549     if (dbg_overlaps >= VERBOSITY_PLACEMENT)
1550       printf("Placement of request %d seems not to be placed\n", p->request->ind);
1551     return 0;
1552   }
1553
1554   struct placement **others;
1555
1556   planned[p->request->ind] = iteration;
1557   GARY_INIT(others, 0);
1558
1559 //printf("Iterating over parts of placement %d (at [%.2f; %.2f] / %d)\n", p->ind, p->x, p->y, p->variant_used);
1560   for (uns i=0; i<GARY_SIZE(parts); i++)
1561   {
1562   //printf("%d:\t", parts[i]->ind);
1563   //dump_part_links(parts[i]);
1564     struct map_placement *mp = parts[i]->placement->next_in_map;
1565     while (mp)
1566     {
1567       if (planned[mp->placement->request->ind] != iteration)
1568       {
1569         struct placement **p = GARY_PUSH(others);
1570         *p = mp->placement;
1571         planned[mp->placement->request->ind] = iteration;
1572       }
1573       mp = mp->next_in_map;
1574     }
1575   }
1576
1577   int overlap = 0;
1578   for (uns i=0; i<GARY_SIZE(others); i++)
1579   {
1580     overlap += overlaps(p, others[i]);
1581   }
1582
1583   GARY_FREE(parts);
1584   GARY_FREE(others);
1585
1586   if (dbg_overlaps >= VERBOSITY_PLACEMENT)
1587   {
1588     printf("Placement %d (of request %d) add %d to overlaps", p->ind, p->request->ind, overlap);
1589     dump_placement_links(p);
1590   }
1591
1592   if (p->x < 0) overlap += 0 - p->x;
1593   if (p->x + p->request->variants[p->variant_used].width > page_width_int)
1594     overlap += p->x + p->request->variants[p->variant_used].width - page_width_int;
1595
1596   if (p->y < 0) overlap += 0 - p->y;
1597   if (p->y + p->request->variants[p->variant_used].height > page_height_int)
1598     overlap += p->y + p->request->variants[p->variant_used].height - page_height_int;
1599
1600   return overlap;
1601 }
1602
1603 int individual_overlap(struct individual *individual)
1604 {
1605   int overlap = 0;
1606
1607   int *planned;
1608   GARY_INIT_ZERO(planned, GARY_SIZE(individual->placements));
1609
1610   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
1611   {
1612     overlap += get_overlap(&individual->placements[i], &planned, i+1);
1613   }
1614
1615   GARY_FREE(planned);
1616
1617 //  printf("Total overlap is %d\n", overlap);
1618
1619   return overlap;
1620 }
1621
1622 double get_distance(struct placement *p)
1623 {
1624   if (p->variant_used < 0) return 0;
1625   struct variant *v = &p->request->variants[p->variant_used];
1626
1627   double dx, dy, distance;
1628   switch (p->request->type)
1629   {
1630     case REQUEST_POINT: ;
1631       struct request_point *rp = (struct request_point *) p->request;
1632       dx = rp->x + v->offset_x - p->x;
1633       dy = rp->y + v->offset_y - p->y;
1634       distance = hypot(dx, dy);
1635       if (dbg_rank >= VERBOSITY_PLACEMENT)
1636         printf("Point placed at [%.2f; %.2f], expected at [%.2f; %.2f]\n", p->x, p->y, rp->x, rp->y);
1637       break;
1638     case REQUEST_SEGMENT: ;
1639       struct request_segment *rs = (struct request_segment *) p->request;
1640       struct sym_text *st = (struct sym_text *) rs->label;
1641
1642       double width = p->request->variants[p->variant_used].width;
1643       double rotated_x = p->x + width * sin(st->rotate / (-180 / M_PI));
1644       double rotated_y = p->y + width * cos(st->rotate / (-180 / M_PI));
1645
1646       if (rs->x1 < rs->x2)
1647       {
1648         if (p->x < rs->x1)
1649         {
1650           dx = rs->x1 - p->x;
1651           dy = rs->y1 - p->y;
1652         }
1653         else if (rotated_x > rs->x2)
1654         {
1655           dx = rotated_x - rs->x2;
1656           dy = rotated_y - rs->y2;
1657         }
1658         else
1659         {
1660           dx = dy = 0;
1661         }
1662       }
1663       else
1664       {
1665         if (p->x < rs->x2)
1666         {
1667           dx = rs->x2 - p->x;
1668           dy = rs->y2 - p->y;
1669         }
1670         else if (rotated_x > rs->x1)
1671         {
1672           dx = rotated_x - rs->x1;
1673           dy = rotated_y - rs->y1;
1674         }
1675         else
1676         {
1677           dx = dy = 0;
1678         }
1679       }
1680
1681       distance = hypot(dx, dy);
1682       break;
1683     case REQUEST_AREA: ;
1684       struct request_area *ra = (struct request_area *) p->request;
1685       dx = ra->cx + v->offset_x - p->x;
1686       dy = ra->cy + v->offset_y - p->y;
1687       distance = hypot(dx, dy);
1688       if (dbg_rank >= VERBOSITY_PLACEMENT)
1689         printf("Area placed at [%.2f; %.2f], expected at [%.2f; %.2f]\n", p->x, p->y, ra->cx, ra->cy);
1690       break;
1691     default:
1692       return 0;
1693   }
1694
1695   if (dbg_rank >= VERBOSITY_PLACEMENT)
1696     printf("Placement %d has distance %.2f\n", p->ind, distance);
1697   return distance;
1698 }
1699
1700 double individual_distances(struct individual *individual)
1701 {
1702   int distances = 0;
1703
1704   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
1705   {
1706     distances += get_distance(&individual->placements[i]);
1707   }
1708
1709   return distances;
1710 }
1711
1712 double get_omittment(struct placement *p)
1713 {
1714   if (p->variant_used >= 0) return 0;
1715
1716   // FIX ME :)
1717   switch (p->request->type)
1718   {
1719     case REQUEST_POINT:
1720     case REQUEST_AREA:
1721       return 10;
1722       break;
1723     default:
1724       return 0;
1725   }
1726 }
1727
1728 double individual_omittment(struct individual *individual)
1729 {
1730   int omittment = 0;
1731
1732   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
1733   {
1734     omittment += get_omittment(&individual->placements[i]);
1735   }
1736
1737   return omittment;
1738 }
1739
1740 int cmp_individual(const void *a, const void *b)
1741 {
1742   struct individual **ia = (struct individual **) a;
1743   struct individual **ib = (struct individual **) b;
1744
1745   return (*ia)->penalty - (*ib)->penalty;
1746 }
1747
1748 void rank_population(void)
1749 {
1750   int penalty;
1751
1752   for (int i=0; i<conf_pop_size; i++)
1753   {
1754     if (dbg_rank >= VERBOSITY_INDIVIDUAL)
1755       printf("Individual %d\n", i);
1756     population1[i]->penalty = 0;
1757
1758     penalty = individual_omittment(population1[i]);
1759     if (dbg_rank >= VERBOSITY_INDIVIDUAL)
1760       printf("Increasing penalty by %d for omittment\n", penalty);
1761     population1[i]->penalty += penalty;
1762
1763     penalty = individual_overlap(population1[i]);
1764     if (dbg_rank >= VERBOSITY_INDIVIDUAL)
1765       printf("Increasing penalty by %d for overlap\n", penalty);
1766     population1[i]->penalty += penalty;
1767
1768     penalty = individual_distances(population1[i]);
1769     if (dbg_rank >= VERBOSITY_INDIVIDUAL)
1770       printf("Increasing penalty by %d for distances\n", penalty);
1771     population1[i]->penalty += penalty;
1772   }
1773 }
1774
1775 struct map_part **get_map_parts(struct placement *p)
1776 {
1777   if (p->variant_used < 0) return NULL;
1778
1779   struct map_part **buffer;
1780   GARY_INIT(buffer, 0);
1781
1782   if (dbg_map_parts >= VERBOSITY_PLACEMENT)
1783     printf("Looking for map parts containing placement of request %d, placed at [%.2f; %.2f]\n", p->request->ind, p->x, p->y);
1784
1785   struct variant v;
1786   switch (p->request->type)
1787   {
1788     case REQUEST_POINT:
1789     case REQUEST_SEGMENT:
1790     case REQUEST_AREA:
1791       v = p->request->variants[p->variant_used];
1792       break;
1793     default:
1794       if (dbg_map_parts >= VERBOSITY_ALL)
1795         printf("Skipping unsupported request type (%d)\n", p->request->type);
1796       return NULL;
1797   }
1798
1799   if (dbg_map_parts >= VERBOSITY_PLACEMENT)
1800     printf("Bitmap is %d x %d\n", v.width, v.height);
1801
1802   int x_min = max2(0, p->x) / conf_map_part_width;
1803   // CHECK ME: Is rounding needed?
1804   int x_max = min2(page_width_int, (p->x + v.width)) / conf_map_part_width;
1805   int y_min = max2(0, p->y) / conf_map_part_height;
1806   // CHECK ME: Is rounding needed?
1807   int y_max = min2(page_height_int, (p->y + v.height)) / conf_map_part_height;
1808
1809   if (dbg_map_parts >= VERBOSITY_PLACEMENT)
1810     printf("Cells between [%d; %d] and [%d; %d] generated\n", x_min, y_min, x_max, y_max);
1811
1812   for (int y=y_min; y<=y_max; y++)
1813     for (int x=x_min; x<=x_max; x++)
1814     {
1815       struct map_part **m = GARY_PUSH(buffer);
1816       if (dbg_map_parts >= VERBOSITY_ALL)
1817         printf("Asking for %d of %zu\n", y * num_map_parts_row + x, GARY_SIZE(p->individual->map));
1818       *m = p->individual->map[y * num_map_parts_row + x];
1819     }
1820
1821   if (dbg_map_parts >= VERBOSITY_PLACEMENT)
1822     printf("Returning %zu map parts potentially containing the symbol\n", GARY_SIZE(buffer));
1823
1824   return buffer;
1825 }
1826
1827 void update_map_parts_delete(struct placement *p)
1828 {
1829   struct map_placement *mp = p->map_links;
1830   while (mp)
1831   {
1832     mp->prev_in_map->next_in_map = mp->next_in_map;
1833     if (mp->next_in_map)
1834       mp->next_in_map->prev_in_map = mp->prev_in_map;
1835
1836     struct map_placement *tmp = mp;
1837     mp = mp->next_in_placement;
1838     free(tmp);
1839   }
1840   p->map_links = NULL;
1841 }
1842
1843 void update_map_parts_create(struct placement *p)
1844 {
1845   struct map_part **parts = get_map_parts(p);
1846   if (parts == NULL) return;
1847
1848   for (uns i=0; i<GARY_SIZE(parts); i++)
1849   {
1850     struct map_placement *mp = xmalloc(sizeof(struct map_placement));
1851     mp->placement = p;
1852     mp->part = parts[i];
1853
1854     mp->next_in_map = parts[i]->placement->next_in_map;
1855     mp->prev_in_map = parts[i]->placement;
1856     parts[i]->placement->next_in_map = mp;
1857     if (mp->next_in_map) mp->next_in_map->prev_in_map = mp;
1858
1859     mp->next_in_placement = p->map_links;
1860     mp->prev_in_placement = NULL;
1861     p->map_links = mp;
1862   }
1863
1864   GARY_FREE(parts);
1865 }
1866
1867 void update_map_parts(struct placement *p)
1868 {
1869   update_map_parts_delete(p);
1870   update_map_parts_create(p);
1871 }
1872
1873 void gen_coords(struct placement *p)
1874 {
1875   switch(p->request->type)
1876   {
1877     case REQUEST_POINT:
1878       gen_coords_point(p);
1879       break;
1880     case REQUEST_AREA:
1881       gen_coords_area(p);
1882       break;
1883     case REQUEST_SEGMENT:
1884       gen_coords_segment(p);
1885       break;
1886     case REQUEST_LINE:
1887       if (dbg_movement)
1888         printf("Not yet implemented\n");
1889       break;
1890     default:
1891       if (dbg_movement >= VERBOSITY_ALL)
1892         printf("Testing request type\n");
1893       ASSERT(p->request->type != REQUEST_INVALID);
1894   }
1895
1896   update_map_parts(p);
1897 }
1898
1899 double gen_movement(void)
1900 {
1901   double m = (random() % 100000) / 10000;
1902   m = pow(m, 1.0/3) * flip(1, -1);
1903   if (dbg_movement >= VERBOSITY_ALL)
1904     printf("Movement %.2f\n", m);
1905   return m;
1906 }
1907
1908 double gen_movement_uniform(void)
1909 {
1910   return (move_max - move_min) * randdouble() * flip(1, -1);
1911 }
1912
1913 void gen_coords_point(struct placement *p)
1914 {
1915   p->x = p->x + gen_movement();
1916 }
1917
1918 void gen_coords_segment(struct placement *p)
1919 {
1920   struct request_segment *rs = (struct request_segment *) p->request;
1921   p->x = (rs->x1 + rs->x2) / 2;
1922   p->y = (rs->y1 + rs->y2) / 2;
1923 }
1924
1925 void gen_coords_area(struct placement *p)
1926 {
1927   struct request_area *ra = (struct request_area *) p->request;
1928
1929   p->x = p->x + gen_movement();
1930   p->y = p->y + gen_movement();
1931
1932   if (dbg_movement >= VERBOSITY_PLACEMENT)
1933     printf("Moved label to [%.2f; %.2f] from [%.2f; %.2f]\n", p->x, p->y, ra->cx, ra->cy);
1934 }
1935
1936 int randint(int min, int max)
1937 {
1938   if (min == max) return min;
1939   int r = random();
1940   return min + (r % (max - min));
1941 }
1942
1943 struct placement **get_closure(struct placement *placement)
1944 {
1945   struct placement **closure;
1946   GARY_INIT(closure, 0);
1947   bool *chosen = xmalloc(GARY_SIZE(placement->individual->placements) * sizeof(bool));
1948   for (uns i=0; i<GARY_SIZE(placement->individual->placements); i++) { chosen[i] = 0; }
1949   chosen[placement->request->ind] = 1;
1950
1951   struct placement **p = GARY_PUSH(closure); *p = placement;
1952
1953   uns first = 0;
1954   while (first < GARY_SIZE(closure))
1955   {
1956     if (dbg_breeding >= VERBOSITY_ALL)
1957       printf("Iterating, first is %u of current %zu\n", first, GARY_SIZE(closure));
1958     struct placement **overlapping = get_overlapping(placement);
1959     if (! overlapping) { first++; continue; }
1960
1961     struct placement **filtered = filter(overlapping, &chosen);
1962     if (dbg_breeding >= VERBOSITY_ALL)
1963       printf("There are %zu new overlapping symbols\n", GARY_SIZE(filtered));
1964     GARY_FREE(overlapping);
1965     overlapping = filtered;
1966     for (uns j=0; j<GARY_SIZE(overlapping); j++)
1967     {
1968       if (! chosen[overlapping[j]->request->ind])
1969       {
1970         if (overlaps(*p, overlapping[j]))
1971         {
1972           p = GARY_PUSH(closure); *p = overlapping[j];
1973           if (dbg_breeding >= VERBOSITY_ALL)
1974             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);
1975           chosen[overlapping[j]->request->ind] = 1;
1976         }
1977       }
1978     }
1979     GARY_FREE(overlapping);
1980     first++;
1981   }
1982
1983   free(chosen);
1984
1985   return closure;
1986 }
1987
1988 void copy_symbols(struct placement **closure, struct individual *parent, struct individual *child, bool **processed_ptr)
1989 {
1990   bool *processed = *processed_ptr;
1991   if (dbg_breeding >= VERBOSITY_ALL)
1992     printf("Will copy %zu symbols\n", GARY_SIZE(closure));
1993
1994   for (uns i=0; i<GARY_SIZE(closure); i++)
1995   {
1996     processed[closure[i]->ind] = 1;
1997     int ind = closure[i]->ind;
1998     child->placements[ind] = parent->placements[ind];
1999     child->placements[ind].individual = child;
2000     child->placements[ind].processed = 0;
2001     child->placements[ind].map_links = NULL;
2002     update_map_parts(&child->placements[ind]);
2003   }
2004 }
2005
2006 void move_symbol(struct placement *p)
2007 {
2008   switch (p->request->type)
2009   {
2010     case REQUEST_POINT:
2011     case REQUEST_AREA:
2012       move_symbol_point(p);
2013       break;
2014     case REQUEST_SEGMENT:
2015       move_symbol_segment(p);
2016       break;
2017     default:
2018       ASSERT(p->request->type != REQUEST_INVALID);
2019   }
2020 }
2021
2022 void move_symbol_point(struct placement *p)
2023 {
2024   p->x += gen_movement_uniform();
2025   p->y += gen_movement_uniform();
2026 }
2027
2028 void move_symbol_segment(struct placement *p)
2029 {
2030   double m = gen_movement_uniform();
2031   // CHECK ME
2032   p->x += m;
2033   p->y += m * ((struct request_segment *) p->request)->slope;
2034 }
2035
2036 void hide_segment_labels(struct individual *individual)
2037 {
2038   // BEWARE: This fully depends on current genetic encoding
2039
2040   int used = -1, num = -1;
2041   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
2042   {
2043     switch (individual->placements[i].request->type)
2044     {
2045       case REQUEST_SECTION:
2046         used = individual->placements[i].variant_used;
2047         num = 0;
2048         break;
2049       case REQUEST_SEGMENT:
2050         if (num == used)
2051           individual->placements[i].variant_used = 0;
2052         else
2053           individual->placements[i].variant_used = -1;
2054         num++;
2055         break;
2056       default:
2057         ;
2058     }
2059   }
2060 }
2061
2062 void init_placement(struct placement *p, struct individual *individual, struct request *r)
2063 {
2064   p->ind = num_placements++;
2065   p->request = r;
2066   p->processed = 0;
2067   p->x = p->y = 0; // To prevent valgrind from complaining
2068   p->variant_used = 0;
2069   p->map_links = NULL;
2070   p->individual = individual;
2071   switch (r->type)
2072   {
2073     case REQUEST_POINT: ;
2074       struct request_point *rp = (struct request_point *) r;
2075       p->x = rp->x;
2076       p->y = rp->y;
2077       break;
2078     case REQUEST_LINE: ;
2079       break;
2080     case REQUEST_SECTION: ;
2081       struct request_section *rls = (struct request_section *) r;
2082       p->variant_used = randint(0, rls->num_segments);
2083       break;
2084     case REQUEST_SEGMENT: ;
2085       struct request_segment *rs = (struct request_segment *) r;
2086       p->x = rs->x2;
2087       p->y = rs->y2;
2088       break;
2089     case REQUEST_AREA: ;
2090       struct request_area *ra = (struct request_area *) r;
2091       p->x = ra->cx;
2092       p->y = ra->cy;
2093       p->variant_used = 0;
2094       break;
2095     default:
2096       ASSERT(p->request->type != REQUEST_INVALID);
2097   }
2098
2099   gen_coords(p);
2100   if (dbg_init >= VERBOSITY_PLACEMENT)
2101     printf("Inited placement to [%.2f; %.2f]\n", p->x, p->y);
2102 }
2103
2104 /**
2105 void reset_individual_map(struct individual *i)
2106 {
2107   for (uns j=0; j<num_map_parts; j++)
2108   {
2109     struct map_placement *mp = i->map[j]->placement;
2110     while (mp)
2111     {
2112       struct map_placement *tmp = mp;
2113       mp = mp->next_in_map;
2114       free(tmp);
2115     }
2116
2117     free(i->map[j]);
2118     struct map_part *part = xmalloc(sizeof(struct map_part));
2119     part->ind = j;
2120
2121     mp = xmalloc(sizeof(struct map_placement));
2122     part->placement = mp;
2123     mp->placement = &dummy_placement;
2124     mp->next_in_map = mp->prev_in_map = NULL;
2125     mp->next_in_placement = mp->prev_in_placement = NULL;
2126     i->map[j] = part;
2127   }
2128 }
2129 **/
2130
2131 /**
2132 void update_individual(struct individual *individual)
2133 {
2134   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
2135   {
2136     update_map_parts_delete(&individual->placements[i]);
2137   }
2138 }
2139 **/
2140
2141 void clear_individual(struct individual *individual)
2142 {
2143   for (uns j=0; j<num_map_parts; j++)
2144   {
2145     struct map_placement *mp = individual->map[j]->placement;
2146     while (mp)
2147     {
2148       struct map_placement *tmp = mp;
2149       mp = mp->next_in_map;
2150       free(tmp);
2151     }
2152
2153     free(individual->map[j]);
2154   }
2155
2156   GARY_FREE(individual->map);
2157   GARY_FREE(individual->placements);
2158   ep_free(ep_individuals, individual);
2159 }
2160
2161 void clear_population(struct individual **pop)
2162 {
2163   for (uns i=0; i<GARY_SIZE(pop); i++)
2164   {
2165     clear_individual(pop[i]);
2166   }
2167 }
2168
2169 struct placement **get_overlapping(struct placement *p)
2170 {
2171   struct placement **buffer;
2172   GARY_INIT(buffer, 0);
2173
2174   struct map_part **parts = get_map_parts(p);
2175   if (! parts) return NULL;
2176
2177   for (uns i=0; i<GARY_SIZE(parts); i++)
2178   {
2179     struct map_placement *mp = parts[i]->placement->next_in_map;
2180     while (mp)
2181     {
2182       if (p->variant_used >= 0)
2183       {
2184         struct placement **p = GARY_PUSH(buffer);
2185         *p = mp->placement;
2186       }
2187       mp = mp->next_in_map;
2188     }
2189   }
2190   GARY_FREE(parts);
2191
2192   if (dbg_map_parts >= VERBOSITY_PLACEMENT)
2193     printf("Returning %zu potentially overlapping placements\n", GARY_SIZE(buffer));
2194
2195   return buffer;
2196 }
2197
2198 struct placement **filter(struct placement **list, bool **pred_ptr)
2199 {
2200   bool *pred = *pred_ptr; // As GARY can't be passed directly
2201   struct placement **filtered;
2202   GARY_INIT(filtered, 0);
2203
2204   for (uns i=0; i<GARY_SIZE(list); i++)
2205   {
2206     if (pred[list[i]->request->ind])
2207       continue;
2208
2209     struct placement **p = GARY_PUSH(filtered);
2210     *p = list[i];
2211   }
2212
2213   return filtered;
2214 }
2215
2216 int flip(int a, int b)
2217 {
2218   return (random() % 2 ? a : b);
2219 }
2220
2221 double randdouble(void)
2222 {
2223   return ((double) rand() / (double) RAND_MAX);
2224 }
2225
2226 void init_individual(struct individual *individual)
2227 {
2228   GARY_INIT(individual->placements, num_requests);
2229   GARY_INIT(individual->map, 0);
2230   for (uns j=0; j<num_map_parts; j++)
2231   {
2232     GARY_PUSH(individual->map);
2233     struct map_part *part = xmalloc(sizeof(struct map_part));
2234     struct map_placement *mp = xmalloc(sizeof(struct map_placement));
2235     part->placement = mp;
2236     part->ind = j;
2237     mp->placement = &dummy_placement;
2238     mp->next_in_map = mp->prev_in_map = NULL;
2239     mp->next_in_placement = mp->prev_in_placement = NULL;
2240     individual->map[j] = part;
2241   }
2242   individual->penalty = 0;
2243 }
2244
2245 void copy_individual(struct individual *src, struct individual *dest)
2246 {
2247   init_individual(dest);
2248   dest->penalty = src->penalty;
2249
2250   for (uns i=0; i<GARY_SIZE(src->placements); i++)
2251   {
2252     dest->placements[i] = src->placements[i];
2253     dest->placements[i].map_links = NULL;
2254     dest->placements[i].individual = dest;
2255
2256     update_map_parts_create(&dest->placements[i]);
2257   }
2258 }