Root/poly2d/p2d_copy.c

1/*
2 * p2d_copy.c - Copy a polygon, with or without reversing it
3 *
4 * Written 2012 by Werner Almesberger
5 * Copyright 2012 Werner Almesberger
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 */
12
13
14#include <math.h>
15
16#include "util.h"
17#include "poly2d.h"
18
19
20struct p2d *p2d_copy(const struct p2d *p)
21{
22    struct p2d *np;
23    const struct v2d *v;
24    struct v2d *nv, **last;
25
26    np = alloc_type(struct p2d);
27    np->v = NULL;
28    np->last = NULL;
29    np->next = NULL;
30
31    last = &np->v;
32    v = p->v;
33    while (v) {
34        nv = alloc_type(struct v2d);
35        nv->x = v->x;
36        nv->y = v->y;
37        nv->next = NULL;
38        *last = nv;
39        last = &nv->next;
40
41        np->last = nv;
42
43        v = v->next;
44        if (v == p->v)
45            break;
46    }
47    if (v)
48        *last = np->v;
49    return np;
50}
51
52
53struct p2d *p2d_copy_all(const struct p2d *p)
54{
55    struct p2d *res = NULL, **last = &res;
56
57    while (p) {
58        *last = p2d_copy(p);
59        last = &(*last)->next;
60        p = p->next;
61    }
62    return res;
63}
64
65
66struct p2d *p2d_reverse(const struct p2d *p)
67{
68    struct p2d *np;
69    const struct v2d *v;
70    struct v2d *nv;
71
72    np = alloc_type(struct p2d);
73    np->v = NULL;
74    np->last = NULL;
75    np->next = NULL;
76
77    v = p->v;
78    while (v) {
79        nv = alloc_type(struct v2d);
80        nv->x = v->x;
81        nv->y = v->y;
82        nv->next = np->v;
83        np->v = nv;
84
85        if (!np->last)
86            np->last= nv;
87
88        v = v->next;
89        if (v == p->v)
90            break;
91    }
92    if (v && np->last)
93        np->last->next = np->v;
94    return np;
95}
96

Archive Download this file

Branches:
master



interactive