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