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