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