#include "directgem.h"
#include "enum.h"
#include "loader.h"
#include "texturemenager.h"

gem_Material::gem_Material( gem_Scene* scene )
{
	pScene		= scene;

	texture1	= NULL;
	texture2	= NULL;
	envmap		= NULL;
}

gem_Material::gem_Material( TCHAR* textname, gem_Scene* scene )
{
	pScene		= scene;

	texture1	= new gem_Map( textname );
	texture2	= NULL;
	envmap		= NULL;
}

gem_Material::~gem_Material()
{
	if( texture1 )
		delete texture1;

	if( texture2 )
		delete texture2;

	if( envmap )
		delete envmap;
}

VOID gem_Material::SetMaterial( LPDIRECT3DDEVICE7 pd3dDevice )
{
	pd3dDevice->SetTexture( 0, GetTexture( texture1->name ) );
}

DWORD gem_Map::Load( FILE* inFile )	
{
	WORD						sign;
	LONG						size;
	LONG						pos;	
	
	size = ReadDword( inFile ) - IDLENGTH;
	pos = ftell( inFile );

	while( ( !feof( inFile ) ) && ftell( inFile )<size+pos )
	{
		sign=ReadWord( inFile );

		if( sign == GEMCHUNK_MAPFILENAME )
		{
			ReadDword( inFile );
			ReadASCIIZ( inFile, name );			
		}
		else
			if( JumpThroughtChunk( inFile )!=GEMERROR_OK )
				return GEMERROR_LOAD;
	}

	if( feof( inFile ) )
		return GEMERROR_LOAD;
	
	return GEMERROR_OK;
}


/*
 *  odczytuje informacje o materiale
 */
DWORD gem_Material::Load( FILE* inFile )
{
	WORD						sign;
	LONG						size;
	LONG						pos;
	TCHAR						name[80];

	size = ReadDword( inFile ) - IDLENGTH;
	pos = ftell( inFile );

	while( ( !feof( inFile ) ) && ftell( inFile )<size+pos )
	{
		sign = ReadWord( inFile );

		switch( sign )
		{
			case GEMCHUNK_MATERIALNAME:
				ReadDword( inFile );
				ReadASCIIZ( inFile, name );				
			break;

			case GEMCHUNK_TEXTURE1:
				texture1 = new gem_Map;
				if( texture1->Load( inFile )!=GEMERROR_OK )
					return GEMERROR_LOAD;
			break;			

			case GEMCHUNK_TEXTURE2:
				texture2 = new gem_Map;
				if( texture2->Load( inFile )!=GEMERROR_OK )
					return GEMERROR_LOAD;
			break;			
			
			default:
				if( JumpThroughtChunk( inFile )!=GEMERROR_OK )
					return GEMERROR_LOAD;
			break;
		}
	}

	if( feof( inFile ) )
		return GEMERROR_LOAD;

	pScene->MaterialList.AddItem( this, name );

	return GEMERROR_OK;
}
