using System; using System.IO; using ImageSharp; using ImageSharp.PixelFormats; using OpenTK.Graphics.OpenGL4; using OpenTK; using org.nhengine.graphics; namespace nhengine { public class SquaredMap : GLObject { private int width, height; private float[] heightMap; public SquaredMap(int width,int height) :base( 12 * width * height ) { this.width = width; this.height = height; this.heightMap = new float[ (width + 1) * (height + 1) ]; normalsEnabled = true; generateHeightMap(); computeGL(); updateGL(); } public SquaredMap(Image heightMap) :base(12 * heightMap.Width * heightMap.Height) { this.width = heightMap.Width; this.height = heightMap.Height; this.heightMap = new float[ (width + 1) * (height + 1) ]; normalsEnabled = true; loadHeightMap(heightMap); computeGL(); updateGL(); } public void generateHeightMap(){ Random rand = new Random(); for (int y = 0; y <= height; y++) { for (int x = 0; x <= width; x++) { float h = (float)rand.NextDouble(); heightMap[x + (y * width)] = (float)(256 * (h * h)); } } } public void loadHeightMap(Image _heightMap){ Rgba32[] pixels = _heightMap.Pixels; for (int y = 0; y <= height; y++) { for (int x = 0; x <= width; x++) { Rgba32 pixel = pixels[ x + (y * _heightMap.Width)]; float h = (pixel.R + pixel.G + pixel.B); heightMap[x + (y * width)] = (float)(h); } } } public void computeGL(){ float left, right, bottom, top, vcenter, hcenter; Console.WriteLine("Creating geometry"); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { int i = x + ((width + 1) * y); int j = x + ((width + 1) * (y + 1)); float[] h = new float[4]; h[0] = heightMap[i]; h[1] = heightMap[i+1]; h[2] = heightMap[j]; h[3] = heightMap[j+1]; float ah = (h[0] + h[1] + h[2] + h[3]) / 4.0f; left = 128 * x; right = 128 * (x + 1); bottom = 128 * y; top = 128 * (y + 1); vcenter = (top + bottom) / 2.0f; hcenter = (left + right) / 2.0f; int b = 4 * (x + (width * y)); setTriangle( b, new Vector3(left, top, h[2]), new Vector3(right, top, h[3]), new Vector3(hcenter,vcenter,ah) ); setTriangle( b + 1, new Vector3(right, top, h[3]), new Vector3(right, bottom, h[1]), new Vector3(hcenter, vcenter, ah) ); setTriangle( b + 2, new Vector3(right, bottom, h[1]), new Vector3(left, bottom, h[0]), new Vector3(hcenter, vcenter, ah) ); setTriangle( b + 3, new Vector3(left, bottom, h[0]), new Vector3(left, top, h[2]), new Vector3(hcenter, vcenter, ah) ); } } Console.WriteLine("Coloring..."); for (int n = 0; n < vertices.Length / 3;n++){ float _h = vertices[(3 * n) + 2] / 512.0f; setColor( n, new Vector4( 0.3f + (0.7f * _h), 0.2f + (0.8f * _h), 0.4f + (0.6f * _h), 1.0f ) ); } } } }