云风的个人空间 : 代码片段[CodeCollection]

首页 :: 索引 :: 修订历史 :: 你好, 44.221.46.132
你的足迹: » 代码片段
这是一个旧版本的CodeCollection于2006-05-21 16:04:31.
一个快速开方的函数
/* 来至 Quake 3 的源码 */
float CarmSqrt(float x){
	union{
		int intPart;
		float floatPart;
	} convertor;
	union{
		int intPart;
		float floatPart;
	} convertor2;
	convertor.floatPart = x;
	convertor2.floatPart = x;
	convertor.intPart = 0x1FBCF800 + (convertor.intPart >> 1);
	convertor2.intPart = 0x5f3759df - (convertor2.intPart >> 1);
	return 0.5f*(convertor.floatPart + (x * convertor2.floatPart));
}

参考链接:[External Link]http://greatsorcerer.go2.icpcn.com/info/fastsqrt.html

快速 double 转整型
union luai_Cast { double l_d; long l_l; };
#define lua_number2int(i,d) \
	{ volatile union luai_Cast u; u.l_d = (d) + 6755399441055744.0; (i) = u.l_l; }

参考链接:[InterWiki]double to int 神奇的 magic number

RGB565 的 alpha 混合
unsigned short alpha_blender(unsigned int x,unsigned int y,unsigned int alpha)
{
	x = (x | (x<<16)) & 0x7E0F81F;
	y = (y | (y<<16)) & 0x7E0F81F;
	unsigned int result = ((x - y) * alpha / 32 + y) & 0x7E0F81F;
	return (unsigned short)((result&0xFFFF) | (result>>16));
}

参考链接:[InterWiki]64K 色的 Alpha 混合

一个不错的字符串 hash 函数
unsigned long hash(const char *name,size_t len)
{
	unsigned long h=(unsigned long)len;
	size_t step = (len>>5)+1;
	for (size_t i=len; i>=step; i-=step)
	    h = h ^ ((h<<5)+(h>>2)+(unsigned long)name[i-1]);
	return h;
}

一个方便的 hash 函数应该散列的比较开,计算速度跟字符串长度关系不大,又不能只计算字符串的开头或末尾。这里的算法是从 Lua 中看来的。

关于脏矩形技术的演示
由于代码过长,单起一页:脏矩形 demo
参考链接:[External Link]Blog上的帖子:脏矩形演示demo