/*
	Lan Wars.
	Copyright (c) 2009, Darragh Coy.
	All rights reserved.
	Original work(s), source code & author(s) details available at: http://www.darraghcoy.com

	Redistribution and use in source and binary forms, with or without modification, are permitted 
	provided that the following conditions are met:

		* 	Redistributions of source code must retain the above copyright notice, this list of 
			conditions and the following disclaimer.
		* 	Redistributions in binary form must reproduce the above copyright notice, this list of 
			conditions and the following disclaimer in the documentation.
		* 	Neither the name of the author nor the names of contributors may be used to endorse or 
			promote products derived from this software without specific prior written permission.
		* 	The use of any third party libraries, modules or data files provided with the source 
			form of the program must follow and respect the individual licensing terms of these 
			components. You do not have permission to modify or circumvent the licensing terms for 
			provided third party components unless the third party licenses specifically allow this. 
			If you do not agree to the terms of provided third party components then you do not have 
			permission to use them in your derived work(s).
		* 	The terms of this license do not apply to separate (but related) distributions if supplied 
			by the author(s), only to the contents of this source distribution, derived works, and the 
			binaries produced by either modified or unmodified versions of the source code. The terms 
			of this license do not also apply to any third party libraries or components provided with 
			the source distribution. Such third party elements are licensed under their own separate 
			agreements.

	THIS SOFTWARE IS PROVIDED BY DARRAGH COY ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, 
	BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
	ARE DISCLAIMED. IN NO EVENT SHALL DARRAGH COY BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
	EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 
	OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
	OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 
	IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

//=====================================================================================================================
/// @brief		Implementation of a bitmap font resource type.
/// @remarks	This is a template specialisation. Resource type implementions implement the resource type that 
///				is implicitly declared by the particular resource manager. For example a PixelShaderResourceManager
///				implicitly declares a resource type that stores pixel shaders and an implementation of this resource 
///				type (loading and freeing) must then be provided in source files.
//=====================================================================================================================

#include "Precompiled.h"
#include "Resources\BitmapFontManager.h"
#include "Resources\BitmapFontResourceData.h"
#include "Resources\TextureManager.h"
#include "Resources\PixelShaderManager.h"
#include "Resources\VertexShaderManager.h"
#include <TinyXML.h>

using namespace Game;

//=====================================================================================================================
/// @brief		Loads the bitmap font resource from the font description in the named xml file.
/// @pre		We should have a valid font manager 
/// @pre		The font manager should have a texture manager
/// @pre		The font manager should have a pixel shader manager
/// @pre		The font manager should have a vertex shader manager
//=====================================================================================================================

template<> void Resource<BitmapFontResourceData*>::LoadData()
{
	// Make sure ok in debug

	ENSURE( m_manager != 0 , "We should have a valid font manager" )
	
	// Convert our manager to a bitmap font manager:
	
	BitmapFontManager * manager = (BitmapFontManager*)(m_manager);
	
	// Make sure this is all ok:
	
	ENSURE( manager->GetTextureManager()		!= 0	, "The font manager should have a texture manager"			)
	ENSURE( manager->GetVertexShaderManager()	!= 0	, "The font manager should have a vertex shader manager"	)
	ENSURE( manager->GetPixelShaderManager()	!= 0	, "The font manager should have a pixel shader manager"		)
	
	// Need to make a new data block:
	
	m_data = new BitmapFontResourceData();

	// This may well fail:
	
	try
	{
		// Open a tiny xml document and load the font settings from that:
		
		TiXmlDocument xml_doc; xml_doc.LoadFile(GetName().c_str());
		
		// Try and get the root document element
		
		TiXmlElement * xml_root = xml_doc.RootElement();
		
		// See if there:
		
		if ( xml_root )
		{	
			// Store the name of the transform uniform variable here:
			
			std::string transform_uniform_name;
		
            // Load all the information for the font:

            for ( TiXmlNode * n = xml_root->FirstChild() ; n != 0 ; n = xml_root->IterateChildren(n) )
            {
				// Make sure this is an element type node:
				
				if ( n->Type() != TiXmlNode::ELEMENT ) continue;
				
				// Is an element: cast to one
				
				TiXmlElement * elem = (TiXmlElement*)(n);
				
				// If the element has no value (its name- shouldn't happen) then skip
				
				if ( elem->Value() == 0 ) continue;
            
                // See what node this is:

                if ( strcmp( elem->Value() , "CharMetric" ) == 0 )
                {
					// Get all the elements for this particular character metric
                
					const char * code	=	elem->Attribute("Code");
					const char * u		=	elem->Attribute("U");
					const char * v		=	elem->Attribute("V");
					const char * s		=	elem->Attribute("S");
					const char * t		=	elem->Attribute("T");
					
					// Make sure all the attributes are there:
					
					if ( code && u && v && s && t )
					{
						// Get the character code:
						
						int c = String::ToIntCritical(code);
						
						// Make sure it is in range: if not then throw an exception and bail
						
						if ( c < 0 || c > 255 ) throw 1;
					
						// Convert all of them and save:
						
						m_data->m_metrics[ c ].m_u = String::ToFloatCritical( u );
						m_data->m_metrics[ c ].m_v = String::ToFloatCritical( v );
						m_data->m_metrics[ c ].m_s = String::ToFloatCritical( s );
						m_data->m_metrics[ c ].m_t = String::ToFloatCritical( t );
					}
                }
                else if ( strcmp( elem->Value() , "FontTexture" ) == 0 )
                {
                    // See if inner text:
                    
                    if ( elem->GetText() )
                    {
						m_data->m_texture = manager->GetTextureManager()->GetTexture( elem->GetText() );
					}					
                }
                else if ( strcmp( elem->Value() , "FontPixelShader" ) == 0 )
                {
                    // See if inner text:
                    
                    if ( elem->GetText() )
                    {
						m_data->m_settings.m_pixel_shader = manager->GetPixelShaderManager()->GetPixelShader( elem->GetText() );
					}					
                }
                else if ( strcmp( elem->Value() , "FontVertexShader" ) == 0 )
                {
                    // See if inner text:
                    
                    if ( elem->GetText() )
                    {
						m_data->m_settings.m_vertex_shader = manager->GetVertexShaderManager()->GetVertexShader( elem->GetText() );
					}					
                }                                
                else if ( strcmp( elem->Value() , "FontSize" ) == 0 )
                {
                    // See if inner text: if so then try and convert it to a string
                    
                    if ( elem->GetText() )
                    {
						m_data->m_settings.m_size = String::ToFloatCritical(elem->GetText());
					}
				}
                else if ( strcmp( elem->Value() , "FontCharSpacing" ) == 0 )
                {                    
                    // See if inner text: if so then try and convert it to a string
                    
                    if ( elem->GetText() )
                    {
						m_data->m_settings.m_char_spacing = String::ToFloatCritical(elem->GetText());
					}              
                }
                else if ( strcmp( elem->Value() , "FontLineSpacing" ) == 0 )
                {                    
                    // See if inner text: if so then try and convert it to a string
                    
                    if ( elem->GetText() )
                    {
						m_data->m_settings.m_line_spacing = String::ToFloatCritical(elem->GetText());
					}                    
                }
                else if ( strcmp( elem->Value() , "FontColorR" ) == 0 )
                {
                    // See if inner text: if so then try and convert it to a string
                    
                    if ( elem->GetText() )
                    {
						m_data->m_settings.m_color.r = String::ToFloatCritical(elem->GetText());
					}                  
                }
                else if ( strcmp( elem->Value() , "FontColorG" ) == 0 )
                {
                    // See if inner text: if so then try and convert it to a string
                    
                    if ( elem->GetText() )
                    {
						m_data->m_settings.m_color.g = String::ToFloatCritical(elem->GetText());
					}
                }
                else if ( strcmp( elem->Value() , "FontColorB" ) == 0 )
                {
                    // See if inner text: if so then try and convert it to a string
                    
                    if ( elem->GetText() )
                    {
						m_data->m_settings.m_color.b = String::ToFloatCritical(elem->GetText());
					}
                }
                else if ( strcmp( elem->Value() , "FontColorA" ) == 0 )
                {
                    // See if inner text: if so then try and convert it to a string
                    
                    if ( elem->GetText() )
                    {
						m_data->m_settings.m_color.a = String::ToFloatCritical(elem->GetText());
					}
                }
                else if ( strcmp( elem->Value() , "WhiteSpacePercentWidth" ) == 0 )
                {
                    // See if inner text: if so then try and convert it to a string
                    
                    if ( elem->GetText() )
                    {
						m_data->m_settings.m_whitespace_width_pc = String::ToFloatCritical(elem->GetText());
					}
                }
                else if ( strcmp( elem->Value() , "ShaderTransformUniformVariable" ) == 0 )
                {
                    // See if inner text: if so then try and convert it to a string
                    
                    if ( elem->GetText() )
                    {
						transform_uniform_name = elem->GetText();
					}
                }                                                 
                
			}	// end for each document child node
                
			// If any of our data elements are invalid then mark the entire font as invalid and don't use:
			
			if ( m_data->m_texture.IsValid()					== false ) throw 1;	
			if ( m_data->m_settings.m_pixel_shader.IsValid()	== false ) throw 1;
			if ( m_data->m_settings.m_vertex_shader.IsValid()	== false ) throw 1;
			
			// See if we have a valid transform uniform variable:
			
			if ( transform_uniform_name.size() > 0 )
			{
				// Ok: try and get the uniform from the shader
				
				m_data->m_settings.m_u_transform = m_data->m_settings.m_vertex_shader.GetUniform(transform_uniform_name.c_str());
				
				// See if valid:
				
				if ( m_data->m_settings.m_u_transform.IsValid() == false ) throw 1;
			}
			else
			{
				// No transform uniform: throw an exception
				
				throw 1;
			}
			
			// Otherwise we're ok:
			
			m_is_valid = true;
		}
		else
		{
			// Throw an exception: document has no data
			
			throw 1;
		}
	}
	catch ( ... )
	{
		// Delete our data:
		
		delete m_data;
		
		// We are no longer valid:
		
		m_is_valid = false;
	}
}

//=====================================================================================================================
/// @brief		Frees the bitmap font resource if loaded correctly
//=====================================================================================================================

template<> void Resource<BitmapFontResourceData*>::FreeData()
{	
	// See if valid:
	
	if ( m_is_valid )
	{
		// Free our data:
		
		delete m_data;
	}	
}

