]> mj.ucw.cz Git - leo.git/blob - labeller.c
Labelling: Using slope for segments
[leo.git] / labeller.c
1 #include <errno.h>
2
3 #include <ucw/lib.h>
4 #include <ucw/gary.h>
5 #include <ucw/mempool.h>
6 #include <ucw/eltpool.h>
7
8 #include "leo.h"
9 #include "sym.h"
10 #include "map.h"
11 #include "labeller.h"
12
13 #define HASH_NODE struct graph_node
14 #define HASH_PREFIX(x) hash_##x
15 #define HASH_KEY_ATOMIC id
16 #define HASH_WANT_FIND
17 #define HASH_WANT_NEW
18 #define HASH_WANT_CLEANUP
19 #include <ucw/hashtable.h>
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <math.h>
24 #include <fcntl.h>
25
26 #define BLOCK_SIZE 4096
27
28 //struct mempool *mpool_requests;
29
30 static struct request_point *requests_point;
31 static struct request_line *requests_line;
32 static struct request_area *requests_area;
33
34 static struct graph_edge **bfs_queue;
35 static struct longline *longlines; int num_longlines;
36 static struct buffer_line *buffer_line;
37 static struct buffer_linelabel *buffer_linelabel;
38
39 struct eltpool *ep_individuals;
40
41 struct individual **population1;
42 struct individual **population2;
43
44 int dbg_segments = 0;
45 int dbg_plan = 0;
46 int dbg_requests = 0;
47 int dbg_graph = 0;
48 int dbg_bfs = 0;
49 int dbg_map_parts = 0;
50 int dbg_movement = 0;
51 int dbg_init = 0;
52 int dbg_overlaps = 0;
53 int dbg_rank = 0;
54 int dbg_evolution = 0;
55 int dbg_mutation = 0;
56
57 int page_width_int;
58 int page_height_int;
59
60 int num_edges_dbg;
61 int num_nodes;
62 int num_edges = 0;
63 int dbg_num_hits = 0;
64
65 int conf_pop_size = 50;
66
67 int conf_penalty_bound = 0;
68 int conf_stagnation_bound = 0;
69 int conf_iteration_limit = 4;
70
71 int conf_term_cond = TERM_COND_ITERATIONS;
72
73 int conf_breed_rbest_perc = 80;
74 int conf_breed_pop_size_perc = 20;
75 int conf_breed_perc = 50;                       // Percentage of new pop created by breeding
76
77 bool conf_mutate_children = 1;
78 double conf_mutate_children_prob = 0.3;
79
80 double conf_mutate_rbest = 1;
81 double conf_mutate_pop_size = 0.9;
82
83 double conf_mutate_move_bound = 1.0;
84 double conf_mutate_regen_bound = 0.0;
85 double conf_mutate_chvar_bound = 0.0;
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 = 100;
94 double conf_max_section_overlay = 10;
95
96 int old_best = 0; // FIXME: Shall be int max
97 int iteration = 0;
98 int pop2_ind;
99
100 int conf_part_size = 50;
101
102 int move_min = 0;
103 int move_max = 1;
104
105 int num_requests = 0;
106
107 int conf_map_part_width = 5;
108 int conf_map_part_height = 5;
109 int num_map_parts_row;
110 int num_map_parts_col;
111 int num_map_parts;
112
113 void make_graph(void);
114 void label_graph(void);
115 void join_edge(struct graph_edge *e, int dir);
116 void bfs(uns longline);
117 void make_segments(void);
118
119 int overlaps(struct placement *p1, struct placement *p2);
120 int get_overlap(struct placement *p);
121 int individual_overlap(struct individual *individual);
122
123 void make_population(void);
124 bool shall_terminate(void);
125 void breed(void);
126 void mutate(void);
127 void elite(void);
128 void rank_population(void);
129 void plan_individual(struct individual *individual);
130
131 int cmp_individual(const void *a, const void *b);
132
133 void make_bitmap(struct variant *v, struct symbol *sym);
134 void make_bitmap_icon(struct variant *v, struct sym_icon *si);
135 void make_bitmap_point(struct variant *v, struct sym_point *sp);
136 void make_bitmap_label(struct variant *v, struct sym_text *text);
137
138 void cut_edge(struct graph_edge *e, double dist);
139 struct request_line *make_new_line(void);
140 struct request_section *make_new_section(struct request_line *rl);
141 struct request_segment *make_new_segment(struct request_section *rls, struct symbol *sym);
142
143 void dump_bitmaps(struct individual *individual);
144 void dump_graph(void);
145 void bfs2(void);
146 void bfs_edge(struct graph_edge *e, struct graph_node *node, struct graph_node *anode, enum edge_dir dir);
147 void bfs_wrapper(void);
148 void oldbfs(void);
149 void dump_longlines(void);
150 void dump_linelabel_requests(void);
151 void dump_individual(struct individual *individual);
152 void print_label(struct symbol *sym);
153 void dump_penalties(void);
154
155 double gen_movement(void);
156 double gen_movement_uniform(void);
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
165 void make_segments_old(void);
166
167 void labeller_cleanup(void);
168
169 struct individual **perform_crossover(struct individual *parent1, struct individual *parent2);
170 void perform_mutation(struct individual *individual);
171
172 void hide_segment_labels(struct individual *individual);
173 void init_placement(struct placement *p, struct individual *individual, struct request *r);
174 void init_individual(struct individual *i);
175 struct map_part **get_parts(struct placement *symbol, struct individual *individual);
176
177 int randint(int min, int max);
178
179 struct placement **get_closure(struct placement *placement, struct individual *parent1, struct individual *parent2);
180 void copy_symbols(struct placement **closure, struct individual *parent, struct individual *child);
181 void move_symbol(struct placement *p);
182 void move_symbol_point(struct placement *p);
183 void move_symbol_segment(struct placement *p);
184
185 struct placement **get_overlapping(struct placement *p);
186 void filter(struct placement **list, bool *pred);
187
188 int flip(int a, int b);
189 double randdouble(void);
190
191 void cleanup(void);
192
193 void copy_individual(struct individual *src, struct individual *dest);
194
195 int max2(int a, int b);
196 int min2(int a, int b);
197 int max4(int a, int b, int c, int d);
198 int min4(int a, int b, int c, int d);
199
200 struct placement dummy_placement;
201
202 int max2(int a, int b)
203 {
204   return (a > b ? a : b);
205 }
206
207 int min2(int a, int b)
208 {
209   return (a < b ? a : b);
210 }
211
212 int max4(int a, int b, int c, int d)
213 {
214   return max2(max2(a, b), max2(c, d));
215 }
216
217 int min4(int a, int b, int c, int d)
218 {
219   return min2(min2(a, b), min2(c, d));
220 }
221
222 void print_label(struct symbol *sym)
223 {
224   switch (sym->type)
225   {
226     case SYMBOLIZER_TEXT: ;
227       struct sym_text *st = (struct sym_text *) sym;
228       printf("%s\n", osm_val_decode(st->text));
229     default:
230       // FIXME
231       ;
232   }
233 }
234
235 void labeller_init(void)
236 {
237   GARY_INIT(requests_point, 0);
238   GARY_INIT(requests_line, 0);
239   GARY_INIT(requests_area, 0);
240   GARY_INIT(buffer_line, 0);
241   GARY_INIT(buffer_linelabel, 0);
242   ep_individuals = ep_new(sizeof(struct individual), 1);
243
244   page_width_int = floor(page_width);
245   page_height_int = floor(page_height);
246
247   num_map_parts_row = (page_width_int + conf_map_part_width) / conf_map_part_width;
248   num_map_parts_col = (page_height_int + conf_map_part_height) / conf_map_part_height;
249   num_map_parts = num_map_parts_row * num_map_parts_col;
250 }
251
252 void make_bitmap(struct variant *v, struct symbol *sym)
253 {
254   switch (sym->type)
255   {
256     case SYMBOLIZER_POINT:
257       make_bitmap_point(v, (struct sym_point *) sym);
258       break;
259     case SYMBOLIZER_ICON:
260       make_bitmap_icon(v, (struct sym_icon *) sym);
261       break;
262     case SYMBOLIZER_TEXT:
263       make_bitmap_label(v, (struct sym_text *) sym);
264       break;
265     default:
266       ASSERT(sym->type != SYMBOLIZER_INVALID);
267   }
268 }
269
270 void make_bitmap_icon(struct variant *v, struct sym_icon *si)
271 {
272   v->width = si->sir.width + 1;
273   v->height = si->sir.height + 1;
274   v->bitmap = malloc(v->width * v->height * sizeof(bool));
275   for (int i=0; i<v->width*v->height; i++) v->bitmap[i] = 1;
276 }
277
278 void make_bitmap_point(struct variant *v, struct sym_point *sp)
279 {
280   v->width = v->height = sp->size + 1;
281   v->bitmap = malloc(v->width * v->height * sizeof(bool));
282   // FIXME: Okay, memset would be much nicer here
283   for (int i=0; i<sp->size*sp->size; i++) v->bitmap[i] = 1;
284 }
285
286 void make_bitmap_label(struct variant *v, struct sym_text *text)
287 {
288   v->width = ceil(text->tw);
289   v->height = ceil(text->th);
290   v->bitmap = malloc(v->width * v->height * sizeof(bool));
291   for (int i=0; i<v->height; i++)
292     for (int j=0; j<v->width; j++)
293     {
294       v->bitmap[i*v->width + j] = 1;
295     }
296 }
297
298 void labeller_add_point(struct symbol *sym, struct osm_object *object, z_index_t zindex)
299 {
300   if (dbg_requests)
301     printf("Adding point\n");
302   if (object->type != OSM_TYPE_NODE)
303   {
304     printf("Warning: Point label requested on non-point object\n");
305     return;
306   }
307
308   struct request_point *r = GARY_PUSH(requests_point);
309
310   r->request.type = REQUEST_POINT;
311   r->request.ind = num_requests++;
312
313   r->sym = sym;
314   r->zindex = zindex;
315
316   r->offset_x = 0;
317   r->offset_y = 0;
318
319   r->num_variants = 1;
320   GARY_INIT(r->request.variants, 0);
321
322   struct variant *v = GARY_PUSH(r->request.variants);
323
324   struct osm_node *n = (struct osm_node *) object; // FIXME: Compiler warning
325   r->x = n->x;
326   r->y = n->y;
327   switch (sym->type)
328   {
329     case SYMBOLIZER_ICON:
330       make_bitmap_icon(v, (struct sym_icon *) sym);
331       r->x = ((struct sym_icon *)sym)->sir.x;
332       r->y = ((struct sym_icon *)sym)->sir.y;
333       break;
334     case SYMBOLIZER_POINT:
335       make_bitmap_point(v, (struct sym_point *) sym);
336       break;
337     case SYMBOLIZER_TEXT: ;
338       struct sym_text *st = (struct sym_text *) sym;
339       struct osm_node *n = (struct osm_node *) object;
340       make_bitmap_label(v, st);
341     default:
342       // FIXME
343       return;
344   }
345
346 //  printf("Inited point to [%.2f; %.2f] on %u\n", r->x, r->y, r->zindex);
347 }
348
349 void labeller_add_line(struct symbol *sym, z_index_t zindex)
350 {
351   if (dbg_requests)
352     printf("Adding line on %u\n", zindex);
353   struct buffer_line *b = GARY_PUSH(buffer_line);
354   b->line = (struct sym_line *) sym;
355   b->zindex = zindex;
356   sym_plan(sym, zindex);
357 }
358
359 void labeller_add_linelabel(struct symbol *sym, struct osm_object *o, z_index_t zindex)
360 {
361   if (o->type != OSM_TYPE_WAY)
362   {
363     // FIXME
364     return;
365   }
366
367   if (dbg_requests)
368     printf("[LAB] Labelling way %ju on %u\n", o->id, zindex);
369   struct buffer_linelabel *ll = GARY_PUSH(buffer_linelabel);
370   ll->way = (struct osm_way *) o;
371   ll->label = sym;
372   ll->zindex = zindex;
373 }
374
375 void labeller_add_arealabel(struct symbol *sym, struct osm_object *o, z_index_t zindex)
376 {
377   if (dbg_requests)
378     printf("Adding area on %u\n", zindex);
379   struct request_area *r = GARY_PUSH(requests_area);
380
381   r->request.type = REQUEST_AREA;
382   r->request.ind = num_requests++;
383
384   r->o = (struct osm_multipolygon *) o;
385   r->zindex = zindex;
386   r->label = sym;
387
388   osm_obj_center(o, &(r->cx), &(r->cy));
389
390   GARY_INIT(r->request.variants, 0);
391   struct variant *v = GARY_PUSH(r->request.variants);
392   switch (sym->type)
393   {
394     case SYMBOLIZER_ICON:
395       if (dbg_requests)
396         printf("DEBUG: Icon label\n");
397       make_bitmap_icon(v, (struct sym_icon *) sym);
398       break;
399     case SYMBOLIZER_TEXT:
400       if (dbg_requests)
401         printf("DEBUG: Text label\n");
402       make_bitmap_label(v, (struct sym_text *) sym);
403     default:
404       // FIXME
405       ;
406   }
407 }
408
409 void make_graph(void)
410 {
411   hash_init();
412   struct mempool *mp_edges = mp_new(BLOCK_SIZE);
413
414   printf("Extracting nodes, will iterate over %lld ways\n", GARY_SIZE(buffer_line));
415   for (uns i=0; i<GARY_SIZE(buffer_line); i++)
416   {
417     struct osm_way *way = (struct osm_way *) buffer_line[i].line->s.o;
418     struct graph_node *g_prev = NULL;
419     struct osm_node *o_prev = NULL;
420
421     CLIST_FOR_EACH(struct osm_ref *, ref, way->nodes)
422     {
423       // FIXME: Shall osm_object's type be checked here?
424       struct osm_node *o_node = (struct osm_node *) ref->o;
425
426       struct graph_node *g_node = hash_find(ref->o->id);
427       if (!g_node)
428       {
429         g_node = hash_new(ref->o->id);
430         GARY_INIT(g_node->edges, 0);
431         g_node->o = o_node;
432         g_node->id = ref->o->id;
433         g_node->num = num_nodes++;
434       }
435
436       if (! g_prev)
437       {
438         g_prev = g_node;
439         o_prev = o_node;
440         continue;
441       }
442
443       struct graph_edge *e = mp_alloc(mp_edges, sizeof(struct graph_edge)); num_edges_dbg++;
444       e->num = num_edges++;
445       e->id = buffer_line[i].line->s.o->id;
446       e->color = buffer_line[i].line->color;
447       e->length = hypot(abs(o_prev->x - o_node->x), abs(o_prev->y - o_node->y));
448       e->visited = -1;
449       e->prev = NULL;
450       e->next = NULL;
451       e->n1 = g_prev;
452       e->n2 = g_node;
453       e->longline = (uns) -1;
454       e->line = buffer_line[i].line;
455       e->dir = DIR_UNSET;
456       e->label = NULL;
457
458       struct graph_edge **edge = GARY_PUSH(g_prev->edges);
459       *edge = e;
460       edge = GARY_PUSH(g_node->edges);
461       *edge = e;
462
463       g_prev = g_node;
464       o_prev = o_node;
465     }
466   }
467
468   printf("Made graph with %d edges\n", num_edges_dbg);
469 }
470
471 void dump_graph(void)
472 {
473   HASH_FOR_ALL(hash, node)
474   {
475     printf("* Node: (%d) #%ju [%.2f; %.2f]\n", node->num, node->id, node->o->x, node->o->y);
476     for (uns i=0; i<GARY_SIZE(node->edges); i++)
477     {
478       struct graph_edge *e = node->edges[i];
479       printf("\t edge (%d) #%ju to ", e->num, e->id);
480       if (node->edges[i]->n1->id == node->id)
481         printf("(%d) #%ju [%.2f; %.2f]\n", e->n2->num, e->n2->id, e->n2->o->x, e->n2->o->y);
482       else if (node->edges[i]->n2->id == node->id)
483         printf("(%d) #%ju [%.2f; %.2f]\n", e->n1->num, e->n1->id, e->n1->o->x, e->n1->o->y);
484       else
485         printf("BEWARE! BEWARE! BEWARE!\n");
486
487       printf("\t\t");
488       if ((node->edges[i]->label)) printf("Labelled\n");
489       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));
490       printf(" colored %d;", node->edges[i]->color);
491       printf("   length %.2f", node->edges[i]->length);
492       printf("\n");
493     }
494   }
495   HASH_END_FOR;
496 }
497
498 void label_graph(void)
499 {
500   if (dbg_graph)
501     printf("There are %u line labels requested\n", GARY_SIZE(buffer_linelabel));
502   for (uns i=0; i<GARY_SIZE(buffer_linelabel); i++)
503   {
504     if (buffer_linelabel[i].label->type == SYMBOLIZER_TEXT)
505     if (dbg_graph)
506       printf("Labelling nodes of way %s\n", osm_val_decode(((struct sym_text *) buffer_linelabel[i].label)->text));
507     CLIST_FOR_EACH(struct osm_ref *, ref, buffer_linelabel[i].way->nodes)
508     {
509       if (dbg_graph)
510         printf("Looking for node %ju\n", ref->o->id);
511       struct graph_node *n = hash_find(ref->o->id);
512       if (n == NULL)
513       {
514         // FIXME: What shall be done?
515       }
516       else
517       {
518         if (dbg_graph)
519           printf("Searching among %u edges\n", GARY_SIZE(n->edges));
520         for (uns j=0; j<GARY_SIZE(n->edges); j++)
521         {
522           if (n->edges[j]->id == buffer_linelabel[i].way->o.id)
523           {
524             if (dbg_graph)
525               printf("Labelling node %ju\n", n->id);
526             n->edges[j]->label = buffer_linelabel[i].label;
527             n->edges[j]->zindex = buffer_linelabel[i].zindex;
528           }
529         }
530       }
531     }
532   }
533 }
534
535 void bfs_edge(struct graph_edge *e, struct graph_node *node, struct graph_node *anode, enum edge_dir dir)
536 {
537   if (dbg_bfs)
538     printf("BFS edge called for edge %d (going %d) in direction %d\n", e->num, e->dir, dir);
539   struct graph_edge *candidate = NULL;
540
541   for (uns i=0; i<GARY_SIZE(node->edges); i++)
542   {
543     struct graph_edge *other = node->edges[i];
544     if ((other->longline != (uns) -1) && (other->longline != e->longline)) continue;
545
546     if ((uns) other->visited != e->longline) {
547     if (dbg_bfs)
548       printf("Pushing new edge %d / %ju\n", other->num, other->id);
549     struct graph_edge **e_ptr = GARY_PUSH(bfs_queue);
550     *e_ptr = other;
551     other->visited = e->longline;
552     }
553
554     if (((other->n1->id == node->id) && (other->n2->id == anode->id)) ||
555         ((other->n2->id == node->id) && (other->n1->id == anode->id)))
556         continue;
557
558     if (((other->n1->id == node->id) || (other->n2->id == node->id)) &&
559         (e->label) && (other->label) &&
560         (e->label->type == SYMBOLIZER_TEXT) && (other->label->type == SYMBOLIZER_TEXT) &&
561         (((struct sym_text *) e->label)->text == ((struct sym_text *) other->label)->text))
562     {
563       if (! candidate || (other->length > candidate->length))
564       candidate = other;
565     }
566   }
567
568   if (candidate)
569   {
570     if (dbg_bfs)
571       printf("New line in longline %u\n", e->longline);
572     struct graph_edge *other = candidate;
573       other->longline = e->longline;
574       other->dir = dir;
575       if (((dir == DIR_BWD) && (other->n1->id == node->id)) ||
576           ((dir == DIR_FWD) && (other->n2->id == node->id)))
577       {
578         struct graph_node *swp = other->n2;
579         other->n2 = other->n1;
580         other->n1 = swp;
581       }
582
583       switch (dir)
584       {
585         case DIR_BWD:
586           e->prev = other;
587           other->next = e;
588           longlines[other->longline].first = other;
589           break;
590         case DIR_FWD:
591           e->next = other;
592           other->prev = e;
593           break;
594         default:
595           printf("Oops\n");
596           ASSERT(0);
597       }
598   }
599 }
600
601 void bfs(uns longline)
602 {
603 if (dbg_bfs)
604   printf("BFS called for longline %u\n", longline);
605 if (dbg_bfs)
606   printf("%d longlines are believed to exist, %d exist\n", num_longlines, GARY_SIZE(longlines));
607   for (uns i=0; i<GARY_SIZE(bfs_queue); i++)
608   {
609     struct graph_edge *cur = bfs_queue[i];
610     if (dbg_bfs)
611       printf("Exploring new edge %d; %d remaining\n", cur->num, GARY_SIZE(bfs_queue));
612     //ASSERT(! cur->visited);
613
614     cur->visited = longline;
615
616     if (cur->longline == (uns) -1)
617       continue;
618
619     if (cur->dir == DIR_UNSET)
620     {
621       cur->dir = DIR_CENTER;
622       bfs_edge(cur, cur->n1, cur->n2, DIR_BWD);
623       bfs_edge(cur, cur->n2, cur->n1, DIR_FWD);
624     }
625     else
626     {
627       switch (cur->dir)
628       {
629         case DIR_BWD:
630           bfs_edge(cur, cur->n1, cur->n2, cur->dir);
631           break;
632         case DIR_FWD:
633           bfs_edge(cur, cur->n2, cur->n1, cur->dir);
634           break;
635         default:
636           // FIXME
637           ;
638       }
639     }
640   }
641 }
642
643 void bfs_wrapper(void)
644 {
645   GARY_INIT(bfs_queue, 0);
646   GARY_INIT(longlines, 0);
647
648   HASH_FOR_ALL(hash, node)
649   {
650     for (uns i=0; i<GARY_SIZE(node->edges); i++)
651     {
652       if ((node->edges[i]->label) && (node->edges[i]->longline == (uns) -1))
653       {
654         GARY_PUSH(longlines);
655         longlines[num_longlines].first = node->edges[i];
656         if (dbg_bfs)
657           printf("Running new BFS\n");
658         if (dbg_bfs)
659           printf("Creating longline %u\n", num_longlines);
660         GARY_RESIZE(bfs_queue, 0);
661         struct graph_edge **e = GARY_PUSH(bfs_queue);
662         *e = node->edges[i];
663         node->edges[i]->longline = num_longlines;
664         bfs(node->edges[i]->longline);
665         //dump_longlines();
666         if (dbg_bfs)
667           printf("Joined %d edges\n", dbg_num_hits); dbg_num_hits = 0;
668         if (dbg_bfs)
669           printf("Planned %u edges\n", GARY_SIZE(bfs_queue));
670         num_longlines++;
671       }
672     }
673   }
674   HASH_END_FOR;
675
676   GARY_FREE(bfs_queue);
677 }
678
679 void dump_longlines(void)
680 {
681 printf("*** Longlines dump\n");
682   for (uns i=0; i<GARY_SIZE(longlines); i++)
683   {
684 printf("Longline %u:", i);
685     struct graph_edge *e = longlines[i].first;
686 if ((e->label) && (e->label->type == SYMBOLIZER_TEXT))
687   printf(" labelled %s", osm_val_decode(((struct sym_text *) e->label)->text));
688 printf("\n");
689
690     while (e)
691     {
692       printf("\t#%ju (%d): [%.2f; %.2f] -- [%.2f; %.2f] (dir %d)\n",
693              e->id, e->num, e->n1->o->x, e->n1->o->y, e->n2->o->x, e->n2->o->y, e->dir);
694
695       e = e->next;
696     }
697   }
698 }
699
700 struct request_line *make_new_line(void)
701 {
702   struct request_line *rl = GARY_PUSH(requests_line);
703   rl->request.ind = num_requests++;
704   rl->request.type = REQUEST_LINE;
705   GARY_INIT(rl->sections, 0);
706   GARY_INIT(rl->request.variants, 0);
707
708   return rl;
709 }
710
711 struct request_section *make_new_section(struct request_line *rl)
712 {
713   struct request_section *rls = GARY_PUSH(rl->sections);
714   rls->request.ind = num_requests++;
715   rls->request.type = REQUEST_SECTION;
716   rls->num_segments = 0;
717   GARY_INIT(rls->segments, 0);
718   GARY_INIT(rls->request.variants, 0);
719
720   return rls;
721 }
722
723 struct request_segment *make_new_segment(struct request_section *rls, struct symbol *sym)
724 {
725   struct request_segment *rs = GARY_PUSH(rls->segments);
726   rls->num_segments++;
727
728   rs->request.ind = num_requests++;
729   rs->request.type = REQUEST_SEGMENT;
730
731   GARY_INIT(rs->request.variants, 0);
732   struct variant *v = GARY_PUSH(rs->request.variants);
733   make_bitmap(v, sym);
734
735   return rs;
736 }
737
738 void cut_edge(struct graph_edge *e, double dist)
739 {
740   if (dbg_segments)
741     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);
742
743   struct graph_edge *new = malloc(sizeof(struct graph_edge));
744   *new = *e;
745   e->next = new;
746
747   // FIXME? Create new label for new edge, don't only copy pointer?
748
749   struct osm_node *n1 = e->n1->o;
750   struct osm_node *n2 = e->n2->o;
751
752   // FIXME
753   if ((n1->x == n2->x) && (n1->y == n2->y))
754   {
755     printf("[%.2f; %.2f] -- [%.2f; %.2f]\n", n1->x, n1->y, n2->x, n2->y);
756     printf("Won't cut point\n");
757     return;
758   }
759
760   struct osm_node *n11 = malloc(sizeof(struct osm_node));
761   struct graph_node *gn = malloc(sizeof(struct graph_node));
762   gn->o = n11;
763   double vsize = sqrt(pow(n1->x - n2->x, 2) + pow(n1->y - n2->y, 2));
764   n11->x = n1->x + (n2->x - n1->x) / vsize * dist;
765   n11->y = n1->y + (n2->y - n1->y) / vsize * dist;
766
767   e->n2 = new->n1 = gn;
768
769   e->length = hypot(abs(n1->x - n11->x), abs(n1->y - n11->y));
770   new->length = hypot(abs(n11->x - n2->x), abs(n11->y - n2->y));
771   new->visited = 0;
772 }
773
774 void make_segments(void)
775 {
776   for (uns i=0; i<GARY_SIZE(longlines); i++)
777   {
778     // Skip lines which are not labelled
779     if (! (longlines[i].first && longlines[i].first->label))
780       continue;
781
782     struct request_line *request = make_new_line();
783     struct request_section *rls = make_new_section(request);
784     struct request_segment *rs = NULL;
785
786     struct graph_edge *e = longlines[i].first;
787     double cur_length = 0;
788
789     struct sym_text *st = NULL;
790     if (e->label->type == SYMBOLIZER_TEXT)
791     {
792       st = (struct sym_text *) e->label;
793     }
794     else
795     {
796       if (dbg_segments)
797         printf("Warning: Skipping line\n");
798       continue;
799       // FIXME;
800     }
801
802     if (dbg_segments)
803       printf("New longline\n");
804     while (e)
805     {
806       if (e->visited < 0)
807       {
808         printf("BEWARE: Edge cycle\n");
809         break;
810       }
811       e->visited = -1; // FIXME
812
813       if (dbg_segments)
814         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);
815
816       if (st && (e->length < st->tw))
817       {
818         e = e->next;
819         //printf("Warning: Skipping segment\n");
820         continue;
821       }
822
823       if (cur_length + e->length > conf_max_section_length + conf_max_section_overlay)
824       {
825         if (dbg_segments)
826           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);
827         // HACK to prevent cutting to 0 lenght
828         cut_edge(e, max2(conf_max_section_length - cur_length, 2));
829       }
830
831       rs = make_new_segment(rls, e->label);
832       rs->label = malloc(sizeof(struct sym_text));
833       *((struct sym_text *) rs->label) = *((struct sym_text *) e->label);
834
835       rs->x1 = e->n1->o->x;
836       rs->y1 = e->n1->o->y;
837       rs->x2 = e->n2->o->x;
838       rs->y2 = e->n2->o->y;
839
840       rs->slope = (rs->y2 - rs->y1) / (rs->x2 - rs->x1);
841       rs->zindex = e->zindex;
842
843       cur_length += e->length;
844       if (cur_length > conf_max_section_length)
845       {
846         if (dbg_segments)
847           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);
848
849         rls = make_new_section(request);
850         cur_length = 0;
851       }
852
853       e = e->next;
854     }
855
856     if (request->sections[0].num_segments == 0)
857     {
858       // FIXME
859       printf("WARNING: 0 segment section\n");
860       GARY_POP(requests_line);
861       num_requests -= 2;
862     }
863   }
864 }
865
866 void dump_linelabel_requests(void)
867 {
868   for (uns i=0; i<GARY_SIZE(requests_line); i++)
869   {
870     if (requests_line[i].sections[0].num_segments == 0)
871     {
872       printf("HEY!\n");
873       continue;
874     }
875     printf("Request for linelabel, %d sections\n", GARY_SIZE(requests_line[i].sections));
876     print_label(requests_line[i].sections[0].segments[0].label);
877     for (uns j=0; j<GARY_SIZE(requests_line[i].sections); j++)
878     {
879       printf("%d section, %d segments\n", j, GARY_SIZE(requests_line[i].sections[j].segments));
880       for (uns k=0; k<GARY_SIZE(requests_line[i].sections[j].segments); k++)
881       {
882         struct request_segment *rs = &requests_line[i].sections[j].segments[k];
883         printf("[%.2f; %.2f] -- [%.2f; %.2f]\n", rs->x1, rs->y1, rs->x2, rs->y2);
884       }
885     }
886     printf("\n");
887   }
888 }
889
890 void dump_bitmaps(struct individual *individual)
891 {
892   bool *bitmap = malloc(page_width_int * page_height_int * sizeof(bool));
893   printf("Bitmap size is %d\n", page_width_int * page_height_int);
894   for (int i=0; i<page_height_int; i++)
895     for (int j=0; j<page_width_int; j++)
896       bitmap[i*page_width_int + j] = 0;
897
898   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
899   {
900     if (individual->placements[i].variant_used == -1) continue;
901
902     struct placement *p = &(individual->placements[i]);
903     struct variant *v = NULL;
904
905     switch (p->request->type)
906     {
907       case REQUEST_SEGMENT: ;
908       case REQUEST_POINT: ;
909       case REQUEST_AREA: ;
910         v = &(p->request->variants[p->variant_used]);
911         break;
912       default:
913         ASSERT(p->request->type != REQUEST_INVALID);
914         continue;
915     }
916
917     for (int row = max2(p->y, 0); row < min2(p->y + v->height, page_height_int); row++)
918     {
919       for (int col = max2(p->x, 0); col < min2(p->x + v->width, page_width_int); col++)
920       {
921         bitmap[row * page_width_int + col] = 1;
922       }
923     }
924   }
925
926   errno = 0;
927   FILE *fd_dump = fopen("dump.pbm", "w");
928   fprintf(fd_dump, "P1\n");
929   fprintf(fd_dump, "%d %d\n", page_width_int, page_height_int);
930   for (int i=0; i<page_height_int; i++)
931   {
932     for (int j=0; j<page_width_int; j++)
933     {
934       fprintf(fd_dump, "%d", bitmap[(int) (i*page_width_int + j)] ? 1 : 0);
935     }
936     fprintf(fd_dump, "\n");
937   }
938   fclose(fd_dump);
939 }
940
941 void dump_individual(struct individual *individual)
942 {
943 printf("*** Dumping INDIVIDUAL ***\n");
944 printf("(There are %d requests)\n", num_requests);
945   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
946   {
947     struct placement *p = &(individual->placements[i]);
948
949     switch (p->request->type)
950     {
951       case REQUEST_POINT:
952         printf("Point at [%.2f; %.2f] on %u\n", p->x, p->y, ((struct request_point *) p->request)->zindex);
953         break;
954       case REQUEST_LINE: ;
955         struct request_line *rl = (struct request_line *) p->request;
956         printf("Line: ");
957         print_label(rl->sections[0].segments[0].label);
958         break;
959       case REQUEST_SECTION: ;
960         printf("*");
961         break;
962       case REQUEST_SEGMENT: ;
963         if (p->variant_used >= 0)
964           printf("Segment placed at [%.2f; %.2f] on %u\n", p->x, p->y, ((struct request_segment *) p->request)->zindex);
965         else
966           printf("Segment not placed\n");
967         break;
968       case REQUEST_AREA: ;
969         struct request_area *ra = (struct request_area *) p->request;
970         printf("Area label ");
971         print_label(ra->label);
972         printf(" at [%.2f; %.2f] on %u\n", p->x, p->y, ((struct request_area *) p->request)->zindex);
973         break;
974       default:
975         printf("Testing request type (dump_individual)\n");
976         ASSERT(p->request->type != 0);
977     }
978   }
979   printf("\nTotal penalty: %d\n", individual->penalty);
980 }
981
982 void plan_individual(struct individual *individual)
983 {
984   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
985   {
986     struct symbol *s = NULL;
987     z_index_t zindex = 0;
988     if (individual->placements[i].variant_used < 0) continue;
989     switch (individual->placements[i].request->type)
990     {
991       case REQUEST_POINT: ;
992         struct request_point *rp = (struct request_point *) individual->placements[i].request;
993         s = rp->sym;
994         zindex = rp->zindex;
995         break;
996       case REQUEST_SEGMENT: ;
997         struct request_segment *rs = (struct request_segment *) individual->placements[i].request;
998         s = rs->label;
999         zindex = rs->zindex;
1000         break;
1001       case REQUEST_LINE: ;
1002         break;
1003       case REQUEST_AREA: ;
1004         struct request_area *ra = (struct request_area *) individual->placements[i].request;
1005         s = ra->label;
1006         zindex = ra->zindex;
1007         break;
1008       default:
1009         ASSERT(individual->placements[i].request != REQUEST_INVALID);
1010         continue;
1011     }
1012
1013 if (dbg_plan)
1014   printf("Will plan symbol at [%.2f; %.2f] on %u\n", individual->placements[i].x, individual->placements[i].y, zindex);
1015
1016     if (s) switch (s->type)
1017     {
1018       case SYMBOLIZER_POINT: ;
1019         struct sym_point *sp = (struct sym_point *) s;
1020         sp->x = individual->placements[i].x;
1021         sp->y = individual->placements[i].y;
1022         sym_plan((struct symbol *) sp, zindex);
1023         break;
1024       case SYMBOLIZER_ICON: ;
1025         struct sym_icon *si = (struct sym_icon *) s;
1026         si->sir.x = individual->placements[i].x;
1027         si->sir.y = individual->placements[i].y;
1028         sym_plan((struct symbol *) si, zindex);
1029         break;
1030       case SYMBOLIZER_TEXT: ;
1031         struct sym_text *st = (struct sym_text *) s;
1032         st->x = individual->placements[i].x;
1033         st->y = individual->placements[i].y;
1034         st->next_duplicate = NULL;
1035         if (dbg_plan) 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);
1036         sym_plan((struct symbol *) st, zindex);
1037         break;
1038       default:
1039         ASSERT(s->type != SYMBOLIZER_INVALID);
1040     }
1041   }
1042 }
1043
1044 void dump_penalties(void)
1045 {
1046   for (int i=0; i<conf_pop_size; i++)
1047   {
1048     printf("Individual %d has penalty %d\n", i, population1[i]->penalty);
1049   }
1050 }
1051
1052 void labeller_label(void)
1053 {
1054   make_graph();
1055   label_graph();
1056   bfs_wrapper();
1057   make_segments();
1058
1059 printf("Having %u point requests, %u line requests and %u area requests\n", GARY_SIZE(requests_point), GARY_SIZE(requests_line), GARY_SIZE(requests_area));
1060
1061   GARY_INIT(population1, conf_pop_size);
1062   GARY_INIT(population2, conf_pop_size);
1063   make_population();
1064   rank_population();
1065   qsort(population1, conf_pop_size, sizeof(struct individual *), cmp_individual);
1066
1067   if (dbg_evolution)
1068     dump_penalties();
1069
1070   printf("Dealing with %d requests\n", num_requests);
1071
1072   mutate_pop_size = conf_mutate_pop_size * conf_pop_size;
1073   mutate_rbest_size = conf_mutate_rbest * conf_pop_size;
1074   if (dbg_evolution)
1075   {
1076     printf("Mutation parameters:\n");
1077     printf(" %d individuals are created\n", mutate_pop_size);
1078     printf(" %d best individuals in old population are considered\n", mutate_rbest_size);
1079   }
1080
1081   elite_pop_size = conf_elite_pop_size * conf_pop_size;
1082   if (dbg_evolution)
1083   {
1084     printf("Elitism parameters:\n");
1085     printf(" %d best individuals are copied\n", elite_pop_size);
1086   }
1087
1088   while (! shall_terminate())
1089   {
1090     iteration++;
1091     if (dbg_evolution)
1092       printf("*** Iteration %d ***\n", iteration);
1093
1094     mutate();
1095     elite();
1096
1097     struct individual **swp = population1;
1098     population1 = population2;
1099     population2 = swp;
1100     pop2_ind = 0;
1101
1102     if (dbg_evolution)
1103       dump_penalties();
1104
1105     rank_population();
1106     qsort(population1, conf_pop_size, sizeof(struct individual *), cmp_individual);
1107
1108     if (dbg_evolution)
1109       dump_penalties();
1110   }
1111
1112   plan_individual(population1[0]);
1113
1114   labeller_cleanup();
1115
1116   return;
1117 }
1118
1119 void labeller_cleanup(void)
1120 {
1121 }
1122
1123 void make_population(void)
1124 {
1125   for (int i=0; i<conf_pop_size; i++)
1126   {
1127     struct individual *i2 = ep_alloc(ep_individuals);
1128     init_individual(i2);
1129     population2[i] = i2;
1130
1131     if (dbg_init)
1132       printf("Making individual %d\n", i);
1133     struct individual *individual = ep_alloc(ep_individuals); init_individual(individual);
1134     population1[i] = individual;
1135
1136     int p = 0;
1137     for (uns j=0; j<GARY_SIZE(requests_point); j++)
1138     {
1139       init_placement(&(individual->placements[p++]), individual, (struct request *) &requests_point[j]);
1140     }
1141
1142     for (uns j=0; j<GARY_SIZE(requests_line); j++)
1143     {
1144       init_placement(&(individual->placements[p++]), individual, (struct request *) &requests_line[j]);
1145
1146       for (uns k=0; k<GARY_SIZE(requests_line[j].sections); k++)
1147       {
1148         init_placement(&(individual->placements[p++]), individual, (struct request *) &requests_line[j].sections[k]);
1149
1150         for (uns l=0; l<GARY_SIZE(requests_line[j].sections[k].segments); l++)
1151         {
1152           init_placement(&(individual->placements[p++]), individual, (struct request *) &requests_line[j].sections[k].segments[l]);
1153         }
1154       }
1155     }
1156
1157     for (uns j=0; j<GARY_SIZE(requests_area); j++)
1158     {
1159       init_placement(&(individual->placements[p++]), individual, (struct request *) &requests_area[j]);
1160     }
1161
1162     hide_segment_labels(individual);
1163
1164     ASSERT(p == num_requests);
1165   }
1166 }
1167
1168 bool shall_terminate(void)
1169 {
1170   switch (conf_term_cond)
1171   {
1172     case TERM_COND_PENALTY:
1173       return (population1[0]->penalty < conf_penalty_bound);
1174     case TERM_COND_STAGNATION:
1175       return (abs(old_best - population1[0]->penalty) < conf_stagnation_bound);
1176     case TERM_COND_ITERATIONS:
1177       return (iteration >= conf_iteration_limit);
1178     default:
1179       // FIXME: Warn the user that no condition is set
1180       return 1;
1181   }
1182 }
1183
1184 void breed(void)
1185 {
1186   int acc = 0;
1187   int i=0;
1188   printf("%.2f\n", ((double) conf_breed_pop_size_perc/100));
1189   int conf_breed_pop_size = ((double) conf_breed_pop_size_perc/100) * conf_pop_size;
1190   struct individual **breed_buffer;
1191   while (i < conf_breed_pop_size)
1192   {
1193   printf("%d < %d, breeding\n", i, conf_breed_pop_size);
1194     int parent1 = randint(1, conf_breed_pop_size);
1195     int parent2 = randint(1, conf_breed_pop_size);
1196     printf("Will breed %d and %d, chosen of %d best of %d population (intended to be %d)\n", parent1, parent2, conf_breed_pop_size, GARY_SIZE(population1), conf_pop_size);
1197     breed_buffer = perform_crossover(population1[parent1], population1[parent2]);
1198     population2[pop2_ind++] = breed_buffer[0];
1199     population2[pop2_ind++] = breed_buffer[1];
1200     free(breed_buffer);
1201     i++;
1202   }
1203
1204   acc += conf_breed_rbest_perc;
1205
1206   return; // FIXME: DEBUG HACK
1207
1208   int remaining = (1 - acc) * (conf_pop_size * conf_breed_perc);
1209   int step = remaining / conf_pop_size;
1210   for (; i<conf_pop_size; i += 2)
1211   {
1212     printf("Asking for %d and %d of %d\n", i*step, i*(step+1), conf_pop_size);
1213     breed_buffer = perform_crossover(population1[i*step], population1[i*step+1]);
1214     population2[pop2_ind++] = breed_buffer[0];
1215     population2[pop2_ind++] = breed_buffer[1];
1216   }
1217
1218   // FIXME: Could there be one missing individual?
1219 }
1220
1221 struct individual **perform_crossover(struct individual *parent1, struct individual *parent2)
1222 {
1223   struct individual **buffer = malloc(2*sizeof(struct individual));
1224   struct individual *child1 = ep_alloc(ep_individuals); init_individual(child1);
1225   struct individual *child2 = ep_alloc(ep_individuals); init_individual(child2);
1226
1227   printf("Performing crossover\n");
1228
1229   for (uns i=0; i<GARY_SIZE(parent1->placements); i++)
1230   {
1231     printf("%dth placement out of %d\n", i, num_requests);
1232     if (! parent1->placements[i].processed)
1233     {
1234       struct placement **clos_symbols = get_closure(&(parent1->placements[i]), parent1, parent2);
1235       int x = randint(1, 2);
1236
1237       if (x == 1)
1238       {
1239         copy_symbols(clos_symbols, parent1, child1);
1240         copy_symbols(clos_symbols, parent2, child2);
1241       }
1242       else
1243       {
1244         copy_symbols(clos_symbols, parent2, child1);
1245         copy_symbols(clos_symbols, parent1, child2);
1246       }
1247       printf("Symbols copied; %lld\n", GARY_SIZE(clos_symbols));
1248       GARY_FREE(clos_symbols);
1249     }
1250
1251     if (conf_mutate_children)
1252     {
1253       if (randint(1, 1000) < conf_mutate_children_prob * 1000) perform_mutation(child1);
1254       if (randint(1, 1000) < conf_mutate_children_prob * 1000) perform_mutation(child2);
1255     }
1256   }
1257
1258   buffer[0] = child1;
1259   buffer[1] = child2;
1260   return buffer;
1261 }
1262
1263 void mutate(void)
1264 {
1265   for (int i=0; i < mutate_pop_size; i++)
1266   {
1267     if (dbg_mutation)
1268       printf("%d\n", i);
1269     int ind = randint(1, mutate_rbest_size);
1270     if (dbg_mutation)
1271       printf("Mutating %d-th individual of original population\n", ind);
1272     copy_individual(population1[ind], population2[pop2_ind]);
1273     if (dbg_mutation)
1274       printf("Individual %d in pop2 inited from individual %d in pop1\n", pop2_ind, ind);
1275     perform_mutation(population2[pop2_ind]);
1276     pop2_ind++;
1277   }
1278 }
1279
1280 void perform_mutation(struct individual *individual)
1281 {
1282   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
1283   {
1284     double x = randdouble();
1285     double acc = 0;
1286
1287     if (x <= acc + conf_mutate_move_bound)
1288     {
1289       if (dbg_mutation)
1290         printf("Mutation: Moving symbol in placement %u\n", i);
1291       move_symbol(&(individual->placements[i]));
1292       continue;
1293     }
1294     acc += conf_mutate_move_bound;
1295
1296     if (x <= acc + conf_mutate_regen_bound)
1297     {
1298       gen_coords(&(individual->placements[i]));
1299       continue;
1300     }
1301     acc += conf_mutate_regen_bound;
1302
1303     if (x <= acc + conf_mutate_chvar_bound)
1304     {
1305       struct placement *p = &(individual->placements[i]);
1306       switch (p->request->type)
1307       {
1308         case REQUEST_POINT:
1309         case REQUEST_SEGMENT:
1310         case REQUEST_AREA:
1311           // Does nothing when there are 0 variants... does it mind?
1312           p->variant_used = randint(0, GARY_SIZE(p->request->variants) - 1);
1313           break;
1314         case REQUEST_SECTION:
1315           p->variant_used = randint(0, GARY_SIZE(((struct request_section *) p->request)->segments)-1);
1316           break;
1317         default:
1318           ;
1319       }
1320     }
1321   }
1322 }
1323
1324 void elite(void)
1325 {
1326   for (int i=0; i<elite_pop_size; i++)
1327   {
1328     copy_individual(population1[i], population2[pop2_ind++]);
1329   }
1330 }
1331
1332 int overlaps(struct placement *p1, struct placement *p2)
1333 {
1334   if (p1->request->type != REQUEST_POINT &&
1335       p1->request->type != REQUEST_SEGMENT &&
1336       p1->request->type != REQUEST_AREA)
1337     return 0;
1338
1339   if (p2->request->type != REQUEST_POINT &&
1340       p2->request->type != REQUEST_SEGMENT &&
1341       p2->request->type != REQUEST_AREA)
1342     return 0;
1343
1344   if (p1->variant_used == -1 || p2->variant_used == -1)
1345     return 0;
1346
1347   struct variant *v1, *v2;
1348
1349   v1 = &(p1->request->variants[p1->variant_used]);
1350   v2 = &(p2->request->variants[p2->variant_used]);
1351
1352   int p1x = p1->x; int p1y = p1->y;
1353   int p2x = p2->x; int p2y = p2->y;
1354
1355   int overlap = 0;
1356   for (int y=max2(0, max2(p1y, p2y)); y<min2(page_height_int, min2(p1y+v1->height, p2y+v2->height)); y++)
1357     for (int x=max2(0, max2(p1x, p2x)); x<min2(page_width_int, min2(p1x+v1->width, p2x+v2->width)); x++)
1358     {
1359       if (v1->bitmap[(y-p1y)*v1->width + (x-p1x)] &&
1360           v2->bitmap[(y-p2y)*v2->width + (x-p2x)])
1361         overlap++;
1362     }
1363
1364   return overlap;
1365 }
1366
1367 int get_overlap(struct placement *p)
1368 {
1369   struct map_part **parts = get_map_parts(p);
1370   if (! parts)
1371   {
1372     if (dbg_overlaps)
1373       printf("Placement of request %d seems not to be placed\n", p->request->ind);
1374     return 0;
1375   }
1376
1377   struct placement **others;
1378   bool *planned;
1379
1380   GARY_INIT_ZERO(planned, num_requests);
1381   planned[p->request->ind] = 1;
1382   GARY_INIT(others, 0);
1383
1384   for (uns i=0; i<GARY_SIZE(parts); i++)
1385   {
1386     struct map_placement *mp = parts[i]->placement->next;
1387     while (mp)
1388     {
1389       if (! planned[mp->placement->request->ind])
1390       {
1391         struct placement **p = GARY_PUSH(others);
1392         *p = mp->placement;
1393         planned[mp->placement->request->ind] = true;
1394       }
1395       mp = mp->next;
1396     }
1397   }
1398
1399   int overlap = 0;
1400   for (uns i=0; i<GARY_SIZE(others); i++)
1401   {
1402     overlap += overlaps(p, others[i]);
1403   }
1404
1405   GARY_FREE(planned);
1406   GARY_FREE(parts);
1407   GARY_FREE(others);
1408
1409   return overlap;
1410 }
1411
1412 int individual_overlap(struct individual *individual)
1413 {
1414   int overlap = 0;
1415
1416   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
1417   {
1418     overlap += get_overlap(&individual->placements[i]);
1419   }
1420
1421   return overlap;
1422 }
1423
1424 int cmp_individual(const void *a, const void *b)
1425 {
1426   struct individual **ia = (struct individual **) a;
1427   struct individual **ib = (struct individual **) b;
1428
1429   return (*ia)->penalty - (*ib)->penalty;
1430 }
1431
1432 void rank_population(void)
1433 {
1434   int penalty;
1435
1436   for (int i=0; i<conf_pop_size; i++)
1437   {
1438     if (dbg_rank)
1439       printf("Individual %d\n", i);
1440     population1[i]->penalty = 0;
1441
1442     penalty = individual_overlap(population1[i]);
1443     if (dbg_rank)
1444       printf("Increasing penalty by %d for overlap\n", penalty);
1445     population1[i]->penalty += penalty;
1446   }
1447 }
1448
1449 struct map_part **get_map_parts(struct placement *p)
1450 {
1451   if (p->variant_used < 0) return NULL;
1452
1453   struct map_part **buffer;
1454   GARY_INIT(buffer, 0);
1455
1456   if (dbg_map_parts)
1457     printf("Looking for map parts containing placement of request %d, placed at [%.2f; %.2f]\n", p->request->ind, p->x, p->y);
1458
1459   struct variant v;
1460   switch (p->request->type)
1461   {
1462     case REQUEST_POINT:
1463     case REQUEST_SEGMENT:
1464     case REQUEST_AREA:
1465       v = p->request->variants[p->variant_used];
1466       break;
1467     default:
1468       return NULL;
1469   }
1470
1471   int x_min = max2(0, p->x) / conf_map_part_width;
1472   int x_max = min2(page_width_int, (p->x + v.width + conf_map_part_width - 1)) / conf_map_part_width;
1473   int y_min = max2(0, p->y) / conf_map_part_height;
1474   int y_max = min2(page_height_int, (p->y + v.height + conf_map_part_height - 1)) / conf_map_part_height;
1475
1476   if (dbg_map_parts)
1477     printf("Cells between [%d; %d] and [%d; %d] generated\n", x_min, y_min, x_max, y_max);
1478
1479   for (int y=y_min; y<=y_max; y++)
1480     for (int x=x_min; x<=x_max; x++)
1481     {
1482       struct map_part **m = GARY_PUSH(buffer);
1483       if (dbg_map_parts)
1484         printf("Asking for %d of %u\n", y * num_map_parts_row + x, GARY_SIZE(p->individual->map));
1485       *m = p->individual->map[y * num_map_parts_row + x];
1486     }
1487
1488   return buffer;
1489 }
1490
1491 void update_map_parts(struct placement *p)
1492 {
1493   struct placement_link *ml = p->map_links;
1494   while (ml)
1495   {
1496     struct map_placement *mp = ml->mp;
1497
1498     mp->prev->next = mp->next;
1499     if (mp->next)
1500       mp->next->prev = mp->prev;
1501     free(mp);
1502
1503     struct placement_link *tmp = ml;
1504     ml = ml->next;
1505     free(tmp);
1506   }
1507   p->map_links = NULL;
1508
1509   struct map_part **parts = get_map_parts(p);
1510   if (parts == NULL) return;
1511
1512   for (uns i=0; i<GARY_SIZE(parts); i++)
1513   {
1514     struct map_placement *mp = malloc(sizeof(struct map_placement));
1515     mp->placement = p;
1516
1517     mp->next = parts[i]->placement->next;
1518     mp->prev = parts[i]->placement;
1519     parts[i]->placement->next = mp;
1520     if (mp->next) mp->next->prev = mp;
1521
1522     struct placement_link *ml = malloc(sizeof(struct placement_link));
1523     ml->mp = mp;
1524     ml->next = p->map_links;
1525     p->map_links = ml;
1526   }
1527
1528   GARY_FREE(parts);
1529 }
1530
1531 void gen_coords(struct placement *p)
1532 {
1533   switch(p->request->type)
1534   {
1535     case REQUEST_POINT:
1536       gen_coords_point(p);
1537       break;
1538     case REQUEST_AREA:
1539       gen_coords_area(p);
1540       break;
1541     case REQUEST_SEGMENT:
1542       gen_coords_segment(p);
1543       break;
1544     case REQUEST_LINE:
1545       if (dbg_movement)
1546         printf("Not yet implemented\n");
1547       break;
1548     default:
1549       if (dbg_movement)
1550         printf("Testing request type\n");
1551       ASSERT(p->request->type != REQUEST_INVALID);
1552   }
1553
1554   update_map_parts(p);
1555 }
1556
1557 double gen_movement(void)
1558 {
1559   double m = (random() % 1000000) / 10000;
1560   m = pow(m, 1.0/3) * flip(1, -1);
1561   if (dbg_movement)
1562     printf("Movement %.2f\n", m);
1563   return m;
1564 }
1565
1566 double gen_movement_uniform(void)
1567 {
1568   return (move_max - move_min) * randdouble() * flip(1, -1);
1569 }
1570
1571 void gen_coords_point(struct placement *p)
1572 {
1573   p->x = p->x + gen_movement();
1574 }
1575
1576 void gen_coords_segment(struct placement *p)
1577 {
1578   struct request_segment *rs = (struct request_segment *) p->request;
1579   int a = flip(1, 2);
1580   p->x = (a == 1 ? rs->x1 : rs->x2);
1581   p->y = (a == 1 ? rs->y1 : rs->y2);
1582 }
1583
1584 void gen_coords_area(struct placement *p)
1585 {
1586   struct request_area *ra = (struct request_area *) p->request;
1587
1588   p->x = p->x + gen_movement();
1589   p->y = p->y + gen_movement();
1590
1591   if (dbg_movement)
1592     printf("Moved label to [%.2f; %.2f] from [%.2f; %.2f]\n", p->x, p->y, ra->cx, ra->cy);
1593 }
1594
1595 struct map_part **get_parts(struct placement *symbol, struct individual *individual)
1596 {
1597   struct map_part **buffer;
1598   GARY_INIT(buffer, 0);
1599   int x_min = symbol->x / conf_part_size;
1600   int x_max = (symbol->x /*+ symbol->bitmap->width*/ + conf_part_size - 1) / conf_part_size;
1601   int y_min = symbol->y / conf_part_size;
1602   int y_max = (symbol->y /*+ symbol->bitmap->height*/ + conf_part_size - 1) / conf_part_size;
1603
1604   for (int x=x_min; x < x_max; x++)
1605     for (int y=y_min; y < y_max; y++)
1606     {
1607       struct map_part *m = GARY_PUSH(buffer);
1608       *m = individual->map[x][y];
1609     }
1610
1611   return buffer;
1612 }
1613
1614 int randint(int min, int max)
1615 {
1616   if (min == max) return min;
1617   int r = random();
1618   //printf("Returning %d + (%d %% (%d - %d)) = %d + %d %% %d = %d + %d = %d\n", min, r, max, min, min, r, max-min, min, r%(max-min), min+(r%(max-min)));
1619   return min + (r % (max - min));
1620   return (r * (max - min));
1621 }
1622
1623 struct placement **get_closure(struct placement *placement, struct individual *parent1, struct individual *parent2 UNUSED)
1624 {
1625   printf("Getting closure\n");
1626   struct placement **closure;
1627   GARY_INIT(closure, 0);
1628   bool *chosen = malloc(GARY_SIZE(parent1->placements) * sizeof(bool));
1629   chosen[placement->request->ind] = 1;
1630
1631   struct placement **p = GARY_PUSH(closure); *p = placement;
1632
1633   uns first = 0;
1634   while (first < GARY_SIZE(closure))
1635   {
1636     printf("Iterating, first is %d\n", first);
1637     struct placement **overlapping = get_overlapping(placement);
1638     filter(overlapping, chosen);
1639     for (uns j=0; j<GARY_SIZE(overlapping); j++)
1640     {
1641       p = GARY_PUSH(closure); *p = overlapping[j];
1642       chosen[overlapping[j]->request->ind] = 1;
1643     }
1644     GARY_FREE(overlapping);
1645     first++;
1646   }
1647
1648   return closure;
1649 }
1650
1651 void copy_symbols(struct placement **closure, struct individual *parent, struct individual *child)
1652 {
1653   //printf("%d\n", child->penalty);
1654   //printf("Closure size: %lld\n", GARY_SIZE(closure));
1655   for (uns i=0; i<GARY_SIZE(closure); i++)
1656   {
1657     int ind = closure[i]->request->ind;
1658     child->placements[ind] = parent->placements[ind];
1659     child->placements[ind].processed = 0;
1660   }
1661 }
1662
1663 void move_symbol(struct placement *p)
1664 {
1665   switch (p->request->type)
1666   {
1667     case REQUEST_POINT:
1668     case REQUEST_AREA:
1669       move_symbol_point(p);
1670       break;
1671     case REQUEST_SEGMENT:
1672       move_symbol_segment(p);
1673       break;
1674     default:
1675       ASSERT(p->request->type != REQUEST_INVALID);
1676   }
1677 }
1678
1679 void move_symbol_point(struct placement *p)
1680 {
1681   p->x += gen_movement_uniform();
1682   p->y += gen_movement_uniform();
1683 }
1684
1685 void move_symbol_segment(struct placement *p)
1686 {
1687   double m = gen_movement_uniform();
1688   // CHECK ME
1689   p->x += m;
1690   p->y += m * ((struct request_segment *) p->request)->slope;
1691 }
1692
1693 void hide_segment_labels(struct individual *individual)
1694 {
1695   // BEWARE: This fully depends on current genetic encoding
1696
1697   int used = -1, num = -1;
1698   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
1699   {
1700     switch (individual->placements[i].request->type)
1701     {
1702       case REQUEST_SECTION:
1703         used = individual->placements[i].variant_used;
1704         num = 0;
1705         break;
1706       case REQUEST_SEGMENT:
1707         if (num == used)
1708           individual->placements[i].variant_used = 0;
1709         else
1710           individual->placements[i].variant_used = -1;
1711         num++;
1712         break;
1713       default:
1714         ;
1715     }
1716   }
1717 }
1718
1719 void init_placement(struct placement *p, struct individual *individual, struct request *r)
1720 {
1721   // FIXME
1722   p->request = r;
1723   p->processed = 0;
1724   p->x = p->y = 0; // To prevent valgrind from complaining
1725   p->variant_used = 0;
1726   p->map_links = NULL;
1727   p->individual = individual;
1728   switch (r->type)
1729   {
1730     case REQUEST_POINT: ;
1731       struct request_point *rp = (struct request_point *) r;
1732       p->x = rp->x;
1733       p->y = rp->y;
1734       break;
1735     case REQUEST_LINE: ;
1736       break;
1737     case REQUEST_SECTION: ;
1738       struct request_section *rls = (struct request_section *) r;
1739       p->variant_used = randint(0, rls->num_segments);
1740       break;
1741     case REQUEST_SEGMENT: ;
1742       struct request_segment *rs = (struct request_segment *) r;
1743       p->x = rs->x2;
1744       p->y = rs->y2;
1745       break;
1746     case REQUEST_AREA: ;
1747       struct request_area *ra = (struct request_area *) r;
1748       p->x = ra->cx;
1749       p->y = ra->cy;
1750       p->variant_used = 0;
1751       break;
1752     default:
1753       ASSERT(p->request->type != REQUEST_INVALID);
1754       printf("Valid request: %d\n", p->request->type);
1755   }
1756
1757   gen_coords(p);
1758   if (dbg_init)
1759     printf("Inited placement to [%.2f; %.2f]\n", p->x, p->y);
1760 }
1761
1762 void init_individual(struct individual *i)
1763 {
1764 //printf("Initing individual\n");
1765   GARY_INIT(i->placements, num_requests);
1766   GARY_INIT(i->map, 0);
1767   for (uns j=0; j<num_map_parts; j++)
1768   {
1769     struct map_part *part = GARY_PUSH(i->map);
1770     GARY_INIT(part->placement, 0);
1771     struct map_placement *mp = GARY_PUSH(part->placement);
1772     mp->placement = &dummy_placement;
1773     mp->next = mp->prev = NULL;
1774   }
1775   i->penalty = 0; // FIXME
1776
1777   if (dbg_init)
1778     printf("Individual inited, has %u map parts\n", GARY_SIZE(i->map));
1779 }
1780
1781 struct placement **get_overlapping(struct placement *p UNUSED)
1782 {
1783   struct placement **buffer;
1784   GARY_INIT(buffer, 0);
1785   return buffer;
1786 }
1787
1788 void filter(struct placement **list UNUSED, bool *pred UNUSED)
1789 {
1790   // FIXME
1791 }
1792
1793 int flip(int a, int b)
1794 {
1795   return (random() % 2 ? a : b);
1796 }
1797
1798 double randdouble(void)
1799 {
1800   return ((double) rand() / (double) RAND_MAX);
1801 }
1802
1803 void cleanup(void)
1804 {
1805   hash_cleanup();
1806   GARY_FREE(requests_point);
1807   GARY_FREE(requests_line);
1808   GARY_FREE(requests_area);
1809 }
1810
1811 void copy_individual(struct individual *src, struct individual *dest)
1812 {
1813   dest->penalty = src->penalty;
1814   GARY_INIT(dest->placements, GARY_SIZE(src->placements));
1815   for (uns i=0; i<GARY_SIZE(src->placements); i++)
1816   {
1817     dest->placements[i] = src->placements[i];
1818     dest->placements[i].map_links = NULL;
1819   }
1820   for (uns j=0; j<num_map_parts; j++)
1821   {
1822     struct map_part *part = GARY_PUSH(dest->map);
1823     GARY_INIT(part->placement, 0);
1824     struct map_placement *mp = GARY_PUSH(part->placement);
1825     mp->placement = &dummy_placement;
1826     mp->next = mp->prev = NULL;
1827   }
1828 }