checkpoint
[anneal.git] / src / edu / berkeley / qfat / Main.java
1 package edu.berkeley.qfat;
2 import java.awt.*;
3 import java.awt.event.*;
4 import javax.swing.*;
5 import javax.media.opengl.*;
6 import javax.media.opengl.glu.*;
7 import java.util.*;
8 import static edu.berkeley.qfat.Geom.*;
9
10 // FIXME: recenter goal to have centroid coincident with tile
11 // FIXME: re-orient goal (how?)
12 //        fish case: ensure that spinal axis of fish is the x-axis of the tile
13
14 public class Main implements GLEventListener, MouseListener, MouseMotionListener, KeyListener, MouseWheelListener {
15     
16     boolean alt = false;
17     boolean shift = false;
18     boolean control = false;
19
20     public void mouseWheelMoved(MouseWheelEvent e) {
21         tz -= e.getWheelRotation();
22     }
23
24     public void keyTyped(KeyEvent e)  { }
25     public void keyPressed(KeyEvent e)  {
26         switch(e.getKeyCode()) {
27             case KeyEvent.VK_CONTROL: control = true; break;
28             case KeyEvent.VK_ALT: alt = true; break;
29             case KeyEvent.VK_SHIFT: shift = true; break;
30         }
31     }
32     public void keyReleased(KeyEvent e) {
33         switch(e.getKeyCode()) {
34             case KeyEvent.VK_CONTROL: control = false; break;
35             case KeyEvent.VK_ALT: alt = false; break;
36             case KeyEvent.VK_SHIFT: shift = false; break;
37         }
38     }
39
40     public void mouseClicked(MouseEvent e) { }
41     public void mouseEntered(MouseEvent e) { }
42     public void mouseExited(MouseEvent e) { }
43     public void mousePressed(MouseEvent e) { }
44     public void mouseReleased(MouseEvent e) { }
45
46     int mousex;
47     int mousey;
48     public void mouseMoved(MouseEvent e) {
49         mousex = e.getX();
50         mousey = e.getY();
51     }
52
53     float tx = 0;
54     float ty = 0;
55     float tz = 0;
56     float anglex = 0;
57     float angley = 0;
58     public void mouseDragged(MouseEvent e) {
59         if (shift) {
60             tx += (mousex - e.getX())/(float)20;
61             ty += (mousey - e.getY())/(float)20;
62         } else {
63             anglex -= mousex - e.getX();
64             angley += mousey - e.getY();
65         }
66         mousex = e.getX();
67         mousey = e.getY();
68     }
69
70     private Geom tile = new Geom();
71     private Geom goal = new Geom();
72
73     /** magnification factor */
74     private static final float MAG = 1;
75
76     Geom.M[] translations;
77     Geom.Vert[] points;
78
79     public Main(StlFile stlf) {
80
81         for(int i=0; i<stlf.coordArray.length; i+=3) {
82             Geom.Vert p0 = goal.register(new Geom.Point(stlf.coordArray[i+0].x * MAG, stlf.coordArray[i+0].y * MAG, stlf.coordArray[i+0].z * MAG));
83             Geom.Vert p1 = goal.register(new Geom.Point(stlf.coordArray[i+1].x * MAG, stlf.coordArray[i+1].y * MAG, stlf.coordArray[i+1].z * MAG));
84             Geom.Vert p2 = goal.register(new Geom.Point(stlf.coordArray[i+2].x * MAG, stlf.coordArray[i+2].y * MAG, stlf.coordArray[i+2].z * MAG));
85             Geom.Vec n  = new Geom.Vec(stlf.normArray[i/3].x * MAG, stlf.normArray[i/3].y  * MAG, stlf.normArray[i/3].z * MAG);
86             Geom.T t  = goal.newT(p0, p1, p2, n);
87         }
88
89         // rotate to align major axis -- this probably needs to be done by a human.
90         goal.transform(new Geom.M(new Geom.Vec(0, 0, 1), (float)(Math.PI/2)));
91
92
93         float goal_width  = goal.diagonal().dot(new Geom.Vec(1, 0, 0));
94         float goal_height = goal.diagonal().dot(new Geom.Vec(0, 1, 0));
95         float goal_depth  = goal.diagonal().dot(new Geom.Vec(0, 0, 1));
96
97         float width  = (float)0.6;
98         float height = (float)0.08;
99         float depth  = (float)0.3;
100         translations = new Geom.M[] {
101
102             new Geom.M(new Geom.Vec(-(width/2),  height,    0)),
103             new Geom.M(new Geom.Vec( (width/2),  height,    0)),
104             new Geom.M(new Geom.Vec(-(width/2), -height,    0)),
105             new Geom.M(new Geom.Vec( (width/2), -height,    0)),
106             new Geom.M(new Geom.Vec(-(width/2),       0,  depth)),
107             new Geom.M(new Geom.Vec( (width/2),       0,  depth)),
108             new Geom.M(new Geom.Vec(-(width/2),       0, -depth)),
109             new Geom.M(new Geom.Vec( (width/2),       0, -depth)),
110
111             new Geom.M(new Geom.Vec( width,           0,    0)),
112             new Geom.M(new Geom.Vec(-width,           0,    0)),
113             /*
114             new Geom.M(new Geom.Vec(     0,           0,    depth)),
115             new Geom.M(new Geom.Vec(     0,           0,   -depth)),
116             */
117         };
118
119
120         Geom.Vert ltf = tile.register(new Geom.Point(-(width/2),  (height/2),  (depth/2)));
121         Geom.Vert mtf = tile.register(new Geom.Point( 0.0,        (height/2),  (depth/2)));
122         Geom.Vert rtf = tile.register(new Geom.Point( (width/2),  (height/2),  (depth/2)));
123         Geom.Vert ltn = tile.register(new Geom.Point(-(width/2),  (height/2), -(depth/2)));
124         Geom.Vert mtn = tile.register(new Geom.Point( 0.0,        (height/2), -(depth/2)));
125         Geom.Vert rtn = tile.register(new Geom.Point( (width/2),  (height/2), -(depth/2)));
126         Geom.Vert lbf = tile.register(new Geom.Point(-(width/2), -(height/2),  (depth/2)));
127         Geom.Vert mbf = tile.register(new Geom.Point( 0.0,       -(height/2),  (depth/2)));
128         Geom.Vert rbf = tile.register(new Geom.Point( (width/2), -(height/2),  (depth/2)));
129         Geom.Vert lbn = tile.register(new Geom.Point(-(width/2), -(height/2), -(depth/2)));
130         Geom.Vert mbn = tile.register(new Geom.Point( 0.0,       -(height/2), -(depth/2)));
131         Geom.Vert rbn = tile.register(new Geom.Point( (width/2), -(height/2), -(depth/2)));
132         
133         points = new Geom.Vert[] {
134             ltf,
135             mtf,
136             rtf,
137             ltn,
138             mtn,
139             rtn,
140             lbf,
141             mbf,
142             rbf,
143             lbn,
144             mbn,
145             rbn
146         };
147
148
149         // top
150         tile.newT(ltf, mtf, mtn);
151         tile.newT(mtn, ltn, ltf);
152         tile.newT(mtf, rtf, rtn);
153         tile.newT(rtn, mtn, mtf);
154
155         // bottom (swap normals)
156         tile.newT(mbf, lbf, mbn);
157         tile.newT(lbn, mbn, lbf);
158         tile.newT(rbf, mbf, rbn);
159         tile.newT(mbn, rbn, mbf);
160         
161         // left
162         tile.newT(ltf, ltn, lbn);
163         tile.newT(lbn, lbf, ltf);
164
165         // right (swap normals)
166         tile.newT(rtn, rtf, rbn);
167         tile.newT(rbf, rbn, rtf);
168
169         // front
170         tile.newT(ltn, mtn, mbn);
171         tile.newT(ltn, mbn, lbn);
172         tile.newT(mtn, rtn, rbn);
173         tile.newT(mtn, rbn, mbn);
174
175         // back
176         tile.newT(mtf, ltf, mbf);
177         tile.newT(mbf, ltf, lbf);
178         tile.newT(rtf, mtf, rbf);
179         tile.newT(rbf, mtf, mbf);
180
181         for(Geom.M m : translations) {
182             for(Geom.T t1 : tile) {
183                 for(Geom.T t2 : tile) {
184                     if (t1==t2) continue;
185
186                     if ((t1.p1().p.times(m).minus(t2.p1().p).mag() < Geom.EPSILON) &&
187                         (t1.p2().p.times(m).minus(t2.p3().p).mag() < Geom.EPSILON) &&
188                         (t1.p3().p.times(m).minus(t2.p2().p).mag() < Geom.EPSILON)) {
189                         t1.e1().bind(t2.e3().pair);
190                         t1.e2().bind(t2.e2().pair);
191                         t1.e3().bind(t2.e1().pair);
192                     }
193                     if ((t1.p2().p.times(m).minus(t2.p1().p).mag() < Geom.EPSILON) &&
194                         (t1.p3().p.times(m).minus(t2.p3().p).mag() < Geom.EPSILON) &&
195                         (t1.p1().p.times(m).minus(t2.p2().p).mag() < Geom.EPSILON)) {
196                         t1.e2().bind(t2.e3().pair);
197                         t1.e3().bind(t2.e2().pair);
198                         t1.e1().bind(t2.e1().pair);
199                     }
200                     if ((t1.p3().p.times(m).minus(t2.p1().p).mag() < Geom.EPSILON) &&
201                         (t1.p1().p.times(m).minus(t2.p3().p).mag() < Geom.EPSILON) &&
202                         (t1.p2().p.times(m).minus(t2.p2().p).mag() < Geom.EPSILON)) {
203                         t1.e3().bind(t2.e3().pair);
204                         t1.e1().bind(t2.e2().pair);
205                         t1.e2().bind(t2.e1().pair);
206                     }
207                 }
208             }
209         }
210
211         //xGeom.Vert mid = lbf.getE(mbn).shatter();
212
213         // rescale to match volume
214         float factor = (float)Math.pow(tile.volume() / goal.volume(), 1.0/3.0);
215         goal.transform(new Geom.M(factor));
216
217         // translate to match centroid
218         goal.transform(new Geom.M(tile.centroid().minus(goal.centroid())));
219
220         //tx.e2.shatter();
221         //tx.e3.shatter();
222
223
224         tile.bind();
225
226         //mid.move(new Geom.Vec((float)0,0,(float)-0.05));
227         //ltn.move(new Geom.Vec((float)0,0,(float)-0.05));
228
229         //mtf.move(new Geom.Vec(0, (float)-0.05, (float)0.05));
230
231
232         System.out.println("tile volume: " + tile.volume());
233         System.out.println("goal volume: " + goal.volume());
234
235         tile.score_against = goal;
236         goal.score_against = tile;
237     }
238         Random random = new Random();
239
240     public synchronized void breakit() {
241         if (verts > 300) return;
242         //double min = (tile.avgedge/tile.numedges)*(1+(4/(double)verts));
243         //if (verts>0 && tile.es.peek().length() < min) return;
244         PriorityQueue<Geom.E> es = new PriorityQueue<Geom.E>();
245         for(Geom.E e : tile.es) es.add(e);
246         for(int i=0; i<10; i++) {
247             Geom.E e = es.poll();
248             verts++;
249             System.out.println("shatter " + e);
250             e.shatter();
251             tile.unbind();
252             tile.bind();
253         }
254     }
255
256     public synchronized void rand(double temperature, Geom.Vert p) {
257         double tile_score = tile.score();
258         double goal_score = goal.score();
259         
260         p.rescore();
261         //if (p.watch==null) return;
262         float r1 = Math.abs(random.nextFloat());
263         r1 = r1 - (float)Math.floor(r1);
264         r1 = r1 * (float)0.01;
265         r1 = r1 - (float)0.005;
266         Geom.Vec v = p.watchback().p.minus(p.p).norm().times(r1);
267
268         //v = p.norm().times(v.dot(p.norm()));
269
270         boolean aspect = false;//(Math.abs(random.nextInt()) % 100) <= 2;
271         Geom.M old_tile_aspect = null;//goal.aspect;
272         boolean good = true;
273         if (aspect) {
274             /*
275             v = v.times(10);
276             tile.aspect = new Geom.M(tile.aspect.a / (v.x+1), tile.aspect.f / (v.y+1), tile.aspect.k / (v.z+1));
277             tile.invaspect = new Geom.M(1/tile.aspect.a, 1/tile.aspect.f, 1/tile.aspect.k);
278             goal.rescore();
279             tile.rescore();
280             */
281         } else {
282             good = p.move(v);
283         }
284         double new_tile_score = tile.score();
285         double new_goal_score = goal.score();
286         double tile_delta = new_tile_score - tile_score;
287         double goal_delta = new_goal_score - goal_score;
288         double delta = tile_delta + goal_delta;
289         double swapProbability = Math.exp((-1 * delta) / temperature);
290         //boolean doSwap = Math.random() < swapProbability;
291         boolean doSwap = good && (tile_delta <= 0 && goal_delta <= 0);
292         if (doSwap) {
293             tile_score = new_tile_score;
294             goal_score = new_goal_score;
295             //System.out.println("score: " + tile_score + " / " + goal_score);
296             if (aspect) System.out.println("aspect " + v);
297         } else {
298             if (aspect) {
299                 //tile.aspect = old_tile_aspect;
300                 //tile.invaspect = new Geom.M(1/tile.aspect.a, 1/tile.aspect.f, 1/tile.aspect.k);
301                 goal.rescore();
302                 tile.rescore();
303             } else {
304                 p.move(v.times(-1));
305             }
306         }
307     }
308
309     /**
310      * Take care of initialization here.
311      */
312     public void init(GLAutoDrawable gld) {
313         GL gl = gld.getGL();
314         gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
315         gl.glViewport(0, 0, 500, 300);
316         gl.glEnable(GL.GL_DEPTH_TEST);
317         gl.glClearDepth(1.0);
318         gl.glDepthFunc(GL.GL_LEQUAL);
319         gl.glMatrixMode(GL.GL_PROJECTION);
320         gl.glLoadIdentity();
321         gl.glMatrixMode(GL.GL_MODELVIEW);
322         display(gld);
323     }
324
325     public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { }
326     public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) { }
327     public synchronized void display(GLAutoDrawable drawable) {
328         GL gl = drawable.getGL();
329         GLU glu = new GLU();
330         gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
331         gl.glPointSize(5.0f);
332         gl.glLoadIdentity();
333         glu.gluPerspective(50-tz, ((float)drawable.getWidth())/drawable.getHeight(), 0.5, 10);
334         glu.gluLookAt(0, 0, -1, 0, 0, 0, 0, 1, 0);
335         gl.glTranslatef(tx/(float)20, ty/(float)20, 0);
336         gl.glRotatef(anglex/3, 0, 1, 0);
337         gl.glRotatef(angley/3, 1, 0, 0);
338
339         gl.glBegin(GL.GL_TRIANGLES);
340         draw(gl, true, tile);
341         gl.glEnd();
342
343         gl.glBegin(GL.GL_TRIANGLES);
344         gl.glColor4f((float)0.5, (float)0.5, (float)0.5, (float)0.8);
345         //draw(gl, false, goal);
346         gl.glEnd();
347
348
349         int i = 0;
350         //gl.glDisable(GL.GL_DEPTH_TEST);
351         gl.glColor4f(1,1,1,1);
352         for(Geom.M m : translations) {
353             //if (v1.z==0 && v1.y==0) continue;
354             i++;
355             if (i != 1 /*&& i!=4*/) continue;
356             Geom.Point p = new Geom.Point(0, 0, 0).times(m);
357             Geom.Vec v = new Geom.Vec(p.x, p.y, p.z);
358             v = v.times((float)1.04);
359             gl.glTranslatef(v.x, v.y, v.z);
360             draw(gl, false, tile);
361             gl.glTranslatef(-v.x, -v.y, -v.z);
362         }
363         //gl.glEnable(GL.GL_DEPTH_TEST);
364     }
365
366     private synchronized void draw(GL gl, boolean triangles, Geom mesh) {
367         float red = 0.0f;
368         float green = 0.0f;
369         float blue = 0.0f;
370         for(Geom.T t : mesh) {
371             if (red < 0.15) red = 1.0f;
372             if (green < 0.15) green = 1.0f;
373             if (blue < 0.15) blue = 1.0f;
374             red -= .09f;
375             green -= .12f;
376             blue -= .15f;
377
378             if (triangles) switch(t.color) {
379                 case 0: gl.glColor4f((float)0.25, (float)0.25, (float)0.75, (float)0.3); break;
380                 case 1: gl.glColor4f((float)0.25, (float)0.75, (float)0.25, (float)0.3); break;
381                 case 2: gl.glColor4f((float)0.75, (float)0.25, (float)0.25, (float)0.3); break;
382                 case 3: gl.glColor4f((float)0.50, (float)0.50, (float)0.50, (float)0.3); break;
383             }
384             //gl.glBegin(GL.GL_LINES);
385
386             if (triangles) {
387                 gl.glBegin(GL.GL_TRIANGLES);
388                 t.glVertices(gl);
389                 gl.glEnd();
390             } else {
391                 gl.glBegin(GL.GL_LINES);
392                 t.e1().p1.p.glVertex(gl);
393                 t.e1().p2.p.glVertex(gl);
394                 t.e2().p1.p.glVertex(gl);
395                 t.e2().p2.p.glVertex(gl);
396                 t.e3().p1.p.glVertex(gl);
397                 t.e3().p2.p.glVertex(gl);
398                 gl.glEnd();
399             }
400
401             Geom.Point centroid = t.centroid();
402             gl.glBegin(GL.GL_LINES);
403             gl.glColor3f(1, 1, 1);
404             /*
405             centroid.glVertex(gl);
406             centroid.plus(t.norm().times(t.diameter())).glVertex(gl);
407             */
408
409             if (mesh==goal)
410                 for(Geom.Vert p : new Geom.Vert[] { t.p1(), t.p2(), t.p3() }) {
411                     p.p.glVertex(gl);
412                     //p.plus(p.norm().times(p.score()*10)).glVertex(gl);
413                     p.partner().p.glVertex(gl);
414                     //tile.nearest(p).centroid().glVertex(gl);
415                 }
416
417             gl.glEnd();
418
419         }
420     }
421
422     public static void main(String[] s) throws Exception {
423         StlFile stlf = new StlFile();
424         stlf.load("simplefish.stl");
425         Main main = new Main(stlf);
426         Frame f = new Frame();
427         GLCapabilities glcaps = new GLCapabilities();
428         GLCanvas glcanvas = new GLCanvas();
429         glcanvas.addGLEventListener(main);
430         f.add(glcanvas, BorderLayout.CENTER);
431         f.pack();
432         f.show();
433         f.setSize(900, 900);
434         f.doLayout();
435
436         glcanvas.addMouseListener(main);
437         glcanvas.addMouseMotionListener(main);
438         glcanvas.addMouseWheelListener(main);
439         glcanvas.addKeyListener(main);
440
441         main.anneal(glcanvas);
442     }
443     public static int verts = 0;
444     public void anneal(GLCanvas glcanvas) throws Exception {
445         int verts = 0;
446         while(true) {
447             //Thread.sleep(10);
448             for(int i=0; i<1; i++) {
449                 glcanvas.repaint();
450                 //tile.ts.get(Math.abs(random.nextInt()) % tile.ts.size()).e1().p1
451                 for(Geom.T t : tile)
452                     for(Geom.Vert p : new Geom.Vert[] { t.p1(), t.p2(), t.p3() }) {
453                         rand(10,p);
454                     }
455                 goal.rescore();
456                 tile.rescore();
457             }
458             breakit();
459        }
460
461     }
462
463 }