官术网_书友最值得收藏!

Normalizing vectors

A vector with a length of 1 is called a normal vector (or unit vector). Generally, unit vectors are used to represent a direction without a magnitude. The dot product of two unit vectors will always fall in the -1 to 1 range.

Aside from the 0 vector, any vector can be normalized by scaling the vector by the inverse of its length:

  1. Implement the normalize function in vec3.cpp. Don't forget to add the function declaration to vec3.h:

    void normalize(vec3 &v) {

        float lenSq = v.x * v.x + v.y * v.y + v.z * v.z;

        if (lenSq < VEC3_EPSILON) { return; }

        float invLen = 1.0f / sqrtf(lenSq);    

        v.x *= invLen;

        v.y *= invLen;

        v.z *= invLen;

    }

  2. Implement the normalized function in vec3.cpp. Don't forget to add the function declaration to vec3.h:

    vec3 normalized(const vec3 &v) {

        float lenSq = v.x * v.x + v.y * v.y + v.z * v.z;

        if (lenSq < VEC3_EPSILON) { return v; }

        float invLen = 1.0f / sqrtf(lenSq);

        return vec3(

            v.x * invLen,

            v.y * invLen,

            v.z * invLen

        );

    }

The normalize function takes a reference to a vector and normalizes it in place. The normalized function, on the other hand, takes a constant reference and does not modify the input vector. Instead, it returns a new vector.

主站蜘蛛池模板: 贺州市| 石柱| 漯河市| 开远市| 安达市| 当阳市| 桂林市| 鄂温| 女性| 司法| 特克斯县| 子洲县| 文安县| 穆棱市| 赣榆县| 松原市| 延吉市| 江阴市| 龙山县| 新民市| 肃南| 西乡县| 武强县| 镇坪县| 湖北省| 郎溪县| 凤山市| 永城市| 皮山县| 桃江县| 陵川县| 莱西市| 旬阳县| 长乐市| 上林县| 宝兴县| 锡林浩特市| 玉溪市| 清水河县| 永平县| 新平|