157955153cdc1b2c28650008a7052f8bb348d28f
[anneal.git] / src / edu / berkeley / qfat / Mesh.java
1 package edu.berkeley.qfat;
2 import java.awt.*;
3 import java.util.*;
4 import java.awt.event.*;
5 import javax.swing.*;
6 import javax.media.opengl.*;
7 import javax.media.opengl.glu.*;
8 import edu.berkeley.qfat.geom.*;
9 import edu.wlu.cs.levy.CG.KDTree;
10 import edu.berkeley.qfat.geom.Point;
11
12 public class Mesh implements Iterable<Mesh.T> {
13
14     public static float EPSILON = (float)0.0001;
15     public static Random random = new Random();
16
17     private PointSet<Vert> pointset = new PointSet<Vert>();
18     public Vert nearest(Point p) { return pointset.nearest(p); }
19
20     public Iterable<E> edges() {
21         return
22             new Iterable<E>() {
23             public Iterator<E> iterator() {
24                 // HACK
25                 HashSet<E> hse = new HashSet<E>();
26                 for(T t : Mesh.this) {
27                     hse.add(t.e1());
28                     hse.add(t.e2());
29                     hse.add(t.e3());
30                     hse.add(t.e1().pair);
31                     hse.add(t.e2().pair);
32                     hse.add(t.e3().pair);
33                 }
34                 return hse.iterator();
35             } };
36     }
37
38     public Iterator<T> iterator() {
39         for(Vert v : pointset)
40             if (v.e != null && v.e.t != null)
41                 return new FaceIterator(v);
42         return new FaceIterator();
43     }
44
45     public Point origin() { return new Point(0, 0, 0); }
46
47     public Mesh score_against = null;
48     public double score = 0;
49     public float score() { return (float)score; }
50
51     public int numedges = 0;
52     public float avgedge = 0;
53
54     public void unbind() {
55         for(Mesh.T t : this) {
56             t.v1().unbind();
57             t.v2().unbind();
58             t.v3().unbind();
59         }
60     }
61
62     public void bind() {
63         for(Mesh.T t : this) {
64             t.e1().dobind();
65             t.e2().dobind();
66             t.e3().dobind();
67         }
68     }
69
70     public float rescore() {
71         int num = 0;
72         double dist = 0;
73         HashSet<Vert> done = new HashSet<Vert>();
74         for(T t : this)
75             for(Vert p : new Vert[] { t.v1(), t.v2(), t.v3() }) {
76                 if (done.contains(p)) continue;
77                 done.add(p);
78                 p.rescore();
79             }
80         /*
81         for(T t : this)
82             for(Vert p : new Vert[] { t.v1(), t.v2(), t.v3() })
83                 p.kdremove();
84         pointset.clear();
85         for(T t : this)
86             for(Vert p : new Vert[] { t.v1(), t.v2(), t.v3() })
87                 p.kdinsert();
88         */
89         return (float)(dist/num);
90     }
91
92     public void transform(Matrix m) {
93         ArrayList<Vert> set = new ArrayList<Vert>();
94         for (Vert v : pointset)
95             set.add(v);
96         for(Vert v : set) v.transform(m);
97     }
98
99     public Vec diagonal() { return pointset.diagonal(); }
100     public Point centroid() { return pointset.centroid(); }
101
102     public float volume() {
103         double total = 0;
104         for(T t : this) {
105             double area = t.area();
106             Vec origin_to_centroid = new Vec(new Point(0, 0, 0), t.centroid());
107             boolean facingAway = t.norm().dot(origin_to_centroid) > 0;
108             double height = Math.abs(t.norm().dot(origin_to_centroid));
109             total += ((facingAway ? 1 : -1) * area * height) / 3.0;
110         }
111         return (float)total;
112     }
113
114
115     public class BindingGroup {
116         public HashSet<E> es = new HashSet<E>();
117         public BindingGroup() { }
118         public BindingGroup(E e) {
119             es.add(e);
120         }
121         public void add(E e) {
122             if (e.bg != null) { merge(e.bg); return; }
123             es.add(e);
124             e.bg = this;
125         }
126         public void merge(BindingGroup bg) {
127             for(E e : bg.es) {
128                 e.bg = null;
129                 add(e);
130             }
131         }
132     }
133
134     public Vert register(Point p) { Vert v = pointset.get(p); return v==null ? new Vert(p) : v; }
135     public final class Vert extends HasPoint {
136         public Point p;
137         public Point getPoint() { return p; }
138         private Vert(Point p) {
139             this.p = p;
140             if (pointset.get(p) != null) throw new Error();
141             pointset.add(this);
142         }
143         public void reinsert() {
144             pointset.remove(this);
145             pointset.add(this);
146         }
147         public void kdremove() {
148             if (!inserted) return;
149             inserted = false;
150             pointset.remove(this);
151         }
152         public void kdinsert() {
153             if (inserted) return;
154             inserted = true;
155             pointset.add(this);
156         }
157
158         public float score() { return oldscore; }
159         public void unscore() {
160             if (watch == null) return;
161             watch.watch_x -= p.x;
162             watch.watch_y -= p.y;
163             watch.watch_z -= p.z;
164             watch.watch_count--;
165             if (watch.watch_count==0) {
166                 watch.watch_x = 0;
167                 watch.watch_y = 0;
168                 watch.watch_z = 0;
169             }
170             watch = null;
171         }
172         public Vert partner() { return watch==null ? this : watch; }
173         public Vert watchback() { return watch_count==0 ? partner() :
174                 register(new Point(watch_x/watch_count, watch_y/watch_count, watch_z/watch_count)); }
175         public void rescore() {
176             if (score_against == null) return;
177
178             score -= oldscore;
179             oldscore = 0;
180
181             if (watch != null) unscore();
182             Vert po = this;
183             if (watch == null) {
184                 watch = score_against.nearest(po.p);
185
186                 // don't attract to vertices that face the other way
187                 if (watch.e == null || watch.norm().dot(norm()) < 0) {
188                     watch = null;
189                 } else {
190                     watch.watch_x += po.p.x;
191                     watch.watch_y += po.p.y;
192                     watch.watch_z += po.p.z;
193                     watch.watch_count++;
194                 }
195             }
196
197             double s1, s2;
198             if (watch_count==0) s1 = 0;
199             else                s1 = p.distance(watch_x/watch_count, watch_y/watch_count, watch_z/watch_count);
200             s2 = watch==null ? 0 : po.p.distance(watch.p);
201             oldscore = (float)(s1 + s2);
202             score += oldscore;
203         }
204
205         /** does NOT update bound pairs! */
206         public boolean transform(Matrix m) {
207             // FIXME: screws up kdtree 
208             // FIXME: screws up hashmap
209             unscore();
210             try {
211                 if (pointset.get(this.p)==null) throw new Error();
212                 pointset.remove(this);
213                 float newx = m.a*p.x + m.b*p.y + m.c*p.z + m.d;
214                 float newy = m.e*p.x + m.f*p.y + m.g*p.z + m.h;
215                 float newz = m.i*p.x + m.j*p.y + m.k*p.z + m.l;
216                 this.p = new Point(newx, newy, newz);
217                 // FIXME: what if we move onto exactly where another point is?
218                 pointset.add(this);
219             } catch (Exception e) {
220                 throw new RuntimeException(e);
221             }
222             rescore();
223             boolean good = true;
224             /*
225             for(T t : this) {
226                 for(E e = this.e; ;) {
227                     if (e.intersects(t)) { good = false; break; }
228                     e = e.pair.next;
229                     if (e == this.e) break;
230                 }
231             }
232             */
233             /*
234                 if (t==this.t) continue;
235                 if (this.intersects(t)) good = false;
236             }
237             */
238             return good;
239         }
240         public boolean move(Vec v) {
241             Matrix m = new Matrix(v);
242             Vert p = this;
243             boolean good = true;
244             do {
245                 good &= p.transform(m);
246                 v = v.times(binding); // bleh wrong
247                 p = p.bound_to;
248             } while (p != this);
249             return good;
250         }
251
252         public E makeE(Vert p2) {
253             E e = getE(p2);
254             if (e != null) return e;
255             e = p2.getE(this);
256             if (this.e == null && p2.e == null) return this.e = new E(this, p2);
257             if (this.e == null && p2.e != null) return p2.makeE(this).pair;
258             return new E(getFreeIncident(), p2);
259         }
260
261         public E getFreeIncident() {
262             E ret = getFreeIncident(e, e);
263             if (ret != null) return ret;
264             ret = getFreeIncident(e.pair.next, e.pair.next);
265             if (ret == null) throw new Error("unable to find free incident to " + this);
266             return ret;
267         }
268
269         public E getFreeIncident(E start, E before) {
270             E e = start;
271             do {
272                 if (e.pair.p2 == this && e.pair.t == null && e.pair.next.t == null) return e.pair;
273                 e = e.pair.next;
274             } while(e != before);
275             return null;
276         }
277
278         public E getE(Vert p2) {
279             E e = this.e;
280             do {
281                 if (e==null) return null;
282                 if (e.p1 == this && e.p2 == p2) return e;
283                 e = e.pair.next;
284             } while (e!=this.e);
285             return null;
286         }
287
288         public boolean isBoundTo(Vert p) {
289             Vert px = p;
290             do {
291                 if (px==this) return true;
292                 px = px.bound_to;
293             } while(px != p);
294             return false;
295         }
296
297         public void unbind() { bound_to = this; binding = new Matrix(); }
298         public void bind(Vert p) { bind(p, new Matrix()); }
299         public void bind(Vert p, Matrix binding) {
300             if (isBoundTo(p)) return;
301             Vert temp_bound_to = p.bound_to;
302             Matrix temp_binding = p.binding;
303             p.bound_to = this.bound_to;
304             p.binding = binding.times(this.binding); // FIXME: may have order wrong here
305             this.bound_to = temp_bound_to;
306             this.binding = temp_binding.times(temp_binding); // FIXME: may have order wrong here
307         }
308         public Vec norm() {
309             Vec norm = new Vec(0, 0, 0);
310             E e = this.e;
311             do {
312                 if (e.t != null) norm = norm.plus(e.t.norm().times((float)e.prev.angle()));
313                 e = e.pair.next;
314             } while(e != this.e);
315             return norm.norm();
316         }
317
318         Vert bound_to = this;
319         int watch_count;
320         float watch_x;
321         float watch_y;
322         float watch_z;
323         Vert watch;
324         E e;                // some edge *leaving* this point
325         Matrix binding = new Matrix();
326         float oldscore = 0;
327         boolean inserted = false;
328     }
329
330     /** [UNIQUE] an edge */
331     public final class E implements Comparable<E> {
332
333         public boolean intersects(T t) {
334             double A0=t.v1().p.x, A1=t.v1().p.y, A2=t.v1().p.z;
335             double B0=t.v2().p.x, B1=t.v2().p.y, B2=t.v2().p.z;
336             double C0=t.v3().p.x, C1=t.v3().p.y, C2=t.v3().p.z;
337             double j0=p1.p.x, j1=p1.p.y, j2=p1.p.z;
338             double k0=p2.p.x, k1=p2.p.y, k2=p2.p.z;
339             double J0, J1, J2;
340             double K0, K1, K2;
341             double i0, i1, i2;
342             double a0, a1, a2;
343             double b0, b1, b2;
344             double c0, c1, c2;
345             double in_det;
346             double R00, R01, R02, R03,
347                 R10, R11, R12, R13,
348                 R20, R21, R22, R23,
349                 R30, R31, R32, R33;
350
351
352             /* a = B - A */
353             a0 = B0 - A0; 
354             a1 = B1 - A1; 
355             a2 = B2 - A2;
356             /* b = C - B */
357             b0 = C0 - A0;
358             b1 = C1 - A1;
359             b2 = C2 - A2;
360             /* c = a &times; b */
361             c0 = a1 * b2 - a2 * b1;
362             c1 = a2 * b0 - a0 * b2;
363             c2 = a0 * b1 - a1 * b0;
364  
365             /* M^(-1) = (1/det(M)) * adj(M) */
366             in_det = 1 / (c0 * c0 + c1 * c1 + c2 * c2);
367             R00 = (b1 * c2 - b2 * c1) * in_det;
368             R01 = (b2 * c0 - b0 * c2) * in_det;
369             R02 = (b0 * c1 - b1 * c0) * in_det;
370             R10 = (c1 * a2 - c2 * a1) * in_det;
371             R11 = (c2 * a0 - c0 * a2) * in_det;
372             R12 = (c0 * a1 - c1 * a0) * in_det;
373             R20 = (c0) * in_det;
374             R21 = (c1) * in_det;
375             R22 = (c2) * in_det;
376   
377             /* O = M^(-1) * A */
378             R03 = -(R00 * A0 + R01 * A1 + R02 * A2);
379             R13 = -(R10 * A0 + R11 * A1 + R12 * A2);
380             R23 = -(R20 * A0 + R21 * A1 + R22 * A2);
381  
382             /* fill in last row of 4x4 matrix */
383             R30 = R31 = R32 = 0;
384             R33 = 1;
385   
386             J2 = R20 * j0 + R21 * j1 + R22 * j2 + R23;
387             K2 = R20 * k0 + R21 * k1 + R22 * k2 + R23;
388             if (J2 * K2 >= 0) return false;
389
390             J0 = R00 * j0 + R01 * j1 + R02 * j2 + R03;
391             K0 = R00 * k0 + R01 * k1 + R02 * k2 + R03;
392             i0 = J0 + J2 * ((K0 - J0) / (J2 - K2));
393             if (i0 < 0 || i0 > 1) return false;
394   
395             J1 = R10 * j0 + R11 * j1 + R12 * j2 + R13;
396             K1 = R10 * k0 + R11 * k1 + R12 * k2 + R13;
397             i1 = J1 + J2 * ((K1 - J1) / (J2 - K2));
398             if (i1 < 0 || i1 > 1 || i0 + i1 > 1) return false;
399
400             return true;            
401         }
402
403         public int compareTo(E e) {
404             return e.length() > length() ? 1 : -1;
405         }
406
407         public final Vert p1, p2;
408         T t;     // triangle to our "left"
409         E prev;  // previous half-edge
410         E next;  // next half-edge
411         E pair;  // partner half-edge
412
413
414         public BindingGroup bg = new BindingGroup(this);
415
416         public void bind(E e) { bind(e, new Matrix()); }
417         public void bind(E e, Matrix m) { e.bg.add(this); }
418
419         public void dobind() {
420             if (bg==null) return;
421             for(E ex : bg.es) {
422                 if (ex==this) continue;
423                 p1.bind(ex.p1);
424                 p2.bind(ex.p2);
425             }
426         }
427
428         boolean shattered = false;
429         public Vert shatter() { return shatter(register(midpoint()), null, null); }
430         public Vert shatter(Vert mid, BindingGroup bg1, BindingGroup bg2) {
431             if (shattered) return mid;
432             shattered = true;
433
434             Vert r = next.p2;
435             E next = this.next;
436             E prev = this.prev;
437
438             if (bg1==null) bg1 = new BindingGroup();
439             if (bg2==null) bg2 = new BindingGroup();
440             for(E e : bg.es) e.shatter(register(e.midpoint()), bg1, bg2);
441             pair.shatter();
442             destroy();
443
444             newT(r, p1, mid, null);
445             newT(r, mid, p2, null);
446             bg1.add(p1.getE(mid));
447             bg2.add(mid.getE(p2));
448             return mid;
449         }
450
451         public boolean destroyed = false;
452         public void destroy() {
453             if (destroyed) return;
454             destroyed = true;
455             pair.destroyed = true;
456             if (next.t != null) next.t.destroy();
457             if (prev.t != null) prev.t.destroy();
458             next.t = null;
459             prev.t = null;
460             pair.next.t = null;
461             pair.prev.t = null;
462             this.bg = null;
463             pair.bg = null;
464             pair.prev.next = next;
465             next.prev = pair.prev;
466             prev.next = pair.next;
467             pair.next = prev;
468             if (p1.e == this) p1.e = prev.next;
469             if (pair.p1.e == pair) pair.p1.e = pair.prev.next;
470             avgedge -= this.length();
471             avgedge -= pair.length();
472             numedges--;
473             numedges--;
474         }
475
476         private void sync() {
477             this.prev.next = this;
478             this.next.prev = this;
479             this.pair.pair = this;
480             if (this.next.p1 != p2) throw new Error();
481             if (this.prev.p2 != p1) throw new Error();
482             if (this.p1.e == null) this.p1.e = this;
483             if (!added) {
484                 added = true;
485                 numedges++;
486                 avgedge += length();
487             }
488         }
489         private boolean added = false;
490
491         public T makeT() { return t==null ? (t = new T(this)) : t; }
492
493         /** angle between this half-edge and the next */
494         public double angle() {
495             Vec v1 = next.p2.p.minus(p2.p);
496             Vec v2 = this.p1.p.minus(p2.p);
497             return Math.acos(v1.norm().dot(v2.norm()));
498         }
499
500         public void makeAdjacent(E e) {
501             if (this.next == e) return;
502             if (p2 != e.p1) throw new Error("cannot make adjacent -- no shared vertex");
503             if (t != null || e.t != null) throw new Error("cannot make adjacent -- edges not both free");
504
505             E freeIncident = p2.getFreeIncident(e, this);
506
507             e.prev.next = freeIncident.next;
508             freeIncident.next.prev = e.prev;
509
510             freeIncident.next = this.next;
511             this.next.prev = freeIncident;
512             
513             this.next = e;
514             e.prev = this;
515
516             sync();
517             freeIncident.sync();
518         }
519
520         /** creates an isolated edge out in the middle of space */
521         public E(Vert p1, Vert p2) {
522             if (p1==p2) throw new Error("attempt to create edge with single vertex: " + p1);
523             this.p1 = p1;
524             this.p2 = p2;
525             this.prev = this.next = this.pair = new E(this, this, this);
526             sync();
527         }
528
529         /** adds a new half-edge from prev.p2 to p2 */
530         public E(E prev, Vert p2) {
531             this.p1 = prev.p2;
532             this.p2 = p2;
533             this.prev = prev;
534             if (p2.getE(p1) != null) throw new Error();
535             if (p2.e==null) {
536                 this.next = this.pair = new E(this, this, prev.next);
537             } else {
538                 E q = p2.getFreeIncident();
539                 this.next = q.next;
540                 this.next.prev = this;
541                 E z = prev.next;
542                 this.prev.next = this;
543                 this.pair = new E(q, this, z);
544             }
545             sync();
546         }
547
548         /** adds a new half-edge to the mesh with a given predecessor, successor, and pair */
549         public E(E prev, E pair, E next) {
550             this.p1 = prev.p2;
551             this.p2 = next.p1;
552             this.prev = prev;
553             this.next = next;
554             this.pair = pair;
555             sync();
556         }
557         public Point midpoint() { return new Point((p1.p.x+p2.p.x)/2, (p1.p.y+p2.p.y)/2, (p1.p.z+p2.p.z)/2); }
558         public boolean has(Vert v) { return v==p1 || v==p2; }
559         public float length() { return p1.p.minus(p2.p).mag(); }
560         public String toString() { return p1+"->"+p2; }
561     }
562
563     public T newT(Vert p1, Vert p2, Vert p3, Vec norm) {
564         if (norm != null) {
565             Vec norm2 = p3.p.minus(p1.p).cross(p2.p.minus(p1.p));
566             float dot = norm.dot(norm2);
567             //if (Math.abs(dot) < EPointSILON) throw new Error("dot products within evertsilon of each other: "+norm+" "+norm2);
568             if (dot < 0) { Vert p = p1; p1=p2; p2 = p; }
569         }
570         E e12 = p1.makeE(p2);
571         E e23 = p2.makeE(p3);
572         E e31 = p3.makeE(p1);
573         while(e12.next != e23 || e23.next != e31 || e31.next != e12) {
574             e12.makeAdjacent(e23);
575             e23.makeAdjacent(e31);
576             e31.makeAdjacent(e12);
577         }
578         T ret = e12.makeT();
579         if (e12.t == null) throw new Error();
580         if (e23.t == null) throw new Error();
581         if (e31.t == null) throw new Error();
582         return ret;
583     }
584
585
586     public class FaceIterator implements Iterator<T> {
587         private HashSet<T> visited = new HashSet<T>();
588         private LinkedList<T> next = new LinkedList<T>();
589         public FaceIterator() { }
590         public FaceIterator(Vert v) { next.addFirst(v.e.t); }
591         public boolean hasNext() { return next.peek()!=null; }
592         public void remove() { throw new Error(); }
593         public T next() {
594             T ret = next.removeFirst();
595             if (ret == null) return null;
596             visited.add(ret);
597             T t1 = ret.e1().pair.t;
598             T t2 = ret.e2().pair.t;
599             T t3 = ret.e3().pair.t;
600             if (t1 != null && !visited.contains(t1)) next.addFirst(t1);
601             if (t2 != null && !visited.contains(t2)) next.addFirst(t2);
602             if (t3 != null && !visited.contains(t3)) next.addFirst(t3);
603             return ret;
604         }
605     }
606
607     /** [UNIQUE] a triangle (face) */
608     public final class T extends Triangle {
609         public final E e1;
610         public final int color;
611
612         public void destroy() {
613         }
614
615         T(E e1) {
616             this.e1 = e1;
617             E e2 = e1.next;
618             E e3 = e2.next;
619             if (e1==e2 || e1==e3) throw new Error();
620             if (e3.next!=e1) throw new Error();
621             if (e1.t!=null || e2.t!=null || e3.t!=null) throw new Error("non-manifold surface or disagreeing normals");
622             e1.t = this;
623             e1.next.t = this;
624             e1.next.next.t = this;
625
626             // FIXME: check for sealed/watertight surface once construction is complete (and infer normal(s)?)
627
628             int color = Math.abs(random.nextInt());
629             while(true) {
630                 color = color % 4;
631                 if (e1().pair.t != null && color == e1().pair.t.color) { color++; continue; }
632                 if (e2().pair.t != null && color == e2().pair.t.color) { color++; continue; }
633                 if (e3().pair.t != null && color == e3().pair.t.color) { color++; continue; }
634                 break;
635             }
636             this.color = color;
637
638             v1().kdinsert();
639             v2().kdinsert();
640             v3().kdinsert();
641         }
642         public E e1() { return e1; }
643         public E e2() { return e1.next; }
644         public E e3() { return e1.prev; }
645         public Vert v1() { return e1.p1; }
646         public Vert v2() { return e1.p2; }
647         public Vert v3() { return e1.next.p2; }
648         public Point p1() { return e1.p1.p; }
649         public Point p2() { return e1.p2.p; }
650         public Point p3() { return e1.next.p2.p; }
651         public boolean hasE(E e) { return e1==e || e1.next==e || e1.prev==e; }
652         public boolean has(Vert v) { return v1()==v || v2()==v || v3()==v; }
653     }
654
655 }