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> pointset = new PointSet<Vert>();
18 public int size() { return pointset.size(); }
19 public Iterable<Vert> vertices() { return pointset; }
21 public Iterable<E> edges() {
24 public Iterator<E> iterator() {
26 HashSet<E> hse = new HashSet<E>();
27 for(T t : Mesh.this) {
35 return hse.iterator();
39 public Iterator<T> iterator() {
41 for(Vert v : pointset)
42 if (v.e != null && v.e.t != null)
43 return new FaceIterator(v);
44 return new FaceIterator();
48 public HashSet<T> ts = new HashSet<T>();
50 public Mesh score_against = null;
51 public double score = 0;
52 public float score() { return (float)score; }
54 public int numedges = 0;
55 public float avgedge = 0;
57 public void rebindPoints() {
59 for(Mesh.T t : this) {
64 // ask edges to re-implement their bindings
65 for(Mesh.T t : this) {
72 public void unApplyQuadricToNeighborAll() {
73 HashSet<Vert> done = new HashSet<Vert>();
75 for(Vert p : new Vert[] { t.v1(), t.v2(), t.v3() }) {
76 if (done.contains(p)) continue;
78 p.unApplyQuadricToNeighbor();
81 public void recomputeAllFundamentalQuadrics() {
82 HashSet<Vert> done = new HashSet<Vert>();
84 for(Vert p : new Vert[] { t.v1(), t.v2(), t.v3() }) {
85 if (done.contains(p)) continue;
87 p.recomputeFundamentalQuadric();
90 public float applyQuadricToNeighborAll() {
93 HashSet<Vert> done = new HashSet<Vert>();
95 for(Vert p : new Vert[] { t.v1(), t.v2(), t.v3() }) {
96 if (done.contains(p)) continue;
98 p.applyQuadricToNeighbor();
101 return (float)(dist/num);
104 public void transform(Matrix m) {
105 ArrayList<Vert> set = new ArrayList<Vert>();
106 for (Vert v : pointset)
108 for(Vert v : set) v.transform(m);
111 public float volume() {
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;
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); }
128 public final class Vert extends HasPoint {
129 public String toString() { return p.toString(); }
131 E e; // some edge *leaving* this point
133 /** the nearest vertex in the "score_against" mesh */
134 Vert nearest_in_other_mesh;
135 /** the number of vertices in the other mesh for which this is the nearest_in_other_mesh */
137 /** the total error quadric (contributions from all vertices in other mesh for which this is nearest) */
138 Matrix quadric = Matrix.ZERO;
140 Vert bound_to = this;
141 Matrix binding = new Matrix();
143 boolean quadricStale = false;
145 public Matrix errorQuadric() { return quadric; }
146 public Point getPoint() { return p; }
147 public float score() { return oldscore; }
149 private Matrix fundamentalQuadric = null;
150 public Matrix fundamentalQuadric() {
151 if (fundamentalQuadric == null) recomputeFundamentalQuadric();
152 return fundamentalQuadric;
155 private Vert(Point p) {
157 if (pointset.get(p) != null) throw new Error();
161 private void glNormal(GL gl) {
163 gl.glNormal3f(norm.x, norm.y, norm.z);
166 public void recomputeFundamentalQuadric() {
167 //if (!quadricStale && fundamentalQuadric != null) return;
168 quadricStale = false;
169 unApplyQuadricToNeighbor();
170 Matrix m = Matrix.ZERO;
175 m = m.plus(t.norm().fundamentalQuadric(t.centroid()));
178 } while(e != this.e);
179 fundamentalQuadric = m.times(1/(float)count);
180 applyQuadricToNeighbor();
183 public void unApplyQuadricToNeighbor() {
184 if (nearest_in_other_mesh == null) return;
185 if (fundamentalQuadric == null) return;
186 nearest_in_other_mesh.unComputeError();
187 nearest_in_other_mesh.quadric = nearest_in_other_mesh.quadric.minus(fundamentalQuadric);
188 nearest_in_other_mesh.quadric_count--;
189 if (nearest_in_other_mesh.quadric_count==0)
190 nearest_in_other_mesh.quadric = Matrix.ZERO;
191 nearest_in_other_mesh.computeError();
192 nearest_in_other_mesh = null;
195 public void applyQuadricToNeighbor() {
196 if (score_against == null) return;
198 Vert new_nearest = score_against.nearest(p);
199 if (nearest_in_other_mesh != null && new_nearest == nearest_in_other_mesh) return;
201 if (nearest_in_other_mesh != null) unApplyQuadricToNeighbor();
202 if (nearest_in_other_mesh != null) throw new Error();
204 nearest_in_other_mesh = new_nearest;
206 // don't attract to vertices that face the other way
207 if (nearest_in_other_mesh.e == null || nearest_in_other_mesh.norm().dot(norm()) < 0) {
208 nearest_in_other_mesh = null;
210 nearest_in_other_mesh.unComputeError();
211 nearest_in_other_mesh.quadric = nearest_in_other_mesh.quadric.plus(fundamentalQuadric());
212 nearest_in_other_mesh.quadric_count++;
213 nearest_in_other_mesh.computeError();
218 public void reComputeErrorAround() {
220 if (nearest_in_other_mesh != null) nearest_in_other_mesh.reComputeError();
223 e.p2.reComputeError();
225 } while (e != this.e);
227 public void reComputeError() {
231 public void unComputeError() {
235 public void computeError() {
236 if (quadric_count == 0) {
239 else if (nearest_in_other_mesh == null) {
240 if (score_against != null) {
241 Vert ne = score_against.nearest(p);
242 oldscore = ne.fundamentalQuadric().preAndPostMultiply(p) * 100 * 10;
247 oldscore = nearest_in_other_mesh.fundamentalQuadric().preAndPostMultiply(p) * 100 * 10;
250 oldscore = (quadric.preAndPostMultiply(p) * 100) / quadric_count;
259 //double ang = Math.abs(e.crossAngle());
260 double ang = Math.abs(e.crossAngle());
261 if (ang > Math.PI) throw new Error();
265 aspects += e.t.aspect()*e.t.aspect();
269 float minangle = (float)(Math.PI * 0.8);
271 oldscore += (ang - minangle);
274 } while (e != this.e);
275 if (numaspects > 0) oldscore += (aspects / numaspects);
277 //System.out.println(oldscore);
278 //oldscore = oldscore*oldscore;
282 /** does NOT update bound pairs! */
283 public boolean transform(Matrix m) {
284 unApplyQuadricToNeighbor();
286 if (pointset.get(this.p)==null) throw new Error();
287 pointset.remove(this);
288 float newx = m.a*p.x + m.b*p.y + m.c*p.z + m.d;
289 float newy = m.e*p.x + m.f*p.y + m.g*p.z + m.h;
290 float newz = m.i*p.x + m.j*p.y + m.k*p.z + m.l;
291 this.p = new Point(newx, newy, newz);
293 } catch (Exception e) {
294 throw new RuntimeException(e);
296 applyQuadricToNeighbor();
298 // FIXME: intersection test needed?
301 // should recompute fundamental quadrics of all vertices sharing a face, but we defer...
305 if (Math.abs(e.crossAngle()) > (Math.PI * 0.9) ||
306 Math.abs(e.next.crossAngle()) > (Math.PI * 0.9)) {
309 if (e.t.aspect() < 0.1) {
313 e.p2.quadricStale = true;
315 } while(e != this.e);
317 if (!ignorecollision)
318 for(T t : Mesh.this) {
322 if (!t.has(e.p1) && !t.has(e.p2) && e.intersects(t)) { good = false; break; }
324 //if (!e.t.has(t.e1().p1) && !e.t.has(t.e1().p2) && t.e1().intersects(e.t)) { good = false; break; }
325 //if (!e.t.has(t.e2().p1) && !e.t.has(t.e2().p2) && t.e2().intersects(e.t)) { good = false; break; }
326 //if (!e.t.has(t.e3().p1) && !e.t.has(t.e3().p2) && t.e3().intersects(e.t)) { good = false; break; }
329 } while(e != this.e);
332 reComputeErrorAround();
336 public boolean move(Vec v) {
337 Matrix m = new Matrix(v);
341 good &= p.transform(m);
347 public E getFreeIncident() {
348 E ret = getFreeIncident(e, e);
349 if (ret != null) return ret;
350 ret = getFreeIncident(e.pair.next, e.pair.next);
354 System.out.println(ex + " " + ex.t);
357 throw new Error("unable to find free incident to " + this);
362 public E getFreeIncident(E start, E before) {
365 if (e.pair.p2 == this && e.pair.t == null && e.pair.next.t == null) return e.pair;
367 } while(e != before);
371 public E getE(Point p2) {
372 Vert v = pointset.get(p2);
373 if (v==null) return null;
376 public E getE(Vert p2) {
379 if (e==null) return null;
380 if (e.p1 == this && e.p2 == p2) return e;
387 Vec norm = new Vec(0, 0, 0);
390 if (e.t != null) norm = norm.plus(e.t.norm().times((float)e.prev.angle()));
392 } while(e != this.e);
396 public boolean isBoundTo(Vert p) {
399 if (px==this) return true;
404 public void unbind() { bound_to = this; binding = new Matrix(); }
405 public void bind(Vert p) { bind(p, new Matrix()); }
406 public void bind(Vert p, Matrix binding) {
407 if (isBoundTo(p)) return;
408 Vert temp_bound_to = p.bound_to;
409 Matrix temp_binding = p.binding;
410 p.bound_to = this.bound_to;
411 p.binding = binding.times(this.binding); // FIXME: may have order wrong here
412 this.bound_to = temp_bound_to;
413 this.binding = temp_binding.times(temp_binding); // FIXME: may have order wrong here
417 public class BindingGroup {
418 private HashSet<E> set = new HashSet<E>();
419 public BindingGroup bind_others;
420 public BindingGroup other() { return bind_others; }
421 public BindingGroup(BindingGroup bind_others) { this.bind_others = bind_others; }
422 public BindingGroup() { this.bind_others = new BindingGroup(this); }
423 public BindingGroup(E e) { this(); set.add(e); }
424 public void add(E e) {
425 if (set.contains(e)) return;
427 BindingGroup e_bind_peers = e.bind_peers;
428 BindingGroup e_bind_to = e.bind_to;
430 e.bind_to = bind_others;
431 for (E epeer : e_bind_peers.set) add(epeer);
432 for (E eother : e_bind_to.set) bind_others.add(eother);
434 for(E eother : bind_others.set) {
435 if (e.next.bind_to.set.contains(eother.prev)) {
436 e.next.next.bindEdge(eother.prev.prev);
438 if (e.prev.bind_to.set.contains(eother.next)) {
439 e.prev.prev.bindEdge(eother.next.next);
444 public void dobind(E e) {
445 for(E ebound : set) {
446 e.p1.bind(ebound.p2);
447 e.p2.bind(ebound.p1);
450 public void shatter(BindingGroup bg1, BindingGroup bg2) {
452 e.shatter(e.midpoint(), bg1, bg2);
457 /** [UNIQUE] an edge */
458 public final class E implements Comparable<E> {
460 public final Vert p1, p2;
461 T t; // triangle to our "left"
462 E prev; // previous half-edge
463 E next; // next half-edge
464 E pair; // partner half-edge
465 public BindingGroup bind_peers = new BindingGroup(this);
466 public BindingGroup bind_to = bind_peers.other();
467 boolean shattered = false;
469 public float comparator() {
470 Vert nearest = score_against.nearest(midpoint());
471 //if (t==null) return length();
473 double ang = Math.abs(crossAngle());
474 float minangle = (float)(Math.PI * 0.9);
479 if ((length() * length()) / t.area() > 10)
480 return (float)(length()*Math.sqrt(t.area()));
481 return length()*t.area();
483 return (float)Math.max(length(), midpoint().distance(nearest.p));
486 public int compareTo(E e) {
487 return e.comparator() > comparator() ? 1 : -1;
489 public void bindEdge(E e) { bind_to.add(e); }
490 public void dobind() { bind_to.dobind(this); }
492 public Point shatter() { return shatter(midpoint(), null, null); }
493 public Point shatter(Point mid, BindingGroup bg1, BindingGroup bg2) {
494 if (shattered || destroyed) return mid;
501 int old_colorclass = t==null ? 0 : t.colorclass;
502 if (bg1==null) bg1 = new BindingGroup();
503 if (bg2==null) bg2 = new BindingGroup();
504 BindingGroup old_bind_to = bind_to;
505 bind_peers.shatter(bg1, bg2);
506 old_bind_to.shatter(bg2.other(), bg1.other());
510 newT(r.p, p1.p, mid, null, old_colorclass);
511 newT(r.p, mid, p2.p, null, old_colorclass);
512 bg1.add(p1.getE(mid));
513 bg2.add(p2.getE(mid).pair);
517 public boolean destroyed = false;
518 public void destroy() {
519 if (destroyed) return;
521 pair.destroyed = true;
523 if (t != null) t.destroy();
526 if (pair.t != null) pair.t.destroy();
529 if (next.t != null) next.t.destroy();
530 if (prev.t != null) prev.t.destroy();
534 if (pair.next.t != null) pair.next.t.destroy();
535 if (pair.prev.t != null) pair.next.t.destroy();
541 this.bind_peers = null;
542 pair.bind_peers = null;
543 pair.prev.next = next;
544 next.prev = pair.prev;
545 prev.next = pair.next;
547 if (p1.e == this) p1.e = prev.next;
548 if (pair.p1.e == pair) pair.p1.e = pair.prev.next;
549 avgedge -= this.length();
550 avgedge -= pair.length();
555 private void sync() {
556 this.prev.next = this;
557 this.next.prev = this;
558 this.pair.pair = this;
559 bind_peers.add(this);
560 if (this.next.p1 != p2) throw new Error();
561 if (this.prev.p2 != p1) throw new Error();
562 if (this.p1.e == null) this.p1.e = this;
569 private boolean added = false;
571 public T makeT(int colorclass) { return t==null ? (t = new T(this, colorclass)) : t; }
573 public double crossAngle() {
574 Vec v1 = t.norm().times(-1);
575 Vec v2 = pair.t.norm().times(-1);
576 return Math.acos(v1.norm().dot(v2.norm()));
579 /** angle between this half-edge and the next */
580 public double angle() {
581 Vec v1 = next.p2.p.minus(p2.p);
582 Vec v2 = this.p1.p.minus(p2.p);
583 return Math.acos(v1.norm().dot(v2.norm()));
586 public void makeAdjacent(E e) {
587 if (this.next == e) return;
588 if (p2 != e.p1) throw new Error("cannot make adjacent -- no shared vertex");
589 if (t != null || e.t != null) throw new Error("cannot make adjacent -- edges not both free");
591 E freeIncident = p2.getFreeIncident(e, this);
593 e.prev.next = freeIncident.next;
594 freeIncident.next.prev = e.prev;
596 freeIncident.next = this.next;
597 this.next.prev = freeIncident;
606 /** creates an isolated edge out in the middle of space */
607 public E(Point p1, Point p2) {
608 if (pointset.get(p1) != null) throw new Error();
609 if (pointset.get(p2) != null) throw new Error();
610 this.p1 = new Vert(p1);
611 this.p2 = new Vert(p2);
612 this.prev = this.next = this.pair = new E(this, this, this);
614 this.p2.e = this.pair;
618 /** adds a new half-edge from prev.p2 to p2 */
619 public E(E prev, Point p) {
621 p2 = pointset.get(p);
622 if (p2 == null) p2 = new Vert(p);
626 if (p2.getE(p1) != null) throw new Error();
628 this.next = this.pair = new E(this, this, prev.next);
630 E q = p2.getFreeIncident();
632 this.next.prev = this;
634 this.prev.next = this;
635 this.pair = new E(q, this, z);
637 if (p2.e==null) p2.e = this.pair;
641 /** adds a new half-edge to the mesh with a given predecessor, successor, and pair */
642 public E(E prev, E pair, E next) {
650 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); }
651 public boolean has(Vert v) { return v==p1 || v==p2; }
652 public float length() { return p1.p.minus(p2.p).mag(); }
653 public String toString() { return p1+"->"+p2; }
655 public boolean intersects(T t) {
656 double A0=t.v1().p.x, A1=t.v1().p.y, A2=t.v1().p.z;
657 double B0=t.v2().p.x, B1=t.v2().p.y, B2=t.v2().p.z;
658 double C0=t.v3().p.x, C1=t.v3().p.y, C2=t.v3().p.z;
659 double j0=p1.p.x, j1=p1.p.y, j2=p1.p.z;
660 double k0=p2.p.x, k1=p2.p.y, k2=p2.p.z;
668 double R00, R01, R02, R03,
682 /* c = a × b */
683 c0 = a1 * b2 - a2 * b1;
684 c1 = a2 * b0 - a0 * b2;
685 c2 = a0 * b1 - a1 * b0;
687 /* M^(-1) = (1/det(M)) * adj(M) */
688 in_det = 1 / (c0 * c0 + c1 * c1 + c2 * c2);
689 R00 = (b1 * c2 - b2 * c1) * in_det;
690 R01 = (b2 * c0 - b0 * c2) * in_det;
691 R02 = (b0 * c1 - b1 * c0) * in_det;
692 R10 = (c1 * a2 - c2 * a1) * in_det;
693 R11 = (c2 * a0 - c0 * a2) * in_det;
694 R12 = (c0 * a1 - c1 * a0) * in_det;
700 R03 = -(R00 * A0 + R01 * A1 + R02 * A2);
701 R13 = -(R10 * A0 + R11 * A1 + R12 * A2);
702 R23 = -(R20 * A0 + R21 * A1 + R22 * A2);
704 /* fill in last row of 4x4 matrix */
708 J2 = R20 * j0 + R21 * j1 + R22 * j2 + R23;
709 K2 = R20 * k0 + R21 * k1 + R22 * k2 + R23;
710 if (J2 * K2 >= 0) return false;
712 J0 = R00 * j0 + R01 * j1 + R02 * j2 + R03;
713 K0 = R00 * k0 + R01 * k1 + R02 * k2 + R03;
714 i0 = J0 + J2 * ((K0 - J0) / (J2 - K2));
715 if (i0 < 0 || i0 > 1) return false;
717 J1 = R10 * j0 + R11 * j1 + R12 * j2 + R13;
718 K1 = R10 * k0 + R11 * k1 + R12 * k2 + R13;
719 i1 = J1 + J2 * ((K1 - J1) / (J2 - K2));
720 if (i1 < 0 || i1 > 1 || i0 + i1 > 1) return false;
726 public E makeE(Point p1, Point p2) {
727 Vert v1 = pointset.get(p1);
728 Vert v2 = pointset.get(p2);
729 if (v1 != null && v2 != null) {
731 if (e != null) return e;
733 if (e != null) return e;
735 if (v1 != null) return new E(v1.getFreeIncident(), p2);
736 if (v2 != null) return new E(v2.getFreeIncident(), p1).pair;
737 return new E(p1, p2);
739 public T newT(Point p1, Point p2, Point p3, Vec norm, int colorclass) {
741 Vec norm2 = p3.minus(p1).cross(p2.minus(p1));
742 float dot = norm.dot(norm2);
743 //if (Math.abs(dot) < EPointSILON) throw new Error("dot products within evertsilon of each other: "+norm+" "+norm2);
744 if (dot < 0) { Point p = p1; p1=p2; p2 = p; }
746 E e12 = makeE(p1, p2);
747 E e23 = makeE(p2, p3);
748 E e31 = makeE(p3, p1);
749 while(e12.next != e23 || e23.next != e31 || e31.next != e12) {
750 e12.makeAdjacent(e23);
751 e23.makeAdjacent(e31);
752 e31.makeAdjacent(e12);
754 T ret = e12.makeT(colorclass);
755 if (e12.t == null) throw new Error();
756 if (e23.t == null) throw new Error();
757 if (e31.t == null) throw new Error();
762 public class FaceIterator implements Iterator<T> {
763 private HashSet<T> visited = new HashSet<T>();
764 private LinkedList<T> next = new LinkedList<T>();
765 public FaceIterator() { }
766 public FaceIterator(Vert v) { next.addFirst(v.e.t); }
767 public boolean hasNext() { return next.peek()!=null; }
768 public void remove() { throw new Error(); }
770 T ret = next.removeFirst();
771 if (ret == null) return null;
773 T t1 = ret.e1().pair.t;
774 T t2 = ret.e2().pair.t;
775 T t3 = ret.e3().pair.t;
776 if (t1 != null && !visited.contains(t1)) next.addFirst(t1);
777 if (t2 != null && !visited.contains(t2)) next.addFirst(t2);
778 if (t3 != null && !visited.contains(t3)) next.addFirst(t3);
783 /** [UNIQUE] a triangle (face) */
784 public final class T extends Triangle {
786 public final int color;
787 public final int colorclass;
789 public void destroy() {
793 T(E e1, int colorclass) {
797 if (e1==e2 || e1==e3) throw new Error();
798 if (e3.next!=e1) throw new Error();
799 if (e1.t!=null || e2.t!=null || e3.t!=null) throw new Error("non-manifold surface or disagreeing normals");
802 e1.next.next.t = this;
804 // FIXME: check for sealed/watertight surface once construction is complete (and infer normal(s)?)
806 int color = Math.abs(random.nextInt());
809 if (e1().pair.t != null && color == e1().pair.t.color) { color++; continue; }
810 if (e2().pair.t != null && color == e2().pair.t.color) { color++; continue; }
811 if (e3().pair.t != null && color == e3().pair.t.color) { color++; continue; }
815 this.colorclass = colorclass;
818 public E e1() { return e1; }
819 public E e2() { return e1.next; }
820 public E e3() { return e1.prev; }
821 public Vert v1() { return e1.p1; }
822 public Vert v2() { return e1.p2; }
823 public Vert v3() { return e1.next.p2; }
824 public Point p1() { return e1.p1.p; }
825 public Point p2() { return e1.p2.p; }
826 public Point p3() { return e1.next.p2.p; }
827 public boolean hasE(E e) { return e1==e || e1.next==e || e1.prev==e; }
828 public boolean has(Vert v) { return v1()==v || v2()==v || v3()==v; }
830 public void glVertices(GL gl) {
832 if (e1().bind_to.set.size() == 0) return;
833 if (e2().bind_to.set.size() == 0) return;
834 if (e3().bind_to.set.size() == 0) return;
842 public boolean tilemesh = false;
843 public boolean ignorecollision = false;