#include <v_lib.h>

#define	FBW		1024
#define	FBH		1024

u8_t	framebuf[FBH][FBW][4];

void	putpixel(u32_t x,u32_t y,vec3_t rgb)
{
	u8_t *ptr;
	if(x > FBW || y > FBH)
		return;
	ptr = framebuf[y][x];
	rgbByteFromFloat(ptr,rgb);
}

void cie2rgb(vec3_t rgb_ret,vec3_t cie)
{
	static matrix3_t cie2rgb_transform={
		{2.739,-1.145,-0.424},
		{-1.11,2.029,0.033},
		{0.138,-0.333,1.105}};
	mat3VecMul(rgb_ret,cie2rgb_transform,cie);
}

void rgb_maximize(vec3_t rgb)
{
	vec_t scale = rgb[vec3MaxInd(rgb)];
	if(scale > 0)
	{
		scale = 1 / scale;
		vec3Scale(rgb,rgb,scale);
	}
}

int main()
{
	int i,j;
	vec3_t rgb = {0,0,1};
	vec3_t cie;
	for(i=0;i<FBH;i++)
	{
		cie[1] = (vec_t)i / FBH * 0.85;
		for(j=0;j<FBW;j++)
		{
			cie[0] = (vec_t)j / FBW * 0.75;
			cie[2] = 1 - (cie[0]+cie[1]);
			if(cie[2] > 0)
			{
				cie2rgb(rgb,cie);
				if(rgb[0] <= 1 && rgb[1] <= 1 && rgb[2] <= 1)
					if(rgb[0] >= 0 && rgb[1] >= 0 && rgb[2] >= 0)
					{
						rgb_maximize(rgb);
						putpixel(j,FBH-i-1,rgb);
					}
			}
		}
	}
	bmpSave("out.bmp",FBW,FBH,framebuf);
	return 0;
}
