OpenGL - 如何计算地形高度网格中的法线? [英] OpenGL - How to calculate normals in a terrain height grid?

查看:25
本文介绍了OpenGL - 如何计算地形高度网格中的法线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的方法是计算两个分别平行于 X 轴和 Y 轴的切向量.然后计算叉积以找到法向量.

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.

我想知道是否有更直接的计算,或者在 CPU 周期方面成本更低.

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

推荐答案

通过使用有限差分法"(或者至少我认为它是这样调用的),您实际上可以在没有叉积的情况下计算它.

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

这篇关于OpenGL - 如何计算地形高度网格中的法线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆