1 package edu.berkeley.qfat;
4 import java.awt.event.*;
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;
12 public class Mesh implements Iterable<Mesh.T> {
14 public static final float EPSILON = (float)0.0001;
15 public static final Random random = new Random();
17 private PointSet<Vert> vertices = new PointSet<Vert>();
19 public int size() { return vertices.size(); }
20 public Iterable<Vert> vertices() { return vertices; }
22 public Iterable<E> edges() {
25 public Iterator<E> iterator() {
27 HashSet<E> hse = new HashSet<E>();
28 for(T t : Mesh.this) {
36 return hse.iterator();
40 public Iterator<T> iterator() {
42 for(Vert v : vertices)
43 if (v.e != null && v.e.t != null)
44 return new FaceIterator(v);
45 return new FaceIterator();
50 public HashSet<T> ts = new HashSet<T>();
51 public RTree<T> tris = new RTree<T>();
53 public Mesh score_against = null;
54 public double score = 0;
55 public float score() { return (float)score; }
57 public int numedges = 0;
58 public float avgedge = 0;
60 public void rebindPoints() {
62 for(Mesh.T t : this) {
67 // ask edges to re-implement their bindings
68 for(Mesh.T t : this) {
75 public void unApplyQuadricToNeighborAll() {
76 HashSet<Vert> done = new HashSet<Vert>();
78 for(Vert p : new Vert[] { t.v1(), t.v2(), t.v3() }) {
79 if (done.contains(p)) continue;
81 p.unApplyQuadricToNeighbor();
84 public void recomputeAllFundamentalQuadrics() {
85 HashSet<Vert> done = new HashSet<Vert>();
87 for(Vert p : new Vert[] { t.v1(), t.v2(), t.v3() }) {
88 if (done.contains(p)) continue;
90 p.recomputeFundamentalQuadric();
93 public float applyQuadricToNeighborAll() {
96 HashSet<Vert> done = new HashSet<Vert>();
98 for(Vert p : new Vert[] { t.v1(), t.v2(), t.v3() }) {
99 if (done.contains(p)) continue;
101 p.applyQuadricToNeighbor();
104 return (float)(dist/num);
107 public void transform(Matrix m) {
108 ArrayList<Vert> set = new ArrayList<Vert>();
109 for (Vert v : vertices)
111 for(Vert v : set) v.transform(m);
114 public float volume() {
117 double area = t.area();
118 Vec origin_to_centroid = new Vec(new Point(0, 0, 0), t.centroid());
119 boolean facingAway = t.norm().dot(origin_to_centroid) > 0;
120 double height = Math.abs(t.norm().dot(origin_to_centroid));
121 total += ((facingAway ? 1 : -1) * area * height) / 3.0;
126 public void rebuild() { /*vertices.rebuild();*/ }
127 public Vec diagonal() { return vertices.diagonal(); }
128 public Point centroid() { return vertices.centroid(); }
129 public Vert nearest(Point p) { return vertices.nearest(p); }
131 public final class Vert extends HasPoint {
132 public String toString() { return p.toString(); }
134 E e; // some edge *leaving* this point
136 /** the nearest vertex in the "score_against" mesh */
137 Vert nearest_in_other_mesh;
138 /** the number of vertices in the other mesh for which this is the nearest_in_other_mesh */
140 /** the total error quadric (contributions from all vertices in other mesh for which this is nearest) */
141 Matrix quadric = Matrix.ZERO;
143 Vert bound_to = this;
144 Matrix binding = Matrix.ONE;
146 boolean quadricStale = false;
148 public Matrix errorQuadric() { return quadric; }
149 public Point getPoint() { return p; }
150 public float score() { return oldscore; }
152 private Matrix fundamentalQuadric = null;
153 public Matrix fundamentalQuadric() {
154 if (fundamentalQuadric == null) recomputeFundamentalQuadric();
155 return fundamentalQuadric;
158 private Vert(Point p) {
160 if (vertices.get(p) != null) throw new Error();
164 private void glNormal(GL gl) {
166 gl.glNormal3f(norm.x, norm.y, norm.z);
169 public void recomputeFundamentalQuadric() {
170 //if (!quadricStale && fundamentalQuadric != null) return;
171 quadricStale = false;
172 unApplyQuadricToNeighbor();
173 Matrix m = Matrix.ZERO;
178 m = m.plus(t.norm().fundamentalQuadric(t.centroid()));
181 } while(e != this.e);
182 fundamentalQuadric = m.times(1/(float)count);
183 applyQuadricToNeighbor();
186 public void unApplyQuadricToNeighbor() {
187 if (nearest_in_other_mesh == null) return;
188 if (fundamentalQuadric == null) return;
189 nearest_in_other_mesh.unComputeError();
190 nearest_in_other_mesh.quadric = nearest_in_other_mesh.quadric.minus(fundamentalQuadric);
191 nearest_in_other_mesh.quadric_count--;
192 if (nearest_in_other_mesh.quadric_count==0)
193 nearest_in_other_mesh.quadric = Matrix.ZERO;
194 nearest_in_other_mesh.computeError();
195 nearest_in_other_mesh = null;
198 public void applyQuadricToNeighbor() {
199 if (score_against == null) return;
201 Vert new_nearest = score_against.nearest(p);
202 if (nearest_in_other_mesh != null && new_nearest == nearest_in_other_mesh) return;
204 if (nearest_in_other_mesh != null) unApplyQuadricToNeighbor();
205 if (nearest_in_other_mesh != null) throw new Error();
207 nearest_in_other_mesh = new_nearest;
209 // don't attract to vertices that face the other way
210 if (nearest_in_other_mesh.e == null || nearest_in_other_mesh.norm().dot(norm()) < 0) {
211 nearest_in_other_mesh = null;
213 nearest_in_other_mesh.unComputeError();
214 nearest_in_other_mesh.quadric = nearest_in_other_mesh.quadric.plus(fundamentalQuadric());
215 nearest_in_other_mesh.quadric_count++;
216 nearest_in_other_mesh.computeError();
221 public void reComputeErrorAround() {
223 if (nearest_in_other_mesh != null) nearest_in_other_mesh.reComputeError();
226 e.p2.reComputeError();
228 } while (e != this.e);
230 public void reComputeError() {
234 public void unComputeError() {
238 public void computeError() {
239 if (quadric_count == 0) {
242 else if (nearest_in_other_mesh == null) {
243 if (score_against != null) {
244 Vert ne = score_against.nearest(p);
245 oldscore = ne.fundamentalQuadric().preAndPostMultiply(p) * 100 * 10;
250 oldscore = nearest_in_other_mesh.fundamentalQuadric().preAndPostMultiply(p) * 100 * 10;
253 oldscore = (quadric.preAndPostMultiply(p) * 100) / quadric_count;
262 //double ang = Math.abs(e.crossAngle());
263 double ang = Math.abs(e.crossAngle());
264 if (ang > Math.PI) throw new Error();
268 aspects += e.t.aspect()*e.t.aspect();
272 float minangle = (float)(Math.PI * 0.8);
274 oldscore += (ang - minangle);
277 } while (e != this.e);
278 if (numaspects > 0) oldscore += (aspects / numaspects);
280 //System.out.println(oldscore);
281 //oldscore = oldscore*oldscore;
285 private void removeTrianglesFromRTree() {
288 if (e.t != null) e.t.removeFromRTree();
290 } while(e != this.e);
292 private void addTrianglesToRTree() {
295 if (e.t != null) e.t.addToRTree();
297 } while(e != this.e);
300 /** does NOT update bound pairs! */
301 public boolean transform(Matrix m) {
302 unApplyQuadricToNeighbor();
305 if (vertices.get(this.p)==null) throw new Error();
306 vertices.remove(this);
307 removeTrianglesFromRTree();
308 float newx = m.a*p.x + m.b*p.y + m.c*p.z + m.d;
309 float newy = m.e*p.x + m.f*p.y + m.g*p.z + m.h;
310 float newz = m.i*p.x + m.j*p.y + m.k*p.z + m.l;
311 this.p = new Point(newx, newy, newz);
312 addTrianglesToRTree();
314 } catch (Exception e) {
315 throw new RuntimeException(e);
317 applyQuadricToNeighbor();
319 // FIXME: intersection test needed?
322 // should recompute fundamental quadrics of all vertices sharing a face, but we defer...
326 if (Math.abs(e.crossAngle()) > (Math.PI * 0.9) ||
327 Math.abs(e.next.crossAngle()) > (Math.PI * 0.9)) {
330 if (e.t.aspect() < 0.1) {
334 e.p2.quadricStale = true;
336 } while(e != this.e);
339 if (!ignorecollision && good) {
341 tris.range(new Segment(oldp, this.p),
343 public void visit(T t) {
347 if (!t.has(e.p1) && !t.has(e.p2) && e.intersects(t)) { good = false; }
349 if (!e.t.has(t.e1().p1) && !e.t.has(t.e1().p2) && t.e1().intersects(e.t)) { good = false; }
350 if (!e.t.has(t.e2().p1) && !e.t.has(t.e2().p2) && t.e2().intersects(e.t)) { good = false; }
351 if (!e.t.has(t.e3().p1) && !e.t.has(t.e3().p2) && t.e3().intersects(e.t)) { good = false; }
354 } while(e != Vert.this.e);
359 for(T t : Mesh.this) {
363 if (!t.has(e.p1) && !t.has(e.p2) && e.intersects(t)) { good = false; break; }
365 if (!e.t.has(t.e1().p1) && !e.t.has(t.e1().p2) && t.e1().intersects(e.t)) { good = false; break; }
366 if (!e.t.has(t.e2().p1) && !e.t.has(t.e2().p2) && t.e2().intersects(e.t)) { good = false; break; }
367 if (!e.t.has(t.e3().p1) && !e.t.has(t.e3().p2) && t.e3().intersects(e.t)) { good = false; break; }
370 } while(e != this.e);
376 reComputeErrorAround();
379 private boolean good;
381 public boolean move(Vec v) {
382 Matrix m = Matrix.translate(v);
386 good &= p.transform(m);
392 public E getFreeIncident() {
393 E ret = getFreeIncident(e, e);
394 if (ret != null) return ret;
395 ret = getFreeIncident(e.pair.next, e.pair.next);
399 System.out.println(ex + " " + ex.t);
402 throw new Error("unable to find free incident to " + this);
407 public E getFreeIncident(E start, E before) {
410 if (e.pair.p2 == this && e.pair.t == null && e.pair.next.t == null) return e.pair;
412 } while(e != before);
416 public E getE(Point p2) {
417 Vert v = vertices.get(p2);
418 if (v==null) return null;
421 public E getE(Vert p2) {
424 if (e==null) return null;
425 if (e.p1 == this && e.p2 == p2) return e;
432 Vec norm = new Vec(0, 0, 0);
435 if (e.t != null) norm = norm.plus(e.t.norm().times((float)e.prev.angle()));
437 } while(e != this.e);
441 public boolean isBoundTo(Vert p) {
444 if (px==this) return true;
449 public void unbind() { bound_to = this; binding = Matrix.ONE; }
450 public void bind(Vert p) { bind(p, Matrix.ONE); }
451 public void bind(Vert p, Matrix binding) {
452 if (isBoundTo(p)) return;
453 Vert temp_bound_to = p.bound_to;
454 Matrix temp_binding = p.binding;
455 p.bound_to = this.bound_to;
456 p.binding = binding.times(this.binding); // FIXME: may have order wrong here
457 this.bound_to = temp_bound_to;
458 this.binding = temp_binding.times(temp_binding); // FIXME: may have order wrong here
462 public class BindingGroup {
463 private HashSet<E> set = new HashSet<E>();
464 public BindingGroup bind_others;
465 public BindingGroup other() { return bind_others; }
466 public BindingGroup(BindingGroup bind_others) { this.bind_others = bind_others; }
467 public BindingGroup() { this.bind_others = new BindingGroup(this); }
468 public BindingGroup(E e) { this(); set.add(e); }
469 public void add(E e) {
470 if (set.contains(e)) return;
472 BindingGroup e_bind_peers = e.bind_peers;
473 BindingGroup e_bind_to = e.bind_to;
475 e.bind_to = bind_others;
476 for (E epeer : e_bind_peers.set) add(epeer);
477 for (E eother : e_bind_to.set) bind_others.add(eother);
479 for(E eother : bind_others.set) {
480 if (e.next.bind_to.set.contains(eother.prev)) {
481 e.next.next.bindEdge(eother.prev.prev);
483 if (e.prev.bind_to.set.contains(eother.next)) {
484 e.prev.prev.bindEdge(eother.next.next);
489 public void dobind(E e) {
490 for(E ebound : set) {
491 e.p1.bind(ebound.p2);
492 e.p2.bind(ebound.p1);
495 public void shatter(BindingGroup bg1, BindingGroup bg2) {
497 e.shatter(e.midpoint(), bg1, bg2);
502 /** [UNIQUE] an edge */
503 public final class E implements Comparable<E> {
505 public final Vert p1, p2;
506 T t; // triangle to our "left"
507 E prev; // previous half-edge
508 E next; // next half-edge
509 E pair; // partner half-edge
510 public BindingGroup bind_peers = new BindingGroup(this);
511 public BindingGroup bind_to = bind_peers.other();
512 boolean shattered = false;
514 public float comparator() {
515 Vert nearest = score_against.nearest(midpoint());
516 //if (t==null) return length();
518 double ang = Math.abs(crossAngle());
519 float minangle = (float)(Math.PI * 0.9);
524 if ((length() * length()) / t.area() > 10)
525 return (float)(length()*Math.sqrt(t.area()));
526 return length()*t.area();
528 return (float)Math.max(length(), midpoint().distance(nearest.p));
531 public int compareTo(E e) {
532 return e.comparator() > comparator() ? 1 : -1;
534 public void bindEdge(E e) { bind_to.add(e); }
535 public void dobind() { bind_to.dobind(this); }
537 public Point shatter() { return shatter(midpoint(), null, null); }
538 public Point shatter(Point mid, BindingGroup bg1, BindingGroup bg2) {
539 if (shattered || destroyed) return mid;
546 int old_colorclass = t==null ? 0 : t.colorclass;
547 if (bg1==null) bg1 = new BindingGroup();
548 if (bg2==null) bg2 = new BindingGroup();
549 BindingGroup old_bind_to = bind_to;
550 bind_peers.shatter(bg1, bg2);
551 old_bind_to.shatter(bg2.other(), bg1.other());
555 newT(r.p, p1.p, mid, null, old_colorclass);
556 newT(r.p, mid, p2.p, null, old_colorclass);
557 bg1.add(p1.getE(mid));
558 bg2.add(p2.getE(mid).pair);
562 public boolean destroyed = false;
563 public void destroy() {
564 if (destroyed) return;
566 pair.destroyed = true;
568 if (t != null) t.destroy();
571 if (pair.t != null) pair.t.destroy();
574 if (next.t != null) next.t.destroy();
575 if (prev.t != null) prev.t.destroy();
579 if (pair.next.t != null) pair.next.t.destroy();
580 if (pair.prev.t != null) pair.next.t.destroy();
586 this.bind_peers = null;
587 pair.bind_peers = null;
588 pair.prev.next = next;
589 next.prev = pair.prev;
590 prev.next = pair.next;
592 if (p1.e == this) p1.e = prev.next;
593 if (pair.p1.e == pair) pair.p1.e = pair.prev.next;
594 avgedge -= this.length();
595 avgedge -= pair.length();
600 private void sync() {
601 this.prev.next = this;
602 this.next.prev = this;
603 this.pair.pair = this;
604 bind_peers.add(this);
605 if (this.next.p1 != p2) throw new Error();
606 if (this.prev.p2 != p1) throw new Error();
607 if (this.p1.e == null) this.p1.e = this;
614 private boolean added = false;
616 public T makeT(int colorclass) { return t==null ? (t = new T(this, colorclass)) : t; }
618 public double crossAngle() {
619 Vec v1 = t.norm().times(-1);
620 Vec v2 = pair.t.norm().times(-1);
621 return Math.acos(v1.norm().dot(v2.norm()));
624 /** angle between this half-edge and the next */
625 public double angle() {
626 Vec v1 = next.p2.p.minus(p2.p);
627 Vec v2 = this.p1.p.minus(p2.p);
628 return Math.acos(v1.norm().dot(v2.norm()));
631 public void makeAdjacent(E e) {
632 if (this.next == e) return;
633 if (p2 != e.p1) throw new Error("cannot make adjacent -- no shared vertex");
634 if (t != null || e.t != null) throw new Error("cannot make adjacent -- edges not both free");
636 E freeIncident = p2.getFreeIncident(e, this);
638 e.prev.next = freeIncident.next;
639 freeIncident.next.prev = e.prev;
641 freeIncident.next = this.next;
642 this.next.prev = freeIncident;
651 /** creates an isolated edge out in the middle of space */
652 public E(Point p1, Point p2) {
653 if (vertices.get(p1) != null) throw new Error();
654 if (vertices.get(p2) != null) throw new Error();
655 this.p1 = new Vert(p1);
656 this.p2 = new Vert(p2);
657 this.prev = this.next = this.pair = new E(this, this, this);
659 this.p2.e = this.pair;
663 /** adds a new half-edge from prev.p2 to p2 */
664 public E(E prev, Point p) {
666 p2 = vertices.get(p);
667 if (p2 == null) p2 = new Vert(p);
671 if (p2.getE(p1) != null) throw new Error();
673 this.next = this.pair = new E(this, this, prev.next);
675 E q = p2.getFreeIncident();
677 this.next.prev = this;
679 this.prev.next = this;
680 this.pair = new E(q, this, z);
682 if (p2.e==null) p2.e = this.pair;
686 /** adds a new half-edge to the mesh with a given predecessor, successor, and pair */
687 public E(E prev, E pair, E next) {
695 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); }
696 public boolean has(Vert v) { return v==p1 || v==p2; }
697 public float length() { return p1.p.minus(p2.p).mag(); }
698 public String toString() { return p1+"->"+p2; }
700 public boolean intersects(T t) {
701 double A0=t.v1().p.x, A1=t.v1().p.y, A2=t.v1().p.z;
702 double B0=t.v2().p.x, B1=t.v2().p.y, B2=t.v2().p.z;
703 double C0=t.v3().p.x, C1=t.v3().p.y, C2=t.v3().p.z;
704 double j0=p1.p.x, j1=p1.p.y, j2=p1.p.z;
705 double k0=p2.p.x, k1=p2.p.y, k2=p2.p.z;
713 double R00, R01, R02, R03,
727 /* c = a × b */
728 c0 = a1 * b2 - a2 * b1;
729 c1 = a2 * b0 - a0 * b2;
730 c2 = a0 * b1 - a1 * b0;
732 /* M^(-1) = (1/det(M)) * adj(M) */
733 in_det = 1 / (c0 * c0 + c1 * c1 + c2 * c2);
734 R00 = (b1 * c2 - b2 * c1) * in_det;
735 R01 = (b2 * c0 - b0 * c2) * in_det;
736 R02 = (b0 * c1 - b1 * c0) * in_det;
737 R10 = (c1 * a2 - c2 * a1) * in_det;
738 R11 = (c2 * a0 - c0 * a2) * in_det;
739 R12 = (c0 * a1 - c1 * a0) * in_det;
745 R03 = -(R00 * A0 + R01 * A1 + R02 * A2);
746 R13 = -(R10 * A0 + R11 * A1 + R12 * A2);
747 R23 = -(R20 * A0 + R21 * A1 + R22 * A2);
749 /* fill in last row of 4x4 matrix */
753 J2 = R20 * j0 + R21 * j1 + R22 * j2 + R23;
754 K2 = R20 * k0 + R21 * k1 + R22 * k2 + R23;
755 if (J2 * K2 >= 0) return false;
757 J0 = R00 * j0 + R01 * j1 + R02 * j2 + R03;
758 K0 = R00 * k0 + R01 * k1 + R02 * k2 + R03;
759 i0 = J0 + J2 * ((K0 - J0) / (J2 - K2));
760 if (i0 < 0 || i0 > 1) return false;
762 J1 = R10 * j0 + R11 * j1 + R12 * j2 + R13;
763 K1 = R10 * k0 + R11 * k1 + R12 * k2 + R13;
764 i1 = J1 + J2 * ((K1 - J1) / (J2 - K2));
765 if (i1 < 0 || i1 > 1 || i0 + i1 > 1) return false;
771 public E makeE(Point p1, Point p2) {
772 Vert v1 = vertices.get(p1);
773 Vert v2 = vertices.get(p2);
774 if (v1 != null && v2 != null) {
776 if (e != null) return e;
778 if (e != null) return e;
780 if (v1 != null) return new E(v1.getFreeIncident(), p2);
781 if (v2 != null) return new E(v2.getFreeIncident(), p1).pair;
782 return new E(p1, p2);
784 public T newT(Point p1, Point p2, Point p3, Vec norm, int colorclass) {
786 Vec norm2 = p3.minus(p1).cross(p2.minus(p1));
787 float dot = norm.dot(norm2);
788 //if (Math.abs(dot) < EPointSILON) throw new Error("dot products within evertsilon of each other: "+norm+" "+norm2);
789 if (dot < 0) { Point p = p1; p1=p2; p2 = p; }
791 E e12 = makeE(p1, p2);
792 E e23 = makeE(p2, p3);
793 E e31 = makeE(p3, p1);
794 while(e12.next != e23 || e23.next != e31 || e31.next != e12) {
795 e12.makeAdjacent(e23);
796 e23.makeAdjacent(e31);
797 e31.makeAdjacent(e12);
799 T ret = e12.makeT(colorclass);
800 if (e12.t == null) throw new Error();
801 if (e23.t == null) throw new Error();
802 if (e31.t == null) throw new Error();
807 public class FaceIterator implements Iterator<T> {
808 private HashSet<T> visited = new HashSet<T>();
809 private LinkedList<T> next = new LinkedList<T>();
810 public FaceIterator() { }
811 public FaceIterator(Vert v) { next.addFirst(v.e.t); }
812 public boolean hasNext() { return next.peek()!=null; }
813 public void remove() { throw new Error(); }
815 T ret = next.removeFirst();
816 if (ret == null) return null;
818 T t1 = ret.e1().pair.t;
819 T t2 = ret.e2().pair.t;
820 T t3 = ret.e3().pair.t;
821 if (t1 != null && !visited.contains(t1)) next.addFirst(t1);
822 if (t2 != null && !visited.contains(t2)) next.addFirst(t2);
823 if (t3 != null && !visited.contains(t3)) next.addFirst(t3);
828 /** [UNIQUE] a triangle (face) */
829 public final class T extends Triangle {
831 public final int color;
832 public final int colorclass;
834 public void removeFromRTree() { tris.remove(this); }
835 public void addToRTree() { tris.insert(this); }
837 public void destroy() {
842 T(E e1, int colorclass) {
846 if (e1==e2 || e1==e3) throw new Error();
847 if (e3.next!=e1) throw new Error();
848 if (e1.t!=null || e2.t!=null || e3.t!=null) throw new Error("non-manifold surface or disagreeing normals");
851 e1.next.next.t = this;
853 // FIXME: check for sealed/watertight surface once construction is complete (and infer normal(s)?)
855 int color = Math.abs(random.nextInt());
858 if (e1().pair.t != null && color == e1().pair.t.color) { color++; continue; }
859 if (e2().pair.t != null && color == e2().pair.t.color) { color++; continue; }
860 if (e3().pair.t != null && color == e3().pair.t.color) { color++; continue; }
864 this.colorclass = colorclass;
868 public E e1() { return e1; }
869 public E e2() { return e1.next; }
870 public E e3() { return e1.prev; }
871 public Vert v1() { return e1.p1; }
872 public Vert v2() { return e1.p2; }
873 public Vert v3() { return e1.next.p2; }
874 public Point p1() { return e1.p1.p; }
875 public Point p2() { return e1.p2.p; }
876 public Point p3() { return e1.next.p2.p; }
877 public boolean hasE(E e) { return e1==e || e1.next==e || e1.prev==e; }
878 public boolean has(Vert v) { return v1()==v || v2()==v || v3()==v; }
880 public void glVertices(GL gl) {
882 if (e1().bind_to.set.size() == 0) return;
883 if (e2().bind_to.set.size() == 0) return;
884 if (e3().bind_to.set.size() == 0) return;
892 public boolean tilemesh = false;
893 public boolean ignorecollision = false;