summaryrefslogtreecommitdiffstats
path: root/jni/feature_mos/src/mosaic/Delaunay.cpp
blob: 0ce09fc5104cb58bec452fececd3a5319b52949a (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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// Delaunay.cpp
// $Id: Delaunay.cpp,v 1.10 2011/06/17 13:35:48 mbansal Exp $

#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include "Delaunay.h"

#define QQ 9   // Optimal value as determined by testing
#define DM 38  // 2^(1+DM/2) element sort capability. DM=38 for >10^6 elements
#define NYL -1
#define valid(l) ccw(orig(basel), dest(l), dest(basel))


CDelaunay::CDelaunay()
{
}

CDelaunay::~CDelaunay()
{
}

// Allocate storage, construct triangulation, compute voronoi corners
int CDelaunay::triangulate(SEdgeVector **edges, int n_sites, int width, int height)
{
  EdgePointer cep;

  deleteAllEdges();
  buildTriangulation(n_sites);
  cep = consolidateEdges();
  *edges = ev;

  // Note: construction_list will change ev
  return constructList(cep, width, height);
}

// builds delaunay triangulation
void CDelaunay::buildTriangulation(int size)
{
  int i, rows;
  EdgePointer lefte, righte;

  rows = (int)( 0.5 + sqrt( (double) size / log( (double) size )));

  // Sort the pointers by  x-coordinate of site
  for ( i=0 ; i < size ; i++ ) {
    sp[i] = (SitePointer) i;
  }

  spsortx( sp, 0, size-1 );
  build( 0, size-1, &lefte, &righte, rows );
  oneBndryEdge = lefte;
}

// Recursive Delaunay Triangulation Procedure
// Contains modifications for axis-switching division.
void CDelaunay::build(int lo, int hi, EdgePointer *le, EdgePointer *re, int rows)
{
  EdgePointer a, b, c, ldo, rdi, ldi, rdo, maxx, minx;
  int split, lowrows;
  int low, high;
  SitePointer s1, s2, s3;
  low = lo;
  high = hi;

  if ( low < (high-2) ) {
    // more than three elements; do recursion
    minx = sp[low];
    maxx = sp[high];
    if (rows == 1) {    // time to switch axis of division
      spsorty( sp, low, high);
      rows = 65536;
    }
    lowrows = rows/2;
    split = low - 1 + (int)
      (0.5 + ((double)(high-low+1) * ((double)lowrows / (double)rows)));
    build( low, split, &ldo, &ldi, lowrows );
    build( split+1, high, &rdi, &rdo, (rows-lowrows) );
    doMerge(&ldo, ldi, rdi, &rdo);
    while (orig(ldo) != minx) {
      ldo = rprev(ldo);
    }
    while (orig(rdo) != maxx) {
      rdo = (SitePointer) lprev(rdo);
    }
    *le = ldo;
    *re = rdo;
  }
  else if (low >= (high - 1)) { // two or one points
    a = makeEdge(sp[low], sp[high]);
    *le = a;
    *re = (EdgePointer) sym(a);
  } else { // three points
    // 3 cases: triangles of 2 orientations, and 3 points on a line
    a = makeEdge((s1 = sp[low]), (s2 = sp[low+1]));
    b = makeEdge(s2, (s3 = sp[high]));
    splice((EdgePointer) sym(a), b);
    if (ccw(s1, s3, s2)) {
      c = connectLeft(b, a);
      *le = (EdgePointer) sym(c);
      *re = c;
    } else {
      *le = a;
      *re = (EdgePointer) sym(b);
      if (ccw(s1, s2, s3)) {
        // not colinear
        c = connectLeft(b, a);
      }
    }
  }
}

// Quad-edge manipulation primitives
EdgePointer CDelaunay::makeEdge(SitePointer origin, SitePointer destination)
{
  EdgePointer temp, ans;
  temp = allocEdge();
  ans = temp;

  onext(temp) = ans;
  orig(temp) = origin;
  onext(++temp) = (EdgePointer) (ans + 3);
  onext(++temp) = (EdgePointer) (ans + 2);
  orig(temp) = destination;
  onext(++temp) = (EdgePointer) (ans + 1);

  return(ans);
}

void CDelaunay::splice(EdgePointer a, EdgePointer b)
{
  EdgePointer alpha, beta, temp;
  alpha = (EdgePointer) rot(onext(a));
  beta = (EdgePointer) rot(onext(b));
  temp = onext(alpha);
  onext(alpha) = onext(beta);
  onext(beta) = temp;
  temp = onext(a);
  onext(a) = onext(b);
  onext(b) = temp;
}

EdgePointer CDelaunay::connectLeft(EdgePointer a, EdgePointer b)
{
  EdgePointer ans;
  ans = makeEdge(dest(a), orig(b));
  splice(ans, (EdgePointer) lnext(a));
  splice((EdgePointer) sym(ans), b);
  return(ans);
}

EdgePointer CDelaunay::connectRight(EdgePointer a, EdgePointer b)
{
  EdgePointer ans;
  ans = makeEdge(dest(a), orig(b));
  splice(ans, (EdgePointer) sym(a));
  splice((EdgePointer) sym(ans), (EdgePointer) oprev(b));
  return(ans);
}

// disconnects e from the rest of the structure and destroys it
void CDelaunay::deleteEdge(EdgePointer e)
{
  splice(e, (EdgePointer) oprev(e));
  splice((EdgePointer) sym(e), (EdgePointer) oprev(sym(e)));
  freeEdge(e);
}

//
// Overall storage allocation
//

// Quad-edge storage allocation
CSite *CDelaunay::allocMemory(int n)
{
  unsigned int size;

  size = ((sizeof(CSite) + sizeof(SitePointer)) * n +
          (sizeof(SitePointer) + sizeof(EdgePointer)) * 12
          ) * n;
  if (!(sa = (CSite*) malloc(size))) {
    return NULL;
  }
  sp = (SitePointer *) (sa + n);
  ev = (SEdgeVector *) (org = sp + n);
  next = (EdgePointer *) (org + 12 * n);
  ei = (struct EDGE_INFO *) (next + 12 * n);
  return sa;
}

void CDelaunay::freeMemory()
{
  if (sa) {
    free(sa);
    sa = (CSite*)NULL;
  }
}

//
// Edge storage management
//

void CDelaunay::deleteAllEdges()
{
    nextEdge = 0;
    availEdge = NYL;
}

EdgePointer CDelaunay::allocEdge()
{
  EdgePointer ans;

  if (availEdge == NYL) {
    ans = nextEdge, nextEdge += 4;
  } else {
    ans = availEdge, availEdge = onext(availEdge);
  }
  return(ans);
}

void CDelaunay::freeEdge(EdgePointer e)
{
  e ^= e & 3;
  onext(e) = availEdge;
  availEdge = e;
}

EdgePointer CDelaunay::consolidateEdges()
{
  EdgePointer e;
  int i,j;

  while (availEdge != NYL) {
    nextEdge -= 4; e = availEdge; availEdge = onext(availEdge);

    if (e==nextEdge) {
      continue; // the one deleted was the last one anyway
    }
    if ((oneBndryEdge&~3) == nextEdge) {
      oneBndryEdge = (EdgePointer) (e | (oneBndryEdge&3));
    }
    for (i=0,j=3; i<4; i++,j=rot(j)) {
      onext(e+i) = onext(nextEdge+i);
      onext(rot(onext(e+i))) = (EdgePointer) (e+j);
    }
  }
  return nextEdge;
}

//
// Sorting Routines
//

int CDelaunay::xcmpsp(int i, int j)
{
  double d = sa[(i>=0)?sp[i]:sp1].X() - sa[(j>=0)?sp[j]:sp1].X();
  if ( d > 0. ) {
    return 1;
  }
  if ( d < 0. ) {
    return -1;
  }
  d = sa[(i>=0)?sp[i]:sp1].Y() - sa[(j>=0)?sp[j]:sp1].Y();
  if ( d > 0. ) {
    return 1;
  }
  if ( d < 0. ) {
    return -1;
  }
  return 0;
}

int CDelaunay::ycmpsp(int i, int j)
{
  double d = sa[(i>=0)?sp[i]:sp1].Y() - sa[(j>=0)?sp[j]:sp1].Y();
  if ( d > 0. ) {
    return 1;
  }
  if ( d < 0. ) {
    return -1;
  }
  d = sa[(i>=0)?sp[i]:sp1].X() - sa[(j>=0)?sp[j]:sp1].X();
  if ( d > 0. ) {
    return 1;
  }
  if ( d < 0. ) {
    return -1;
  }
  return 0;
}

int CDelaunay::cmpev(int i, int j)
{
  return (ev[i].first - ev[j].first);
}

void CDelaunay::swapsp(int i, int j)
{
  int t;
  t = (i>=0) ? sp[i] : sp1;

  if (i>=0) {
    sp[i] = (j>=0)?sp[j]:sp1;
  } else {
    sp1 = (j>=0)?sp[j]:sp1;
  }

  if (j>=0) {
    sp[j] = (SitePointer) t;
  } else {
    sp1 = (SitePointer) t;
  }
}

void CDelaunay::swapev(int i, int j)
{
  SEdgeVector temp;

  temp = ev[i];
  ev[i] = ev[j];
  ev[j] = temp;
}

void CDelaunay::copysp(int i, int j)
{
  if (j>=0) {
    sp[j] = (i>=0)?sp[i]:sp1;
  } else {
    sp1 = (i>=0)?sp[i]:sp1;
  }
}

void CDelaunay::copyev(int i, int j)
{
  ev[j] = ev[i];
}

void CDelaunay::spsortx(SitePointer *sp_in, int low, int high)
{
  sp = sp_in;
  rcssort(low,high,-1,&CDelaunay::xcmpsp,&CDelaunay::swapsp,&CDelaunay::copysp);
}

void CDelaunay::spsorty(SitePointer *sp_in, int low, int high )
{
  sp = sp_in;
  rcssort(low,high,-1,&CDelaunay::ycmpsp,&CDelaunay::swapsp,&CDelaunay::copysp);
}

void CDelaunay::rcssort(int lowelt, int highelt, int temp,
                    int (CDelaunay::*comparison)(int,int),
                    void (CDelaunay::*swap)(int,int),
                    void (CDelaunay::*copy)(int,int))
{
  int m,sij,si,sj,sL,sk;
  int stack[DM];

  if (highelt-lowelt<=1) {
    return;
  }
  if (highelt-lowelt>QQ) {
    m = 0;
    si = lowelt; sj = highelt;
    for (;;) { // partition [si,sj] about median-of-3.
      sij = (sj+si) >> 1;

      // Now to sort elements si,sij,sj into order & set temp=their median
      if ( (this->*comparison)( si,sij ) > 0 ) {
        (this->*swap)( si,sij );
      }
      if ( (this->*comparison)( sij,sj ) > 0 ) {
        (this->*swap)( sj,sij );
        if ( (this->*comparison)( si,sij ) > 0 ) {
          (this->*swap)( si,sij );
        }
      }
      (this->*copy)( sij,temp );

      // Now to partition into elements <=temp, >=temp, and ==temp.
      sk = si; sL = sj;
      do {
        do {
          sL--;
        } while( (this->*comparison)( sL,temp ) > 0 );
        do {
          sk++;
        } while( (this->*comparison)( temp,sk ) > 0 );
        if ( sk < sL ) {
          (this->*swap)( sL,sk );
        }
      } while(sk <= sL);

      // Now to recurse on shorter partition, store longer partition on stack
      if ( sL-si > sj-sk ) {
        if ( sL-si < QQ ) {
          if( m==0 ) {
            break;  // empty stack && both partitions < QQ so break
          } else {
            sj = stack[--m];
            si = stack[--m];
          }
        }
        else {
          if ( sj-sk < QQ ) {
            sj = sL;
          } else {
            stack[m++] = si;
            stack[m++] = sL;
            si = sk;
          }
        }
      }
      else {
        if ( sj-sk < QQ ) {
          if ( m==0 ) {
            break; // empty stack && both partitions < QQ so break
          } else {
            sj = stack[--m];
            si = stack[--m];
          }
        }
        else {
          if ( sL-si < QQ ) {
            si = sk;
          } else {
            stack[m++] = sk;
            stack[m++] = sj;
            sj = sL;
          }
        }
      }
    }
  }

  // Now for 0 or Data bounded  "straight insertion" sort of [0,nels-1]; if it is
  // known that el[-1] = -INF, then can omit the "sk>=0" test and save time.
  for (si=lowelt; si<highelt; si++) {
    if ( (this->*comparison)( si,si+1 ) > 0 ) {
      (this->*copy)( si+1,temp );
      sj = sk = si;
      sj++;
      do {
        (this->*copy)( sk,sj );
        sj = sk;
        sk--;
      } while ( (this->*comparison)( sk,temp ) > 0 && sk>=lowelt );
      (this->*copy)( temp,sj );
    }
  }
}

//
// Geometric primitives
//

// incircle, as in the Guibas-Stolfi paper.
int CDelaunay::incircle(SitePointer a, SitePointer b, SitePointer c, SitePointer d)
{
  double adx, ady, bdx, bdy, cdx, cdy, dx, dy, nad, nbd, ncd;
  dx = sa[d].X();
  dy = sa[d].Y();
  adx = sa[a].X() - dx;
  ady = sa[a].Y() - dy;
  bdx = sa[b].X() - dx;
  bdy = sa[b].Y() - dy;
  cdx = sa[c].X() - dx;
  cdy = sa[c].Y() - dy;
  nad = adx*adx+ady*ady;
  nbd = bdx*bdx+bdy*bdy;
  ncd = cdx*cdx+cdy*cdy;
  return( (0.0 < (nad * (bdx * cdy - bdy * cdx)
                  + nbd * (cdx * ady - cdy * adx)
                  + ncd * (adx * bdy - ady * bdx))) ? TRUE : FALSE );
}

// TRUE iff A, B, C form a counterclockwise oriented triangle
int CDelaunay::ccw(SitePointer a, SitePointer b, SitePointer c)
{
  int result;

  double ax = sa[a].X();
  double bx = sa[b].X();
  double cx = sa[c].X();
  double ay = sa[a].Y();
  double by = sa[b].Y();
  double cy = sa[c].Y();

  double val = (ax - cx)*(by - cy) - (bx - cx)*(ay - cy);
  if ( val > 0.0) {
    return true;
  }

  return false;
}

//
// The Merge Procedure.
//

void CDelaunay::doMerge(EdgePointer *ldo, EdgePointer ldi, EdgePointer rdi, EdgePointer *rdo)
{
  int rvalid, lvalid;
  EdgePointer basel,lcand,rcand,t;

  for (;;) {
    while (ccw(orig(ldi), dest(ldi), orig(rdi))) {
        ldi = (EdgePointer) lnext(ldi);
    }
    if (ccw(dest(rdi), orig(rdi), orig(ldi))) {
        rdi = (EdgePointer)rprev(rdi);
    } else {
      break;
    }
  }

  basel = connectLeft((EdgePointer) sym(rdi), ldi);
  lcand = rprev(basel);
  rcand = (EdgePointer) oprev(basel);
  if (orig(basel) == orig(*rdo)) {
    *rdo = basel;
  }
  if (dest(basel) == orig(*ldo)) {
    *ldo = (EdgePointer) sym(basel);
  }

  for (;;) {
#if 1
    if (valid(t=onext(lcand))) {
#else
    t = (EdgePointer)onext(lcand);
    if (valid(basel, t)) {
#endif
      while (incircle(dest(lcand), dest(t), orig(lcand), orig(basel))) {
        deleteEdge(lcand);
        lcand = t;
        t = onext(lcand);
      }
    }
#if 1
    if (valid(t=(EdgePointer)oprev(rcand))) {
#else
    t = (EdgePointer)oprev(rcand);
    if (valid(basel, t)) {
#endif
      while (incircle(dest(t), dest(rcand), orig(rcand), dest(basel))) {
        deleteEdge(rcand);
        rcand = t;
        t = (EdgePointer)oprev(rcand);
      }
    }

#if 1
    lvalid = valid(lcand);
    rvalid = valid(rcand);
#else
    lvalid = valid(basel, lcand);
    rvalid = valid(basel, rcand);
#endif
    if ((! lvalid) && (! rvalid)) {
      return;
    }

    if (!lvalid ||
        (rvalid && incircle(dest(lcand), orig(lcand), orig(rcand), dest(rcand)))) {
      basel = connectLeft(rcand, (EdgePointer) sym(basel));
      rcand = (EdgePointer) lnext(sym(basel));
    } else {
      basel = (EdgePointer) sym(connectRight(lcand, basel));
      lcand = rprev(basel);
    }
  }
}

int CDelaunay::constructList(EdgePointer last, int width, int height)
{
  int c, i;
  EdgePointer curr, src, nex;
  SEdgeVector *currv, *prevv;

  c = (int) ((curr = (EdgePointer) ((last & ~3))) >> 1);

  for (last -= 4; last >= 0; last -= 4) {
    src = orig(last);
    nex = dest(last);
    orig(--curr) = src;
    orig(--curr) = nex;
    orig(--curr) = nex;
    orig(--curr) = src;
  }
  rcssort(0, c - 1, -1, &CDelaunay::cmpev, &CDelaunay::swapev, &CDelaunay::copyev);

  // Throw out any edges that are too far apart
  currv = prevv = ev;
  for (i = c; i--; currv++) {
      if ((int) fabs(sa[currv->first].getVCenter().x - sa[currv->second].getVCenter().x) <= width &&
          (int) fabs(sa[currv->first].getVCenter().y - sa[currv->second].getVCenter().y) <= height) {
          *(prevv++) = *currv;
      } else {
        c--;
      }
  }
  return c;
}

// Fill in site neighbor information
void CDelaunay::linkNeighbors(SEdgeVector *edge, int nedge, int nsite)
{
  int i;

  for (i = 0; i < nsite; i++) {
    sa[i].setNeighbor(edge);
    sa[i].setNumNeighbors(0);
    for (; edge->first == i && nedge; edge++, nedge--) {
      sa[i].incrNumNeighbors();
    }
  }
}