Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenGL - How to calculate normals in a terrain height grid?

Tags:

My approach is to calculate two tangent vectors parallel to axis X and Y respectively. Then calculate the cross product to find the normal vector.

The tangent vector is given by the line that crosses the middle point on the two nearest segments as is shown in the following picture.

enter image description here

I was wondering whether there is a more direct calculation, or less expensive in terms of CPU cycles.

like image 452
rraallvv Avatar asked Dec 21 '12 01:12

rraallvv


People also ask

How to calculate normals opengl?

A surface normal for a triangle can be calculated by taking the vector cross product of two edges of that triangle. The order of the vertices used in the calculation will affect the direction of the normal (in or out of the face w.r.t. winding).

What is normals in opengl?

A normal vector (or normal, for short) is a vector that points in a direction that's perpendicular to a surface. For a flat surface, one perpendicular direction is the same for every point on the surface, but for a general curved surface, the normal direction might be different at each point on the surface.


1 Answers

You can actually calculate it without a cross product, by using the "finite difference method" (or at least I think it is called in this way).

Actually it is fast enough that I use it to calculate the normals on the fly in a vertex shader.

  // # P.xy store the position for which we want to calculate the normals   // # height() here is a function that return the height at a point in the terrain    // read neightbor heights using an arbitrary small offset   vec3 off = vec3(1.0, 1.0, 0.0);   float hL = height(P.xy - off.xz);   float hR = height(P.xy + off.xz);   float hD = height(P.xy - off.zy);   float hU = height(P.xy + off.zy);    // deduce terrain normal   N.x = hL - hR;   N.y = hD - hU;   N.z = 2.0;   N = normalize(N); 
like image 97
Gigi Avatar answered Sep 21 '22 13:09

Gigi