I'm trying to calculate normals of my grid surface. The map is 29952px x 19968px and each cell is 128px x 128px. So I have 36895 vertices.
My flat map array is sent to shaders with the following structure:
float vertices[368950] = {
// x y z znoise xTex yTex xNorm yNorm zNorm Type
16384,16256,-16256, 0, 0.54, 0.45, 0, 0, 1, 1,
16256,16384,-16384, 0, 0.54, 0.45, 0, 0, 1, 1,
......
}
I calculate the zNoise with a function
float noise(float x, float y){};
And it works (I add it to y and z in the vertex shader).
Method 1
If i calculate normals using finite-difference method i obtain a nice result. Pseudo-Code:
vec3 off = vec3(1.0, 1.0, 0.0);
float hL = noise(P.xy - off.xz);
float hR = noise(P.xy + off.xz);
float hD = noise(P.xy - off.zy);
float hU = noise(P.xy + off.zy);
N.x = hL - hR;
N.y = hD - hU;
N.z = 2.0;
N = normalize(N);
But, in the case I need to edit the map manually, for example in a Editor context, where you set the zNoise with a tool to create mountains as you want, this method won't help.
I get this nice result (seen from minimap) (Normals are quite dark purposely)
Method 2
| | |
--6----1----+-
|\ |\ | Y
| \ | \ | ^
| \ | \ | |
| \| \| |
--5----+----2-- +-----> X
|\ |\ |
| \ | \ |
| \ | \ |
| \| \|
--+----4----3--
| | |
So i'm trying to calculate the normal using the adjacent triangles, but the result is very different (it seems that there's a bug somewhere):
Code:
std::array<glm::vec3, 6> getAdjacentVertices(glm::vec2 pos) {
std::array<glm::vec3, 6> output;
output = {
// getVertex is a function that returns a glm::vec3
// with values x, y+znoise, z+znoise
getVertex(pos.x, pos.y + 128), // up
getVertex(pos.x + 128, pos.y), // right
getVertex(pos.x + 128, pos.y - 128), // down-right
getVertex(pos.x, pos.y - 128), // down
getVertex(pos.x - 128, pos.y), // left
getVertex(pos.x - 128, pos.y + 128), // up-left
};
return output;
}
And the last function:
glm::vec3 mapgen::updatedNormals(glm::vec2 pos) {
bool notBorderLineX = pos.x > 128 && pos.x < 29952 - 128;
bool notBorderLineY = pos.y > 128 && pos.y < 19968 - 128;
if (notBorderLineX && notBorderLineY) {
glm::vec3 a = getVertex(pos.x, pos.y);
std::array<glm::vec3, 6> adjVertices = getAdjacentVertices(pos);
glm::vec3 sum(0.f);
for (int i = 0; i < 6; i++) {
int j;
(i == 0) ? j = 5 : j = i - 1;
glm::vec3 side1 = adjVertices[i] - a;
glm::vec3 side2 = adjVertices[j] - a;
sum += glm::cross(side1, side2);
}
return glm::normalize(sum);
}
else {
return glm::vec3(0.3333f);
}
}
I get this bad result (seen from minimap) unfortunately
Note: The buildings are in different positions but the surface has the same seed using the two methods.
Could anyone help? ? Thanks in advance.