提到 向量运算,首先就是 点乘 和 叉乘。
点乘(Dot Product):
也叫向量的内积、数量积,公式描述为:
向量a·向量b = |a||b| cosθ
= a1·b1 + a2·b2
点乘 的几何意义是一个向量在另外一个向量上的投影。
叉乘(Cross Product):
也叫向量积,数学中又称外积、叉积,物理中称矢积,是一种在向量空间中向量的二元运算。与点积不同,它的运算结果是一个向量而不是一个标量。并且两个向量的叉积与这两个向量和垂直(根据上图的右手定则)。
向量a×向量b = | i j k | // 注:i、j、k分别为空间中相互垂直的三条坐标轴的单位向量
|a1 b1 c1|
|a2 b2 c2|
= (b1c2-b2c1, c1a2-a1c2, a1b2-a2b1)
叉乘 对应的模长(标量值)可以描述为:|a||b|sinθ ,对应 向量 ab 构成平行四边形的面积。
定义基础操作(BaseOperatin.h),封装用于后续调用:
/* 基本操作定义 - 基本运算
linolzhang, 2010.2.10
*/
#ifndef BASEOPERATION_H
#define BASEOPERATION_H
#include <cmath>
#include <ctime>
// 预定义变量
#define PI 3.14159265359f // 定义PI值
#define EPSILON 1.0e-5
#define TO_RADIANS(degree) (float)((degree * PI) / 180.0f) // 角度转换成弧度
#define TO_DEGREE(radians) (float)((radians * 180.0f) / PI) // 弧度转换成角度
// ----------------------------------------------
// 基本数学运算 - 截取,求整
template <class T>
inline const T clamp(T x, T min, T max) // 规范x值 -> 到[min, max]之间
{
return (x < min) ? min : (x > max) ? max : x;
}
template <class T>
inline const bool SameSign(T x1,T x2) // 是否同号
{
return x1<0&&x2<0||x1>0&&x2>0||x1==0&&x2==0?true:false;
}
inline const int round(float f) // 小数变整数 -> 四舍五入
{
return int(f + 0.5f);
}
inline const int getCloser(int arg,int firstVal,int secondVal) // 求与给定值接近的值
{
return abs(arg - firstVal)<abs(arg - secondVal)?firstVal:secondVal;
}
inline const bool isPowerOf2(int arg) // 是否是2的次方, [0,1024]
{
if(arg > 1024 || arg<0)
return false;
int pOf2 = 1024;
while( pOf2 > 1)
{
if(pOf2 == arg)
return true;
pOf2 /= 2;
}
return false;
}
inline const int getClosestP2(int arg) // 得到与arg最接近的2的次方数
{
if( !isPowerOf2(arg) )
{
if(arg > 1024) return 1024;
if(arg < 1024 && arg > 512) return getCloser(arg, 1024, 512);
if(arg < 512 && arg > 256) return getCloser(arg, 512, 256);
if(arg < 256 && arg > 128) return getCloser(arg, 256, 128);
if(arg < 128 && arg > 64) return getCloser(arg, 128, 64);
if(arg < 64 && arg > 32) return getCloser(arg, 64, 32);
return 32;
}
return arg;
}
// ----------------------------------------------
// 基本运算 - 快速求 平方根,sin,cos,快速内存拷贝
inline const float fastSquareRoot(float x)
{
__asm
{
fld x;
fsqrt;
fstp x;
}
return x;
}
inline const float fastSin(float x)
{
__asm
{
fld x;
fsin;
fstp x;
}
return x;
}
inline const float fastCos(float x)
{
__asm
{
fld x;
fcos;
fstp x;
}
return x;
}
inline void fast_memcpy(void *dst, const void *src, size_t len)
{
__asm
{
push esi ;
push edi ;
mov esi, [src] ; //source array
mov edi, [dst] ; //destination array
mov ecx, [len]
shr ecx, 2 ; //convert to DWORD count
rep movsd ;
pop edi ;
pop esi ;
ret ;
}
}
// ----------------------------------------------
// 基本运算 - 随机数相关
inline void SetSeed() // 设置随机种子
{
srand((unsigned)time(NULL));
}
inline const float getRand