Normal3DCG
法線
法線を出すには、
1.三角形の3つの頂点から、その三角形の2つの辺をベクトルとして出す。
2.その2つの辺を外積して、1つの方向ベクトルを出す。
3.そのままでは計算に使えないので、各要素の合計が1になるベクトルに
変換する(正規化)。
という手順になります。
法線の計算では、ゼロによる除算に気を付けてください。(他の場合でもそうですが)
軸に水平なポリゴンの面などの場合、まれにゼロで割るケースが
発生しますので、防止用のコードを書いておきましょう。
面を構成するa,b,c3つの点は時計回りとすると
法線 = 単位ベクトル化( 外積 ( b - a, c - a ) );
C++
TVector normal(TVector &a, TVector &b, TVector &c)//3つの点は時計回り
{
return normalize(cross(b-a,c-a));
};
gcc用
Vertex normal(Vertex &a, Vertex &b)
{
Vertex ret = cross(a, b);
return normalize(ret);
};
Vertex normal(Vertex &a, Vertex &b, Vertex &c)
{
Vertex ba = b - a;
Vertex ca = c - a;
Vertex ret = cross(ba, ca);
return normalize(ret);
};
Java
static Vertex tmp1 = new Vertex();
static Vertex tmp2 = new Vertex();
static Vertex normal(Vertex dest, Vertex v1, Vertex v2, Vertex v3)
{//v1, v2, v3が三角形の3つの頂点 destが法線を入れる変数
tmp1.x = v3.x - v1.x; tmp1.y = v3.y - v1.y; tmp1.z = v3.z - v1.z;
tmp2.x = v2.x - v1.x; tmp2.y = v2.y - v1.y; tmp2.z = v2.z - v1.z;
dest = cross(dest, tmp1, tmp2);
if (dest.x == 0) dest.x = 0.00000001f;
if (dest.y == 0) dest.y = 0.00000001f;
if (dest.z == 0) dest.z = 0.00000001f;
normalize(dest);
return dest;
}
2008年03月07日(金) 16:40:51 Modified by eruvasu