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

冷暖自知 提交于 2019-12-17 17:31:13

问题


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.

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


回答1:


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);


来源:https://stackoverflow.com/questions/13983189/opengl-how-to-calculate-normals-in-a-terrain-height-grid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!