#include "main.h"
#include "dib.h"
#include "writer.h"
#include <gl\gl.h>


int strlen(char *s)
{
	int i=0;
	while(*s++) i++;
	return i;
}

int Average(unsigned char c1, unsigned char c2, unsigned char c3, unsigned char c4)
{
	return	((c1&0xfc)>>2)+
			((c2&0xfc)>>2)+
			((c3&0xfc)>>2)+
			((c4&0xfc)>>2);
}

static int NextPow2 (int x) 
{
	int n=1;
	while (n<x) n<<=1;
	return n;
}

int createdibornot=0;
TDib *dib;

void drawfont(KTEXT *text)
{
	if (createdibornot==0)
	{
	dib = new TDib(4096, 256);
	createdibornot=1;
	}

	for (int i=0;i<dib->xres*dib->yres;i++)
	{
	dib->vscreen[i]=0;
	}


	HDC hdc = dib->hdc;
	int nHeight = -MulDiv(text->pointsize*2, GetDeviceCaps(hdc, LOGPIXELSY), 73);
	SetBkMode(hdc, TRANSPARENT);
	HFONT hfont = CreateFont(	nHeight, 0, 0, 0, text->weight, FALSE, FALSE, FALSE,
								DEFAULT_CHARSET, OUT_TT_ONLY_PRECIS, CLIP_DEFAULT_PRECIS,
								DEFAULT_QUALITY, VARIABLE_PITCH, "Arial");
	SelectObject (hdc, hfont);
	SetTextCharacterExtra(hdc, text->spacing);
	SetTextColor(hdc, 0xffffff);
	TextOut(hdc, 1, 1, text->text, strlen(text->text));

	SIZE size;
	GetTextExtentPoint32(hdc, text->text, strlen(text->text), &size);


	int orgx=size.cx;
	int orgy=size.cy;

	text->orgx=orgx;
	text->orgy=orgy;

	char *outbuf=new char[size.cx*size.cy];
	memset(outbuf, 0, size.cx*size.cy);

	size.cx=NextPow2(size.cx);
	size.cy=NextPow2(size.cy);

	text->wfix=orgx/(float)(size.cx);
	text->hfix=orgy/(float)(size.cy);


	int o=0;

	
	for (int y=1;y<(size.cy>>1)-1;y++)
	{
		outbuf[o++]=0;
		for (int x=1;x<(size.cx>>1)-1;x++)
		{
			int ofs=(x+y*dib->xres)<<1;
			
			outbuf[o]=Average(	dib->vscreen[ofs],
								dib->vscreen[ofs+1], 
								dib->vscreen[ofs+dib->xres],
								dib->vscreen[ofs+dib->xres+1]);
		
							
								
			o++;	
		}
		outbuf[o++]=0;
	}

	DeleteObject(hfont);


	text->width=(size.cx>>1);
	text->height=(size.cy>>1);

	glGenTextures(1, &text->glhandle);
	glBindTexture(GL_TEXTURE_2D, text->glhandle);
	glTexImage2D(GL_TEXTURE_2D, 0, 1, text->width, text->height, 0, GL_LUMINANCE , GL_UNSIGNED_BYTE, outbuf);	
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);

	delete outbuf;
}


