checkpoint
[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.bind.*;
11 import edu.berkeley.qfat.geom.Point;
12 import com.infomatiq.jsi.IntProcedure;
13
14 // EDGES RUN COUNTER-CLOCKWISE
15
16 public class Mesh implements Iterable<Mesh.T> {
17
18     public static final float EPSILON = (float)0.0001;
19     public static final Random random = new Random();
20
21     private RTree<T>         triangles = new RTree<T>();
22     private PointSet<Vertex> vertices  = new PointSet<Vertex>();
23
24     public boolean option_wireframe    = false;
25     public boolean option_errorNormals = false;
26     public boolean option_selectable   = true;
27
28     public void render(GL gl, Matrix m) {
29         if (option_wireframe) {
30             gl.glDisable(GL.GL_LIGHTING);
31             gl.glBegin(GL.GL_LINES);
32             gl.glColor3f(1, 1, 1);
33             for (T t : this) {
34                 // fixme used to be .goodp
35                 m.times(t.e1().v1.p).glVertex(gl);
36                 m.times(t.e1().v2.p).glVertex(gl);
37                 m.times(t.e2().v1.p).glVertex(gl);
38                 m.times(t.e2().v2.p).glVertex(gl);
39                 m.times(t.e3().v1.p).glVertex(gl);
40                 m.times(t.e3().v2.p).glVertex(gl);
41             }
42             gl.glEnd();
43             gl.glEnable(GL.GL_LIGHTING);
44             return;
45         }
46         for(T t : this) {
47             gl.glColor4f((float)(0.25+(0.05*t.color)),
48                          (float)(0.25+(0.05*t.color)),
49                          (float)(0.75+(0.05*t.color)),
50                          (float)0.3); 
51             /*
52             if (t.red) {
53             gl.glColor4f((float)(0.75+(0.05*t.color)),
54                          (float)(0.25+(0.05*t.color)),
55                          (float)(0.25+(0.05*t.color)),
56                          (float)0.3); 
57             }
58             */
59             t.glTriangle(gl, m);
60         }
61         if (option_errorNormals)
62             for(T t : this)
63                 for(Mesh.Vertex p : new Mesh.Vertex[] { t.v1(), t.v2(), t.v3() }) {
64                     if (p.ok) {
65                         gl.glBegin(GL.GL_LINES);
66                         gl.glColor3f(1, 1, 1);
67                         p.p.glVertex(gl);
68                         p.p.plus(p.norm().times((float)p.error()*10)).glVertex(gl);
69                         gl.glEnd();
70                     }
71                 }
72     }
73
74     public boolean immutableVertices;
75     public Mesh    error_against      = null;
76     public double  error              = 0;
77
78     public Mesh(boolean immutableVertices) { this.immutableVertices = immutableVertices; }
79
80     public void makeVerticesImmutable() { this.immutableVertices = true; }
81     public float error() { return (float)error; }
82
83     public int size() { return vertices.size(); }
84     public Iterable<Vertex> vertices() { return vertices; }
85     public Iterator<T> iterator() { return triangles.iterator(); }
86
87     public void rebindPoints() {
88         // unbind all points
89         for(Mesh.T t : this) {
90             t.v1().unbind();
91             t.v2().unbind();
92             t.v3().unbind();
93         }
94         // ask edges to re-implement their bindings
95         for(Mesh.T t : this) {
96             t.e1().dobind();
97             t.e2().dobind();
98             t.e3().dobind();
99         }
100         System.out.println("rebound!");
101     }
102
103     public void transform(Matrix m) {
104         ArrayList<Vertex> set = new ArrayList<Vertex>();
105         for(Vertex v : vertices) set.add(v);
106         for(Vertex v : set) v.transform(m.times(v.p), true, null);
107         for(Vertex v : set) v.goodp = v.p;
108     }
109
110     public void rebuild() { /*vertices.rebuild();*/ }
111     public Vec diagonal() { return vertices.diagonal(); }
112     public Point centroid() { return vertices.centroid(); }
113     public Vertex nearest(Point p) { return vertices.nearest(p); }
114
115     /** compute the volume of the mesh */
116     public float volume() {
117         double total = 0;
118         for(T t : this) {
119             double area = t.area();
120             Vec origin_to_centroid = new Vec(new Point(0, 0, 0), t.centroid());
121             boolean facingAway = t.norm().dot(origin_to_centroid) > 0;
122             double height = Math.abs(t.norm().dot(origin_to_centroid));
123             total += ((facingAway ? 1 : -1) * area * height) / 3.0;
124         }
125         return (float)total;
126     }
127
128
129     public void subdivide() {
130         for (Vertex v : vertices()) v.original = true;
131         HashSet<E> edges = new HashSet<E>();
132         HashSet<E> flip = new HashSet<E>();
133         HashSet<T> tris = new HashSet<T>();
134         int count = 0;
135         for (T t : this) {
136             tris.add(t);
137             edges.add(t.e1());
138             edges.add(t.e2());
139             edges.add(t.e3());
140             count++;
141         }
142         System.out.println("triangles="+count);
143         count = 0;
144         for(E e : edges) {
145             if (e.destroyed || e.shattered) continue;
146             e.shatter().edge = true;
147             for(E ex : (Iterable<E>)e.getBoundPeers()) {
148                 Vertex m = nearest(ex.midpoint());
149                 m.edge = true;
150                 E e3 = ex.v1.getE(m).next;
151                 if (e3.v2.original)
152                     flip.add(e3);
153             }
154         }
155
156         int i=0;
157
158         for(E e : flip) {
159             e.flip();
160             System.out.println("flip!");
161             i++;
162         }
163
164         System.out.println("count="+count);
165
166         rebindPoints();
167         HashSet<Vertex> verts = new HashSet<Vertex>();
168         for(Vertex v : vertices()) verts.add(v);
169         for (Vertex v : verts)
170             v.clearWish();
171         for (Vertex v : verts) {
172             if (v.edge) {
173                 for(E e = v.e; e!=null; e=e.pair.next==v.e?null:e.pair.next) {
174                     if (e.v2.original) {
175                         v.wish(e.v2);
176                         v.wish(e.v2);
177                         v.wish(e.v2);
178                         v.wish(e.v2);
179                     }
180                 }
181                 for(E e = v.e; e!=null; e=e.pair.next==v.e?null:e.pair.next) {
182                     for(E e2 = e.v2.e; e2!=null; e2=e2.pair.next==e.v2.e?null:e2.pair.next) {
183                         if (e2.v2.original) {
184                             v.wish(e.v2);
185                         }
186                     }
187                 }
188             }
189         }
190         for (Vertex v : verts)
191             v.grantWish();
192         System.out.println("-------------------------------------------------------------------");
193         /*
194         for (Vertex v : verts) {
195             if (v.original) {
196                 int n=0;
197                 for(E e = v.e; e!=null; e=e.pair.next==v.e?null:e.pair.next) {
198                     n++;
199                     v.wish(e.midpoint());
200                     v.wish(e.midpoint());
201                     v.wish(e.next.pair.t.centroid());
202                 }
203                 v.avgWish();
204                 v.wishes = 3;
205                 for(int j=0; j<n-3; j++)
206                     v.wish(v.getPoint());
207             }
208         }
209         for (Vertex v : verts)
210             v.avgWish();
211         for (Vertex v : verts)
212             v.grantWish();
213         */
214     }
215
216     // Vertexices //////////////////////////////////////////////////////////////////////////////
217
218     /** a vertex in the mesh */
219     public final class Vertex extends HasQuadric implements Visitor {
220         public Point p, goodp;
221         public Point oldp;
222         E e;                // some edge *leaving* this point
223
224         public boolean original = false;
225         public boolean edge = false;
226         public boolean face = false;
227
228         private int wishes = 0;
229         private Point wish = Point.ZERO;
230         public void clearWish() { wishes = 0; wish = Point.ZERO; }
231         public void wish(HasPoint hp) {
232             Point p = hp.getPoint();
233             wishes++;
234             wish = new Point(wish.x+p.x, wish.y+p.y, wish.z+p.z);
235         }
236         public void grantWish() {
237             for(Vertex v : (Iterable<Vertex>)getBoundPeers()) {
238                 if (v==this) continue;
239                 if (v.wishes==0) continue;
240                 Point p = this.getBindingMatrix(v).times(v.wish.minus(Point.ZERO).div(v.wishes).plus(Point.ZERO));
241                 wish = p.minus(Point.ZERO).times(v.wishes).plus(wish);
242                 wishes += v.wishes;
243                 v.clearWish();
244             }
245             if (wishes==0) return;
246             Vec d = wish.minus(Point.ZERO).div(wishes).plus(Point.ZERO).minus(getPoint());
247             move(d, false);
248             clearWish();
249         }
250         public void avgWish() {
251             if (wishes==0) return;
252             wish = wish.minus(Point.ZERO).div(wishes).plus(Point.ZERO);
253             wishes = 1;
254         }
255
256         private boolean illegal = false;
257
258         public boolean visible = false;
259
260         public Point getPoint() { return p; }
261         public float error() { return olderror; }
262
263         private Vertex(Point p) {
264             this.p = p;
265             this.goodp = p;
266             this.oldp = p;
267             if (vertices.get(p) != null) throw new Error();
268             vertices.add(this);
269         }
270
271         public void reinsert() {
272             vertices.remove(this);
273             vertices.add(this);
274             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next) e.t.reinsert();
275         }
276
277         // the average of all adjacent points
278         public Point recenter() {
279             int count = 0;
280             Vec vec = Vec.ZERO;
281             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next) {
282                 vec = vec.plus(e.getOther(this).getPoint().minus(Point.ZERO));
283                 count++;
284             }
285             return Point.ZERO.plus(vec.div(count));
286         }
287
288         public float olderror = 0;
289         public void setError(float nerror) {
290             error -= olderror;
291             olderror = nerror;
292             error += olderror;
293         }
294
295         /*
296         public Vertex hack(GL gl, Point mouse) {
297             double dist = Double.MAX_VALUE;
298             Vertex cur = null;
299             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next) {
300                 Vertex v = e.getOther(this);
301                 double dist2 = v.getPoint().glProject(gl).distance(mouse);
302                 if ((cur==null || dist2 < dist) && v.visible) {
303                     dist = dist2;
304                     cur = v;
305                 }
306             }
307             return cur;
308         }
309         */
310
311         public float averageTriangleArea() {
312             int count = 0;
313             float ret = 0;
314             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next) {
315                 ret += e.t.area();
316                 count++;
317             }
318             return ret/count;
319         }
320         public float averageEdgeLength() {
321             int count = 0;
322             float ret = 0;
323             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next) {
324                 ret += e.length();
325                 count++;
326             }
327             return ret/count;
328         }
329
330         public Matrix _recomputeFundamentalQuadric() {
331             Matrix m = Matrix.ZERO;
332             int count = 0;
333             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next) {
334                 m = m.plus(e.t.norm().fundamentalQuadric(e.t.centroid()));
335                 count++;
336             }
337             if (count > 0) {
338                 m = m.plus(norm().fundamentalQuadric(this.p).times(count));
339                 count *= 2;
340             }
341             return m.times(1/(float)count);
342         }
343
344         public HasQuadric nearest() { return error_against==null ? null : error_against.vertices.nearest(p, this); }
345         public void computeError() {
346             if (error_against==null) return;
347             if (nearest_in_other_mesh == null && nearest()==null) return;
348             float nerror =
349                 nearest_in_other_mesh != null
350                 ? nearest_in_other_mesh.fundamentalQuadric().preAndPostMultiply(p)
351                 : nearest().fundamentalQuadric().preAndPostMultiply(p);
352             if (quadric_count != 0)
353                 nerror = (nerror + quadric.preAndPostMultiply(p))/(quadric_count+1);
354
355             if (!immutableVertices && quadric_count == 0) {
356                 //nerror = Math.max(nerror, 0.4f);
357                 //nerror *= 2;
358             }
359             //System.out.println(nerror);
360             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next) {
361                 double ang = e.dihedralAngle();
362                 if (ang > Math.PI) throw new Error();
363                 if (ang < -Math.PI) throw new Error();
364                 float minangle = (float)(Math.PI * 0.8);
365                 //nerror += ((ang / Math.PI)*(ang/Math.PI)) * e.length() * 0.05;
366
367                 //nerror += (1-e.t.quality())*0.0001;
368                 if (ang > minangle) nerror += (ang - minangle);
369
370                 //System.out.println(((ang / Math.PI)*(ang/Math.PI)) * 0.000001);
371                 /*
372                 if (e.t.aspect() < 0.2) {
373                     nerror += (0.2-e.t.aspect()) * 10;
374                 }
375                 */
376             }
377             if (!immutableVertices) {
378                 Vertex n = (Vertex)nearest();
379                 float d = norm().dot(n.norm());
380                 if (d > 1 || d < -1) throw new Error();
381                 if (d >= 0) {
382                     nerror *= (2.0f - d);
383                 } else {
384                     nerror += 0.0003 * (2.0f + d);
385                     nerror *= (2.0f + d);
386                 }
387             }
388
389             setError(nerror);
390         }
391
392         public boolean move(Vec vv, boolean ignoreProblems) {
393
394             boolean good = true;
395
396             //     t1' = M * t1
397             //     t2' = t2.getMatrix(t1) * t1'
398             //     t2' = t2.getMatrix(t1) * M * t1
399             //     t1 =     t1.getMatrix(t2) * t2
400             // M * t1 = M * t1.getMatrix(t2) * t2
401
402             /*
403             if (bindingGroup!=null && this != bindingGroup.getMaster()) {
404                 Matrix m2 = getBindingMatrix(bindingGroup.getMaster());
405                 Vec v2 = m2.times(vv.plus(getPoint())).minus(m2.times(getPoint()));
406                 return ((Vertex)bindingGroup.getMaster()).move(v2, ignoreProblems);
407             }
408             */
409
410             Point op = this.p;
411             Point pt = vv.plus(getPoint());
412             Point pp = pt;
413             pt = getBindingConstraint().getProjection(pp);
414             if (pt==null) return false;
415             System.out.println(pt.minus(pp).mag() + " " + getBindingConstraint());
416
417             for(Vertex v : (Iterable<Vertex>)getBoundPeers()) {
418                 Point pt2 = v.getBindingMatrix(this).times(pt);
419                 /*
420                 if (Math.abs( v.p.minus(pt2).mag() / pt.minus(op).mag() ) > 5)
421                     throw new Error(v.p+" "+pt2+"\n"+op+" "+pt+"\n"+v.getBindingMatrix(this));
422                 if (Math.abs( v.p.minus(pt2).mag() / pt.minus(op).mag() ) < 1/5) throw new Error();
423                 */
424                 good &= v.transform(pt2, ignoreProblems, v.getBindingMatrix(this));
425             }
426
427             if (!good && !ignoreProblems) {
428                 for(Vertex v : (Iterable<Vertex>)getBoundPeers()) 
429                     v.transform(v.oldp, true, null);
430             }
431
432             for(Vertex v : (Iterable<Vertex>)getBoundPeers())
433                 v.recomputeFundamentalQuadricIfNeighborChanged();
434             for(Vertex v : (Iterable<Vertex>)getBoundPeers())
435                 v.reComputeErrorAround();
436             ok = true;
437             return good;
438         }
439         public boolean ok = true;
440
441         /** does NOT update bound pairs! */
442         private boolean transform(Point newp, boolean ignoreProblems, Matrix yes) {
443             this.oldp = this.p;
444             if (immutableVertices) throw new Error();
445
446             unApplyQuadricToNeighbor();
447
448             boolean illegalbefore = illegal;
449             illegal = false;
450             /*
451             if (this.p.minus(newp).mag() > 0.1 && !ignoreProblems) {
452                 try {
453                     throw new Exception(""+this.p.minus(newp).mag()+" "+ignoreProblems+" "+yes);
454                 } catch(Exception e) {
455                     e.printStackTrace();
456                 }
457                 illegal = true;
458             }
459             */
460
461             this.p = newp;
462             reinsert();
463             applyQuadricToNeighbor();
464
465             if (!ignoreProblems) {
466                 checkLegality();
467             }
468             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next)
469                 e.v2.quadricStale = true;
470             return !illegal || (illegalbefore && illegal);
471         } 
472
473         public void checkLegality() {
474             /*
475             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next) {
476                 if (Math.abs(e.dihedralAngle()) > (Math.PI * 0.9) ||
477                     Math.abs(e.next.dihedralAngle()) > (Math.PI * 0.9)) illegal = true;
478                 if (e.t.aspect() < 0.2) illegal = true;
479             }
480             */
481             if (!illegal) triangles.range(oldp, this.p, (Visitor<T>)this);
482         }
483
484         public void reComputeErrorAround() {
485             reComputeError();
486             if (nearest_in_other_mesh != null)
487                 nearest_in_other_mesh.reComputeError();
488             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next)
489                 e.v2.reComputeError();
490         }
491
492         public boolean visit(Object o) {
493             if (o instanceof Vertex)
494                 return ((Vertex)o).e != null && ((Vertex)o).norm().dot(Vertex.this.norm()) >= 0;
495             T t = (T)o;
496             if (illegal) return false;
497             for(E e = Vertex.this.e; e!=null; e=e.pair.next==Vertex.this.e?null:e.pair.next) {
498                 if (!t.has(e.v1) && !t.has(e.v2) && e.intersects(t)) { illegal = true; }
499                 if (e.t != null) {
500                     if (!e.t.has(t.e1().v1) && !e.t.has(t.e1().v2) && t.e1().intersects(e.t)) { illegal = true; }
501                     if (!e.t.has(t.e2().v1) && !e.t.has(t.e2().v2) && t.e2().intersects(e.t)) { illegal = true; }
502                     if (!e.t.has(t.e3().v1) && !e.t.has(t.e3().v2) && t.e3().intersects(e.t)) { illegal = true; }
503                 }
504             }
505             return !illegal;
506         }
507
508         public E getEdge() { return e; }
509         public E getFreeIncident() {
510             E ret = getFreeIncident(e, e);
511             if (ret != null) return ret;
512             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next)
513                 System.out.println(e + " " + e.t);
514             throw new Error("unable to find free incident to " + this);
515         }
516
517         public E getFreeIncident(E start, E before) {
518             for(E e = start; e!=null; e=e.pair.next==before?null:e.pair.next)
519                 if (e.pair.v2 == this && e.pair.t == null && e.pair.next.t == null)
520                     return e.pair;
521             return null;
522         }
523
524         public E getE(Point v2) {
525             Vertex v = vertices.get(v2);
526             if (v==null) return null;
527             return getE(v);
528         }
529         public E getE(Vertex v2) {
530             if (this.e!=null && this!=this.e.v1 && this!=this.e.v2) throw new RuntimeException();
531             int i=0;
532             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next) {
533                 if (e.v1 == this && e.v2 == v2) return e;
534                 i++;
535                 e.sanity();
536                 if (e.destroyed) throw new RuntimeException("fark " + i + " " + e.prev + " " + (e.prev.next==e) + " " + e.prev.destroyed);
537             }
538             return null;
539         }
540
541         private void glNormal(GL gl) {
542             Vec norm = norm();
543             gl.glNormal3f(norm.x, norm.y, norm.z);
544         }
545         public Vec norm() {
546             Vec norm = new Vec(0, 0, 0);
547             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next)
548                 if (e.t != null)
549                     norm = norm.plus(e.t.norm().times((float)e.prev.angle()));
550             return norm.norm();
551         }
552
553         public void bindTo(Vertex p) { bindTo(Matrix.ONE, p); }
554     }
555
556
557     /** [UNIQUE] an edge */
558     public final class E extends HasBindingGroup implements Comparable<E> {
559
560         public void sanity() {
561             if (destroyed) return;
562             if (pair!=null && (pair.v1!=v2 || pair.v2!=v1)) throw new RuntimeException();
563             if (next!=null && next.v1!=v2) throw new RuntimeException();
564             if (prev!=null && prev.v2!=v1) throw new RuntimeException();
565         }
566
567         public final Vertex v1, v2;
568         T t;     // triangle to our "left"
569         E prev;  // previous half-edge
570         E next;  // next half-edge
571         E pair;  // partner half-edge
572         boolean shattered = false;
573
574         public boolean intersects(T t) { return t.intersects(v1.p, v2.p); }
575
576         public Segment getSegment() { return new Segment(v1.getPoint(), v2.getPoint()); }
577
578         public void flip() {
579             // FIXME: coplanarity check needed
580             if (destroyed) return;
581             for (E e : (Iterable<E>)getBoundPeers()) {
582                 if (!e.pair.isBoundTo(pair)) throw new RuntimeException("cannot flip!");
583             }
584             Vertex v1 = t.getOtherVertex(this);
585             Vertex v2 = pair.t.getOtherVertex(pair);
586             destroy();
587             pair.destroy();
588             T t1 = newT(v1, v2, this.v2);
589             T t2 = newT(v2, v1, this.v1);
590             t1.e1().sanity();
591             t1.e2().sanity();
592             t1.e3().sanity();
593             t2.e1().sanity();
594             t2.e2().sanity();
595             t2.e3().sanity();
596
597             for (E e : (Iterable<E>)getBoundPeers()) {
598                 if (e==this) continue;
599                 if (e.destroyed) continue;
600                 Vertex v1e = e.t.getOtherVertex(e);
601                 Vertex v2e = e.pair.t.getOtherVertex(e.pair);
602                 e.destroy();
603                 e.pair.destroy();
604                 if (v1e.getE(v2e)!=null) throw new RuntimeException();
605                 newT(v1e, v2e, e.v2).red = true;
606                 newT(v2e, v1e, e.v1).red = true;
607                 v2e.getE(v1e).bindTo(e.getBindingMatrix(this), v1.getE(v2));
608                 v1e.getE(v2e).bindTo(e.pair.getBindingMatrix(this.pair), v2.getE(v1));
609             }
610
611         }
612
613         public void bindingGroupChanged() {
614             HashSet<E> nbg = new HashSet<E>();
615             for(E eother : (Iterable<E>)getBoundPeers()) nbg.add(eother);
616             for(E eother : nbg) {
617                 if (next==null || prev==null) continue;
618                 if (eother.next==null || eother.prev==null) continue;
619
620                 if (next.isBoundTo(eother.pair.prev.pair) && !prev.isBoundTo(eother.pair.next.pair))
621                     prev.bindTo(next.getBindingMatrix(eother.pair.prev.pair), eother.pair.next.pair);
622                 if (!next.isBoundTo(eother.pair.prev.pair) && prev.isBoundTo(eother.pair.next.pair))
623                     next.bindTo(prev.getBindingMatrix(eother.pair.next.pair), eother.pair.prev.pair);
624
625                 /*
626                 if (next.isBoundTo(eother.prev) && !prev.isBoundTo(eother.next))
627                     prev.bindTo(next.getBindingMatrix(eother.prev), eother.next);
628                 if (!next.isBoundTo(eother.prev) && prev.isBoundTo(eother.next))
629                     next.bindTo(prev.getBindingMatrix(eother.next), eother.prev);
630                 */
631                 if (next.isBoundTo(eother.next) && !prev.isBoundTo(eother.prev))
632                     prev.bindTo(next.getBindingMatrix(eother.next), eother.prev);
633                 if (!next.isBoundTo(eother.next) && prev.isBoundTo(eother.prev))
634                     next.bindTo(prev.getBindingMatrix(eother.prev), eother.next);
635             }
636
637         }
638
639         public float stretchRatio() {
640             Vertex nearest = error_against.nearest(midpoint());
641             float nearest_distance = midpoint().distance(nearest.p);
642             float other_distance =
643                 (v1.p.distance(error_against.nearest(v1.p).p)+
644                  v2.p.distance(error_against.nearest(v2.p).p))/2;
645             return nearest_distance/other_distance;
646         }
647         public float comparator() {
648             return length();
649         }
650         public int compareTo(E e) {
651             return e.comparator() > comparator() ? 1 : -1;
652         }
653         public void bindEdge(E e, Matrix m) {
654             _bindEdge(e, m);
655             pair._bindEdge(e.pair, m);
656         }
657         public void _bindEdge(E e, Matrix m) {
658             e = e.pair;
659             /*
660             //assumes edges are identical length at binding time
661             Vec reflectionPlaneNormal = e.v2.p.minus(e.v1.p).norm();
662             float a = reflectionPlaneNormal.x;
663             float b = reflectionPlaneNormal.y;
664             float c = reflectionPlaneNormal.z;
665             Matrix reflectionMatrix =
666                 new Matrix( 1-2*a*a,  -2*a*b,  -2*a*c, 0,
667                             -2*a*b,  1-2*b*b,  -2*b*c, 0,
668                             -2*a*c,   -2*b*c, 1-2*c*c, 0,
669                             0,       0,       0,       1);
670             m = m.times(Matrix.translate(e.midpoint().minus(Point.ORIGIN))
671                         .times(reflectionMatrix)
672                         .times(Matrix.translate(Point.ORIGIN.minus(e.midpoint()))));
673             System.out.println(reflectionPlaneNormal);
674             System.out.println("  " + v1.p + " " + m.times(e.v1.p));
675             System.out.println("  " + v2.p + " " + m.times(e.v2.p));
676             */
677             /*
678             if (m.times(e.v1.p).minus(v1.p).mag() > EPSILON) throw new Error();
679             if (m.times(e.v2.p).minus(v2.p).mag() > EPSILON) throw new Error();
680             */
681             this.bindTo(m, e);
682         }
683         
684         public void dobind() {
685             for(E e : (Iterable<E>)getBoundPeers()) {
686                 if (e==this) continue;
687                 v1.bindTo(getBindingMatrix(e), e.v1);
688                 v2.bindTo(getBindingMatrix(e), e.v2);
689                 /*
690                 e.v1.setConstraint(getAffineConstraint());
691                 e.v2.setConstraint(getAffineConstraint());
692                 */
693             }
694         }
695
696         public Vertex shatter() {
697             if (shattered || destroyed) return nearest(midpoint());
698             shattered = true;
699             E first = null;
700             E firste = null;
701             E firstx = null;
702             E firstq = null;
703             for(E e : (Iterable<E>)getBoundPeers()) {
704                 E enext = e.next;
705                 E eprev = e.prev;
706                 E pnext = e.pair.next;
707                 E pprev = e.pair.prev;
708                 Point mid = e.midpoint();
709                 Vertex r = e.next.v2;
710                 Vertex l = e.pair.next.v2;
711                 if (!e.destroyed) {
712                     e.destroy();
713                     e.pair.destroy();
714                     newT(r.p, e.v1.p, mid,    null, 0);
715                     newT(r.p, mid,    e.v2.p, null, 0);
716                     newT(l.p, mid,    e.v1.p, null, 0);
717                     newT(l.p, e.v2.p, mid,    null, 0);
718                 }
719             }
720             for(E e : (Iterable<E>)getBoundPeers()) {
721                 Point mid = e.midpoint();
722                 if (first==null) {
723                     first = e.v1.getE(mid);
724                     firste = e;
725                     firstx = e.pair;
726                     firstq = e.v2.getE(mid).pair;
727                     continue;
728                 }
729                 e.v1.getE(mid).          bindTo(e.getBindingMatrix(firste), first);
730                 e.v1.getE(mid).pair.     bindTo(e.getBindingMatrix(firste), first.pair);
731                 e.v2.getE(mid).pair.     bindTo(e.getBindingMatrix(firste), firstq);
732                 e.v2.getE(mid).pair.pair.bindTo(e.getBindingMatrix(firste), firstq.pair);
733             }
734             /*
735             first.setConstraint(firste.getAffineConstraint());
736             firstq.setConstraint(firste.getAffineConstraint());
737             */
738             return nearest(midpoint());
739         }
740
741         public boolean destroyed = false;
742         public void destroy() {
743             if (destroyed) return;
744             destroyed = true;
745             pair.destroyed = true;
746
747             if (t != null) t.destroy();
748             t = null;
749
750             if (pair.t != null) pair.t.destroy();
751             pair.t = null;
752
753             if (next.t != null) next.t.destroy();
754             if (prev.t != null) prev.t.destroy();
755             next.t = null;
756             prev.t = null;
757
758             if (pair.next.t != null) pair.next.t.destroy();
759             if (pair.prev.t != null) pair.next.t.destroy();
760             pair.next.t = null;
761             pair.prev.t = null;
762
763             pair.prev.next = next;
764             next.prev = pair.prev;
765             prev.next = pair.next;
766             pair.next.prev = prev;
767
768             if (v1.e == this) v1.e = pair.next;
769             if (pair.v1.e == pair) pair.v1.e = next;
770
771             if (v2.e == this) throw new RuntimeException();
772             if (pair.v2.e == pair) throw new RuntimeException();
773
774             /*
775             next = pair;
776             prev = pair;
777             pair.next = this;
778             pair.prev = this;
779             */
780
781             /*
782             pair.prev = null;
783             pair.next = null;
784             next = null;
785             prev = null;
786             */
787
788             /*
789             sanity();
790             next.sanity();
791             prev.sanity();
792             pair.sanity();
793             */
794         }
795
796         private void sync() {
797             this.prev.next = this;
798             this.next.prev = this;
799             this.pair.pair = this;
800             if (this.next.v1 != v2) throw new Error();
801             if (this.prev.v2 != v1) throw new Error();
802             if (this.v1.e == null) this.v1.e = this;
803             if (!added) added = true;
804         }
805         private boolean added = false;
806
807         public T makeT(int colorclass) { return t==null ? (t = new T(this, colorclass)) : t; }
808
809         public double dihedralAngle() {
810             Vec v1 = t.norm().times(-1);
811             Vec v2 = pair.t.norm().times(-1);
812             double prod = v1.norm().dot(v2.norm());
813             prod = Math.min(1,prod);
814             prod = Math.max(-1,prod);
815             double ret = Math.acos(prod);
816             if (Double.isNaN(ret)) throw new Error("nan! " + prod);
817             return ret;
818         }
819
820         /** angle between this half-edge and the next */
821         public double angle() {
822             Vec v1 = next.v2.p.minus(this.v2.p);
823             Vec v2 = this.v1.p.minus(this.v2.p);
824             return Math.acos(v1.norm().dot(v2.norm()));
825         }
826
827         public Vertex getOther(Vertex v) {
828             if (this.v1 == v) return v2;
829             if (this.v2 == v) return v1;
830             throw new Error();
831         }
832
833         public void makeAdjacent(E e) {
834             if (this.next == e) return;
835             if (v2 != e.v1) throw new Error("cannot make adjacent -- no shared vertex: " + this + " " + e);
836             if (t != null || e.t != null) throw new Error("cannot make adjacent -- edges not both free " + t + " " + e.t);
837
838             E freeIncident = v2.getFreeIncident(e, this);
839
840             e.prev.next = freeIncident.next;
841             freeIncident.next.prev = e.prev;
842
843             freeIncident.next = this.next;
844             this.next.prev = freeIncident;
845             
846             this.next = e;
847             e.prev = this;
848
849             sync();
850             freeIncident.sync();
851         }
852
853         /** creates an isolated edge out in the middle of space */
854         public E(Point v1, Point v2) {
855             if (vertices.get(v1) != null) throw new Error();
856             if (vertices.get(v2) != null) throw new Error();
857             this.v1 = new Vertex(v1);
858             this.v2 = new Vertex(v2);
859             this.prev = this.next = this.pair = new E(this, this, this);
860             this.v1.e = this;
861             this.v2.e = this.pair;
862             sync();
863         }
864
865         /** adds a new half-edge from prev.v2 to v2 */
866         public E(E prev, Point p) {
867             Vertex v2;
868             v2 = vertices.get(p);
869             if (v2 == null) v2 = new Vertex(p);
870             this.v1 = prev.v2;
871             this.v2 = v2;
872             this.prev = prev;
873             if (prev.destroyed) throw new RuntimeException();
874             if (v2.getE(v1) != null) throw new Error();
875             if (v2.e==null) {
876                 this.next = this.pair = new E(this, this, prev.next);
877             } else {
878                 E q = v2.getFreeIncident();
879                 this.next = q.next;
880                 this.next.prev = this;
881                 E z = prev.next;
882                 this.prev.next = this;
883                 this.pair = new E(q, this, z);
884             }
885             if (v2.e==null) v2.e = this.pair;
886             sync();
887         }
888
889         /** adds a new half-edge to the mesh with a given predecessor, successor, and pair */
890         public E(E prev, E pair, E next) {
891             this.v1 = prev.v2;
892             this.v2 = next.v1;
893             if (prev.destroyed) throw new RuntimeException();
894             this.prev = prev;
895             this.next = next;
896             this.pair = pair;
897             sync();
898         }
899         public Point midpoint() { return new Point((v1.p.x+v2.p.x)/2, (v1.p.y+v2.p.y)/2, (v1.p.z+v2.p.z)/2); }
900         public boolean has(Vertex v) { return v==v1 || v==v2; }
901         public float length() { return v1.p.minus(v2.p).mag(); }
902         public String toString() { return v1+"->"+v2; }
903
904     }
905
906     public E makeE(Point p1, Point p2) {
907         Vertex v1 = vertices.get(p1);
908         Vertex v2 = vertices.get(p2);
909         if (v1 != null && v2 != null) {
910             E e = v1.getE(v2);
911             if (e != null) return e;
912             e = v2.getE(v1);
913             if (e != null) return e;
914         }
915         if (v1 != null) return new E(v1.getFreeIncident(), p2);
916         if (v2 != null) return new E(v2.getFreeIncident(), p1).pair;
917         return new E(p1, p2);
918     }
919     public boolean coalesce = false;
920     private static float round(float f) {
921         return Math.round(f*1000)/1000f;
922     }
923     public T newT(HasPoint v1, HasPoint v2, HasPoint v3) {
924         return newT(v1.getPoint(), v2.getPoint(), v3.getPoint(), null, 0);
925     }
926     public T newT(Point v1, Point v2, Point v3, Vec norm, int colorclass) {
927         if (coalesce) {
928
929             for(Vertex v : vertices) { if (v1.distance(v.p) < EPSILON) { v1 = v.p; break; } }
930             for(Vertex v : vertices) { if (v2.distance(v.p) < EPSILON) { v2 = v.p; break; } }
931             for(Vertex v : vertices) { if (v3.distance(v.p) < EPSILON) { v3 = v.p; break; } }
932             /*
933             v1 = new Point(round(v1.x), round(v1.y), round(v1.z));
934             v2 = new Point(round(v2.x), round(v2.y), round(v2.z));
935             v3 = new Point(round(v3.x), round(v3.y), round(v3.z));
936             */
937         }
938         if (norm != null) {
939             Vec norm2 = v3.minus(v1).cross(v2.minus(v1));
940             float dot = norm.dot(norm2);
941             //if (Math.abs(dot) < EPointSILON) throw new Error("dot products within evertsilon of each other: "+norm+" "+norm2);
942             if (dot < 0) { Point p = v1; v1=v2; v2 = p; }
943         }
944         E e12 = makeE(v1, v2);
945         E e23 = makeE(v2, v3);
946         E e31 = makeE(v3, v1);
947         while(e12.next != e23 || e23.next != e31 || e31.next != e12) {
948             e12.makeAdjacent(e23);
949             e23.makeAdjacent(e31);
950             e31.makeAdjacent(e12);
951         }
952         T ret = e12.makeT(colorclass);
953         if (e12.t == null) throw new Error();
954         if (e23.t == null) throw new Error();
955         if (e31.t == null) throw new Error();
956         return ret;
957     }
958
959     private int max_serial = 0;
960     /** [UNIQUE] a triangle (face) */
961     public final class T extends Triangle {
962         public final E e1;
963         public final int color;
964         public final int colorclass;
965
966         public boolean red = false;
967         public boolean old = false;
968
969         public final int serial = max_serial++;
970         public boolean occluded;
971
972         public Point shatter() {
973             if (destroyed) return null;
974             E e = e1();
975             
976             HashSet<E> forward = new HashSet<E>();
977             HashSet<E> backward = new HashSet<E>();
978             HashSet<E> both = new HashSet<E>();
979
980             for(E eb : (Iterable<E>)e.getBoundPeers()) {
981                 if (eb==e) continue;
982                 if (eb.next.isBoundTo(e.next) && eb.prev.isBoundTo(e.prev)) {
983                     forward.add(eb);
984                     both.add(eb);
985                 }
986                 if (eb.pair.next.pair.isBoundTo(e.prev) && eb.pair.prev.pair.isBoundTo(e.next)) {
987                     backward.add(eb.pair);
988                     both.add(eb.pair);
989                 }
990             }
991
992             Vertex v1 = e.t.v1();
993             Vertex v2 = e.t.v2();
994             Vertex v3 = e.t.v3();
995             Point c = e.t.centroid();
996             E e_next = e.next;
997             E e_prev = e.prev;
998             e.t.destroy();
999             newT(v1, v2, c);
1000             newT(c,  v2, v3);
1001             newT(v3, v1, c);
1002
1003             // FIXME: forward too
1004             for(E ex : backward) {
1005                 Vertex v1x = ex.t.v1();
1006                 Vertex v2x = ex.t.v2();
1007                 Vertex v3x = ex.t.v3();
1008                 Point cx = ex.t.centroid();
1009                 E ex_next = ex.next;
1010                 E ex_prev = ex.prev;
1011                 ex.t.destroy();
1012                 newT(v1x, v2x, cx);
1013                 newT(cx,  v2x, v3x);
1014                 newT(v3x, v1x, cx);
1015
1016                 // FIXME: i have no idea if this is right
1017                 e.next.bindTo(e.getBindingMatrix(ex.pair), ex.prev);
1018                 e.prev.bindTo(e.getBindingMatrix(ex.pair), ex.next);
1019                 e.next.pair.bindTo(e.getBindingMatrix(ex.pair), ex.prev.pair);
1020                 e.prev.pair.bindTo(e.getBindingMatrix(ex.pair), ex.next.pair);
1021
1022                 e_next.next.bindTo(e_next.getBindingMatrix(ex_prev.pair), ex_prev.prev.pair);
1023                 e_next.prev.bindTo(e_next.getBindingMatrix(ex_prev.pair), ex_prev.next.pair);
1024
1025                 e_prev.next.bindTo(e_prev.getBindingMatrix(ex_next.pair), ex_next.prev.pair);
1026                 e_prev.prev.bindTo(e_prev.getBindingMatrix(ex_next.pair), ex_next.next.pair);
1027             }
1028
1029             /*
1030
1031             E first = null;
1032             E firste = null;
1033             E firstx = null;
1034             E firstq = null;
1035             for(E e : (Iterable<E>)getBoundPeers()) {
1036                 E enext = e.next;
1037                 E eprev = e.prev;
1038                 E pnext = e.pair.next;
1039                 E pprev = e.pair.prev;
1040                 Point mid = e.midpoint();
1041                 Vertex r = e.next.v2;
1042                 Vertex l = e.pair.next.v2;
1043                 if (!e.destroyed) {
1044                     e.destroy();
1045                     e.pair.destroy();
1046                     newT(r.p, e.v1.p, mid,    null, 0);
1047                     newT(r.p, mid,    e.v2.p, null, 0);
1048                     newT(l.p, mid,    e.v1.p, null, 0);
1049                     newT(l.p, e.v2.p, mid,    null, 0);
1050                 }
1051             }
1052             for(E e : (Iterable<E>)getBoundPeers()) {
1053                 Point mid = e.midpoint();
1054                 if (first==null) {
1055                     first = e.v1.getE(mid);
1056                     firste = e;
1057                     firstx = e.pair;
1058                     firstq = e.v2.getE(mid).pair;
1059                     continue;
1060                 }
1061                 e.v1.getE(mid).          bindTo(e.getBindingMatrix(firste), first);
1062                 e.v1.getE(mid).pair.     bindTo(e.getBindingMatrix(firste), first.pair);
1063                 e.v2.getE(mid).pair.     bindTo(e.getBindingMatrix(firste), firstq);
1064                 e.v2.getE(mid).pair.pair.bindTo(e.getBindingMatrix(firste), firstq.pair);
1065             }
1066             */
1067             /*
1068             first.setConstraint(firste.getAffineConstraint());
1069             firstq.setConstraint(firste.getAffineConstraint());
1070             */
1071             return null;
1072         }
1073
1074
1075         T(E e1, int colorclass) {
1076             this.e1 = e1;
1077             E e2 = e1.next;
1078             E e3 = e2.next;
1079             if (e1==e2 || e1==e3) throw new Error();
1080             if (e3.next!=e1) throw new Error();
1081             if (e1.t!=null || e2.t!=null || e3.t!=null) throw new Error("non-manifold surface or disagreeing normals");
1082             e1.t = this;
1083             e1.next.t = this;
1084             e1.next.next.t = this;
1085
1086             // FIXME: check for sealed/watertight surface once construction is complete (and infer normal(s)?)
1087
1088             int color = Math.abs(random.nextInt());
1089             while(true) {
1090                 color = color % 4;
1091                 if (e1().pair.t != null && color == e1().pair.t.color) { color++; continue; }
1092                 if (e2().pair.t != null && color == e2().pair.t.color) { color++; continue; }
1093                 if (e3().pair.t != null && color == e3().pair.t.color) { color++; continue; }
1094                 break;
1095             }
1096             this.color = color;
1097             this.colorclass = colorclass;
1098             triangles.add(this);
1099         }
1100         public E e1() { return e1; }
1101         public E e2() { return e1.next; }
1102         public E e3() { return e1.prev; }
1103         public Vertex v1() { return e1.v1; }
1104         public Vertex v2() { return e1.v2; }
1105         public Vertex v3() { return e1.next.v2; }
1106         public Point p1() { return e1.v1.p; }
1107         public Point p2() { return e1.v2.p; }
1108         public Point p3() { return e1.next.v2.p; }
1109         public boolean hasE(E e) { return e1==e || e1.next==e || e1.prev==e; }
1110         public boolean has(Vertex v) { return v1()==v || v2()==v || v3()==v; }
1111
1112         public Vertex getOtherVertex(E e) {
1113             if (!hasE(e)) throw new RuntimeException();
1114             if (!e.has(v1())) return v1();
1115             if (!e.has(v2())) return v2();
1116             if (!e.has(v3())) return v3();
1117             throw new RuntimeException();
1118         }
1119
1120         public void removeFromRTree() { triangles.remove(this); }
1121         public void addToRTree() { triangles.insert(this); }
1122         public void destroy() {
1123             if (e1 != null) {
1124                 e1.t = null;
1125                 e1.next.t = null;
1126                 e1.prev.t = null;
1127             }
1128             triangles.remove(this);
1129             destroyed = true;
1130         }
1131         public void reinsert() { triangles.remove(this); triangles.add(this); }
1132
1133         private boolean destroyed = false;
1134         public boolean destroyed() { return destroyed; }
1135
1136         public boolean shouldBeDrawn() {
1137
1138             if (e1().bindingGroupSize() <= 1) return false;
1139             if (e2().bindingGroupSize() <= 1) return false;
1140             if (e3().bindingGroupSize() <= 1) return false;
1141
1142             return true;
1143         }
1144
1145         public void glTriangle(GL gl, Matrix m) {
1146             gl.glPushName(serial);
1147             gl.glBegin(GL.GL_TRIANGLES);
1148             glVertices(gl, m);
1149             gl.glEnd();
1150             gl.glPopName();
1151         }
1152
1153         /** issue gl.glVertex() for each of the triangle's points */
1154         public void glVertices(GL gl, Matrix m) {
1155             if (!shouldBeDrawn()) return;
1156             super.glVertices(gl, m);
1157         }
1158     }
1159 }