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