6c663d01f36ffe372c05b78547611b3c58cc2681
[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         for(Mesh.Vert vert : goal.vertices()) {
213             System.out.println("error: " + vert.quadric().preAndPostMultiply(vert.p));
214         }
215
216
217         //xMesh.Vert mid = lbf.getE(mbn).shatter();
218
219         // rescale to match volume
220         float factor = (float)Math.pow(tile.volume() / goal.volume(), 1.0/3.0);
221         goal.transform(new Matrix(factor));
222
223         // translate to match centroid
224         goal.transform(new Matrix(tile.centroid().minus(goal.centroid())));
225
226         //tx.e2.shatter();
227         //tx.e3.shatter();
228
229
230         tile.bind();
231
232         //mid.move(new Vec((float)0,0,(float)-0.05));
233         //ltn.move(new Vec((float)0,0,(float)-0.05));
234
235         //mtf.move(new Vec(0, (float)-0.05, (float)0.05));
236
237
238         System.out.println("tile volume: " + tile.volume());
239         System.out.println("goal volume: " + goal.volume());
240
241         tile.score_against = goal;
242         goal.score_against = tile;
243     }
244         Random random = new Random();
245
246     public synchronized void breakit() {
247         if (verts > 300) return;
248         //double min = (tile.avgedge/tile.numedges)*(1+(4/(double)verts));
249         //if (verts>0 && tile.es.peek().length() < min) return;
250         PriorityQueue<Mesh.E> es = new PriorityQueue<Mesh.E>();
251         for(Mesh.E e : tile.edges()) es.add(e);
252         for(int i=0; i<10; i++) {
253             Mesh.E e = es.poll();
254             verts++;
255             System.out.println("shatter " + e);
256             e.shatter();
257             tile.unbind();
258             tile.bind();
259         }
260     }
261
262     public synchronized void rand(double temperature, Mesh.Vert p) {
263         double tile_score = tile.score();
264         double goal_score = goal.score();
265         
266         p.rescore();
267         //if (p.watch==null) return;
268         float r1 = Math.abs(random.nextFloat());
269         r1 = r1 - (float)Math.floor(r1);
270         r1 = r1 * (float)0.01;
271         r1 = r1 - (float)0.005;
272         Vec v = p.watchback().minus(p.p).norm().times(r1);
273
274         //v = p.norm().times(v.dot(p.norm()));
275
276         boolean aspect = false;//(Math.abs(random.nextInt()) % 100) <= 2;
277         Matrix old_tile_aspect = null;//goal.aspect;
278         boolean good = true;
279         if (aspect) {
280             /*
281             v = v.times(10);
282             tile.aspect = new Matrix(tile.aspect.a / (v.x+1), tile.aspect.f / (v.y+1), tile.aspect.k / (v.z+1));
283             tile.invaspect = new Matrix(1/tile.aspect.a, 1/tile.aspect.f, 1/tile.aspect.k);
284             goal.rescore();
285             tile.rescore();
286             */
287         } else {
288             good = p.move(v);
289         }
290         double new_tile_score = tile.score();
291         double new_goal_score = goal.score();
292         double tile_delta = new_tile_score - tile_score;
293         double goal_delta = new_goal_score - goal_score;
294         double delta = tile_delta + goal_delta;
295         double swapProbability = Math.exp((-1 * delta) / temperature);
296         //boolean doSwap = Math.random() < swapProbability;
297         boolean doSwap = good && (tile_delta <= 0 && goal_delta <= 0);
298         if (doSwap) {
299             tile_score = new_tile_score;
300             goal_score = new_goal_score;
301             //System.out.println("score: " + tile_score + " / " + goal_score);
302             if (aspect) System.out.println("aspect " + v);
303         } else {
304             if (aspect) {
305                 //tile.aspect = old_tile_aspect;
306                 //tile.invaspect = new Matrix(1/tile.aspect.a, 1/tile.aspect.f, 1/tile.aspect.k);
307                 goal.rescore();
308                 tile.rescore();
309             } else {
310                 p.move(v.times(-1));
311             }
312         }
313     }
314
315     /**
316      * Take care of initialization here.
317      */
318     public void init(GLAutoDrawable gld) {
319         GL gl = gld.getGL();
320         gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
321         gl.glViewport(0, 0, 500, 300);
322         gl.glEnable(GL.GL_DEPTH_TEST);
323         gl.glClearDepth(1.0);
324         gl.glDepthFunc(GL.GL_LEQUAL);
325         gl.glMatrixMode(GL.GL_PROJECTION);
326         gl.glLoadIdentity();
327         gl.glMatrixMode(GL.GL_MODELVIEW);
328         display(gld);
329     }
330
331     public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { }
332     public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) { }
333     public synchronized void display(GLAutoDrawable drawable) {
334         GL gl = drawable.getGL();
335         GLU glu = new GLU();
336         gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
337         gl.glPointSize(5.0f);
338         gl.glLoadIdentity();
339         glu.gluPerspective(50-tz, ((float)drawable.getWidth())/drawable.getHeight(), 0.5, 10);
340         glu.gluLookAt(0, 0, -1, 0, 0, 0, 0, 1, 0);
341         gl.glTranslatef(tx/(float)20, ty/(float)20, 0);
342         gl.glRotatef(anglex/3, 0, 1, 0);
343         gl.glRotatef(angley/3, 1, 0, 0);
344
345         gl.glBegin(GL.GL_TRIANGLES);
346         draw(gl, true, tile);
347         gl.glEnd();
348
349         gl.glBegin(GL.GL_TRIANGLES);
350         gl.glColor4f((float)0.5, (float)0.5, (float)0.5, (float)0.8);
351         //draw(gl, false, goal);
352         gl.glEnd();
353
354
355         int i = 0;
356         //gl.glDisable(GL.GL_DEPTH_TEST);
357         gl.glColor4f(1,1,1,1);
358         for(Matrix m : translations) {
359             //if (v1.z==0 && v1.y==0) continue;
360             i++;
361             if (i != 1 /*&& i!=4*/) continue;
362             Point p = new Point(0, 0, 0).times(m);
363             Vec v = new Vec(p.x, p.y, p.z);
364             v = v.times((float)1.04);
365             gl.glTranslatef(v.x, v.y, v.z);
366             draw(gl, false, tile);
367             gl.glTranslatef(-v.x, -v.y, -v.z);
368         }
369         //gl.glEnable(GL.GL_DEPTH_TEST);
370     }
371
372     private synchronized void draw(GL gl, boolean triangles, Mesh mesh) {
373         float red = 0.0f;
374         float green = 0.0f;
375         float blue = 0.0f;
376         for(Mesh.T t : mesh) {
377             if (red < 0.15) red = 1.0f;
378             if (green < 0.15) green = 1.0f;
379             if (blue < 0.15) blue = 1.0f;
380             red -= .09f;
381             green -= .12f;
382             blue -= .15f;
383
384             if (triangles) switch(t.color) {
385                 case 0: gl.glColor4f((float)0.25, (float)0.25, (float)0.75, (float)0.3); break;
386                 case 1: gl.glColor4f((float)0.25, (float)0.75, (float)0.25, (float)0.3); break;
387                 case 2: gl.glColor4f((float)0.75, (float)0.25, (float)0.25, (float)0.3); break;
388                 case 3: gl.glColor4f((float)0.50, (float)0.50, (float)0.50, (float)0.3); break;
389             }
390             //gl.glBegin(GL.GL_LINES);
391
392             if (triangles) {
393                 gl.glBegin(GL.GL_TRIANGLES);
394                 t.glVertices(gl);
395                 gl.glEnd();
396             } else {
397                 gl.glBegin(GL.GL_LINES);
398                 t.e1().p1.p.glVertex(gl);
399                 t.e1().p2.p.glVertex(gl);
400                 t.e2().p1.p.glVertex(gl);
401                 t.e2().p2.p.glVertex(gl);
402                 t.e3().p1.p.glVertex(gl);
403                 t.e3().p2.p.glVertex(gl);
404                 gl.glEnd();
405             }
406
407             Point centroid = t.centroid();
408             gl.glBegin(GL.GL_LINES);
409             gl.glColor3f(1, 1, 1);
410             /*
411             centroid.glVertex(gl);
412             centroid.plus(t.norm().times(t.diameter())).glVertex(gl);
413             */
414
415             if (mesh==goal)
416                 for(Mesh.Vert p : new Mesh.Vert[] { t.v1(), t.v2(), t.v3() }) {
417                     p.p.glVertex(gl);
418                     //p.plus(p.norm().times(p.score()*10)).glVertex(gl);
419                     p.partner().p.glVertex(gl);
420                     //tile.nearest(p).centroid().glVertex(gl);
421                 }
422
423             gl.glEnd();
424
425         }
426     }
427
428     public static void main(String[] s) throws Exception {
429         StlFile stlf = new StlFile();
430         stlf.load("simplefish.stl");
431         Main main = new Main(stlf);
432         Frame f = new Frame();
433         GLCapabilities glcaps = new GLCapabilities();
434         GLCanvas glcanvas = new GLCanvas();
435         glcanvas.addGLEventListener(main);
436         f.add(glcanvas, BorderLayout.CENTER);
437         f.pack();
438         f.show();
439         f.setSize(900, 900);
440         f.doLayout();
441
442         glcanvas.addMouseListener(main);
443         glcanvas.addMouseMotionListener(main);
444         glcanvas.addMouseWheelListener(main);
445         glcanvas.addKeyListener(main);
446
447         main.anneal(glcanvas);
448     }
449     public static int verts = 0;
450     public void anneal(GLCanvas glcanvas) throws Exception {
451         int verts = 0;
452         while(true) {
453             //Thread.sleep(10);
454             for(int i=0; i<1; i++) {
455                 glcanvas.repaint();
456                 //tile.ts.get(Math.abs(random.nextInt()) % tile.ts.size()).e1().p1
457                 for(Mesh.T t : tile)
458                     for(Mesh.Vert p : new Mesh.Vert[] { t.v1(), t.v2(), t.v3() }) {
459                         rand(10,p);
460                     }
461                 goal.rescore();
462                 tile.rescore();
463             }
464             breakit();
465        }
466
467     }
468
469 }