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 immutableVertices;
21 public boolean ignorecollision = false;
22 public Mesh score_against = null;
23 public double score = 0;
25 public Mesh(boolean immutableVertices) { this.immutableVertices = immutableVertices; }
27 public void makeVerticesImmutable() { this.immutableVertices = true; }
28 public float score() { return (float)score; }
30 public int size() { return vertices.size(); }
31 public Iterable<Vertex> vertices() { return vertices; }
32 public Iterator<T> iterator() { return tris.iterator(); }
34 public void rebindPoints() {
36 for(Mesh.T t : this) {
41 // ask edges to re-implement their bindings
42 for(Mesh.T t : this) {
49 public void unApplyQuadricToNeighborAll() {
50 HashSet<Vertex> done = new HashSet<Vertex>();
52 for(Vertex p : new Vertex[] { t.v1(), t.v2(), t.v3() }) {
53 if (done.contains(p)) continue;
55 p.unApplyQuadricToNeighbor();
58 public void recomputeAllFundamentalQuadrics() {
59 HashSet<Vertex> done = new HashSet<Vertex>();
61 for(Vertex p : new Vertex[] { t.v1(), t.v2(), t.v3() }) {
62 if (done.contains(p)) continue;
64 p.recomputeFundamentalQuadric();
67 public float applyQuadricToNeighborAll() {
70 HashSet<Vertex> done = new HashSet<Vertex>();
72 for(Vertex p : new Vertex[] { t.v1(), t.v2(), t.v3() }) {
73 if (done.contains(p)) continue;
75 p.applyQuadricToNeighbor();
78 return (float)(dist/num);
81 public void transform(Matrix m) {
82 ArrayList<Vertex> set = new ArrayList<Vertex>();
83 for(Vertex v : vertices) set.add(v);
84 for(Vertex v : set) v.transform(m);
87 public void rebuild() { /*vertices.rebuild();*/ }
88 public Vec diagonal() { return vertices.diagonal(); }
89 public Point centroid() { return vertices.centroid(); }
90 public Vertex nearest(Point p) { return vertices.nearest(p); }
92 /** compute the volume of the mesh */
93 public float volume() {
96 double area = t.area();
97 Vec origin_to_centroid = new Vec(new Point(0, 0, 0), t.centroid());
98 boolean facingAway = t.norm().dot(origin_to_centroid) > 0;
99 double height = Math.abs(t.norm().dot(origin_to_centroid));
100 total += ((facingAway ? 1 : -1) * area * height) / 3.0;
106 // Vertexices //////////////////////////////////////////////////////////////////////////////
108 public final class Vertex extends HasPoint {
109 public String toString() { return p.toString(); }
111 E e; // some edge *leaving* this point
113 /** the nearest vertex in the "score_against" mesh */
114 Vertex nearest_in_other_mesh;
115 /** the number of vertices in the other mesh for which this is the nearest_in_other_mesh */
117 /** the total error quadric (contributions from all vertices in other mesh for which this is nearest) */
118 Matrix quadric = Matrix.ZERO;
120 Vertex bound_to = this;
121 Matrix binding = Matrix.ONE;
123 boolean quadricStale = false;
125 public Matrix errorQuadric() { return quadric; }
126 public Point getPoint() { return p; }
127 public float score() { return oldscore; }
129 private Matrix fundamentalQuadric = null;
130 public Matrix fundamentalQuadric() {
131 if (fundamentalQuadric == null) recomputeFundamentalQuadric();
132 return fundamentalQuadric;
135 private Vertex(Point p) {
137 if (vertices.get(p) != null) throw new Error();
141 private void glNormal(GL gl) {
143 gl.glNormal3f(norm.x, norm.y, norm.z);
146 public void recomputeFundamentalQuadric() {
147 //if (!quadricStale && fundamentalQuadric != null) return;
148 quadricStale = false;
149 unApplyQuadricToNeighbor();
150 Matrix m = Matrix.ZERO;
155 m = m.plus(t.norm().fundamentalQuadric(t.centroid()));
158 } while(e != this.e);
159 fundamentalQuadric = m.times(1/(float)count);
160 applyQuadricToNeighbor();
163 public void unApplyQuadricToNeighbor() {
164 if (nearest_in_other_mesh == null) return;
165 if (fundamentalQuadric == null) return;
166 nearest_in_other_mesh.unComputeError();
167 nearest_in_other_mesh.quadric = nearest_in_other_mesh.quadric.minus(fundamentalQuadric);
168 nearest_in_other_mesh.quadric_count--;
169 if (nearest_in_other_mesh.quadric_count==0)
170 nearest_in_other_mesh.quadric = Matrix.ZERO;
171 nearest_in_other_mesh.computeError();
172 nearest_in_other_mesh = null;
175 public void applyQuadricToNeighbor() {
176 if (score_against == null) return;
178 Vertex new_nearest = score_against.nearest(p);
179 if (nearest_in_other_mesh != null && new_nearest == nearest_in_other_mesh) return;
181 if (nearest_in_other_mesh != null) unApplyQuadricToNeighbor();
182 if (nearest_in_other_mesh != null) throw new Error();
184 nearest_in_other_mesh = new_nearest;
186 // don't attract to vertices that face the other way
187 if (nearest_in_other_mesh.e == null || nearest_in_other_mesh.norm().dot(norm()) < 0) {
188 nearest_in_other_mesh = null;
190 nearest_in_other_mesh.unComputeError();
191 nearest_in_other_mesh.quadric = nearest_in_other_mesh.quadric.plus(fundamentalQuadric());
192 nearest_in_other_mesh.quadric_count++;
193 nearest_in_other_mesh.computeError();
198 public void reComputeErrorAround() {
200 if (nearest_in_other_mesh != null) nearest_in_other_mesh.reComputeError();
203 e.p2.reComputeError();
205 } while (e != this.e);
207 public void reComputeError() {
211 public void unComputeError() {
215 public void computeError() {
216 if (quadric_count == 0) {
217 if (immutableVertices) {
218 } else if (nearest_in_other_mesh == null) {
219 if (score_against != null) {
220 Vertex ne = score_against.nearest(p);
221 oldscore = ne.fundamentalQuadric().preAndPostMultiply(p) * 100 * 10;
226 oldscore = nearest_in_other_mesh.fundamentalQuadric().preAndPostMultiply(p) * 100 * 10;
229 oldscore = (quadric.preAndPostMultiply(p) * 100) / quadric_count;
238 //double ang = Math.abs(e.crossAngle());
239 double ang = Math.abs(e.crossAngle());
240 if (ang > Math.PI) throw new Error();
244 aspects += e.t.aspect()*e.t.aspect();
248 float minangle = (float)(Math.PI * 0.8);
250 oldscore += (ang - minangle);
253 } while (e != this.e);
254 if (numaspects > 0) oldscore += (aspects / numaspects);
256 //System.out.println(oldscore);
257 //oldscore = oldscore*oldscore;
261 private void removeTrianglesFromRTree() {
264 if (e.t != null) e.t.removeFromRTree();
266 } while(e != this.e);
268 private void addTrianglesToRTree() {
271 if (e.t != null) e.t.addToRTree();
273 } while(e != this.e);
276 /** does NOT update bound pairs! */
277 public boolean transform(Matrix m) {
278 if (immutableVertices) throw new Error();
279 unApplyQuadricToNeighbor();
282 if (vertices.get(this.p)==null) throw new Error();
283 vertices.remove(this);
284 removeTrianglesFromRTree();
285 float newx = m.a*p.x + m.b*p.y + m.c*p.z + m.d;
286 float newy = m.e*p.x + m.f*p.y + m.g*p.z + m.h;
287 float newz = m.i*p.x + m.j*p.y + m.k*p.z + m.l;
288 this.p = new Point(newx, newy, newz);
289 addTrianglesToRTree();
291 } catch (Exception e) {
292 throw new RuntimeException(e);
294 applyQuadricToNeighbor();
296 // FIXME: intersection test needed?
299 // should recompute fundamental quadrics of all vertices sharing a face, but we defer...
303 if (Math.abs(e.crossAngle()) > (Math.PI * 0.9) ||
304 Math.abs(e.next.crossAngle()) > (Math.PI * 0.9)) {
307 if (e.t.aspect() < 0.1) {
311 e.p2.quadricStale = true;
313 } while(e != this.e);
316 if (!ignorecollision && good) {
318 tris.range(new Segment(oldp, this.p),
320 public void visit(T t) {
324 if (!t.has(e.p1) && !t.has(e.p2) && e.intersects(t)) { good = false; }
326 if (!e.t.has(t.e1().p1) && !e.t.has(t.e1().p2) && t.e1().intersects(e.t)) { good = false; }
327 if (!e.t.has(t.e2().p1) && !e.t.has(t.e2().p2) && t.e2().intersects(e.t)) { good = false; }
328 if (!e.t.has(t.e3().p1) && !e.t.has(t.e3().p2) && t.e3().intersects(e.t)) { good = false; }
331 } while(e != Vertex.this.e);
336 for(T t : Mesh.this) {
340 if (!t.has(e.p1) && !t.has(e.p2) && e.intersects(t)) { good = false; break; }
342 if (!e.t.has(t.e1().p1) && !e.t.has(t.e1().p2) && t.e1().intersects(e.t)) { good = false; break; }
343 if (!e.t.has(t.e2().p1) && !e.t.has(t.e2().p2) && t.e2().intersects(e.t)) { good = false; break; }
344 if (!e.t.has(t.e3().p1) && !e.t.has(t.e3().p2) && t.e3().intersects(e.t)) { good = false; break; }
347 } while(e != this.e);
353 reComputeErrorAround();
356 private boolean good;
358 public boolean move(Vec v) {
359 Matrix m = Matrix.translate(v);
363 good &= p.transform(m);
369 public E getFreeIncident() {
370 E ret = getFreeIncident(e, e);
371 if (ret != null) return ret;
372 ret = getFreeIncident(e.pair.next, e.pair.next);
376 System.out.println(ex + " " + ex.t);
379 throw new Error("unable to find free incident to " + this);
384 public E getFreeIncident(E start, E before) {
387 if (e.pair.p2 == this && e.pair.t == null && e.pair.next.t == null) return e.pair;
389 } while(e != before);
393 public E getE(Point p2) {
394 Vertex v = vertices.get(p2);
395 if (v==null) return null;
398 public E getE(Vertex p2) {
401 if (e==null) return null;
402 if (e.p1 == this && e.p2 == p2) return e;
409 Vec norm = new Vec(0, 0, 0);
412 if (e.t != null) norm = norm.plus(e.t.norm().times((float)e.prev.angle()));
414 } while(e != this.e);
418 public boolean isBoundTo(Vertex p) {
421 if (px==this) return true;
426 public void unbind() { bound_to = this; binding = Matrix.ONE; }
427 public void bind(Vertex p) { bind(p, Matrix.ONE); }
428 public void bind(Vertex p, Matrix binding) {
429 if (isBoundTo(p)) return;
430 Vertex temp_bound_to = p.bound_to;
431 Matrix temp_binding = p.binding;
432 p.bound_to = this.bound_to;
433 p.binding = binding.times(this.binding); // FIXME: may have order wrong here
434 this.bound_to = temp_bound_to;
435 this.binding = temp_binding.times(temp_binding); // FIXME: may have order wrong here
439 public class BindingGroup {
440 private HashSet<E> set = new HashSet<E>();
441 public BindingGroup bind_others;
442 public BindingGroup other() { return bind_others; }
443 public BindingGroup(BindingGroup bind_others) { this.bind_others = bind_others; }
444 public BindingGroup() { this.bind_others = new BindingGroup(this); }
445 public BindingGroup(E e) { this(); set.add(e); }
446 public void add(E e) {
447 if (set.contains(e)) return;
449 BindingGroup e_bind_peers = e.bind_peers;
450 BindingGroup e_bind_to = e.bind_to;
452 e.bind_to = bind_others;
453 for (E epeer : e_bind_peers.set) add(epeer);
454 for (E eother : e_bind_to.set) bind_others.add(eother);
456 for(E eother : bind_others.set) {
457 if (e.next.bind_to.set.contains(eother.prev)) {
458 e.next.next.bindEdge(eother.prev.prev);
460 if (e.prev.bind_to.set.contains(eother.next)) {
461 e.prev.prev.bindEdge(eother.next.next);
466 public void dobind(E e) {
467 for(E ebound : set) {
468 e.p1.bind(ebound.p2);
469 e.p2.bind(ebound.p1);
472 public void shatter(BindingGroup bg1, BindingGroup bg2) {
474 e.shatter(e.midpoint(), bg1, bg2);
479 /** [UNIQUE] an edge */
480 public final class E implements Comparable<E> {
482 public final Vertex p1, p2;
483 T t; // triangle to our "left"
484 E prev; // previous half-edge
485 E next; // next half-edge
486 E pair; // partner half-edge
487 public BindingGroup bind_peers = new BindingGroup(this);
488 public BindingGroup bind_to = bind_peers.other();
489 boolean shattered = false;
491 public boolean intersects(T t) { return t.intersects(p1.p, p2.p); }
492 public float comparator() {
493 Vertex nearest = score_against.nearest(midpoint());
494 //if (t==null) return length();
496 double ang = Math.abs(crossAngle());
497 float minangle = (float)(Math.PI * 0.9);
502 if ((length() * length()) / t.area() > 10)
503 return (float)(length()*Math.sqrt(t.area()));
504 return length()*t.area();
506 return (float)Math.max(length(), midpoint().distance(nearest.p));
509 public int compareTo(E e) {
510 return e.comparator() > comparator() ? 1 : -1;
512 public void bindEdge(E e) { bind_to.add(e); }
513 public void dobind() { bind_to.dobind(this); }
515 public Point shatter() { return shatter(midpoint(), null, null); }
516 public Point shatter(Point mid, BindingGroup bg1, BindingGroup bg2) {
517 if (shattered || destroyed) return mid;
524 int old_colorclass = t==null ? 0 : t.colorclass;
525 if (bg1==null) bg1 = new BindingGroup();
526 if (bg2==null) bg2 = new BindingGroup();
527 BindingGroup old_bind_to = bind_to;
528 bind_peers.shatter(bg1, bg2);
529 old_bind_to.shatter(bg2.other(), bg1.other());
533 newT(r.p, p1.p, mid, null, old_colorclass);
534 newT(r.p, mid, p2.p, null, old_colorclass);
535 bg1.add(p1.getE(mid));
536 bg2.add(p2.getE(mid).pair);
540 public boolean destroyed = false;
541 public void destroy() {
542 if (destroyed) return;
544 pair.destroyed = true;
546 if (t != null) t.destroy();
549 if (pair.t != null) pair.t.destroy();
552 if (next.t != null) next.t.destroy();
553 if (prev.t != null) prev.t.destroy();
557 if (pair.next.t != null) pair.next.t.destroy();
558 if (pair.prev.t != null) pair.next.t.destroy();
564 this.bind_peers = null;
565 pair.bind_peers = null;
566 pair.prev.next = next;
567 next.prev = pair.prev;
568 prev.next = pair.next;
570 if (p1.e == this) p1.e = prev.next;
571 if (pair.p1.e == pair) pair.p1.e = pair.prev.next;
574 private void sync() {
575 this.prev.next = this;
576 this.next.prev = this;
577 this.pair.pair = this;
578 bind_peers.add(this);
579 if (this.next.p1 != p2) throw new Error();
580 if (this.prev.p2 != p1) throw new Error();
581 if (this.p1.e == null) this.p1.e = this;
582 if (!added) added = true;
584 private boolean added = false;
586 public T makeT(int colorclass) { return t==null ? (t = new T(this, colorclass)) : t; }
588 public double crossAngle() {
589 Vec v1 = t.norm().times(-1);
590 Vec v2 = pair.t.norm().times(-1);
591 return Math.acos(v1.norm().dot(v2.norm()));
594 /** angle between this half-edge and the next */
595 public double angle() {
596 Vec v1 = next.p2.p.minus(p2.p);
597 Vec v2 = this.p1.p.minus(p2.p);
598 return Math.acos(v1.norm().dot(v2.norm()));
601 public void makeAdjacent(E e) {
602 if (this.next == e) return;
603 if (p2 != e.p1) throw new Error("cannot make adjacent -- no shared vertex");
604 if (t != null || e.t != null) throw new Error("cannot make adjacent -- edges not both free");
606 E freeIncident = p2.getFreeIncident(e, this);
608 e.prev.next = freeIncident.next;
609 freeIncident.next.prev = e.prev;
611 freeIncident.next = this.next;
612 this.next.prev = freeIncident;
621 /** creates an isolated edge out in the middle of space */
622 public E(Point p1, Point p2) {
623 if (vertices.get(p1) != null) throw new Error();
624 if (vertices.get(p2) != null) throw new Error();
625 this.p1 = new Vertex(p1);
626 this.p2 = new Vertex(p2);
627 this.prev = this.next = this.pair = new E(this, this, this);
629 this.p2.e = this.pair;
633 /** adds a new half-edge from prev.p2 to p2 */
634 public E(E prev, Point p) {
636 p2 = vertices.get(p);
637 if (p2 == null) p2 = new Vertex(p);
641 if (p2.getE(p1) != null) throw new Error();
643 this.next = this.pair = new E(this, this, prev.next);
645 E q = p2.getFreeIncident();
647 this.next.prev = this;
649 this.prev.next = this;
650 this.pair = new E(q, this, z);
652 if (p2.e==null) p2.e = this.pair;
656 /** adds a new half-edge to the mesh with a given predecessor, successor, and pair */
657 public E(E prev, E pair, E next) {
665 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); }
666 public boolean has(Vertex v) { return v==p1 || v==p2; }
667 public float length() { return p1.p.minus(p2.p).mag(); }
668 public String toString() { return p1+"->"+p2; }
672 public E makeE(Point p1, Point p2) {
673 Vertex v1 = vertices.get(p1);
674 Vertex v2 = vertices.get(p2);
675 if (v1 != null && v2 != null) {
677 if (e != null) return e;
679 if (e != null) return e;
681 if (v1 != null) return new E(v1.getFreeIncident(), p2);
682 if (v2 != null) return new E(v2.getFreeIncident(), p1).pair;
683 return new E(p1, p2);
685 public T newT(Point p1, Point p2, Point p3, Vec norm, int colorclass) {
687 Vec norm2 = p3.minus(p1).cross(p2.minus(p1));
688 float dot = norm.dot(norm2);
689 //if (Math.abs(dot) < EPointSILON) throw new Error("dot products within evertsilon of each other: "+norm+" "+norm2);
690 if (dot < 0) { Point p = p1; p1=p2; p2 = p; }
692 E e12 = makeE(p1, p2);
693 E e23 = makeE(p2, p3);
694 E e31 = makeE(p3, p1);
695 while(e12.next != e23 || e23.next != e31 || e31.next != e12) {
696 e12.makeAdjacent(e23);
697 e23.makeAdjacent(e31);
698 e31.makeAdjacent(e12);
700 T ret = e12.makeT(colorclass);
701 if (e12.t == null) throw new Error();
702 if (e23.t == null) throw new Error();
703 if (e31.t == null) throw new Error();
708 /** [UNIQUE] a triangle (face) */
709 public final class T extends Triangle {
711 public final int color;
712 public final int colorclass;
714 public void removeFromRTree() { tris.remove(this); }
715 public void addToRTree() { tris.insert(this); }
717 public void destroy() { tris.remove(this); }
719 T(E e1, int colorclass) {
723 if (e1==e2 || e1==e3) throw new Error();
724 if (e3.next!=e1) throw new Error();
725 if (e1.t!=null || e2.t!=null || e3.t!=null) throw new Error("non-manifold surface or disagreeing normals");
728 e1.next.next.t = this;
730 // FIXME: check for sealed/watertight surface once construction is complete (and infer normal(s)?)
732 int color = Math.abs(random.nextInt());
735 if (e1().pair.t != null && color == e1().pair.t.color) { color++; continue; }
736 if (e2().pair.t != null && color == e2().pair.t.color) { color++; continue; }
737 if (e3().pair.t != null && color == e3().pair.t.color) { color++; continue; }
741 this.colorclass = colorclass;
744 public E e1() { return e1; }
745 public E e2() { return e1.next; }
746 public E e3() { return e1.prev; }
747 public Vertex v1() { return e1.p1; }
748 public Vertex v2() { return e1.p2; }
749 public Vertex v3() { return e1.next.p2; }
750 public Point p1() { return e1.p1.p; }
751 public Point p2() { return e1.p2.p; }
752 public Point p3() { return e1.next.p2.p; }
753 public boolean hasE(E e) { return e1==e || e1.next==e || e1.prev==e; }
754 public boolean has(Vertex v) { return v1()==v || v2()==v || v3()==v; }
756 public boolean shouldBeDrawn() {
757 if (e1().bind_to.set.size() == 0) return false;
758 if (e2().bind_to.set.size() == 0) return false;
759 if (e3().bind_to.set.size() == 0) return false;