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