summaryrefslogtreecommitdiff
path: root/meme/overlay.c
blob: df3f3cf8b5bdcd42a9d66cca00954ccde928d8f6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/*
 * overlay.c - Overlay in Gnuplot format
 *
 * Written 2015 by Werner Almesberger
 * Copyright 2015 Werner Almesberger
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 */


#include <stdlib.h>
#include <stdio.h>
#include <math.h>

#include "util.h"
#include "overlay.h"


struct point {
	float x, y;
	struct point *next;
};

struct path {
	struct point *points;
	struct path *next;
};


static struct path *paths = NULL;


void overlay_draw(void (*moveto)(void *user, int x, int y),
    void (*lineto)(void *user, int x, int y), void *user)
{
	const struct path *path;
	const struct point *p;

	for (path = paths; path; path = path->next) {
		p = path->points;
		moveto(user, p->x, p->y);
		for (p = p->next; p; p = p->next)
			lineto(user, p->x, p->y);
	}
}


static void overlay_load_file(FILE *file)
{
	struct path *path = NULL;
	struct point *p;
	int lineno = 0;
	char buf[1024];
	int n;
	double x, y, z;

	while (fgets(buf, sizeof(buf), file)) {
		lineno++;
		if (*buf == '#')
			continue;
		n = sscanf(buf, "%lf %lf %lf\n", &x, &y, &z);
		switch (n) {
		case -1:
			path = NULL;
			continue;
		case 2:
			/* fall through */
		case 3:
			break;
		default:
			fprintf(stderr, "invalid data at line %d\n", lineno);
			exit(1);
		}

		if (!path) {
			path = alloc_type(struct path);
			path->next = paths;
			path->points = NULL;
			paths = path;
		}
		p = alloc_type(struct point);
		p->x = round(x * 1000);
		p->y = round(y * 1000);
		p->next = path->points;
		path->points = p;
	}
}


void overlay_load(const char *name)
{
	FILE *file;

	file = fopen(name, "r");
	if (!file) {
		perror(name);
		exit(1);
	}
	overlay_load_file(file);
	fclose(file);
}