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