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