Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "terrain.h"
- Terrain::Terrain(int width, int height)
- {
- _width = width;
- _length = height;
- heights = new float*[_length];
- for(int i = 0; i < _length; i++)
- heights[i] = new float[_width];
- normals = new vec3D*[_length];
- for(int i = 0; i < _length; i++)
- normals[i] = new vec3D[_width];
- computedNormals = false;
- }
- Terrain::~Terrain()
- {
- for(int i = 0; i < _length; i++)
- delete[] heights[i];
- delete[] heights;
- for(int i = 0; i < _length; i++)
- delete[] normals[i];
- delete[] normals;
- }
- void Terrain::setHeight(int x, int z, float y)
- {
- heights[z][x] = y;
- computedNormals = true;
- }
- void Terrain::computeNormals()
- {
- if(computedNormals)
- return;
- vec3D** normals2 = new vec3D*[_length];
- for(int i = 0; i < _length; i++)
- normals2[i] = new vec3D[_width];
- for(int z = 0; z < _length; z++)
- {
- for(int x = 0; x < _width; x++)
- {
- vec3D sun(0.0f, 0.0f, 0.0f);
- vec3D out;
- vec3D in;
- vec3D left;
- vec3D right;
- if(z > 0)
- out = vec3D(0.0f, heights[z - 1][x] - heights[z][x], -1.0f);
- if(z < _length - 1)
- in = vec3D(0.0f, heights[z + 1][x] - heights[z][x], 1.0f);
- if(x > 0)
- left = vec3D(-1.0f, heights[z][x - 1] - heights[z][x], 0.0f);
- if(x > 0 && z > 0)
- sun += out.cross(left).normalize();
- if(x > 0 && z < _length - 1)
- sun += left.cross(in).normalize();
- if(x < _width - 1 && z < _length - 1)
- sun += in.cross(right).normalize();
- if(x < _width - 1 && z > 0)
- sun += right.cross(out).normalize();
- normals2[z][x] = sun;
- }
- }
- const float FALLOUT_RATIO = 0.5f;
- for(int z = 0; z < _length; z++)
- {
- for(int x = 0; x < _width; x++)
- {
- vec3D sun = normals2[z][x];
- if(x > 0)
- sun += normals2[z][x - 1] * FALLOUT_RATIO;
- if(x < _width - 1)
- sun += normals2[z][x + 1] * FALLOUT_RATIO;
- if(z > 0)
- sun += normals2[z - 1][x] * FALLOUT_RATIO;
- if(z < 0)
- sun += normals2[z + 1][x] * FALLOUT_RATIO;
- if(sun.length() == 0)
- sun = vec3D(0.0f, 1.0f, 0.0f);
- normals[z][x] = sun;
- }
- }
- for(int i = 0; i < _length; i++)
- delete[] normals2[_length];
- delete[] normals2;
- computedNormals = true;
- }
- vec3D Terrain::getNormals(int x, int z)
- {
- if(!computedNormals)
- computeNormals();
- return normals[z][x];
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement