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