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