checkpoint
[anneal.git] / src / edu / berkeley / qfat / geom / BindingGroup.java
1 package edu.berkeley.qfat.geom;
2 import javax.media.opengl.*;
3 import java.util.*;
4
5 public class BindingGroup<T extends HasBindingGroup> implements Iterable<T> {
6
7     private T                  master   = null;
8     private HashMap<T,Matrix>  matrices = new HashMap<T,Matrix>();
9
10     public BindingGroup(T master) {
11         this.master = master;
12         matrices.put(master, Matrix.ONE);
13     }
14
15     public void merge(BindingGroup<T> bg, Matrix m) {
16         for(HasBindingGroup hbg : bg.matrices.keySet()) {
17             matrices.put((T)hbg, bg.matrices.get(hbg).times(m));
18             hbg.bindingGroup = this;
19         }
20         for(HasBindingGroup hbg : bg.matrices.keySet())
21             hbg.bindingGroupChanged(this);
22         bg.matrices.clear();
23         bg.master = null;
24     }
25
26     public T getMaster() { return master; }
27     public Matrix getMatrix(T t) { return matrices.get(t); }
28
29     public Iterator<T> iterator() { return matrices.keySet().iterator(); }
30
31     /** t1 = getMatrix(t1, t2) * t2 */
32     public Matrix getMatrix(T t1, T t2) {
33         //                    t1 = getMatrix(t1) * master
34         // getMatrix(t2)^-1 * t2 =                 master
35         //                    t1 = getMatrix(t1) * getMatrix(t2)^-1 * t2
36         return getMatrix(t1).times(getMatrix(t2).inverse());
37     }
38
39     public void unbind(T trem) {
40         if (trem != master) {
41             matrices.remove(trem);
42             return;
43         }
44         if (matrices.size()==1) {
45             master = null;
46             matrices.remove(trem);
47             return;
48         }
49         Iterator<T> it = iterator();
50         T newmaster = it.next();
51         if (newmaster==trem) newmaster = it.next();
52         if (newmaster==trem) throw new Error();
53         HashMap<T,Matrix> newmatrices = new HashMap<T,Matrix>();
54         for(T t : matrices.keySet()) {
55             if (t==trem) continue;
56             newmatrices.put(t, getMatrix(t, newmaster));
57         }
58         master = newmaster;
59         matrices = newmatrices;
60     }
61
62     public boolean contains(HasBindingGroup t) {
63         return matrices.get((T)t) != null;
64     }
65 }