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         bg.matrices.clear();
21         bg.master = null;
22     }
23
24     public T getMaster() { return master; }
25     public Matrix getMatrix(T t) { return matrices.get(t); }
26
27     public Iterator<T> iterator() { return matrices.keySet().iterator(); }
28
29     /** t1 = getMatrix(t1, t2) * t2 */
30     public Matrix getMatrix(T t1, T t2) {
31         //                    t1 = getMatrix(t1) * master
32         // getMatrix(t2)^-1 * t2 =                 master
33         //                    t1 = getMatrix(t1) * getMatrix(t2)^-1 * t2
34         return getMatrix(t1).times(getMatrix(t2).inverse());
35     }
36
37     public void unbind(T trem) {
38         if (trem != master) {
39             matrices.remove(trem);
40             return;
41         }
42         if (matrices.size()==1) {
43             master = null;
44             matrices.remove(trem);
45             return;
46         }
47         Iterator<T> it = iterator();
48         T newmaster = it.next();
49         if (newmaster==trem) newmaster = it.next();
50         if (newmaster==trem) throw new Error();
51         HashMap<T,Matrix> newmatrices = new HashMap<T,Matrix>();
52         for(T t : matrices.keySet()) {
53             if (t==trem) continue;
54             newmatrices.put(t, getMatrix(t, newmaster));
55         }
56         master = newmaster;
57         matrices = newmatrices;
58     }
59
60     public boolean contains(HasBindingGroup t) {
61         return matrices.get((T)t) != null;
62     }
63 }