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