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