/** Draw a 2d function */ import javax.media.opengl.*; public class Function2D{ private static float sqr(float x){ return x*x; } //function that looks like a hat public static float f (float x, float y){ float twopi = 2.0f*(float)Math.PI; float a = sqr(twopi*(x-0.5f)) + sqr(twopi*(y-0.5f)); return (float) (0.8f*(- (0.2f)*Math.sin(twopi*x)*Math.cos(twopi*y) + (1.5f)*Math.cos(7.0f*a/4.0f)*Math.exp(-a))); } //normal to a triangle public static Vector3D normal (Vector3D a, Vector3D b, Vector3D c){ return b.subtract(a).cross(c.subtract(a)); } public static void surface(GL gl, int level){ Vector3D a,b,c,n; float h = 1.0f/level; float hh = h/10.0f; for (int i = 0; i < level; i++){ float x = i*h; gl.glBegin(GL.GL_TRIANGLE_STRIP); for (int j = 0; j <= level; j++){ float y = j*h; a = new Vector3D(x+h, f(x+h,y), y); b = new Vector3D(x+h+hh, f(x+h+hh,y), y); c = new Vector3D(x+h, f(x+h,y+hh), y+hh); n = normal(a,c,b); gl.glTexCoord2d(x+h,y); gl.glNormal3d(n.x,n.y,n.z); gl.glVertex3d(a.x,a.y,a.z); a = new Vector3D(x, f(x,y), y); b = new Vector3D(x+hh, f(x+hh,y), y); c = new Vector3D(x, f(x,y+hh), y+hh); n = normal(a,c,b); gl.glTexCoord2d(x,y); gl.glNormal3d(n.x,n.y,n.z); gl.glVertex3d(a.x,a.y,a.z); } gl.glEnd(); } } }