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 RTree<T> tris = new RTree<T>();
18 private PointSet<Vert> vertices = new PointSet<Vert>();
20 public Mesh score_against = null;
21 public double score = 0;
22 public float score() { return (float)score; }
23 public int numedges = 0;
24 public float avgedge = 0;
26 public int size() { return vertices.size(); }
27 public Iterable<Vert> vertices() { return vertices; }
29 public Iterator<T> iterator() {
30 return tris.iterator();
33 public void rebindPoints() {
35 for(Mesh.T t : this) {
40 // ask edges to re-implement their bindings
41 for(Mesh.T t : this) {
48 public void unApplyQuadricToNeighborAll() {
49 HashSet<Vert> done = new HashSet<Vert>();
51 for(Vert p : new Vert[] { t.v1(), t.v2(), t.v3() }) {
52 if (done.contains(p)) continue;
54 p.unApplyQuadricToNeighbor();
57 public void recomputeAllFundamentalQuadrics() {
58 HashSet<Vert> done = new HashSet<Vert>();
60 for(Vert p : new Vert[] { t.v1(), t.v2(), t.v3() }) {
61 if (done.contains(p)) continue;
63 p.recomputeFundamentalQuadric();
66 public float applyQuadricToNeighborAll() {
69 HashSet<Vert> done = new HashSet<Vert>();
71 for(Vert p : new Vert[] { t.v1(), t.v2(), t.v3() }) {
72 if (done.contains(p)) continue;
74 p.applyQuadricToNeighbor();
77 return (float)(dist/num);
80 public void transform(Matrix m) {
81 ArrayList<Vert> set = new ArrayList<Vert>();
82 for (Vert v : vertices)
84 for(Vert v : set) v.transform(m);
87 public float volume() {
90 double area = t.area();
91 Vec origin_to_centroid = new Vec(new Point(0, 0, 0), t.centroid());
92 boolean facingAway = t.norm().dot(origin_to_centroid) > 0;
93 double height = Math.abs(t.norm().dot(origin_to_centroid));
94 total += ((facingAway ? 1 : -1) * area * height) / 3.0;
99 public void rebuild() { /*vertices.rebuild();*/ }
100 public Vec diagonal() { return vertices.diagonal(); }
101 public Point centroid() { return vertices.centroid(); }
102 public Vert nearest(Point p) { return vertices.nearest(p); }
104 public final class Vert extends HasPoint {
105 public String toString() { return p.toString(); }
107 E e; // some edge *leaving* this point
109 /** the nearest vertex in the "score_against" mesh */
110 Vert nearest_in_other_mesh;
111 /** the number of vertices in the other mesh for which this is the nearest_in_other_mesh */
113 /** the total error quadric (contributions from all vertices in other mesh for which this is nearest) */
114 Matrix quadric = Matrix.ZERO;
116 Vert bound_to = this;
117 Matrix binding = Matrix.ONE;
119 boolean quadricStale = false;
121 public Matrix errorQuadric() { return quadric; }
122 public Point getPoint() { return p; }
123 public float score() { return oldscore; }
125 private Matrix fundamentalQuadric = null;
126 public Matrix fundamentalQuadric() {
127 if (fundamentalQuadric == null) recomputeFundamentalQuadric();
128 return fundamentalQuadric;
131 private Vert(Point p) {
133 if (vertices.get(p) != null) throw new Error();
137 private void glNormal(GL gl) {
139 gl.glNormal3f(norm.x, norm.y, norm.z);
142 public void recomputeFundamentalQuadric() {
143 //if (!quadricStale && fundamentalQuadric != null) return;
144 quadricStale = false;
145 unApplyQuadricToNeighbor();
146 Matrix m = Matrix.ZERO;
151 m = m.plus(t.norm().fundamentalQuadric(t.centroid()));
154 } while(e != this.e);
155 fundamentalQuadric = m.times(1/(float)count);
156 applyQuadricToNeighbor();
159 public void unApplyQuadricToNeighbor() {
160 if (nearest_in_other_mesh == null) return;
161 if (fundamentalQuadric == null) return;
162 nearest_in_other_mesh.unComputeError();
163 nearest_in_other_mesh.quadric = nearest_in_other_mesh.quadric.minus(fundamentalQuadric);
164 nearest_in_other_mesh.quadric_count--;
165 if (nearest_in_other_mesh.quadric_count==0)
166 nearest_in_other_mesh.quadric = Matrix.ZERO;
167 nearest_in_other_mesh.computeError();
168 nearest_in_other_mesh = null;
171 public void applyQuadricToNeighbor() {
172 if (score_against == null) return;
174 Vert new_nearest = score_against.nearest(p);
175 if (nearest_in_other_mesh != null && new_nearest == nearest_in_other_mesh) return;
177 if (nearest_in_other_mesh != null) unApplyQuadricToNeighbor();
178 if (nearest_in_other_mesh != null) throw new Error();
180 nearest_in_other_mesh = new_nearest;
182 // don't attract to vertices that face the other way
183 if (nearest_in_other_mesh.e == null || nearest_in_other_mesh.norm().dot(norm()) < 0) {
184 nearest_in_other_mesh = null;
186 nearest_in_other_mesh.unComputeError();
187 nearest_in_other_mesh.quadric = nearest_in_other_mesh.quadric.plus(fundamentalQuadric());
188 nearest_in_other_mesh.quadric_count++;
189 nearest_in_other_mesh.computeError();
194 public void reComputeErrorAround() {
196 if (nearest_in_other_mesh != null) nearest_in_other_mesh.reComputeError();
199 e.p2.reComputeError();
201 } while (e != this.e);
203 public void reComputeError() {
207 public void unComputeError() {
211 public void computeError() {
212 if (quadric_count == 0) {
215 else if (nearest_in_other_mesh == null) {
216 if (score_against != null) {
217 Vert ne = score_against.nearest(p);
218 oldscore = ne.fundamentalQuadric().preAndPostMultiply(p) * 100 * 10;
223 oldscore = nearest_in_other_mesh.fundamentalQuadric().preAndPostMultiply(p) * 100 * 10;
226 oldscore = (quadric.preAndPostMultiply(p) * 100) / quadric_count;
235 //double ang = Math.abs(e.crossAngle());
236 double ang = Math.abs(e.crossAngle());
237 if (ang > Math.PI) throw new Error();
241 aspects += e.t.aspect()*e.t.aspect();
245 float minangle = (float)(Math.PI * 0.8);
247 oldscore += (ang - minangle);
250 } while (e != this.e);
251 if (numaspects > 0) oldscore += (aspects / numaspects);
253 //System.out.println(oldscore);
254 //oldscore = oldscore*oldscore;
258 private void removeTrianglesFromRTree() {
261 if (e.t != null) e.t.removeFromRTree();
263 } while(e != this.e);
265 private void addTrianglesToRTree() {
268 if (e.t != null) e.t.addToRTree();
270 } while(e != this.e);
273 /** does NOT update bound pairs! */
274 public boolean transform(Matrix m) {
275 unApplyQuadricToNeighbor();
278 if (vertices.get(this.p)==null) throw new Error();
279 vertices.remove(this);
280 removeTrianglesFromRTree();
281 float newx = m.a*p.x + m.b*p.y + m.c*p.z + m.d;
282 float newy = m.e*p.x + m.f*p.y + m.g*p.z + m.h;
283 float newz = m.i*p.x + m.j*p.y + m.k*p.z + m.l;
284 this.p = new Point(newx, newy, newz);
285 addTrianglesToRTree();
287 } catch (Exception e) {
288 throw new RuntimeException(e);
290 applyQuadricToNeighbor();
292 // FIXME: intersection test needed?
295 // should recompute fundamental quadrics of all vertices sharing a face, but we defer...
299 if (Math.abs(e.crossAngle()) > (Math.PI * 0.9) ||
300 Math.abs(e.next.crossAngle()) > (Math.PI * 0.9)) {
303 if (e.t.aspect() < 0.1) {
307 e.p2.quadricStale = true;
309 } while(e != this.e);
312 if (!ignorecollision && good) {
314 tris.range(new Segment(oldp, this.p),
316 public void visit(T t) {
320 if (!t.has(e.p1) && !t.has(e.p2) && e.intersects(t)) { good = false; }
322 if (!e.t.has(t.e1().p1) && !e.t.has(t.e1().p2) && t.e1().intersects(e.t)) { good = false; }
323 if (!e.t.has(t.e2().p1) && !e.t.has(t.e2().p2) && t.e2().intersects(e.t)) { good = false; }
324 if (!e.t.has(t.e3().p1) && !e.t.has(t.e3().p2) && t.e3().intersects(e.t)) { good = false; }
327 } while(e != Vert.this.e);
332 for(T t : Mesh.this) {
336 if (!t.has(e.p1) && !t.has(e.p2) && e.intersects(t)) { good = false; break; }
338 if (!e.t.has(t.e1().p1) && !e.t.has(t.e1().p2) && t.e1().intersects(e.t)) { good = false; break; }
339 if (!e.t.has(t.e2().p1) && !e.t.has(t.e2().p2) && t.e2().intersects(e.t)) { good = false; break; }
340 if (!e.t.has(t.e3().p1) && !e.t.has(t.e3().p2) && t.e3().intersects(e.t)) { good = false; break; }
343 } while(e != this.e);
349 reComputeErrorAround();
352 private boolean good;
354 public boolean move(Vec v) {
355 Matrix m = Matrix.translate(v);
359 good &= p.transform(m);
365 public E getFreeIncident() {
366 E ret = getFreeIncident(e, e);
367 if (ret != null) return ret;
368 ret = getFreeIncident(e.pair.next, e.pair.next);
372 System.out.println(ex + " " + ex.t);
375 throw new Error("unable to find free incident to " + this);
380 public E getFreeIncident(E start, E before) {
383 if (e.pair.p2 == this && e.pair.t == null && e.pair.next.t == null) return e.pair;
385 } while(e != before);
389 public E getE(Point p2) {
390 Vert v = vertices.get(p2);
391 if (v==null) return null;
394 public E getE(Vert p2) {
397 if (e==null) return null;
398 if (e.p1 == this && e.p2 == p2) return e;
405 Vec norm = new Vec(0, 0, 0);
408 if (e.t != null) norm = norm.plus(e.t.norm().times((float)e.prev.angle()));
410 } while(e != this.e);
414 public boolean isBoundTo(Vert p) {
417 if (px==this) return true;
422 public void unbind() { bound_to = this; binding = Matrix.ONE; }
423 public void bind(Vert p) { bind(p, Matrix.ONE); }
424 public void bind(Vert p, Matrix binding) {
425 if (isBoundTo(p)) return;
426 Vert temp_bound_to = p.bound_to;
427 Matrix temp_binding = p.binding;
428 p.bound_to = this.bound_to;
429 p.binding = binding.times(this.binding); // FIXME: may have order wrong here
430 this.bound_to = temp_bound_to;
431 this.binding = temp_binding.times(temp_binding); // FIXME: may have order wrong here
435 public class BindingGroup {
436 private HashSet<E> set = new HashSet<E>();
437 public BindingGroup bind_others;
438 public BindingGroup other() { return bind_others; }
439 public BindingGroup(BindingGroup bind_others) { this.bind_others = bind_others; }
440 public BindingGroup() { this.bind_others = new BindingGroup(this); }
441 public BindingGroup(E e) { this(); set.add(e); }
442 public void add(E e) {
443 if (set.contains(e)) return;
445 BindingGroup e_bind_peers = e.bind_peers;
446 BindingGroup e_bind_to = e.bind_to;
448 e.bind_to = bind_others;
449 for (E epeer : e_bind_peers.set) add(epeer);
450 for (E eother : e_bind_to.set) bind_others.add(eother);
452 for(E eother : bind_others.set) {
453 if (e.next.bind_to.set.contains(eother.prev)) {
454 e.next.next.bindEdge(eother.prev.prev);
456 if (e.prev.bind_to.set.contains(eother.next)) {
457 e.prev.prev.bindEdge(eother.next.next);
462 public void dobind(E e) {
463 for(E ebound : set) {
464 e.p1.bind(ebound.p2);
465 e.p2.bind(ebound.p1);
468 public void shatter(BindingGroup bg1, BindingGroup bg2) {
470 e.shatter(e.midpoint(), bg1, bg2);
475 /** [UNIQUE] an edge */
476 public final class E implements Comparable<E> {
478 public final Vert p1, p2;
479 T t; // triangle to our "left"
480 E prev; // previous half-edge
481 E next; // next half-edge
482 E pair; // partner half-edge
483 public BindingGroup bind_peers = new BindingGroup(this);
484 public BindingGroup bind_to = bind_peers.other();
485 boolean shattered = false;
487 public float comparator() {
488 Vert nearest = score_against.nearest(midpoint());
489 //if (t==null) return length();
491 double ang = Math.abs(crossAngle());
492 float minangle = (float)(Math.PI * 0.9);
497 if ((length() * length()) / t.area() > 10)
498 return (float)(length()*Math.sqrt(t.area()));
499 return length()*t.area();
501 return (float)Math.max(length(), midpoint().distance(nearest.p));
504 public int compareTo(E e) {
505 return e.comparator() > comparator() ? 1 : -1;
507 public void bindEdge(E e) { bind_to.add(e); }
508 public void dobind() { bind_to.dobind(this); }
510 public Point shatter() { return shatter(midpoint(), null, null); }
511 public Point shatter(Point mid, BindingGroup bg1, BindingGroup bg2) {
512 if (shattered || destroyed) return mid;
519 int old_colorclass = t==null ? 0 : t.colorclass;
520 if (bg1==null) bg1 = new BindingGroup();
521 if (bg2==null) bg2 = new BindingGroup();
522 BindingGroup old_bind_to = bind_to;
523 bind_peers.shatter(bg1, bg2);
524 old_bind_to.shatter(bg2.other(), bg1.other());
528 newT(r.p, p1.p, mid, null, old_colorclass);
529 newT(r.p, mid, p2.p, null, old_colorclass);
530 bg1.add(p1.getE(mid));
531 bg2.add(p2.getE(mid).pair);
535 public boolean destroyed = false;
536 public void destroy() {
537 if (destroyed) return;
539 pair.destroyed = true;
541 if (t != null) t.destroy();
544 if (pair.t != null) pair.t.destroy();
547 if (next.t != null) next.t.destroy();
548 if (prev.t != null) prev.t.destroy();
552 if (pair.next.t != null) pair.next.t.destroy();
553 if (pair.prev.t != null) pair.next.t.destroy();
559 this.bind_peers = null;
560 pair.bind_peers = null;
561 pair.prev.next = next;
562 next.prev = pair.prev;
563 prev.next = pair.next;
565 if (p1.e == this) p1.e = prev.next;
566 if (pair.p1.e == pair) pair.p1.e = pair.prev.next;
567 avgedge -= this.length();
568 avgedge -= pair.length();
573 private void sync() {
574 this.prev.next = this;
575 this.next.prev = this;
576 this.pair.pair = this;
577 bind_peers.add(this);
578 if (this.next.p1 != p2) throw new Error();
579 if (this.prev.p2 != p1) throw new Error();
580 if (this.p1.e == null) this.p1.e = this;
587 private boolean added = false;
589 public T makeT(int colorclass) { return t==null ? (t = new T(this, colorclass)) : t; }
591 public double crossAngle() {
592 Vec v1 = t.norm().times(-1);
593 Vec v2 = pair.t.norm().times(-1);
594 return Math.acos(v1.norm().dot(v2.norm()));
597 /** angle between this half-edge and the next */
598 public double angle() {
599 Vec v1 = next.p2.p.minus(p2.p);
600 Vec v2 = this.p1.p.minus(p2.p);
601 return Math.acos(v1.norm().dot(v2.norm()));
604 public void makeAdjacent(E e) {
605 if (this.next == e) return;
606 if (p2 != e.p1) throw new Error("cannot make adjacent -- no shared vertex");
607 if (t != null || e.t != null) throw new Error("cannot make adjacent -- edges not both free");
609 E freeIncident = p2.getFreeIncident(e, this);
611 e.prev.next = freeIncident.next;
612 freeIncident.next.prev = e.prev;
614 freeIncident.next = this.next;
615 this.next.prev = freeIncident;
624 /** creates an isolated edge out in the middle of space */
625 public E(Point p1, Point p2) {
626 if (vertices.get(p1) != null) throw new Error();
627 if (vertices.get(p2) != null) throw new Error();
628 this.p1 = new Vert(p1);
629 this.p2 = new Vert(p2);
630 this.prev = this.next = this.pair = new E(this, this, this);
632 this.p2.e = this.pair;
636 /** adds a new half-edge from prev.p2 to p2 */
637 public E(E prev, Point p) {
639 p2 = vertices.get(p);
640 if (p2 == null) p2 = new Vert(p);
644 if (p2.getE(p1) != null) throw new Error();
646 this.next = this.pair = new E(this, this, prev.next);
648 E q = p2.getFreeIncident();
650 this.next.prev = this;
652 this.prev.next = this;
653 this.pair = new E(q, this, z);
655 if (p2.e==null) p2.e = this.pair;
659 /** adds a new half-edge to the mesh with a given predecessor, successor, and pair */
660 public E(E prev, E pair, E next) {
668 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); }
669 public boolean has(Vert v) { return v==p1 || v==p2; }
670 public float length() { return p1.p.minus(p2.p).mag(); }
671 public String toString() { return p1+"->"+p2; }
673 public boolean intersects(T t) {
674 double A0=t.v1().p.x, A1=t.v1().p.y, A2=t.v1().p.z;
675 double B0=t.v2().p.x, B1=t.v2().p.y, B2=t.v2().p.z;
676 double C0=t.v3().p.x, C1=t.v3().p.y, C2=t.v3().p.z;
677 double j0=p1.p.x, j1=p1.p.y, j2=p1.p.z;
678 double k0=p2.p.x, k1=p2.p.y, k2=p2.p.z;
686 double R00, R01, R02, R03,
700 /* c = a × b */
701 c0 = a1 * b2 - a2 * b1;
702 c1 = a2 * b0 - a0 * b2;
703 c2 = a0 * b1 - a1 * b0;
705 /* M^(-1) = (1/det(M)) * adj(M) */
706 in_det = 1 / (c0 * c0 + c1 * c1 + c2 * c2);
707 R00 = (b1 * c2 - b2 * c1) * in_det;
708 R01 = (b2 * c0 - b0 * c2) * in_det;
709 R02 = (b0 * c1 - b1 * c0) * in_det;
710 R10 = (c1 * a2 - c2 * a1) * in_det;
711 R11 = (c2 * a0 - c0 * a2) * in_det;
712 R12 = (c0 * a1 - c1 * a0) * in_det;
718 R03 = -(R00 * A0 + R01 * A1 + R02 * A2);
719 R13 = -(R10 * A0 + R11 * A1 + R12 * A2);
720 R23 = -(R20 * A0 + R21 * A1 + R22 * A2);
722 /* fill in last row of 4x4 matrix */
726 J2 = R20 * j0 + R21 * j1 + R22 * j2 + R23;
727 K2 = R20 * k0 + R21 * k1 + R22 * k2 + R23;
728 if (J2 * K2 >= 0) return false;
730 J0 = R00 * j0 + R01 * j1 + R02 * j2 + R03;
731 K0 = R00 * k0 + R01 * k1 + R02 * k2 + R03;
732 i0 = J0 + J2 * ((K0 - J0) / (J2 - K2));
733 if (i0 < 0 || i0 > 1) return false;
735 J1 = R10 * j0 + R11 * j1 + R12 * j2 + R13;
736 K1 = R10 * k0 + R11 * k1 + R12 * k2 + R13;
737 i1 = J1 + J2 * ((K1 - J1) / (J2 - K2));
738 if (i1 < 0 || i1 > 1 || i0 + i1 > 1) return false;
744 public E makeE(Point p1, Point p2) {
745 Vert v1 = vertices.get(p1);
746 Vert v2 = vertices.get(p2);
747 if (v1 != null && v2 != null) {
749 if (e != null) return e;
751 if (e != null) return e;
753 if (v1 != null) return new E(v1.getFreeIncident(), p2);
754 if (v2 != null) return new E(v2.getFreeIncident(), p1).pair;
755 return new E(p1, p2);
757 public T newT(Point p1, Point p2, Point p3, Vec norm, int colorclass) {
759 Vec norm2 = p3.minus(p1).cross(p2.minus(p1));
760 float dot = norm.dot(norm2);
761 //if (Math.abs(dot) < EPointSILON) throw new Error("dot products within evertsilon of each other: "+norm+" "+norm2);
762 if (dot < 0) { Point p = p1; p1=p2; p2 = p; }
764 E e12 = makeE(p1, p2);
765 E e23 = makeE(p2, p3);
766 E e31 = makeE(p3, p1);
767 while(e12.next != e23 || e23.next != e31 || e31.next != e12) {
768 e12.makeAdjacent(e23);
769 e23.makeAdjacent(e31);
770 e31.makeAdjacent(e12);
772 T ret = e12.makeT(colorclass);
773 if (e12.t == null) throw new Error();
774 if (e23.t == null) throw new Error();
775 if (e31.t == null) throw new Error();
780 public class FaceIterator implements Iterator<T> {
781 private HashSet<T> visited = new HashSet<T>();
782 private LinkedList<T> next = new LinkedList<T>();
783 public FaceIterator() { }
784 public FaceIterator(Vert v) { next.addFirst(v.e.t); }
785 public boolean hasNext() { return next.peek()!=null; }
786 public void remove() { throw new Error(); }
788 T ret = next.removeFirst();
789 if (ret == null) return null;
791 T t1 = ret.e1().pair.t;
792 T t2 = ret.e2().pair.t;
793 T t3 = ret.e3().pair.t;
794 if (t1 != null && !visited.contains(t1)) next.addFirst(t1);
795 if (t2 != null && !visited.contains(t2)) next.addFirst(t2);
796 if (t3 != null && !visited.contains(t3)) next.addFirst(t3);
801 /** [UNIQUE] a triangle (face) */
802 public final class T extends Triangle {
804 public final int color;
805 public final int colorclass;
807 public void removeFromRTree() { tris.remove(this); }
808 public void addToRTree() { tris.insert(this); }
810 public void destroy() { tris.remove(this); }
812 T(E e1, int colorclass) {
816 if (e1==e2 || e1==e3) throw new Error();
817 if (e3.next!=e1) throw new Error();
818 if (e1.t!=null || e2.t!=null || e3.t!=null) throw new Error("non-manifold surface or disagreeing normals");
821 e1.next.next.t = this;
823 // FIXME: check for sealed/watertight surface once construction is complete (and infer normal(s)?)
825 int color = Math.abs(random.nextInt());
828 if (e1().pair.t != null && color == e1().pair.t.color) { color++; continue; }
829 if (e2().pair.t != null && color == e2().pair.t.color) { color++; continue; }
830 if (e3().pair.t != null && color == e3().pair.t.color) { color++; continue; }
834 this.colorclass = colorclass;
837 public E e1() { return e1; }
838 public E e2() { return e1.next; }
839 public E e3() { return e1.prev; }
840 public Vert v1() { return e1.p1; }
841 public Vert v2() { return e1.p2; }
842 public Vert v3() { return e1.next.p2; }
843 public Point p1() { return e1.p1.p; }
844 public Point p2() { return e1.p2.p; }
845 public Point p3() { return e1.next.p2.p; }
846 public boolean hasE(E e) { return e1==e || e1.next==e || e1.prev==e; }
847 public boolean has(Vert v) { return v1()==v || v2()==v || v3()==v; }
849 public void glVertices(GL gl) {
852 if (e1().bind_to.set.size() == 0) return;
853 if (e2().bind_to.set.size() == 0) return;
854 if (e3().bind_to.set.size() == 0) return;
863 public boolean tilemesh = false;
864 public boolean ignorecollision = false;