// Copyright 1994 Brad Pitzel
//
// Feel free to use/distribute/modify as long as credit/copyrights for myself 
// are included.

#include <iostream.h>
#include "SBitmap.h"

// copy with scaling	
void SBitmap::scaleCopy( const Bitmap& b, int w, int h )
	{
	// check if scale factor=1
	if ( (b.width()==w) && (b.height()==h) )
		{
		copy( b );
		}
	else	{
		allocMem(w,h);
		
		if (Vimage!=NULL)
			{
			gl_scalebox( b.width(), b.height(), 
			             (unsigned char *)b.map(),
				     w, h, Vimage);
			}
		}
	}


// Simple rotate bitmap routine.
// Not optimized for speed. Use to create rotated versions of bitmaps
// at game initialization, not for on-the-fly rotation.
// width() and height() do not change, therefore.
// parts of the bitmap could be rotated 'out'.
void SBitmap::rot(Angle degrees)
	{
	
//	cout << "W:" << width() << " H:"<< height() <<" Size:" << size() << endl;
	unsigned char *buf = new unsigned char[size()];

	if (buf==NULL) 
		{
		cerr << "SBitmap::rot(), unable to allocated memory.\n";
		return;
		}

	int x,y,x1,y1;
	double xo,yo;
	unsigned char c;
	
	// middle of bitmap
	xo = (double)( width() >> 1  );
	yo = (double)( height() >> 1 );
	
	// loop through each pixel in new buffer, and rotate *backwards*
	// into the bitmap to see what color it should have.
	// This method avoids getting holes in the bitmap
	for(y=0; y<height(); y++)
		for(x=0; x<width(); x++)
			{
			x1 = (int) ( xo + ((double)x-xo)*FastMath::cos(-degrees) -
					  ((double)y-yo)*FastMath::sin(-degrees));

			y1 = (int) ( yo + ((double)x-xo)*FastMath::sin(-degrees) +
					  ((double)y-yo)*FastMath::cos(-degrees));


			if ( (x1<0) || (x1>=width()) ||
			     (y1<0) || (y1>=height()) )
			     	{
			     	c = 0;
			     	}
			else	{
				c = *(Vimage + offset( x1,y1 ) ); 
				}
				     	
			*(buf + offset((int)x, (int)y) ) = c;

			}
	// delete original- if we had allocated the mem ourselves
	if (VallocImage) delete [] Vimage;
	
	VallocImage = 1;

	// set bitmap to new rotated bitmap
	Vimage = buf;

	}

// compile bitmap to speed up the put() operation
void SBitmap::compile()
	{
	
	// bitmap was compiled previously
	if (VcompiledImage) 
		{
		delete [] VcompiledImage;
		VcompiledImage=NULL;
		}

	// can't compile if we ain't got no bitmap :-)
	if (Vimage==NULL) return;

	// determined the size of the compiled bitmap;
	int size = gl_compiledboxmasksize( Vwidth, Vheight, Vimage );
	
	VcompiledImage = new unsigned char[size];
	
	// determine if 'new' succeeded
	if (Vimage==NULL)
		{
		return;
		}

	gl_compileboxmask( Vwidth, Vheight, Vimage, VcompiledImage );	
	}
