開源的遊戲引擎irrlicht中不使用比較、條件、三元運算求最值與中值的代碼

看過論壇裏很多人問這個問題,呵呵,其實在開源的遊戲引擎irrlicht的1.6版本里有相當好的解決解決方案。

所在文件名爲irrMath.h

 

typedef __int32   s32;

 

1、最小值

inline s32 s32_min(s32 a, s32 b)
{
    const s32 mask = (a - b) >> 31; // 取得a-b的符號位
    return (a & mask) | (b & ~mask); // 利用位運算取得返回值

}

 

 2、最大值

inline s32 s32_max(s32 a, s32 b)
{
    const s32 mask = (a - b) >> 31;
    return (b & mask) | (a & ~mask);
}

 

3、中值

inline s32 s32_clamp (s32 value, s32 low, s32 high)
{
    return s32_min(s32_max(value,low), high);
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章