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<Vertex> vertices = new PointSet<Vertex>();
20 public boolean tilemesh = false;
21 public boolean ignorecollision = false;
22 public Mesh score_against = null;
23 public double score = 0;
24 public float score() { return (float)score; }
26 public int size() { return vertices.size(); }
27 public Iterable<Vertex> 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<Vertex> done = new HashSet<Vertex>();
51 for(Vertex p : new Vertex[] { t.v1(), t.v2(), t.v3() }) {
52 if (done.contains(p)) continue;
54 p.unApplyQuadricToNeighbor();
57 public void recomputeAllFundamentalQuadrics() {
58 HashSet<Vertex> done = new HashSet<Vertex>();
60 for(Vertex p : new Vertex[] { t.v1(), t.v2(), t.v3() }) {
61 if (done.contains(p)) continue;
63 p.recomputeFundamentalQuadric();
66 public float applyQuadricToNeighborAll() {
69 HashSet<Vertex> done = new HashSet<Vertex>();
71 for(Vertex p : new Vertex[] { 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<Vertex> set = new ArrayList<Vertex>();
82 for(Vertex v : vertices) set.add(v);
83 for(Vertex v : set) v.transform(m);
86 public void rebuild() { /*vertices.rebuild();*/ }
87 public Vec diagonal() { return vertices.diagonal(); }
88 public Point centroid() { return vertices.centroid(); }
89 public Vertex nearest(Point p) { return vertices.nearest(p); }
91 /** compute the volume of the mesh */
92 public float volume() {
95 double area = t.area();
96 Vec origin_to_centroid = new Vec(new Point(0, 0, 0), t.centroid());
97 boolean facingAway = t.norm().dot(origin_to_centroid) > 0;
98 double height = Math.abs(t.norm().dot(origin_to_centroid));
99 total += ((facingAway ? 1 : -1) * area * height) / 3.0;
105 // Vertexices //////////////////////////////////////////////////////////////////////////////
107 public final class Vertex extends HasPoint {
108 public String toString() { return p.toString(); }
110 E e; // some edge *leaving* this point
112 /** the nearest vertex in the "score_against" mesh */
113 Vertex nearest_in_other_mesh;
114 /** the number of vertices in the other mesh for which this is the nearest_in_other_mesh */
116 /** the total error quadric (contributions from all vertices in other mesh for which this is nearest) */
117 Matrix quadric = Matrix.ZERO;
119 Vertex bound_to = this;
120 Matrix binding = Matrix.ONE;
122 boolean quadricStale = false;
124 public Matrix errorQuadric() { return quadric; }
125 public Point getPoint() { return p; }
126 public float score() { return oldscore; }
128 private Matrix fundamentalQuadric = null;
129 public Matrix fundamentalQuadric() {
130 if (fundamentalQuadric == null) recomputeFundamentalQuadric();
131 return fundamentalQuadric;
134 private Vertex(Point p) {
136 if (vertices.get(p) != null) throw new Error();
140 private void glNormal(GL gl) {
142 gl.glNormal3f(norm.x, norm.y, norm.z);
145 public void recomputeFundamentalQuadric() {
146 //if (!quadricStale && fundamentalQuadric != null) return;
147 quadricStale = false;
148 unApplyQuadricToNeighbor();
149 Matrix m = Matrix.ZERO;
154 m = m.plus(t.norm().fundamentalQuadric(t.centroid()));
157 } while(e != this.e);
158 fundamentalQuadric = m.times(1/(float)count);
159 applyQuadricToNeighbor();
162 public void unApplyQuadricToNeighbor() {
163 if (nearest_in_other_mesh == null) return;
164 if (fundamentalQuadric == null) return;
165 nearest_in_other_mesh.unComputeError();
166 nearest_in_other_mesh.quadric = nearest_in_other_mesh.quadric.minus(fundamentalQuadric);
167 nearest_in_other_mesh.quadric_count--;
168 if (nearest_in_other_mesh.quadric_count==0)
169 nearest_in_other_mesh.quadric = Matrix.ZERO;
170 nearest_in_other_mesh.computeError();
171 nearest_in_other_mesh = null;
174 public void applyQuadricToNeighbor() {
175 if (score_against == null) return;
177 Vertex new_nearest = score_against.nearest(p);
178 if (nearest_in_other_mesh != null && new_nearest == nearest_in_other_mesh) return;
180 if (nearest_in_other_mesh != null) unApplyQuadricToNeighbor();
181 if (nearest_in_other_mesh != null) throw new Error();
183 nearest_in_other_mesh = new_nearest;
185 // don't attract to vertices that face the other way
186 if (nearest_in_other_mesh.e == null || nearest_in_other_mesh.norm().dot(norm()) < 0) {
187 nearest_in_other_mesh = null;
189 nearest_in_other_mesh.unComputeError();
190 nearest_in_other_mesh.quadric = nearest_in_other_mesh.quadric.plus(fundamentalQuadric());
191 nearest_in_other_mesh.quadric_count++;
192 nearest_in_other_mesh.computeError();
197 public void reComputeErrorAround() {
199 if (nearest_in_other_mesh != null) nearest_in_other_mesh.reComputeError();
202 e.p2.reComputeError();
204 } while (e != this.e);
206 public void reComputeError() {
210 public void unComputeError() {
214 public void computeError() {
215 if (quadric_count == 0) {
217 } else if (nearest_in_other_mesh == null) {
218 if (score_against != null) {
219 Vertex ne = score_against.nearest(p);
220 oldscore = ne.fundamentalQuadric().preAndPostMultiply(p) * 100 * 10;
225 oldscore = nearest_in_other_mesh.fundamentalQuadric().preAndPostMultiply(p) * 100 * 10;
228 oldscore = (quadric.preAndPostMultiply(p) * 100) / quadric_count;
237 //double ang = Math.abs(e.crossAngle());
238 double ang = Math.abs(e.crossAngle());
239 if (ang > Math.PI) throw new Error();
243 aspects += e.t.aspect()*e.t.aspect();
247 float minangle = (float)(Math.PI * 0.8);
249 oldscore += (ang - minangle);
252 } while (e != this.e);
253 if (numaspects > 0) oldscore += (aspects / numaspects);
255 //System.out.println(oldscore);
256 //oldscore = oldscore*oldscore;
260 private void removeTrianglesFromRTree() {
263 if (e.t != null) e.t.removeFromRTree();
265 } while(e != this.e);
267 private void addTrianglesToRTree() {
270 if (e.t != null) e.t.addToRTree();
272 } while(e != this.e);
275 /** does NOT update bound pairs! */
276 public boolean transform(Matrix m) {
277 unApplyQuadricToNeighbor();
280 if (vertices.get(this.p)==null) throw new Error();
281 vertices.remove(this);
282 removeTrianglesFromRTree();
283 float newx = m.a*p.x + m.b*p.y + m.c*p.z + m.d;
284 float newy = m.e*p.x + m.f*p.y + m.g*p.z + m.h;
285 float newz = m.i*p.x + m.j*p.y + m.k*p.z + m.l;
286 this.p = new Point(newx, newy, newz);
287 addTrianglesToRTree();
289 } catch (Exception e) {
290 throw new RuntimeException(e);
292 applyQuadricToNeighbor();
294 // FIXME: intersection test needed?
297 // should recompute fundamental quadrics of all vertices sharing a face, but we defer...
301 if (Math.abs(e.crossAngle()) > (Math.PI * 0.9) ||
302 Math.abs(e.next.crossAngle()) > (Math.PI * 0.9)) {
305 if (e.t.aspect() < 0.1) {
309 e.p2.quadricStale = true;
311 } while(e != this.e);
314 if (!ignorecollision && good) {
316 tris.range(new Segment(oldp, this.p),
318 public void visit(T t) {
322 if (!t.has(e.p1) && !t.has(e.p2) && e.intersects(t)) { good = false; }
324 if (!e.t.has(t.e1().p1) && !e.t.has(t.e1().p2) && t.e1().intersects(e.t)) { good = false; }
325 if (!e.t.has(t.e2().p1) && !e.t.has(t.e2().p2) && t.e2().intersects(e.t)) { good = false; }
326 if (!e.t.has(t.e3().p1) && !e.t.has(t.e3().p2) && t.e3().intersects(e.t)) { good = false; }
329 } while(e != Vertex.this.e);
334 for(T t : Mesh.this) {
338 if (!t.has(e.p1) && !t.has(e.p2) && e.intersects(t)) { good = false; break; }
340 if (!e.t.has(t.e1().p1) && !e.t.has(t.e1().p2) && t.e1().intersects(e.t)) { good = false; break; }
341 if (!e.t.has(t.e2().p1) && !e.t.has(t.e2().p2) && t.e2().intersects(e.t)) { good = false; break; }
342 if (!e.t.has(t.e3().p1) && !e.t.has(t.e3().p2) && t.e3().intersects(e.t)) { good = false; break; }
345 } while(e != this.e);
351 reComputeErrorAround();
354 private boolean good;
356 public boolean move(Vec v) {
357 Matrix m = Matrix.translate(v);
361 good &= p.transform(m);
367 public E getFreeIncident() {
368 E ret = getFreeIncident(e, e);
369 if (ret != null) return ret;
370 ret = getFreeIncident(e.pair.next, e.pair.next);
374 System.out.println(ex + " " + ex.t);
377 throw new Error("unable to find free incident to " + this);
382 public E getFreeIncident(E start, E before) {
385 if (e.pair.p2 == this && e.pair.t == null && e.pair.next.t == null) return e.pair;
387 } while(e != before);
391 public E getE(Point p2) {
392 Vertex v = vertices.get(p2);
393 if (v==null) return null;
396 public E getE(Vertex p2) {
399 if (e==null) return null;
400 if (e.p1 == this && e.p2 == p2) return e;
407 Vec norm = new Vec(0, 0, 0);
410 if (e.t != null) norm = norm.plus(e.t.norm().times((float)e.prev.angle()));
412 } while(e != this.e);
416 public boolean isBoundTo(Vertex p) {
419 if (px==this) return true;
424 public void unbind() { bound_to = this; binding = Matrix.ONE; }
425 public void bind(Vertex p) { bind(p, Matrix.ONE); }
426 public void bind(Vertex p, Matrix binding) {
427 if (isBoundTo(p)) return;
428 Vertex temp_bound_to = p.bound_to;
429 Matrix temp_binding = p.binding;
430 p.bound_to = this.bound_to;
431 p.binding = binding.times(this.binding); // FIXME: may have order wrong here
432 this.bound_to = temp_bound_to;
433 this.binding = temp_binding.times(temp_binding); // FIXME: may have order wrong here
437 public class BindingGroup {
438 private HashSet<E> set = new HashSet<E>();
439 public BindingGroup bind_others;
440 public BindingGroup other() { return bind_others; }
441 public BindingGroup(BindingGroup bind_others) { this.bind_others = bind_others; }
442 public BindingGroup() { this.bind_others = new BindingGroup(this); }
443 public BindingGroup(E e) { this(); set.add(e); }
444 public void add(E e) {
445 if (set.contains(e)) return;
447 BindingGroup e_bind_peers = e.bind_peers;
448 BindingGroup e_bind_to = e.bind_to;
450 e.bind_to = bind_others;
451 for (E epeer : e_bind_peers.set) add(epeer);
452 for (E eother : e_bind_to.set) bind_others.add(eother);
454 for(E eother : bind_others.set) {
455 if (e.next.bind_to.set.contains(eother.prev)) {
456 e.next.next.bindEdge(eother.prev.prev);
458 if (e.prev.bind_to.set.contains(eother.next)) {
459 e.prev.prev.bindEdge(eother.next.next);
464 public void dobind(E e) {
465 for(E ebound : set) {
466 e.p1.bind(ebound.p2);
467 e.p2.bind(ebound.p1);
470 public void shatter(BindingGroup bg1, BindingGroup bg2) {
472 e.shatter(e.midpoint(), bg1, bg2);
477 /** [UNIQUE] an edge */
478 public final class E implements Comparable<E> {
480 public final Vertex p1, p2;
481 T t; // triangle to our "left"
482 E prev; // previous half-edge
483 E next; // next half-edge
484 E pair; // partner half-edge
485 public BindingGroup bind_peers = new BindingGroup(this);
486 public BindingGroup bind_to = bind_peers.other();
487 boolean shattered = false;
489 public boolean intersects(T t) { return t.intersects(p1.p, p2.p); }
490 public float comparator() {
491 Vertex nearest = score_against.nearest(midpoint());
492 //if (t==null) return length();
494 double ang = Math.abs(crossAngle());
495 float minangle = (float)(Math.PI * 0.9);
500 if ((length() * length()) / t.area() > 10)
501 return (float)(length()*Math.sqrt(t.area()));
502 return length()*t.area();
504 return (float)Math.max(length(), midpoint().distance(nearest.p));
507 public int compareTo(E e) {
508 return e.comparator() > comparator() ? 1 : -1;
510 public void bindEdge(E e) { bind_to.add(e); }
511 public void dobind() { bind_to.dobind(this); }
513 public Point shatter() { return shatter(midpoint(), null, null); }
514 public Point shatter(Point mid, BindingGroup bg1, BindingGroup bg2) {
515 if (shattered || destroyed) return mid;
522 int old_colorclass = t==null ? 0 : t.colorclass;
523 if (bg1==null) bg1 = new BindingGroup();
524 if (bg2==null) bg2 = new BindingGroup();
525 BindingGroup old_bind_to = bind_to;
526 bind_peers.shatter(bg1, bg2);
527 old_bind_to.shatter(bg2.other(), bg1.other());
531 newT(r.p, p1.p, mid, null, old_colorclass);
532 newT(r.p, mid, p2.p, null, old_colorclass);
533 bg1.add(p1.getE(mid));
534 bg2.add(p2.getE(mid).pair);
538 public boolean destroyed = false;
539 public void destroy() {
540 if (destroyed) return;
542 pair.destroyed = true;
544 if (t != null) t.destroy();
547 if (pair.t != null) pair.t.destroy();
550 if (next.t != null) next.t.destroy();
551 if (prev.t != null) prev.t.destroy();
555 if (pair.next.t != null) pair.next.t.destroy();
556 if (pair.prev.t != null) pair.next.t.destroy();
562 this.bind_peers = null;
563 pair.bind_peers = null;
564 pair.prev.next = next;
565 next.prev = pair.prev;
566 prev.next = pair.next;
568 if (p1.e == this) p1.e = prev.next;
569 if (pair.p1.e == pair) pair.p1.e = pair.prev.next;
572 private void sync() {
573 this.prev.next = this;
574 this.next.prev = this;
575 this.pair.pair = this;
576 bind_peers.add(this);
577 if (this.next.p1 != p2) throw new Error();
578 if (this.prev.p2 != p1) throw new Error();
579 if (this.p1.e == null) this.p1.e = this;
580 if (!added) added = true;
582 private boolean added = false;
584 public T makeT(int colorclass) { return t==null ? (t = new T(this, colorclass)) : t; }
586 public double crossAngle() {
587 Vec v1 = t.norm().times(-1);
588 Vec v2 = pair.t.norm().times(-1);
589 return Math.acos(v1.norm().dot(v2.norm()));
592 /** angle between this half-edge and the next */
593 public double angle() {
594 Vec v1 = next.p2.p.minus(p2.p);
595 Vec v2 = this.p1.p.minus(p2.p);
596 return Math.acos(v1.norm().dot(v2.norm()));
599 public void makeAdjacent(E e) {
600 if (this.next == e) return;
601 if (p2 != e.p1) throw new Error("cannot make adjacent -- no shared vertex");
602 if (t != null || e.t != null) throw new Error("cannot make adjacent -- edges not both free");
604 E freeIncident = p2.getFreeIncident(e, this);
606 e.prev.next = freeIncident.next;
607 freeIncident.next.prev = e.prev;
609 freeIncident.next = this.next;
610 this.next.prev = freeIncident;
619 /** creates an isolated edge out in the middle of space */
620 public E(Point p1, Point p2) {
621 if (vertices.get(p1) != null) throw new Error();
622 if (vertices.get(p2) != null) throw new Error();
623 this.p1 = new Vertex(p1);
624 this.p2 = new Vertex(p2);
625 this.prev = this.next = this.pair = new E(this, this, this);
627 this.p2.e = this.pair;
631 /** adds a new half-edge from prev.p2 to p2 */
632 public E(E prev, Point p) {
634 p2 = vertices.get(p);
635 if (p2 == null) p2 = new Vertex(p);
639 if (p2.getE(p1) != null) throw new Error();
641 this.next = this.pair = new E(this, this, prev.next);
643 E q = p2.getFreeIncident();
645 this.next.prev = this;
647 this.prev.next = this;
648 this.pair = new E(q, this, z);
650 if (p2.e==null) p2.e = this.pair;
654 /** adds a new half-edge to the mesh with a given predecessor, successor, and pair */
655 public E(E prev, E pair, E next) {
663 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); }
664 public boolean has(Vertex v) { return v==p1 || v==p2; }
665 public float length() { return p1.p.minus(p2.p).mag(); }
666 public String toString() { return p1+"->"+p2; }
670 public E makeE(Point p1, Point p2) {
671 Vertex v1 = vertices.get(p1);
672 Vertex v2 = vertices.get(p2);
673 if (v1 != null && v2 != null) {
675 if (e != null) return e;
677 if (e != null) return e;
679 if (v1 != null) return new E(v1.getFreeIncident(), p2);
680 if (v2 != null) return new E(v2.getFreeIncident(), p1).pair;
681 return new E(p1, p2);
683 public T newT(Point p1, Point p2, Point p3, Vec norm, int colorclass) {
685 Vec norm2 = p3.minus(p1).cross(p2.minus(p1));
686 float dot = norm.dot(norm2);
687 //if (Math.abs(dot) < EPointSILON) throw new Error("dot products within evertsilon of each other: "+norm+" "+norm2);
688 if (dot < 0) { Point p = p1; p1=p2; p2 = p; }
690 E e12 = makeE(p1, p2);
691 E e23 = makeE(p2, p3);
692 E e31 = makeE(p3, p1);
693 while(e12.next != e23 || e23.next != e31 || e31.next != e12) {
694 e12.makeAdjacent(e23);
695 e23.makeAdjacent(e31);
696 e31.makeAdjacent(e12);
698 T ret = e12.makeT(colorclass);
699 if (e12.t == null) throw new Error();
700 if (e23.t == null) throw new Error();
701 if (e31.t == null) throw new Error();
706 /** [UNIQUE] a triangle (face) */
707 public final class T extends Triangle {
709 public final int color;
710 public final int colorclass;
712 public void removeFromRTree() { tris.remove(this); }
713 public void addToRTree() { tris.insert(this); }
715 public void destroy() { tris.remove(this); }
717 T(E e1, int colorclass) {
721 if (e1==e2 || e1==e3) throw new Error();
722 if (e3.next!=e1) throw new Error();
723 if (e1.t!=null || e2.t!=null || e3.t!=null) throw new Error("non-manifold surface or disagreeing normals");
726 e1.next.next.t = this;
728 // FIXME: check for sealed/watertight surface once construction is complete (and infer normal(s)?)
730 int color = Math.abs(random.nextInt());
733 if (e1().pair.t != null && color == e1().pair.t.color) { color++; continue; }
734 if (e2().pair.t != null && color == e2().pair.t.color) { color++; continue; }
735 if (e3().pair.t != null && color == e3().pair.t.color) { color++; continue; }
739 this.colorclass = colorclass;
742 public E e1() { return e1; }
743 public E e2() { return e1.next; }
744 public E e3() { return e1.prev; }
745 public Vertex v1() { return e1.p1; }
746 public Vertex v2() { return e1.p2; }
747 public Vertex v3() { return e1.next.p2; }
748 public Point p1() { return e1.p1.p; }
749 public Point p2() { return e1.p2.p; }
750 public Point p3() { return e1.next.p2.p; }
751 public boolean hasE(E e) { return e1==e || e1.next==e || e1.prev==e; }
752 public boolean has(Vertex v) { return v1()==v || v2()==v || v3()==v; }
754 public boolean shouldBeDrawn() {
755 if (e1().bind_to.set.size() == 0) return false;
756 if (e2().bind_to.set.size() == 0) return false;
757 if (e3().bind_to.set.size() == 0) return false;