package de.gamezock.metacraft.ui; import javax.media.opengl.GL; import javax.media.opengl.GL2; import javax.vecmath.Point3f; import javax.vecmath.Vector3f; import de.gamezock.metacraft.data.Map; import de.gamezock.metacraft.data.Tile; public class Renderer { private Main main; public Renderer(Main main) { this.main = main; } private void renderTileQuad(GL2 gl, Tile tile, int x, int y) { float[][] heightmap = tile.getData().getHeightmap(); float[] h = new float[4]; h[0] = heightmap[x][y]; h[1] = heightmap[x+1][y]; h[2] = heightmap[x+1][y+1]; h[3] = heightmap[x][y+1]; float center = (h[0] + h[1] + h[2] + h[3]) / 4; for(int i = 0; i < 4; ++i) { int i_1 = (i+1)%4; int i_2 = (i+2)%4; Point3f v1 = new Point3f(x + i_1/2, y + i/2, h[i]); Point3f v2 = new Point3f(x+0.5f, y+0.5f, center); Point3f v3 = new Point3f(x + i_2/2, y + i_1/2, h[i_1]); Vector3f edge1 = new Vector3f(), edge2 = new Vector3f(); edge1.sub(v1, v2); edge2.sub(v3, v2); Vector3f normal = new Vector3f(); normal.cross(edge1, edge2); normal.normalize(); gl.glColor3f(1, 1, 1); gl.glNormal3f(normal.x, normal.y, normal.z); gl.glVertex3f(v1.x, v1.y, v1.z); gl.glVertex3f(v2.x, v2.y, v2.z); gl.glVertex3f(v3.x, v3.y, v3.z); } } private void renderTile(GL2 gl, Tile tile) { gl.glBegin(GL.GL_TRIANGLES); for(int i = 0; i < tile.getData().getSize(); ++i) { for(int j = 0; j < tile.getData().getSize(); ++j) { renderTileQuad(gl, tile, i, j); } } gl.glEnd(); } public void render(GL2 gl) { gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); Map currentMap = main.getCurrentMap(); gl.glPushMatrix(); gl.glRotatef((System.currentTimeMillis()%3600)/10.0f, 0, 0, 1); for(int i = 0; i < currentMap.getWidth(); ++i) { for(int j = 0; j < currentMap.getHeight(); ++j) { gl.glPushMatrix(); gl.glTranslatef(i*currentMap.getTileSize(), j*currentMap.getTileSize(), currentMap.getTileHeight(i, j)); renderTile(gl, currentMap.getTile(i, j)); gl.glPopMatrix(); } } gl.glPopMatrix(); } }