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

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.

主站蜘蛛池模板: 青川县| 嘉善县| 成都市| 洪洞县| 甘泉县| 乌苏市| 曲阜市| 房山区| 东光县| 澄城县| 青川县| 富阳市| 柳林县| 潮安县| 南雄市| 穆棱市| 景泰县| 宝兴县| 绥化市| 广东省| 平陆县| 沅江市| 克拉玛依市| 安宁市| 阳朔县| 武乡县| 乐安县| 江口县| 和政县| 西藏| 阜南县| 巴青县| 海城市| 泗水县| 施秉县| 吴堡县| 宣化县| 虹口区| 佳木斯市| 横山县| 大邑县|