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
23     public boolean option_wireframe = false;
24     public boolean option_errorNormals = false;
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     // Vertexices //////////////////////////////////////////////////////////////////////////////
119
120     /** a vertex in the mesh */
121     public final class Vertex extends HasQuadric implements Visitor {
122         public Point p, goodp;
123         public Point oldp;
124         E e;                // some edge *leaving* this point
125
126         private boolean illegal = false;
127
128         public boolean visible = false;
129
130         public Point getPoint() { return p; }
131         public float error() { return olderror; }
132
133         private Vertex(Point p) {
134             this.p = p;
135             this.goodp = p;
136             this.oldp = p;
137             if (vertices.get(p) != null) throw new Error();
138             vertices.add(this);
139         }
140
141         public void reinsert() {
142             vertices.remove(this);
143             vertices.add(this);
144             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next) e.t.reinsert();
145         }
146
147         public float olderror = 0;
148         public void setError(float nerror) {
149             error -= olderror;
150             olderror = nerror;
151             error += olderror;
152         }
153
154         /*
155         public Vertex hack(GL gl, Point mouse) {
156             double dist = Double.MAX_VALUE;
157             Vertex cur = null;
158             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next) {
159                 Vertex v = e.getOther(this);
160                 double dist2 = v.getPoint().glProject(gl).distance(mouse);
161                 if ((cur==null || dist2 < dist) && v.visible) {
162                     dist = dist2;
163                     cur = v;
164                 }
165             }
166             return cur;
167         }
168         */
169
170         public float averageTriangleArea() {
171             int count = 0;
172             float ret = 0;
173             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next) {
174                 ret += e.t.area();
175                 count++;
176             }
177             return ret/count;
178         }
179         public float averageEdgeLength() {
180             int count = 0;
181             float ret = 0;
182             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next) {
183                 ret += e.length();
184                 count++;
185             }
186             return ret/count;
187         }
188
189         public Matrix _recomputeFundamentalQuadric() {
190             Matrix m = Matrix.ZERO;
191             int count = 0;
192             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next) {
193                 m = m.plus(e.t.norm().fundamentalQuadric(e.t.centroid()));
194                 count++;
195             }
196             if (count > 0) {
197                 m = m.plus(norm().fundamentalQuadric(this.p).times(count));
198                 count *= 2;
199             }
200             return m.times(1/(float)count);
201         }
202
203         public HasQuadric nearest() { return error_against==null ? null : error_against.vertices.nearest(p, this); }
204         public void computeError() {
205             if (error_against==null) return;
206             float nerror =
207                 nearest_in_other_mesh != null
208                 ? nearest_in_other_mesh.fundamentalQuadric().preAndPostMultiply(p)
209                 : nearest().fundamentalQuadric().preAndPostMultiply(p);
210             if (quadric_count != 0)
211                 nerror = (nerror + quadric.preAndPostMultiply(p))/(quadric_count+1);
212
213             if (!immutableVertices && quadric_count == 0) {
214                 //nerror = Math.max(nerror, 0.4f);
215                 //nerror *= 2;
216             }
217             //System.out.println(nerror);
218             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next) {
219                 double ang = e.dihedralAngle();
220                 if (ang > Math.PI) throw new Error();
221                 if (ang < -Math.PI) throw new Error();
222                 float minangle = (float)(Math.PI * 0.8);
223                 //nerror += ((ang / Math.PI)*(ang/Math.PI)) * e.length() * 0.05;
224
225                 nerror += (1-e.t.quality())*0.0001;
226                 if (ang > minangle) nerror += (ang - minangle);
227
228                 //System.out.println(((ang / Math.PI)*(ang/Math.PI)) * 0.000001);
229                 /*
230                 if (e.t.aspect() < 0.2) {
231                     nerror += (0.2-e.t.aspect()) * 10;
232                 }
233                 */
234             }
235             if (!immutableVertices) {
236                 Vertex n = (Vertex)nearest();
237                 float d = norm().dot(n.norm());
238                 if (d > 1 || d < -1) throw new Error();
239                 if (d >= 0) {
240                     nerror *= (2.0f - d);
241                 } else {
242                     nerror += 0.0003 * (2.0f + d);
243                     nerror *= (2.0f + d);
244                 }
245             }
246
247             setError(nerror);
248         }
249
250         public boolean move(Matrix m, boolean ignoreProblems) {
251
252             boolean good = true;
253
254             //     t1' = M * t1
255             //     t2' = t2.getMatrix(t1) * t1'
256             //     t2' = t2.getMatrix(t1) * M * t1
257             //     t1 =     t1.getMatrix(t2) * t2
258             // M * t1 = M * t1.getMatrix(t2) * t2
259
260             if (bindingGroup!=null && this != bindingGroup.getMaster()) {
261                 Matrix v = getBindingMatrix(bindingGroup.getMaster());
262                 return ((Vertex)bindingGroup.getMaster()).move(v.inverse().times(m).times(v), ignoreProblems);
263             }
264
265             if (bindingGroup != null) {
266                 Matrix m2 = null;
267                 for(int i=0; i<20 && !m.equals(m2); i++) {
268                     m2 = m.times(getConstraint());
269                     //System.out.println(m.minus(m2));
270                 }
271                 if (!m.equals(m2)) return true;
272             }
273             ok = false;
274             Point op = this.p;
275             Point pt = m.times(this.p);
276             for(Vertex v : (Iterable<Vertex>)getBoundPeers()) {
277                 Point pt2 = v.getBindingMatrix(this).times(pt);
278                 /*
279                 if (Math.abs( v.p.minus(pt2).mag() / pt.minus(op).mag() ) > 5)
280                     throw new Error(v.p+" "+pt2+"\n"+op+" "+pt+"\n"+v.getBindingMatrix(this));
281                 if (Math.abs( v.p.minus(pt2).mag() / pt.minus(op).mag() ) < 1/5) throw new Error();
282                 */
283                 good &= v.transform(pt2, ignoreProblems, v.getBindingMatrix(this));
284             }
285
286             if (!good && !ignoreProblems) {
287                 for(Vertex v : (Iterable<Vertex>)getBoundPeers()) 
288                     v.transform(v.oldp, true, null);
289             }
290
291             for(Vertex v : (Iterable<Vertex>)getBoundPeers())
292                 v.recomputeFundamentalQuadricIfNeighborChanged();
293             for(Vertex v : (Iterable<Vertex>)getBoundPeers())
294                 v.reComputeErrorAround();
295             ok = true;
296             return good;
297         }
298         public boolean ok = true;
299
300         /** does NOT update bound pairs! */
301         private boolean transform(Point newp, boolean ignoreProblems, Matrix yes) {
302             this.oldp = this.p;
303             if (immutableVertices) throw new Error();
304
305             unApplyQuadricToNeighbor();
306
307
308             boolean illegalbefore = illegal;
309             illegal = false;
310             /*
311             if (this.p.minus(newp).mag() > 0.1 && !ignoreProblems) {
312                 try {
313                     throw new Exception(""+this.p.minus(newp).mag()+" "+ignoreProblems+" "+yes);
314                 } catch(Exception e) {
315                     e.printStackTrace();
316                 }
317                 illegal = true;
318             }
319             */
320
321             this.p = newp;
322             reinsert();
323             applyQuadricToNeighbor();
324
325             if (!ignoreProblems) {
326                 checkLegality();
327             }
328             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next)
329                 e.p2.quadricStale = true;
330             return !illegal || (illegalbefore && illegal);
331         } 
332
333         public void checkLegality() {
334             /*
335             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next) {
336                 if (Math.abs(e.dihedralAngle()) > (Math.PI * 0.9) ||
337                     Math.abs(e.next.dihedralAngle()) > (Math.PI * 0.9)) illegal = true;
338                 if (e.t.aspect() < 0.2) illegal = true;
339             }
340             */
341             if (!illegal) triangles.range(oldp, this.p, (Visitor<T>)this);
342         }
343
344         public void reComputeErrorAround() {
345             reComputeError();
346             if (nearest_in_other_mesh != null)
347                 nearest_in_other_mesh.reComputeError();
348             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next)
349                 e.p2.reComputeError();
350         }
351
352         public boolean visit(Object o) {
353             if (o instanceof Vertex)
354                 return ((Vertex)o).e != null && ((Vertex)o).norm().dot(Vertex.this.norm()) >= 0;
355             T t = (T)o;
356             if (illegal) return false;
357             for(E e = Vertex.this.e; e!=null; e=e.pair.next==Vertex.this.e?null:e.pair.next) {
358                 if (!t.has(e.p1) && !t.has(e.p2) && e.intersects(t)) { illegal = true; }
359                 if (e.t != null) {
360                     if (!e.t.has(t.e1().p1) && !e.t.has(t.e1().p2) && t.e1().intersects(e.t)) { illegal = true; }
361                     if (!e.t.has(t.e2().p1) && !e.t.has(t.e2().p2) && t.e2().intersects(e.t)) { illegal = true; }
362                     if (!e.t.has(t.e3().p1) && !e.t.has(t.e3().p2) && t.e3().intersects(e.t)) { illegal = true; }
363                 }
364             }
365             return !illegal;
366         }
367
368         public E getEdge() { return e; }
369         public E getFreeIncident() {
370             E ret = getFreeIncident(e, e);
371             if (ret != null) return ret;
372             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next)
373                 System.out.println(e + " " + e.t);
374             throw new Error("unable to find free incident to " + this);
375         }
376
377         public E getFreeIncident(E start, E before) {
378             for(E e = start; e!=null; e=e.pair.next==before?null:e.pair.next)
379                 if (e.pair.p2 == this && e.pair.t == null && e.pair.next.t == null)
380                     return e.pair;
381             return null;
382         }
383
384         public E getE(Point p2) {
385             Vertex v = vertices.get(p2);
386             if (v==null) return null;
387             return getE(v);
388         }
389         public E getE(Vertex p2) {
390             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next)
391                 if (e.p1 == this && e.p2 == p2) return e;
392             return null;
393         }
394
395         private void glNormal(GL gl) {
396             Vec norm = norm();
397             gl.glNormal3f(norm.x, norm.y, norm.z);
398         }
399         public Vec norm() {
400             Vec norm = new Vec(0, 0, 0);
401             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next)
402                 if (e.t != null)
403                     norm = norm.plus(e.t.norm().times((float)e.prev.angle()));
404             return norm.norm();
405         }
406
407         public void bindTo(Vertex p) { bindTo(Matrix.ONE, p); }
408     }
409
410
411     /** [UNIQUE] an edge */
412     public final class E extends HasBindingGroup implements Comparable<E> {
413
414         public final Vertex p1, p2;
415         T t;     // triangle to our "left"
416         E prev;  // previous half-edge
417         E next;  // next half-edge
418         E pair;  // partner half-edge
419         boolean shattered = false;
420
421         public boolean intersects(T t) { return t.intersects(p1.p, p2.p); }
422
423         public Segment getSegment() { return new Segment(p1.getPoint(), p2.getPoint()); }
424
425         public void bindingGroupChanged(edu.berkeley.qfat.geom.BindingGroup newBindingGroup_) {
426
427             edu.berkeley.qfat.geom.BindingGroup<E> newBindingGroup =
428                 (edu.berkeley.qfat.geom.BindingGroup<E>)newBindingGroup_;
429             if (newBindingGroup==null) return;
430             if (this==newBindingGroup.getMaster()) return;
431             HashSet<E> nbg = new HashSet<E>();
432             for(E eother : (Iterable<E>)newBindingGroup) nbg.add(eother);
433             for(E eother : nbg) {
434                 if (next==null || prev==null) continue;
435                 if (eother.next==null || eother.prev==null) continue;
436
437                 if (next.isBoundTo(eother.pair.prev.pair) && !prev.isBoundTo(eother.pair.next.pair))
438                     prev.bindTo(next.getBindingMatrix(eother.pair.prev.pair), eother.pair.next.pair);
439                 if (!next.isBoundTo(eother.pair.prev.pair) && prev.isBoundTo(eother.pair.next.pair))
440                     next.bindTo(prev.getBindingMatrix(eother.pair.next.pair), eother.pair.prev.pair);
441
442                 /*
443                 if (next.isBoundTo(eother.prev) && !prev.isBoundTo(eother.next))
444                     prev.bindTo(next.getBindingMatrix(eother.prev), eother.next);
445                 if (!next.isBoundTo(eother.prev) && prev.isBoundTo(eother.next))
446                     next.bindTo(prev.getBindingMatrix(eother.next), eother.prev);
447                 */
448                 if (next.isBoundTo(eother.next) && !prev.isBoundTo(eother.prev))
449                     prev.bindTo(next.getBindingMatrix(eother.next), eother.prev);
450                 if (!next.isBoundTo(eother.next) && prev.isBoundTo(eother.prev))
451                     next.bindTo(prev.getBindingMatrix(eother.prev), eother.next);
452             }
453
454         }
455
456         public float stretchRatio() {
457             Vertex nearest = error_against.nearest(midpoint());
458             float nearest_distance = midpoint().distance(nearest.p);
459             float other_distance =
460                 (p1.p.distance(error_against.nearest(p1.p).p)+
461                  p2.p.distance(error_against.nearest(p2.p).p))/2;
462             return nearest_distance/other_distance;
463         }
464         public float comparator() {
465             return length();
466         }
467         public int compareTo(E e) {
468             return e.comparator() > comparator() ? 1 : -1;
469         }
470         public void bindEdge(E e, Matrix m) {
471             _bindEdge(e, m);
472             pair._bindEdge(e.pair, m);
473         }
474         public void _bindEdge(E e, Matrix m) {
475             e = e.pair;
476             /*
477             //assumes edges are identical length at binding time
478             Vec reflectionPlaneNormal = e.p2.p.minus(e.p1.p).norm();
479             float a = reflectionPlaneNormal.x;
480             float b = reflectionPlaneNormal.y;
481             float c = reflectionPlaneNormal.z;
482             Matrix reflectionMatrix =
483                 new Matrix( 1-2*a*a,  -2*a*b,  -2*a*c, 0,
484                             -2*a*b,  1-2*b*b,  -2*b*c, 0,
485                             -2*a*c,   -2*b*c, 1-2*c*c, 0,
486                             0,       0,       0,       1);
487             m = m.times(Matrix.translate(e.midpoint().minus(Point.ORIGIN))
488                         .times(reflectionMatrix)
489                         .times(Matrix.translate(Point.ORIGIN.minus(e.midpoint()))));
490             System.out.println(reflectionPlaneNormal);
491             System.out.println("  " + p1.p + " " + m.times(e.p1.p));
492             System.out.println("  " + p2.p + " " + m.times(e.p2.p));
493             */
494             /*
495             if (m.times(e.p1.p).minus(p1.p).mag() > EPSILON) throw new Error();
496             if (m.times(e.p2.p).minus(p2.p).mag() > EPSILON) throw new Error();
497             */
498             this.bindTo(m, e);
499         }
500         
501         public void dobind() {
502             for(E e : (Iterable<E>)getBoundPeers()) {
503                 if (e==this) continue;
504                 p1.bindTo(getBindingMatrix(e), e.p1);
505                 p2.bindTo(getBindingMatrix(e), e.p2);
506                 e.p1.setConstraint(getConstraint());
507                 e.p2.setConstraint(getConstraint());
508             }
509         }
510
511         public Point shatter() {
512             if (shattered || destroyed) return null;
513             shattered = true;
514             E first = null;
515             E firste = null;
516             E firstx = null;
517             E firstq = null;
518             for(E e : (Iterable<E>)getBoundPeers()) {
519                 E enext = e.next;
520                 E eprev = e.prev;
521                 E pnext = e.pair.next;
522                 E pprev = e.pair.prev;
523                 Point mid = e.midpoint();
524                 Vertex r = e.next.p2;
525                 Vertex l = e.pair.next.p2;
526                 if (!e.destroyed) {
527                     e.destroy();
528                     e.pair.destroy();
529                     newT(r.p, e.p1.p, mid,    null, 0);
530                     newT(r.p, mid,    e.p2.p, null, 0);
531                     newT(l.p, mid,    e.p1.p, null, 0);
532                     newT(l.p, e.p2.p, mid,    null, 0);
533                 }
534             }
535             for(E e : (Iterable<E>)getBoundPeers()) {
536                 Point mid = e.midpoint();
537                 if (first==null) {
538                     first = e.p1.getE(mid);
539                     firste = e;
540                     firstx = e.pair;
541                     firstq = e.p2.getE(mid).pair;
542                     continue;
543                 }
544                 e.p1.getE(mid).          bindTo(e.getBindingMatrix(firste), first);
545                 e.p1.getE(mid).pair.     bindTo(e.getBindingMatrix(firste), first.pair);
546                 e.p2.getE(mid).pair.     bindTo(e.getBindingMatrix(firste), firstq);
547                 e.p2.getE(mid).pair.pair.bindTo(e.getBindingMatrix(firste), firstq.pair);
548             }
549             /*
550             first.setConstraint(firste.getConstraint());
551             firstq.setConstraint(firste.getConstraint());
552             */
553             return null;
554         }
555
556         public boolean destroyed = false;
557         public void destroy() {
558             if (destroyed) return;
559             destroyed = true;
560             pair.destroyed = true;
561
562             if (t != null) t.destroy();
563             t = null;
564
565             if (pair.t != null) pair.t.destroy();
566             pair.t = null;
567
568             if (next.t != null) next.t.destroy();
569             if (prev.t != null) prev.t.destroy();
570             next.t = null;
571             prev.t = null;
572
573             if (pair.next.t != null) pair.next.t.destroy();
574             if (pair.prev.t != null) pair.next.t.destroy();
575             pair.next.t = null;
576             pair.prev.t = null;
577
578             pair.prev.next = next;
579             next.prev = pair.prev;
580             prev.next = pair.next;
581             pair.next = prev;
582             if (p1.e == this) p1.e = prev.next;
583             if (pair.p1.e == pair) pair.p1.e = pair.prev.next;
584         }
585
586         private void sync() {
587             this.prev.next = this;
588             this.next.prev = this;
589             this.pair.pair = this;
590             if (this.next.p1 != p2) throw new Error();
591             if (this.prev.p2 != p1) throw new Error();
592             if (this.p1.e == null) this.p1.e = this;
593             if (!added) added = true;
594         }
595         private boolean added = false;
596
597         public T makeT(int colorclass) { return t==null ? (t = new T(this, colorclass)) : t; }
598
599         public double dihedralAngle() {
600             Vec v1 = t.norm().times(-1);
601             Vec v2 = pair.t.norm().times(-1);
602             double prod = v1.norm().dot(v2.norm());
603             prod = Math.min(1,prod);
604             prod = Math.max(-1,prod);
605             double ret = Math.acos(prod);
606             if (Double.isNaN(ret)) throw new Error("nan! " + prod);
607             return ret;
608         }
609
610         /** angle between this half-edge and the next */
611         public double angle() {
612             Vec v1 = next.p2.p.minus(p2.p);
613             Vec v2 = this.p1.p.minus(p2.p);
614             return Math.acos(v1.norm().dot(v2.norm()));
615         }
616
617         public Vertex getOther(Vertex v) {
618             if (this.p1 == v) return p2;
619             if (this.p2 == v) return p1;
620             throw new Error();
621         }
622
623         public void makeAdjacent(E e) {
624             if (this.next == e) return;
625             if (p2 != e.p1) throw new Error("cannot make adjacent -- no shared vertex");
626             if (t != null || e.t != null) throw new Error("cannot make adjacent -- edges not both free ");
627
628             E freeIncident = p2.getFreeIncident(e, this);
629
630             e.prev.next = freeIncident.next;
631             freeIncident.next.prev = e.prev;
632
633             freeIncident.next = this.next;
634             this.next.prev = freeIncident;
635             
636             this.next = e;
637             e.prev = this;
638
639             sync();
640             freeIncident.sync();
641         }
642
643         /** creates an isolated edge out in the middle of space */
644         public E(Point p1, Point p2) {
645             if (vertices.get(p1) != null) throw new Error();
646             if (vertices.get(p2) != null) throw new Error();
647             this.p1 = new Vertex(p1);
648             this.p2 = new Vertex(p2);
649             this.prev = this.next = this.pair = new E(this, this, this);
650             this.p1.e = this;
651             this.p2.e = this.pair;
652             sync();
653         }
654
655         /** adds a new half-edge from prev.p2 to p2 */
656         public E(E prev, Point p) {
657             Vertex p2;
658             p2 = vertices.get(p);
659             if (p2 == null) p2 = new Vertex(p);
660             this.p1 = prev.p2;
661             this.p2 = p2;
662             this.prev = prev;
663             if (p2.getE(p1) != null) throw new Error();
664             if (p2.e==null) {
665                 this.next = this.pair = new E(this, this, prev.next);
666             } else {
667                 E q = p2.getFreeIncident();
668                 this.next = q.next;
669                 this.next.prev = this;
670                 E z = prev.next;
671                 this.prev.next = this;
672                 this.pair = new E(q, this, z);
673             }
674             if (p2.e==null) p2.e = this.pair;
675             sync();
676         }
677
678         /** adds a new half-edge to the mesh with a given predecessor, successor, and pair */
679         public E(E prev, E pair, E next) {
680             this.p1 = prev.p2;
681             this.p2 = next.p1;
682             this.prev = prev;
683             this.next = next;
684             this.pair = pair;
685             sync();
686         }
687         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); }
688         public boolean has(Vertex v) { return v==p1 || v==p2; }
689         public float length() { return p1.p.minus(p2.p).mag(); }
690         public String toString() { return p1+"->"+p2; }
691
692     }
693
694     public E makeE(Point p1, Point p2) {
695         Vertex v1 = vertices.get(p1);
696         Vertex v2 = vertices.get(p2);
697         if (v1 != null && v2 != null) {
698             E e = v1.getE(v2);
699             if (e != null) return e;
700             e = v2.getE(v1);
701             if (e != null) return e;
702         }
703         if (v1 != null) return new E(v1.getFreeIncident(), p2);
704         if (v2 != null) return new E(v2.getFreeIncident(), p1).pair;
705         return new E(p1, p2);
706     }
707     public boolean coalesce = false;
708     private static float round(float f) {
709         return Math.round(f*1000)/1000f;
710     }
711     public T newT(Point p1, Point p2, Point p3, Vec norm, int colorclass) {
712         if (coalesce) {
713
714             for(Vertex v : vertices) { if (p1.distance(v.p) < EPSILON) { p1 = v.p; break; } }
715             for(Vertex v : vertices) { if (p2.distance(v.p) < EPSILON) { p2 = v.p; break; } }
716             for(Vertex v : vertices) { if (p3.distance(v.p) < EPSILON) { p3 = v.p; break; } }
717             /*
718             p1 = new Point(round(p1.x), round(p1.y), round(p1.z));
719             p2 = new Point(round(p2.x), round(p2.y), round(p2.z));
720             p3 = new Point(round(p3.x), round(p3.y), round(p3.z));
721             */
722         }
723         if (norm != null) {
724             Vec norm2 = p3.minus(p1).cross(p2.minus(p1));
725             float dot = norm.dot(norm2);
726             //if (Math.abs(dot) < EPointSILON) throw new Error("dot products within evertsilon of each other: "+norm+" "+norm2);
727             if (dot < 0) { Point p = p1; p1=p2; p2 = p; }
728         }
729         E e12 = makeE(p1, p2);
730         E e23 = makeE(p2, p3);
731         E e31 = makeE(p3, p1);
732         while(e12.next != e23 || e23.next != e31 || e31.next != e12) {
733             e12.makeAdjacent(e23);
734             e23.makeAdjacent(e31);
735             e31.makeAdjacent(e12);
736         }
737         T ret = e12.makeT(colorclass);
738         if (e12.t == null) throw new Error();
739         if (e23.t == null) throw new Error();
740         if (e31.t == null) throw new Error();
741         return ret;
742     }
743
744     private int max_serial = 0;
745     /** [UNIQUE] a triangle (face) */
746     public final class T extends Triangle {
747         public final E e1;
748         public final int color;
749         public final int colorclass;
750
751         public final int serial = max_serial++;
752         public boolean occluded;
753
754         T(E e1, int colorclass) {
755             this.e1 = e1;
756             E e2 = e1.next;
757             E e3 = e2.next;
758             if (e1==e2 || e1==e3) throw new Error();
759             if (e3.next!=e1) throw new Error();
760             if (e1.t!=null || e2.t!=null || e3.t!=null) throw new Error("non-manifold surface or disagreeing normals");
761             e1.t = this;
762             e1.next.t = this;
763             e1.next.next.t = this;
764
765             // FIXME: check for sealed/watertight surface once construction is complete (and infer normal(s)?)
766
767             int color = Math.abs(random.nextInt());
768             while(true) {
769                 color = color % 4;
770                 if (e1().pair.t != null && color == e1().pair.t.color) { color++; continue; }
771                 if (e2().pair.t != null && color == e2().pair.t.color) { color++; continue; }
772                 if (e3().pair.t != null && color == e3().pair.t.color) { color++; continue; }
773                 break;
774             }
775             this.color = color;
776             this.colorclass = colorclass;
777             triangles.add(this);
778         }
779         public E e1() { return e1; }
780         public E e2() { return e1.next; }
781         public E e3() { return e1.prev; }
782         public Vertex v1() { return e1.p1; }
783         public Vertex v2() { return e1.p2; }
784         public Vertex v3() { return e1.next.p2; }
785         public Point p1() { return e1.p1.p; }
786         public Point p2() { return e1.p2.p; }
787         public Point p3() { return e1.next.p2.p; }
788         public boolean hasE(E e) { return e1==e || e1.next==e || e1.prev==e; }
789         public boolean has(Vertex v) { return v1()==v || v2()==v || v3()==v; }
790
791         public void removeFromRTree() { triangles.remove(this); }
792         public void addToRTree() { triangles.insert(this); }
793         public void destroy() { triangles.remove(this); }
794         public void reinsert() { triangles.remove(this); triangles.add(this); }
795
796         public boolean shouldBeDrawn() {
797
798             if (e1().bindingGroupSize() <= 1) return false;
799             if (e2().bindingGroupSize() <= 1) return false;
800             if (e3().bindingGroupSize() <= 1) return false;
801
802             return true;
803         }
804
805         public void glTriangle(GL gl, Matrix m) {
806             gl.glPushName(serial);
807             gl.glBegin(GL.GL_TRIANGLES);
808             glVertices(gl, m);
809             gl.glEnd();
810             gl.glPopName();
811         }
812
813         /** issue gl.glVertex() for each of the triangle's points */
814         public void glVertices(GL gl, Matrix m) {
815             if (!shouldBeDrawn()) return;
816             super.glVertices(gl, m);
817         }
818     }
819 }