checkpoint
[anneal.git] / src / edu / berkeley / qfat / MeshViewer.java
1 package edu.berkeley.qfat;
2 import java.io.*;
3 import java.nio.*;
4 import java.awt.*;
5 import java.awt.event.*;
6 import javax.swing.*;
7 import javax.media.opengl.*;
8 import javax.media.opengl.glu.*;
9 import com.sun.opengl.util.*;
10 import java.util.*;
11 import edu.berkeley.qfat.geom.*;
12 import edu.berkeley.qfat.geom.Point;
13
14 public class MeshViewer implements GLEventListener, MouseListener, MouseMotionListener, KeyListener, MouseWheelListener  {
15
16     public boolean force = false;
17     public Mesh tile = new Mesh(false);
18     public Mesh goal = new Mesh(false);
19     public Matrix[] transforms;
20     public Mesh.Vertex[] points;
21
22     public int whichNeighbor = 1;
23
24     public double temp;
25     public boolean tileon = true;
26     public boolean tilemeshon = false;
27     public boolean goalon = true;
28     public boolean anneal = false;
29     public boolean hillclimb = false;
30     public boolean neighbors = false;
31     public boolean neighborsWire = false;
32     public boolean neighborsWireOne = false;
33     public boolean errorNormals = false;
34
35     public int breaks = 0;
36     boolean alt = false;
37     boolean shift = false;
38     boolean control = false;
39
40     public Point getMouse() {
41         return new Point(mousex, glcanvas.getHeight()-mousey, 0);
42     }
43
44     public void mouseWheelMoved(MouseWheelEvent e) {
45         tz -= e.getWheelRotation();
46     }
47
48     public void keyTyped(KeyEvent e)  { }
49     public void keyPressed(KeyEvent e)  {
50         switch(e.getKeyCode()) {
51             case KeyEvent.VK_CONTROL: control = true; break;
52             case KeyEvent.VK_ALT: alt = true; break;
53             case KeyEvent.VK_SHIFT: shift = true; break;
54             case KeyEvent.VK_SPACE: breaks++; force = true; break;
55             case KeyEvent.VK_UP: temp = temp * 2; break;
56             case KeyEvent.VK_ENTER: temp = 10; break;
57             case KeyEvent.VK_LEFT: whichNeighbor--; break;
58             case KeyEvent.VK_RIGHT: whichNeighbor++; break;
59             case KeyEvent.VK_D: dump(); break;
60             case KeyEvent.VK_E: errorNormals = !errorNormals; break;
61             case KeyEvent.VK_A: hillclimb = false; anneal = !anneal; break;
62             case KeyEvent.VK_H: anneal = true; hillclimb = !hillclimb; break;
63             case KeyEvent.VK_N: neighbors = !neighbors; break;
64             case KeyEvent.VK_T: tileon = !tileon; break;
65             case KeyEvent.VK_G: goalon = !goalon; break;
66             case KeyEvent.VK_M: tilemeshon = !tilemeshon; break;
67         }
68     }
69     public synchronized void dump() {
70         try {
71         PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream("dump.stl")));
72         pw.println("solid dump");
73         for(Mesh.T t : tile) {
74             Vec normal = t.norm();
75             pw.println("facet normal " + normal.x + " " + normal.y + " " + normal.z);
76             pw.println("  outer loop");
77             for(Mesh.Vertex v : new Mesh.Vertex[] { t.v1(), t.v2(), t.v3() }) {
78                 pw.println("    vertex " + v.p.x + " " + v.p.y + " " + v.p.z);
79             }
80             pw.println("  endloop");
81             pw.println("endfacet");
82         }
83         pw.println("endsolid dump");
84         pw.flush();
85         pw.close();
86         } catch (Exception e) { throw new RuntimeException(e); }
87     }
88     public void keyReleased(KeyEvent e) {
89         switch(e.getKeyCode()) {
90             case KeyEvent.VK_CONTROL: control = false; break;
91             case KeyEvent.VK_ALT: alt = false; break;
92             case KeyEvent.VK_SHIFT: shift = false; break;
93         }
94     }
95
96     public void mouseClicked(MouseEvent e) { }
97     public void mouseEntered(MouseEvent e) { }
98     public void mouseExited(MouseEvent e) { }
99     public void mousePressed(MouseEvent e) { }
100     public void mouseReleased(MouseEvent e) { }
101
102     int mousex;
103     int mousey;
104     public void mouseMoved(MouseEvent e) {
105         mousex = e.getX();
106         mousey = e.getY();
107     }
108
109     float tx = 0;
110     float ty = 0;
111     float tz = 0;
112     float anglex = 0;
113     float angley = 0;
114     public void mouseDragged(MouseEvent e) {
115         if (shift) {
116             tx += (mousex - e.getX())/(float)20;
117             ty += (mousey - e.getY())/(float)20;
118         } else {
119             anglex -= mousex - e.getX();
120             angley += mousey - e.getY();
121         }
122         mousex = e.getX();
123         mousey = e.getY();
124     }
125
126     /**
127      * Take care of initialization here.
128      */
129     public void init(GLAutoDrawable gld) {
130         GL gl = gld.getGL();
131         gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
132         gl.glViewport(0, 0, 500, 300);
133         gl.glEnable(GL.GL_DEPTH_TEST);
134         gl.glClearDepth(1.0);
135         gl.glDepthFunc(GL.GL_LEQUAL);
136         gl.glMatrixMode(GL.GL_PROJECTION);
137         gl.glLoadIdentity();
138         gl.glMatrixMode(GL.GL_MODELVIEW);
139
140         float mat_specular[] = { 0.5f, 0.5f, 0.5f, 0.5f };
141         float mat_shininess[] = { 50.0f };
142         gl.glShadeModel(GL.GL_SMOOTH);
143         //gl.glMaterialfv(GL.GL_FRONT, GL.GL_DIFFUSE, mat_specular, 0);
144         //gl.glMaterialfv(GL.GL_FRONT, GL.GL_SPECULAR, mat_specular, 0);  
145         //gl.glMaterialfv(GL.GL_FRONT, GL.GL_AMBIENT, new float[] { 0.3f, 0.3f, 0.3f, 0.3f }, 0);  
146         //gl.glMaterialfv(GL.GL_FRONT, GL.GL_SHININESS, mat_shininess, 0);
147         gl.glLightfv(GL.GL_LIGHT0, GL.GL_POSITION, new float[] { 1.0f,    4.0f,  -10.0f, 0.0f }, 0);
148         gl.glLightfv(GL.GL_LIGHT1, GL.GL_POSITION, new float[] { -10.0f, 10.0f,   10.0f, 0.0f }, 0);
149         gl.glLightfv(GL.GL_LIGHT2, GL.GL_POSITION, new float[] { 10.0f, -10.0f,   10.0f, 0.0f }, 0);
150         gl.glLightfv(GL.GL_LIGHT3, GL.GL_POSITION, new float[] { 10.0f,  10.0f,  -10.0f, 0.0f }, 0);
151         gl.glLightfv(GL.GL_LIGHT4, GL.GL_POSITION, new float[] { -10.0f, 10.0f,  -10.0f, 0.0f }, 0);
152         gl.glLightfv(GL.GL_LIGHT5, GL.GL_POSITION, new float[] { 10.0f, -10.0f,  -10.0f, 0.0f }, 0);
153         gl.glEnable(GL.GL_LIGHTING);
154         gl.glEnable(GL.GL_LIGHT0);
155         /*
156         gl.glEnable(GL.GL_LIGHT1);
157         gl.glEnable(GL.GL_LIGHT2);
158         gl.glEnable(GL.GL_LIGHT3);
159         gl.glEnable(GL.GL_LIGHT4);
160         gl.glEnable(GL.GL_LIGHT5);
161         */
162         gl.glColorMaterial(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT_AND_DIFFUSE);
163         gl.glEnable(GL.GL_COLOR_MATERIAL);
164
165         display(gld);
166     }
167
168     public int temps;
169     public int accepts;
170     public    int vertss;
171     public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { }
172     public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) { }
173     public void display(GLAutoDrawable drawable) {
174
175         if (transforms==null) return;
176
177
178         glcanvas.setSize(f.getWidth(), f.getHeight() - 100);
179         Graphics2D g = (Graphics2D)f.getGraphics();
180         g.setColor(Color.black);
181         g.fillRect(0, f.getHeight()-100, f.getWidth(), f.getHeight());
182         g.setColor(Color.red);
183         int top = f.getHeight()-70;
184         g.drawString("temperature: "+temps, 10, 30+top);
185         g.drawString("acceptance: "+accepts, 10, 50+top);
186         g.drawString("vertices: "+vertss, 10, 70+top);
187         g.fillRect(140, 25+top, temps, 10);
188         g.fillRect(140, 45+top, accepts, 10);
189         g.fillRect(140, 65+top, vertss, 10);
190
191         GL gl = drawable.getGL();
192         GLU glu = new GLU();
193         gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
194         gl.glPointSize(5.0f);
195         gl.glLoadIdentity();
196         glu.gluPerspective(50, ((float)drawable.getWidth())/drawable.getHeight(), 0.5, 10);
197         glu.gluLookAt(0, 0, -((tz/10)-1), 0, 0, 0, 0, 1, 0);
198         gl.glRotatef(anglex/3, 0, 1, 0);
199         gl.glRotatef(-(angley/3), 1, 0, 0);
200
201
202         gl.glDisable(GL.GL_LIGHTING);
203         gl.glColor4f(1, 0, 0, 1);
204         gl.glBegin(GL.GL_LINES);
205         gl.glVertex3f(0,0,0);
206         gl.glVertex3f(.3f,0,0);
207         gl.glEnd();
208         gl.glColor4f(0, 1, 0, 1);
209         gl.glBegin(GL.GL_LINES);
210         gl.glVertex3f(0,0,0);
211         gl.glVertex3f(0,.3f,0);
212         gl.glEnd();
213         gl.glColor4f(0, 0, 1, 1);
214         gl.glBegin(GL.GL_LINES);
215         gl.glVertex3f(0,0,0);
216         gl.glVertex3f(0,0,.3f);
217         gl.glEnd();
218         gl.glEnable(GL.GL_LIGHTING);
219
220
221         gl.glBegin(GL.GL_TRIANGLES);
222         if (tileon)
223             draw(gl, true, safeTriangles);
224         if (tilemeshon)
225             draw(gl, false, safeTriangles);
226         gl.glEnd();
227
228         //draw(gl, false, tile);
229
230         gl.glBegin(GL.GL_TRIANGLES);
231         gl.glColor4f((float)0.5, (float)0.5, (float)0.5, (float)0.8);
232         if (goalon)
233             draw(gl, false, goal);
234         gl.glEnd();
235
236
237         int i = 0;
238         //gl.glDisable(GL.GL_DEPTH_TEST);
239         gl.glColor4f(1,1,1,1);
240         for(Matrix m : transforms) {
241             /*
242               gl.glColor4f(0, 1, 1, 1);
243               gl.glBegin(GL.GL_LINES);
244               new Point(0,0,0).glVertex(gl);
245               new Point(0,0,0).plus(m.getTranslationalComponent()).glVertex(gl);
246               gl.glEnd();
247               gl.glEnable(GL.GL_LIGHTING);
248             */
249             //if (v1.z==0 && v1.y==0) continue;
250             i++;
251             if (neighborsWireOne && i!=whichNeighbor) continue;
252             //if (i>4) continue;
253             /*
254             Point p = new Point(0, 0, 0).times(m);
255             Vec v = new Vec(p.x, p.y, p.z);
256             v = v.times((float)1.04);
257             gl.glTranslatef(v.x, v.y, v.z);
258             */
259             if (neighbors) draw(gl, true, safeTriangles, m);
260             else if (neighborsWire || neighborsWireOne) draw(gl, false, safeTriangles, m);
261             /*
262             gl.glTranslatef(-v.x, -v.y, -v.z);
263             */
264         }
265         //gl.glEnable(GL.GL_DEPTH_TEST);
266
267         gl.glDisable(GL.GL_LIGHTING);
268         gl.glShadeModel(GL.GL_FLAT);
269         if (closest != null) {
270             gl.glColor3f(1,1,1);
271             gl.glBegin(gl.GL_POINTS);
272             closest.getPoint().glVertex(gl);
273             gl.glEnd();
274             Mesh.Vertex v2 = closest.hack(gl, getMouse());
275             gl.glBegin(GL.GL_LINES);        
276             closest.getPoint().glVertex(gl);                                                                                                  
277             if (v2 != null) v2.getPoint().glVertex(gl);
278             gl.glEnd();
279         }
280
281         gl.glFlush();
282         gl.glDrawBuffer(GL.GL_BACK);
283         gl.glReadBuffer( GL.GL_BACK );
284         gl.glPixelStorei( GL.GL_PACK_ALIGNMENT, 1);
285         gl.glFlush();
286         gl.glDisable(GL.GL_LIGHTING);
287         gl.glShadeModel(GL.GL_FLAT);
288
289         IntBuffer buf = ByteBuffer.allocateDirect(9*4*4).order(ByteOrder.nativeOrder()).asIntBuffer();
290         gl.glColor3f(0,0,0);
291         gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
292         double dist = Double.MAX_VALUE;
293         closest = null;
294         synchronized(safeTriangles) {
295             for(Mesh.T t : safeTriangles)
296                 t.glTriangle(gl, null);
297             for(Mesh.Vertex v : tile.vertices()) {
298                 Point p = v.getPoint();
299                 gl.glColor3f(1,1,1);
300                 gl.glBegin(gl.GL_POINTS);
301                 p.glVertex(gl);
302                 gl.glEnd();
303                 gl.glFlush();
304
305                 Point projected = p.glProject(gl);
306                 int x = (int)projected.x;
307                 int y = (int)projected.y;
308                 gl.glReadPixels(x-1, y-1, 3, 3, gl.GL_RGB, gl.GL_UNSIGNED_BYTE, buf);
309
310                 boolean vis = false;
311                 for(int j=0; j<9*4; j++) vis |= buf.get(j)!=0;
312                 v.visible = vis;
313                 if (vis) {
314                     gl.glColor3f(0,0,0);
315                     gl.glBegin(gl.GL_POINTS);
316                     p.glVertex(gl);
317                     gl.glEnd();
318                     y = glcanvas.getHeight()-y;
319                     if (closest==null || (x-mousex)*(x-mousex)+(y-mousey)*(y-mousey) < dist) {
320                         dist = (x-mousex)*(x-mousex)+(y-mousey)*(y-mousey);
321                         closest = v;
322                     }
323                 }
324             }
325         }
326         gl.glShadeModel(GL.GL_SMOOTH);
327         gl.glEnable(GL.GL_LIGHTING);
328         gl.glDrawBuffer(GL.GL_FRONT);
329
330
331
332         /*
333         IntBuffer selectionBuffer =
334         ByteBuffer.allocateDirect(4*10000).order(ByteOrder.nativeOrder()).asIntBuffer();
335         gl.glSelectBuffer(selectionBuffer.capacity(), selectionBuffer);
336         gl.glInitNames();
337         gl.glRenderMode(GL.GL_SELECT);
338         draw(gl, true, safeTriangles);
339         int hits = gl.glRenderMode(GL.GL_RENDER);
340         synchronized(safeTriangles) {
341             for(Mesh.T t : safeTriangles) {
342                 t.occluded = true;
343             }
344             processHits(hits, selectionBuffer);
345         }
346         */
347     }
348     Mesh.Vertex closest = null;
349
350     // I copied this method without changes from the mentioned base class.
351     // It extracts the data in the selection buffer and writes it on the console.
352     public void processHits(int hits, IntBuffer buffer) {
353         /*
354         System.out.println("---------------------------------");
355         System.out.println(" HITS: " + hits);
356         */
357         int offset = 0;
358         int names;
359         float z1, z2;
360         for (int i = 0; i < hits; i++) {
361             /*
362             System.out.println("- - - - - - - - - - - -");
363             System.out.println(" hit: " + (i + 1));
364             */
365             names = buffer.get(offset);
366             offset++;
367             z1 = (float) buffer.get(offset) / 0x7fffffff;
368             offset++;
369             z2 = (float) buffer.get(offset) / 0x7fffffff;
370             offset++;
371             /*
372             System.out.println(" number of names: " + names);
373             System.out.println(" z1: " + z1);
374             System.out.println(" z2: " + z2);
375             System.out.println(" names: ");
376             */
377
378             for (int j = 0; j < names; j++) {
379                 int who = buffer.get(offset);
380                 for(Mesh.T t : safeTriangles) {
381                     if (t.serial==who) {
382                         t.occluded = false;
383                     }
384                 }
385                 /*
386                 System.out.print("  " + who);
387                 if (j == (names - 1)) {
388                     System.out.println("<-");
389                 } else {
390                     System.out.println();
391                     }
392                 */
393                 offset++;
394             }
395             /*
396             System.out.println("- - - - - - - - - - - -");
397             */
398         }
399         /*
400         System.out.println("--------------------------------- ");
401         */
402     }
403
404     protected HashSet<Mesh.T> safeTriangles = new HashSet<Mesh.T>();
405
406     private void draw(GL gl, boolean triangles, Iterable<Mesh.T> tris) { draw(gl, triangles, tris, Matrix.ONE); }
407     private void draw(GL gl, boolean triangles, Iterable<Mesh.T> tris, Matrix m) {
408         float red = 0.0f;
409         float green = 0.0f;
410         float blue = 0.0f;
411         synchronized(safeTriangles) {
412         for(Mesh.T t : tris) {
413             if (red < 0.15) red = 1.0f;
414             if (green < 0.15) green = 1.0f;
415             if (blue < 0.15) blue = 1.0f;
416             red -= .09f;
417             green -= .12f;
418             blue -= .15f;
419
420             if (triangles) switch(t.color/*class*/) {
421                 case 0: gl.glColor4f((float)0.25, (float)0.25, (float)0.75, (float)0.3); break;
422                 case 1: gl.glColor4f((float)0.25, (float)0.75, (float)0.25, (float)0.3); break;
423                 case 2: gl.glColor4f((float)0.75, (float)0.25, (float)0.25, (float)0.3); break;
424                 case 3: gl.glColor4f((float)0.50, (float)0.50, (float)0.50, (float)0.3); break;
425                 case 4: gl.glColor4f((float)0.25, (float)0.75, (float)0.75, (float)0.3); break;
426                 case 5: gl.glColor4f((float)0.25, (float)0.75, (float)0.75, (float)0.3); break;
427                 case 6: gl.glColor4f((float)0.75, (float)0.25, (float)0.75, (float)0.3); break;
428             }
429             
430             gl.glColor4f((float)0.25, (float)0.25, (float)0.75, (float)0.3); 
431             //if (t.v1().visible && t.v2().visible && t.v3().visible) continue;
432
433             /*
434             if (t.e1().pair.t==null) gl.glColor4f((float)0.25, (float)0.25, (float)0.75, (float)0.3);
435             else if (t.e2().pair.t==null) gl.glColor4f((float)0.25, (float)0.25, (float)0.75, (float)0.3);
436             else if (t.e3().pair.t==null) gl.glColor4f((float)0.25, (float)0.25, (float)0.75, (float)0.3);
437             else  gl.glColor4f((float)0.75, (float)0.25, (float)0.25, (float)0.3);
438             */
439             //gl.glBegin(GL.GL_LINES);
440
441             if (triangles) {
442                 t.glTriangle(gl, m);
443             } else {
444                 gl.glDisable(GL.GL_LIGHTING);
445                 gl.glBegin(GL.GL_LINES);
446                 gl.glColor3f(1, 1, 1);
447                 m.times(t.e1().p1.goodp).glVertex(gl);
448                 m.times(t.e1().p2.goodp).glVertex(gl);
449                 m.times(t.e2().p1.goodp).glVertex(gl);
450                 m.times(t.e2().p2.goodp).glVertex(gl);
451                 m.times(t.e3().p1.goodp).glVertex(gl);
452                 m.times(t.e3().p2.goodp).glVertex(gl);
453                 gl.glEnd();
454                 gl.glEnable(GL.GL_LIGHTING);
455             }
456
457             Point centroid = t.centroid();
458             gl.glBegin(GL.GL_LINES);
459             gl.glColor3f(1, 1, 1);
460
461             if (triangles && errorNormals)
462                 for(Mesh.Vertex p : new Mesh.Vertex[] { t.v1(), t.v2(), t.v3() }) {
463                     if (p.ok) {
464                         //gl.glDisable(GL.GL_LIGHTING);
465                         gl.glBegin(GL.GL_LINES);
466                         gl.glColor3f(1, 1, 1);
467                         p.p.glVertex(gl);
468                         p.p.plus(p.norm().times((float)p.error()*10)).glVertex(gl);
469                         //if (p.nearest_in_other_mesh != null) p.nearest_in_other_mesh.p.glVertex(gl);
470                         //tile.nearest(p).centroid().glVertex(gl);
471                         gl.glEnd();
472                         //gl.glEnable(GL.GL_LIGHTING);
473                     }
474                 }
475             gl.glEnd();
476             
477         }
478         }
479     }
480
481
482     //private JTextArea ocanvas = new JTextArea();
483     private JFrame f;
484     private GLCanvas glcanvas;
485     public MeshViewer(JFrame f) {
486         this.f = f;
487
488         GLCapabilities glcaps = new GLCapabilities();
489         glcanvas = new GLCanvas();
490         glcanvas.addGLEventListener(this);
491         f.add(glcanvas, BorderLayout.CENTER);
492
493         glcanvas.addMouseListener(this);
494         glcanvas.addMouseMotionListener(this);
495         glcanvas.addMouseWheelListener(this);
496         glcanvas.addKeyListener(this);
497     }
498     public void repaint() {
499         glcanvas.repaint();
500     }
501
502
503
504 }