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