1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
|
public void init(GLAutoDrawable arg0) {
this.gl = arg0.getGL();
gl.glShadeModel(GL.GL_SMOOTH); // Enable Smooth Shading
gl.glClearColor(1f, 1f, 1f, 1f);
gl.glClearDepth(1.0f);
arg0.addMouseListener(this);
arg0.addMouseMotionListener(this);
}
public void display(GLAutoDrawable arg0) {
this.gl = arg0.getGL();
gl.glLoadIdentity();
gl.glTranslatef(0f, 0f, -5f);
drawWorld(gl);
GLU glu = new GLU();
int viewport[] = new int[4];
double mvmatrix[] = new double[16];
double projmatrix[] = new double[16];
int realy = 0;// GL y coord pos
double wcoord[] = new double[4];// wx, wy, wz;// returned xyz coords
if (mouse != null) {
int x = mouse.getX(), y = mouse.getY();
switch (mouse.getButton()) {
case MouseEvent.BUTTON1:
gl.glGetIntegerv(GL.GL_VIEWPORT, viewport, 0);
gl.glGetDoublev(GL.GL_MODELVIEW_MATRIX, mvmatrix, 0);
gl.glGetDoublev(GL.GL_PROJECTION_MATRIX, projmatrix, 0);
// note viewport[3] is height of window in pixels
realy = viewport[3] - (int) y - 1;
System.out.println("Coordinates at cursor are (" + x + ", " + realy + ")");
glu.gluUnProject((double) x, (double) realy, (z+(-5f)), //
mvmatrix, 0,//
projmatrix, 0,//
viewport, 0, //
wcoord, 0);
System.out.println("World coords at z="+(z+(-5f))+" are (" //
+ wcoord[0] + ", " + wcoord[1] + ", " + wcoord[2] + ")");
break;
case MouseEvent.BUTTON2:
break;
default:
break;
}
}
}
private void drawWorld(GL gl) {
gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
Node n0 = new Node(gl, new GLU(), -0.35f, 0.25f, z);
n0.draw();
Node n1 = new Node(gl, new GLU(), 0.35f, 0.25f, z);
n1.draw();
Node n2 = new Node(gl, new GLU(), 0.35f, -0.25f, z);
n2.draw();
Node n3 = new Node(gl, new GLU(), -0.35f, -0.25f, z);
n3.draw();
gl.glFlush();
}
public void reshape(GLAutoDrawable arg0, int x, int y, int w, int h) {
this.gl = arg0.getGL();
final GLU glu = new GLU();
gl.glViewport(0, 0, w, h);
gl.glMatrixMode(GL.GL_PROJECTION);
gl.glLoadIdentity();
glu.gluPerspective(45, w / h, 1.0, 100);
gl.glMatrixMode(GL.GL_MODELVIEW);
gl.glLoadIdentity();
}
/**Far away in the same class*/
class Node {
private GL gl;
private GLU glu;
public float x, y, z;
private final float c = 0.025f;
int id = 0;
public Node(GL gl, GLU glu) {
this.gl = gl;
this.glu = glu;
}
public Node(GL gl, GLU glu, float x, float y, float z) {
this.gl = gl;
this.glu = glu;
this.x = x;
this.y = y;
this.z = z;
}
public void draw() {
gl.glPolygonMode(GL.GL_FRONT, GL.GL_FILL);
gl.glColor3f(1f, 0f, 0f);
gl.glBegin(GL.GL_POLYGON);
gl.glVertex3f(x - c, y + c, z);
gl.glVertex3f(x + c, y + c, z);
gl.glVertex3f(x + c, y - c, z);
gl.glVertex3f(x - c, y - c, z);
gl.glEnd();
}
} |
Partager