code:
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011      Zynga Inc.

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

Use any of these editors to generate BMFonts:
http://glyphdesigner.71squared.com/ (Commercial, Mac OS X)
http://www.n4te.com/hiero/hiero.jnlp (Free, Java)
http://slick.cokeandcode.com/demos/hiero.jnlp (Free, Java)
http://www.angelcode.com/products/bmfont/ (Free, Windows only)

****************************************************************************/
#include "CCLabelBMFont.h"

#include "platform/platform.h"
#include "CCMutableDictionary.h"
#include "CCConfiguration.h"
#include "CCDrawingPrimitives.h"
#include "CCSprite.h"
#include "CCPointExtension.h"

#include "CCFileUtils.h"
#include "support/data_support/uthash.h"
namespace cocos2d{

    static int cc_wcslen(const unsigned short* str)
    {
        int i=0;
        while(*str++) i++;
        return i;
    }

    /* Code from GLIB gutf8.c starts here. */

    #define UTF8_COMPUTE(Char, Mask, Len)		\
      if (Char < 128)				\
        {						\
          Len = 1;					\
          Mask = 0x7f;				\
        }						\
      else if ((Char & 0xe0) == 0xc0)		\
        {						\
          Len = 2;					\
          Mask = 0x1f;				\
        }						\
      else if ((Char & 0xf0) == 0xe0)		\
        {						\
          Len = 3;					\
          Mask = 0x0f;				\
        }						\
      else if ((Char & 0xf8) == 0xf0)		\
        {						\
          Len = 4;					\
          Mask = 0x07;				\
        }						\
      else if ((Char & 0xfc) == 0xf8)		\
        {						\
          Len = 5;					\
          Mask = 0x03;				\
        }						\
      else if ((Char & 0xfe) == 0xfc)		\
        {						\
          Len = 6;					\
          Mask = 0x01;				\
        }						\
      else						\
        Len = -1;

    #define UTF8_LENGTH(Char)			\
      ((Char) < 0x80 ? 1 :				\
       ((Char) < 0x800 ? 2 :			\
        ((Char) < 0x10000 ? 3 :			\
         ((Char) < 0x200000 ? 4 :			\
          ((Char) < 0x4000000 ? 5 : 6)))))

    #define UTF8_GET(Result, Chars, Count, Mask, Len)	\
      (Result) = (Chars)[0] & (Mask);			\
      for ((Count) = 1; (Count) < (Len); ++(Count))		\
        {							\
          if (((Chars)[(Count)] & 0xc0) != 0x80)		\
	    {						\
	      (Result) = -1;				\
	      break;					\
	    }						\
          (Result) <<= 6;					\
          (Result) |= ((Chars)[(Count)] & 0x3f);		\
        }

    #define UNICODE_VALID(Char)			\
      ((Char) < 0x110000 &&				\
       (((Char) & 0xFFFFF800) != 0xD800) &&		\
       ((Char) < 0xFDD0 || (Char) > 0xFDEF) &&	\
       ((Char) & 0xFFFE) != 0xFFFE)

    static const char utf8_skip_data[256] = {
      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
      1, 1, 1, 1, 1, 1, 1,
      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
      1, 1, 1, 1, 1, 1, 1,
      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
      1, 1, 1, 1, 1, 1, 1,
      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
      1, 1, 1, 1, 1, 1, 1,
      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
      1, 1, 1, 1, 1, 1, 1,
      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
      1, 1, 1, 1, 1, 1, 1,
      2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
      2, 2, 2, 2, 2, 2, 2,
      3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5,
      5, 5, 5, 6, 6, 1, 1
    };

    static const char *const g_utf8_skip = utf8_skip_data;

    #define cc_utf8_next_char(p) (char *)((p) + g_utf8_skip[*(unsigned char *)(p)])

	/*
	 * @str:	the string to search through.
	 * @c:		the character to find.
	 *
	 * Returns the index of the first occurrence of the character, if found.  Otherwise -1 is returned.
	 *
	 * Return value: the index of the first occurrence of the character if found or -1 otherwise.
	 * */
	static unsigned int cc_utf8_find_char(std::vector<unsigned short> str, unsigned short c)
	{
		unsigned int len = str.size();

		for (unsigned int i = 0; i < len; ++i)
			if (str[i] == c) return i;

		return -1;
	}

	/*
	 * @str:	the string to search through.
	 * @c:		the character to not look for.
	 *
	 * Return value: the index of the last character that is not c.
	 * */
	static unsigned int cc_utf8_find_last_not_char(std::vector<unsigned short> str, unsigned short c)
	{
		int len = str.size();

		int i = len - 1;
		for (; i >= 0; --i)
			if (str[i] != c) return i;

		return i;
	}

	/*
	 * @str:	the string to trim
	 * @index:	the index to start trimming from.
	 *
	 * Trims str st str=[0, index) after the operation.
	 *
	 * Return value: the trimmed string.
	 * */
	static void cc_utf8_trim_from(std::vector<unsigned short>* str, int index)
	{
		int size = str->size();
		if (index >= size || index < 0)
			return;

		str->erase(str->begin() + index, str->begin() + size);
	}

	/*
	 * @ch is the unicode character whitespace?
	 *
	 * Reference: http://en.wikipedia.org/wiki/Whitespace_character#Unicode
	 *
	 * Return value: weather the character is a whitespace character.
	 * */
	static bool isspace_unicode(unsigned short ch)
	{
		return  ch >= 0x0009 && ch <= 0x000D || ch == 0x0020 || ch == 0x0085 || ch == 0x00A0 || ch == 0x1680
			|| (ch >= 0x2000 && ch <= 0x200A) || ch == 0x2028 || ch == 0x2029 || ch == 0x202F
			||  ch == 0x205F || ch == 0x3000;
	}

	static void cc_utf8_trim_ws(std::vector<unsigned short>* str)
	{
		using namespace std;
		int len = str->size();

		if ( len <= 0 )
			return;

		int last_index = len - 1;

		// Only start trimming if the last character is whitespace..
		if (isspace_unicode((*str)[last_index]))
		{
			for (int i = last_index - 1; i >= 0; --i)
			{
				if (isspace_unicode((*str)[i]))
					last_index = i;
				else
					break;
			}

			cc_utf8_trim_from(str, last_index);
		}
	}

    /*
     * g_utf8_strlen:
     * @p: pointer to the start of a UTF-8 encoded string.
     * @max: the maximum number of bytes to examine. If @max
     *       is less than 0, then the string is assumed to be
     *       null-terminated. If @max is 0, @p will not be examined and
     *       may be %NULL.
     *
     * Returns the length of the string in characters.
     *
     * Return value: the length of the string in characters
     **/
    static long
    cc_utf8_strlen (const char * p, int max)
    {
      long len = 0;
      const char *start = p;

      if (!(p != NULL || max == 0))
      {
          return 0;
      }

      if (max < 0)
        {
          while (*p)
	    {
	      p = cc_utf8_next_char (p);
	      ++len;
	    }
        }
      else
        {
          if (max == 0 || !*p)
	    return 0;

          p = cc_utf8_next_char (p);

          while (p - start < max && *p)
	    {
	      ++len;
	      p = cc_utf8_next_char (p);
	    }

          /* only do the last len increment if we got a complete
           * char (don't count partial chars)
           */
          if (p - start == max)
	    ++len;
        }

      return len;
    }

    /*
     * g_utf8_get_char:
     * @p: a pointer to Unicode character encoded as UTF-8
     *
     * Converts a sequence of bytes encoded as UTF-8 to a Unicode character.
     * If @p does not point to a valid UTF-8 encoded character, results are
     * undefined. If you are not sure that the bytes are complete
     * valid Unicode characters, you should use g_utf8_get_char_validated()
     * instead.
     *
     * Return value: the resulting character
     **/
    static unsigned int
    cc_utf8_get_char (const char * p)
    {
      int i, mask = 0, len;
      unsigned int result;
      unsigned char c = (unsigned char) *p;

      UTF8_COMPUTE (c, mask, len);
      if (len == -1)
        return (unsigned int) - 1;
      UTF8_GET (result, p, i, mask, len);

      return result;
    }

	/*
	 * cc_utf8_from_cstr:
	 * @str_old: pointer to the start of a C string.
	 *
	 * Creates a utf8 string from a cstring.
	 *
	 * Return value: the newly created utf8 string.
	 * */
	static unsigned short* cc_utf8_from_cstr(const char* str_old)
	{
		int len = cc_utf8_strlen(str_old, -1);

		unsigned short* str_new = new unsigned short[len + 1];
		str_new[len] = 0;

		for (int i = 0; i < len; ++i)
		{
			str_new[i] = cc_utf8_get_char(str_old);
			str_old = cc_utf8_next_char(str_old);
		}

		return str_new;
	}

	static std::vector<unsigned short> cc_utf8_vec_from_cstr(const unsigned short* str)
	{
		int len = cc_wcslen(str);
		std::vector<unsigned short> str_new;

		for (int i = 0; i < len; ++i)
			str_new.push_back(str[i]);

		return str_new;
	}

	//
	//FNTConfig Cache - free functions
	//
	CCMutableDictionary<std::string, CCBMFontConfiguration*> *configurations = NULL;
	CCBMFontConfiguration* FNTConfigLoadFile( const char *fntFile)
	{
		CCBMFontConfiguration *pRet = NULL;

		if( configurations == NULL )
		{
			configurations = new CCMutableDictionary<std::string, CCBMFontConfiguration*>();
		}
		std::string key(fntFile);
		pRet = configurations->objectForKey(key);
		if( pRet == NULL )
		{
			pRet = CCBMFontConfiguration::configurationWithFNTFile(fntFile);
			configurations->setObject(pRet, key);
		}

		return pRet;
	}

	void FNTConfigRemoveCache( void )
	{
		if (configurations)
		{
			configurations->removeAllObjects();
			CC_SAFE_RELEASE_NULL(configurations);
		}
	}

	//
	//Hash Element
	//
	// Equal function for targetSet.
	typedef struct _KerningHashElement
	{
		int				key;		// key for the hash. 16-bit for 1st element, 16-bit for 2nd element
		int				amount;
		UT_hash_handle	hh;
	} tKerningHashElement;
	//
	//BitmapFontConfiguration
	//

	CCBMFontConfiguration * CCBMFontConfiguration::configurationWithFNTFile(const char *FNTfile)
	{
		CCBMFontConfiguration * pRet = new CCBMFontConfiguration();
		if (pRet->initWithFNTfile(FNTfile))
		{
			pRet->autorelease();
			return pRet;
		}
		CC_SAFE_DELETE(pRet);
		return NULL;
	}

	bool CCBMFontConfiguration::initWithFNTfile(const char *FNTfile)
	{
		CCAssert(FNTfile != NULL && strlen(FNTfile)!=0, "");
		m_pKerningDictionary = NULL;
		this->parseConfigFile(FNTfile);
		return true;
	}

	CCBMFontConfiguration::CCBMFontConfiguration()
		: m_pBitmapFontArray(new std::map<unsigned int, ccBMFontDef>)
		, m_uCommonHeight(0)
		, m_pKerningDictionary(NULL)
	{

	}

	CCBMFontConfiguration::~CCBMFontConfiguration()
	{
		CCLOGINFO( "cocos2d: deallocing CCBMFontConfiguration" );
		CC_SAFE_DELETE(m_pBitmapFontArray);
		this->purgeKerningDictionary();
		m_sAtlasName.clear();
	}

	char * CCBMFontConfiguration::description(void)
	{
		char *ret = new char[100];
		sprintf(ret, "<CCBMFontConfiguration | Kernings:%d | Image = %s>", HASH_COUNT(m_pKerningDictionary), m_sAtlasName.c_str());
		return ret;
	}

	void CCBMFontConfiguration::purgeKerningDictionary()
	{
		tKerningHashElement *current;
		while(m_pKerningDictionary)
		{
			current = m_pKerningDictionary;
			HASH_DEL(m_pKerningDictionary,current);
			free(current);
		}
	}

	void CCBMFontConfiguration::parseConfigFile(const char *controlFile)
	{
		std::string fullpath = CCFileUtils::fullPathFromRelativePath(controlFile);

		CCFileData data(fullpath.c_str(), "rb");
		unsigned long nBufSize = data.getSize();
		char* pBuffer = (char*) data.getBuffer();

		CCAssert(pBuffer, "CCBMFontConfiguration::parseConfigFile | Open file error.");

		if (!pBuffer)
		{
			return;
		}

		// parse spacing / padding
		std::string line;
		std::string strLeft(pBuffer, nBufSize);
		while (strLeft.length() > 0)
		{
			int pos = strLeft.find('\n');

			if (pos != (int)std::string::npos)
			{
				// the data is more than a line.get one line
				line = strLeft.substr(0, pos);
				strLeft = strLeft.substr(pos + 1);
			}
			else
			{
				// get the left data
				line = strLeft;
				strLeft.erase();
			}

			if(line.substr(0,strlen("info face")) == "info face")
			{
				// XXX: info parsing is incomplete
				// Not needed for the Hiero editors, but needed for the AngelCode editor
				//			[self parseInfoArguments:line];
				this->parseInfoArguments(line);
			}
			// Check to see if the start of the line is something we are interested in
			else if(line.substr(0,strlen("common lineHeight")) == "common lineHeight")
			{
				this->parseCommonArguments(line);
			}
			else if(line.substr(0,strlen("page id")) == "page id")
			{
				this->parseImageFileName(line, controlFile);
			}
			else if(line.substr(0,strlen("chars c")) == "chars c")
			{
				// Ignore this line
			}
			else if(line.substr(0,strlen("char")) == "char")
			{
				// Parse the current line and create a new CharDef
				ccBMFontDef characterDefinition;
				this->parseCharacterDefinition(line, &characterDefinition);

				// Add the CharDef returned to the charArray
				(*m_pBitmapFontArray)[ characterDefinition.charID ] = characterDefinition;
			}
			else if(line.substr(0,strlen("kernings count")) == "kernings count")
			{
				this->parseKerningCapacity(line);
			}
			else if(line.substr(0,strlen("kerning first")) == "kerning first")
			{
				this->parseKerningEntry(line);
			}
		}
	}

	void CCBMFontConfiguration::parseImageFileName(std::string line, const char *fntFile)
	{
		//////////////////////////////////////////////////////////////////////////
		// line to parse:
		// page id=0 file="bitmapFontTest.png"
		//////////////////////////////////////////////////////////////////////////

		// page ID. Sanity check
		int index = line.find('=')+1;
		int index2 = line.find(' ', index);
		std::string value = line.substr(index, index2-index);
		CCAssert(atoi(value.c_str()) == 0, "LabelBMFont file could not be found");
		// file
		index = line.find('"')+1;
		index2 = line.find('"', index);
		value = line.substr(index, index2-index);

		m_sAtlasName = CCFileUtils::fullPathFromRelativeFile(value.c_str(), fntFile);
	}

	void CCBMFontConfiguration::parseInfoArguments(std::string line)
	{
		//////////////////////////////////////////////////////////////////////////
		// possible lines to parse:
		// info face="Script" size=32 bold=0 italic=0 charset="" unicode=1 stretchH=100 smooth=1 aa=1 padding=1,4,3,2 spacing=0,0 outline=0
		// info face="Cracked" size=36 bold=0 italic=0 charset="" unicode=0 stretchH=100 smooth=1 aa=1 padding=0,0,0,0 spacing=1,1
		//////////////////////////////////////////////////////////////////////////

		// padding
		int index = line.find("padding=");
		int index2 = line.find(' ', index);
		std::string value = line.substr(index, index2-index);
		sscanf(value.c_str(), "padding=%d,%d,%d,%d", &m_tPadding.top, &m_tPadding.right, &m_tPadding.bottom, &m_tPadding.left);
		CCLOG("cocos2d: padding: %d,%d,%d,%d", m_tPadding.left, m_tPadding.top, m_tPadding.right, m_tPadding.bottom);
	}

	void CCBMFontConfiguration::parseCommonArguments(std::string line)
	{
		//////////////////////////////////////////////////////////////////////////
		// line to parse:
		// common lineHeight=104 base=26 scaleW=1024 scaleH=512 pages=1 packed=0
		//////////////////////////////////////////////////////////////////////////

		// Height
		int index = line.find("lineHeight=");
		int index2 = line.find(' ', index);
		std::string value = line.substr(index, index2-index);
		sscanf(value.c_str(), "lineHeight=%u", &m_uCommonHeight);
		// scaleW. sanity check
		index = line.find("scaleW=") + strlen("scaleW=");
		index2 = line.find(' ', index);
		value = line.substr(index, index2-index);
		CCAssert(atoi(value.c_str()) <= CCConfiguration::sharedConfiguration()->getMaxTextureSize(), "CCLabelBMFont: page can't be larger than supported");
		// scaleH. sanity check
		index = line.find("scaleH=") + strlen("scaleH=");
		index2 = line.find(' ', index);
		value = line.substr(index, index2-index);
		CCAssert(atoi(value.c_str()) <= CCConfiguration::sharedConfiguration()->getMaxTextureSize(), "CCLabelBMFont: page can't be larger than supported");
		// pages. sanity check
		index = line.find("pages=") + strlen("pages=");
		index2 = line.find(' ', index);
		value = line.substr(index, index2-index);
		CCAssert(atoi(value.c_str()) == 1, "CCBitfontAtlas: only supports 1 page");

		// packed (ignore) What does this mean ??
	}

	void CCBMFontConfiguration::parseCharacterDefinition(std::string line, ccBMFontDef *characterDefinition)
	{
		//////////////////////////////////////////////////////////////////////////
		// line to parse:
		// char id=32   x=0     y=0     width=0     height=0     xoffset=0     yoffset=44    xadvance=14     page=0  chnl=0
		//////////////////////////////////////////////////////////////////////////

		// Character ID
		int index = line.find("id=");
		int index2 = line.find(' ', index);
		std::string value = line.substr(index, index2-index);
		sscanf(value.c_str(), "id=%u", &characterDefinition->charID);

		// Character x
		index = line.find("x=");
		index2 = line.find(' ', index);
		value = line.substr(index, index2-index);
		sscanf(value.c_str(), "x=%f", &characterDefinition->rect.origin.x);
		// Character y
		index = line.find("y=");
		index2 = line.find(' ', index);
		value = line.substr(index, index2-index);
		sscanf(value.c_str(), "y=%f", &characterDefinition->rect.origin.y);
		// Character width
		index = line.find("width=");
		index2 = line.find(' ', index);
		value = line.substr(index, index2-index);
		sscanf(value.c_str(), "width=%f", &characterDefinition->rect.size.width);
		// Character height
		index = line.find("height=");
		index2 = line.find(' ', index);
		value = line.substr(index, index2-index);
		sscanf(value.c_str(), "height=%f", &characterDefinition->rect.size.height);
		// Character xoffset
		index = line.find("xoffset=");
		index2 = line.find(' ', index);
		value = line.substr(index, index2-index);
		sscanf(value.c_str(), "xoffset=%d", &characterDefinition->xOffset);
		// Character yoffset
		index = line.find("yoffset=");
		index2 = line.find(' ', index);
		value = line.substr(index, index2-index);
		sscanf(value.c_str(), "yoffset=%d", &characterDefinition->yOffset);
		// Character xadvance
		index = line.find("xadvance=");
		index2 = line.find(' ', index);
		value = line.substr(index, index2-index);
		sscanf(value.c_str(), "xadvance=%d", &characterDefinition->xAdvance);
	}

	void CCBMFontConfiguration::parseKerningCapacity(std::string line)
	{
		// When using uthash there is not need to parse the capacity.

		//	CCAssert(!kerningDictionary, @"dictionary already initialized");
		//
		//	// Break the values for this line up using =
		//	CCMutableArray *values = [line componentsSeparatedByString:@"="];
		//	NSEnumerator *nse = [values objectEnumerator];
		//	CCString *propertyValue;
		//
		//	// We need to move past the first entry in the array before we start assigning values
		//	[nse nextObject];
		//
		//	// count
		//	propertyValue = [nse nextObject];
		//	int capacity = [propertyValue intValue];
		//
		//	if( capacity != -1 )
		//		kerningDictionary = ccHashSetNew(capacity, targetSetEql);
	}

	void CCBMFontConfiguration::parseKerningEntry(std::string line)
	{
		//////////////////////////////////////////////////////////////////////////
		// line to parse:
		// kerning first=121  second=44  amount=-7
		//////////////////////////////////////////////////////////////////////////

		// first
		int first;
		int index = line.find("first=");
		int index2 = line.find(' ', index);
		std::string value = line.substr(index, index2-index);
		sscanf(value.c_str(), "first=%d", &first);

		// second
		int second;
		index = line.find("second=");
		index2 = line.find(' ', index);
		value = line.substr(index, index2-index);
		sscanf(value.c_str(), "second=%d", &second);

		// amount
		int amount;
		index = line.find("amount=");
		index2 = line.find(' ', index);
		value = line.substr(index, index2-index);
		sscanf(value.c_str(), "amount=%d", &amount);

		tKerningHashElement *element = (tKerningHashElement *)calloc( sizeof( *element ), 1 );
		element->amount = amount;
		element->key = (first<<16) | (second&0xffff);
		HASH_ADD_INT(m_pKerningDictionary,key, element);
	}
	//
	//CCLabelBMFont
	//

	//LabelBMFont - Purge Cache
	void CCLabelBMFont::purgeCachedData()
	{
		FNTConfigRemoveCache();
	}

	//LabelBMFont - Creation & Init
	CCLabelBMFont *CCLabelBMFont::labelWithString(const char *str, const char *fntFile)
	{
		return labelWithString(str, fntFile, CCTextAlignmentLeft, 0);
	}

	//LabelBMFont - Creation & Init
	CCLabelBMFont *CCLabelBMFont::labelWithString(const char *str, const char *fntFile, CCTextAlignment alignment
		, float width)
	{
		CCLabelBMFont *pRet = new CCLabelBMFont();
		if(pRet && pRet->initWithString(str, fntFile, alignment, width))
		{
			pRet->autorelease();
			return pRet;
		}
		CC_SAFE_DELETE(pRet)
			return NULL;
	}

	bool CCLabelBMFont::initWithString(const char *theString, const char *fntFile)
	{
		return initWithString(theString, fntFile, CCTextAlignmentCenter, 0);
	}

	bool CCLabelBMFont::initWithString(const char *theString, const char *fntFile, CCTextAlignment alignment
		, float width)
	{
		CCAssert(theString != NULL, "");
		CC_SAFE_RELEASE(m_pConfiguration);// allow re-init
		m_pConfiguration = FNTConfigLoadFile(fntFile);
		m_pConfiguration->retain();
		CCAssert( m_pConfiguration, "Error creating config for LabelBMFont");

		if (CCSpriteBatchNode::initWithFile(m_pConfiguration->m_sAtlasName.c_str(), strlen(theString)))
		{
			m_pAlignment = alignment;
			m_fWidth = width;
			m_sString = cc_utf8_from_cstr(theString);
			m_cOpacity = 255;
			m_tColor = ccWHITE;
			m_tContentSize = CCSizeZero;
			m_bIsOpacityModifyRGB = m_pobTextureAtlas->getTexture()->getHasPremultipliedAlpha();
			this->setString(theString);
			setAnchorPoint(ccp(0.5f, 0.5f));
			return true;
		}
		return false;
	}

	CCLabelBMFont::~CCLabelBMFont()
	{
		CC_SAFE_DELETE(m_sString);
		CC_SAFE_RELEASE(m_pConfiguration);
	}

	// LabelBMFont - Atlas generation
	int CCLabelBMFont::kerningAmountForFirst(unsigned short first, unsigned short second)
	{
		int ret = 0;
		unsigned int key = (first<<16) | (second & 0xffff);

		if( m_pConfiguration->m_pKerningDictionary ) {
			tKerningHashElement *element = NULL;
			HASH_FIND_INT(m_pConfiguration->m_pKerningDictionary, &key, element);
			if(element)
				ret = element->amount;
		}
		return ret;
	}

	void CCLabelBMFont::createFontChars()
	{
		int nextFontPositionX = 0;
        int nextFontPositionY = 0;
		unsigned short prev = -1;
		int kerningAmount = 0;

		CCSize tmpSize = CCSizeZero;

        int longestLine = 0;
        unsigned int totalHeight = 0;

        unsigned int quantityOfLines = 1;

		unsigned int stringLen = cc_wcslen(m_sString);
		if (stringLen == 0)
		{
			return;
		}

        for (unsigned int i = 0; i < stringLen - 1; ++i)
        {
            unsigned short c = m_sString[i];
            if (c == '\n')
            {
                quantityOfLines++;
            }
        }

        totalHeight = m_pConfiguration->m_uCommonHeight * quantityOfLines;
        nextFontPositionY = -(m_pConfiguration->m_uCommonHeight - m_pConfiguration->m_uCommonHeight * quantityOfLines);

		for (unsigned int i= 0; i < stringLen; i++)
		{
			unsigned short c = m_sString[i];

            if (c == '\n')
            {
                nextFontPositionX = 0;
                nextFontPositionY -= m_pConfiguration->m_uCommonHeight;
                continue;
            }

            std::map<unsigned int, ccBMFontDef>::iterator it = m_pConfiguration->m_pBitmapFontArray->find(c);
            CCAssert(it != m_pConfiguration->m_pBitmapFontArray->end(), "LabelBMFont: character is not supported");

			kerningAmount = this->kerningAmountForFirst(prev, c);

			const ccBMFontDef& fontDef = (*(m_pConfiguration->m_pBitmapFontArray))[c];

			CCRect rect = fontDef.rect;

			CCSprite *fontChar;

			fontChar = (CCSprite*)(this->getChildByTag(i));
			if( ! fontChar )
			{
				fontChar = new CCSprite();
				fontChar->initWithBatchNodeRectInPixels(this, rect);
				this->addChild(fontChar, 0, i);
				fontChar->release();
			}
			else
			{
				// reusing fonts
				fontChar->setTextureRectInPixels(rect, false, rect.size);

				// restore to default in case they were modified
				fontChar->setIsVisible(true);
				fontChar->setOpacity(255);
			}

            float yOffset = (float)(m_pConfiguration->m_uCommonHeight) - fontDef.yOffset;
			fontChar->setPositionInPixels( ccp( nextFontPositionX + fontDef.xOffset + fontDef.rect.size.width / 2.0f + kerningAmount,
				                                (float) nextFontPositionY + yOffset - rect.size.height/2.0f ) );

			//		NSLog(@"position.y: %f", fontChar.position.y);

			// update kerning
			nextFontPositionX += (*(m_pConfiguration->m_pBitmapFontArray))[c].xAdvance + kerningAmount;
			prev = c;

			// Apply label properties
			fontChar->setIsOpacityModifyRGB(m_bIsOpacityModifyRGB);
			// Color MUST be set before opacity, since opacity might change color if OpacityModifyRGB is on
			fontChar->setColor(m_tColor);

			// only apply opaccity if it is different than 255 )
			// to prevent modifying the color too (issue #610)
			if( m_cOpacity != 255 )
			{
				fontChar->setOpacity(m_cOpacity);
			}

            if (longestLine < nextFontPositionX)
            {
                longestLine = nextFontPositionX;
            }
		}

        tmpSize.width  = (float) longestLine;
        tmpSize.height = (float) totalHeight;

		this->setContentSizeInPixels(tmpSize);
	}

	//LabelBMFont - CCLabelProtocol protocol
	void CCLabelBMFont::setString(const char *newString)
	{
		this->setString(newString, false);
	}

	void CCLabelBMFont::setString(const char *newString, bool fromUpdate)
	{
		if (fromUpdate)
		{
			m_sString = cc_utf8_from_cstr(newString);
		}
		else
		{
			m_sString_initial = std::string(newString);
		}

		updateString(fromUpdate);
	}

	void CCLabelBMFont::updateString(bool fromUpdate)
	{

		if (m_pChildren && m_pChildren->count() != 0)
		{
			CCObject* child;
			CCARRAY_FOREACH(m_pChildren, child)
			{
				CCNode* pNode = (CCNode*) child;
				if (pNode)
				{
					pNode->setIsVisible(false);
				}
			}
		}
		this->createFontChars();

		if (!fromUpdate)
			updateLabel();
	}

	const char* CCLabelBMFont::getString(void)
	{
		return m_sString_initial.c_str();
	}

    void CCLabelBMFont::setCString(const char *label)
    {
        setString(label);
    }

	//LabelBMFont - CCRGBAProtocol protocol
	void CCLabelBMFont::setColor(const ccColor3B& var)
	{
		m_tColor = var;
		if (m_pChildren && m_pChildren->count() != 0)
		{
            CCObject* child;
            CCARRAY_FOREACH(m_pChildren, child)
            {
                CCSprite* pNode = (CCSprite*) child;
                if (pNode)
                {
                    pNode->setColor(m_tColor);
                }
            }
		}
	}
	const ccColor3B& CCLabelBMFont::getColor()
	{
		return m_tColor;
	}
	void CCLabelBMFont::setOpacity(GLubyte var)
	{
		m_cOpacity = var;

		if (m_pChildren && m_pChildren->count() != 0)
		{
            CCObject* child;
            CCARRAY_FOREACH(m_pChildren, child)
            {
                CCNode* pNode = (CCNode*) child;
                if (pNode)
                {
                    CCRGBAProtocol *pRGBAProtocol = dynamic_cast<CCRGBAProtocol*>(pNode);
                    if (pRGBAProtocol)
                    {
                        pRGBAProtocol->setOpacity(m_cOpacity);
                    }
                }
            }
		}
	}
	GLubyte CCLabelBMFont::getOpacity()
	{
		return m_cOpacity;
	}
	void CCLabelBMFont::setIsOpacityModifyRGB(bool var)
	{
		m_bIsOpacityModifyRGB = var;
		if (m_pChildren && m_pChildren->count() != 0)
		{
            CCObject* child;
            CCARRAY_FOREACH(m_pChildren, child)
            {
                CCNode* pNode = (CCNode*) child;
                if (pNode)
                {
                    CCRGBAProtocol *pRGBAProtocol = dynamic_cast<CCRGBAProtocol*>(pNode);
                    if (pRGBAProtocol)
                    {
                        pRGBAProtocol->setIsOpacityModifyRGB(m_bIsOpacityModifyRGB);
                    }
                }
            }
		}
	}
	bool CCLabelBMFont::getIsOpacityModifyRGB()
	{
		return m_bIsOpacityModifyRGB;
	}

	// LabelBMFont - AnchorPoint
	void CCLabelBMFont::setAnchorPoint(const CCPoint& point)
	{
		if( ! CCPoint::CCPointEqualToPoint(point, m_tAnchorPoint) )
		{
			CCSpriteBatchNode::setAnchorPoint(point);
			updateLabel();
		}
	}

	// LabelBMFont - Alignment
	void CCLabelBMFont::updateLabel()
	{
		using namespace std;

		this->setString(m_sString_initial.c_str(), true);

		if (m_fWidth > 0)
		{
			// Step 1: Make multiline
			vector<unsigned short> str_whole = cc_utf8_vec_from_cstr(m_sString);
			unsigned int stringLength = str_whole.size();
			vector<unsigned short> multiline_string;
			vector<unsigned short> last_word;
			int line = 1, i = 0;
			bool start_line = false, start_word = false;
			float startOfLine = -1, startOfWord = -1;
			int skip = 0;

			CCArray* children = getChildren();
			for (unsigned int j = 0; j < children->count(); j++)
			{
				CCSprite* characterSprite;

				while (!(characterSprite = (CCSprite*)this->getChildByTag(j + skip)))
					skip++;

				if (!characterSprite->getIsVisible()) continue;

				if (i >= stringLength || i < 0)
					break;

				unsigned short character = str_whole[i];

				if (!start_word)
				{
					startOfWord = characterSprite->getPosition().x - characterSprite->getContentSize().width/2.0f;
					start_word = true;
				}
				if (!start_line)
				{
					startOfLine = startOfWord;
					start_line = true;
				}

				// Newline.
				if (character == '\n')
				{
					cc_utf8_trim_ws(&last_word);

// 					int found = cc_utf8_find_char(last_word, ' ');
// 					if (found != -1)
// 						cc_utf8_trim_from(&last_word, found + 1);

					multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end());
					last_word.clear();
					start_word = false;
					start_line = false;
					startOfWord = -1;
					startOfLine = -1;
					i++;
					line++;

					if (i >= stringLength || i < 0)
						break;

					character = str_whole[i];

					if (!startOfWord)
					{
						startOfWord = characterSprite->getPosition().x - characterSprite->getContentSize().width/2.0f;
						start_word = true;
					}
					if (!startOfLine)
					{
						startOfLine  = startOfWord;
						start_line = true;
					}
				}

				// Whitespace.
				if (isspace_unicode(character))
				{
					last_word.push_back(character);
					multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end());
					last_word.clear();
					start_word = false;
					startOfWord = -1;
					i++;
					continue;
				}

				// Out of bounds.
				if (characterSprite->getPosition().x + characterSprite->getContentSize().width / 2.0f - startOfLine
					> m_fWidth )
				{
					if (!m_bLineBreakWithoutSpaces)
					{
						last_word.push_back(character);

						int found = cc_utf8_find_last_not_char(multiline_string, ' ');
						if (found != -1)
							cc_utf8_trim_ws(&multiline_string);
						else
							multiline_string.clear();

						if (multiline_string.size() > 0)
							multiline_string.push_back('\n');

						line++;
						start_line = false;
						startOfLine = -1;
						i++;
					}
					else
					{
						cc_utf8_trim_ws(&last_word);

						last_word.push_back('\n');
						multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end());
						last_word.clear();
						start_word = false;
						start_line = false;
						startOfWord = -1;
						startOfLine = -1;
						line++;

						if (i >= stringLength || i < 0)
							break;

						if (!startOfWord)
						{
							startOfWord = characterSprite->getPosition().x - characterSprite->getContentSize().width/2.0f;
							start_word = true;
						}
						if (!startOfLine)
						{
							startOfLine  = startOfWord;
							start_line = true;
						}

						j--;
					}

					continue;
				}
				else
				{
					// Character is normal.
					last_word.push_back(character);
					i++;
					continue;
				}
			}

			multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end());

			int size = multiline_string.size();
			unsigned short* str_new = new unsigned short[size + 1];

			for (int i = 0; i < size; ++i)
				str_new[i] = multiline_string[i];

			str_new[size] = 0;

			delete[] m_sString;
			m_sString = str_new;
			updateString(true);
		}

		// Step 2: Make alignment
		if (m_pAlignment != CCTextAlignmentLeft)
		{
			int i = 0;

			int lineNumber = 0;
			int str_len = cc_wcslen(m_sString);
			vector<unsigned short> last_line;
			for (int ctr = 0; ctr <= str_len; ++ctr)
			{
				if (m_sString[ctr] == '\n' || m_sString[ctr] == 0)
				{
					float lineWidth = 0.0f;
					int line_length = last_line.size();
					int index = i + line_length - 1 + lineNumber;
					if (index < 0) continue;

					CCSprite* lastChar = (CCSprite*)getChildByTag(index);

					lineWidth = lastChar->getPosition().x + lastChar->getContentSize().width/2.0f;

					float shift = 0;
					switch (m_pAlignment)
					{
					case CCTextAlignmentCenter:
						shift = getContentSize().width/2.0f - lineWidth/2.0f;
						break;
					case CCTextAlignmentRight:
						shift = getContentSize().width - lineWidth;
					default:
						break;
					}

					if (shift != 0)
					{
						for (unsigned j = 0; j < line_length; j++)
						{
							index = i + j + lineNumber;
							if (index < 0) continue;

							CCSprite* characterSprite = (CCSprite*)getChildByTag(index);
							characterSprite->setPosition(ccpAdd(characterSprite->getPosition(), ccp(shift, 0.0f)));
						}
					}

					i += line_length;
					lineNumber++;

					last_line.clear();
					continue;
				}

				last_line.push_back(m_sString[ctr]);
			}
		}
	}

	// LabelBMFont - Alignment
	void CCLabelBMFont::setAlignment(CCTextAlignment alignment)
	{
		this->m_pAlignment = alignment;
		updateLabel();
	}

	void CCLabelBMFont::setWidth(float width)
	{
		this->m_fWidth = width;
		updateLabel();
	}

	void CCLabelBMFont::setLineBreakWithoutSpace( bool breakWithoutSpace )
	{
		m_bLineBreakWithoutSpaces = breakWithoutSpace;
		updateLabel();
	}

	//LabelBMFont - Debug draw
#if CC_LABELBMFONT_DEBUG_DRAW
	void CCLabelBMFont::draw()
	{
		CCSpriteBatchNode::draw();
		const CCSize& s = this->getContentSize();
		CCPoint vertices[4]={
			ccp(0,0),ccp(s.width,0),
			ccp(s.width,s.height),ccp(0,s.height),
		};
		ccDrawPoly(vertices, 4, true);
	}

#endif // CC_LABELBMFONT_DEBUG_DRAW

}


code:
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCLabelTTF.h"
#include "CCDirector.h"

namespace cocos2d{
	//
	//CCLabelTTF
	//
    CCLabelTTF::CCLabelTTF()
        : m_eAlignment(CCTextAlignmentCenter)
        , m_pFontName(NULL)
        , m_fFontSize(0.0)
        , m_pString(NULL)
    {
    }

    CCLabelTTF::~CCLabelTTF()
    {
		CC_SAFE_DELETE(m_pFontName);
		CC_SAFE_DELETE(m_pString);
    }

	CCLabelTTF * CCLabelTTF::labelWithString(const char *label, const CCSize& dimensions, CCTextAlignment alignment, const char *fontName, float fontSize)
	{
		CCLabelTTF *pRet = new CCLabelTTF();
		if(pRet && pRet->initWithString(label, dimensions, alignment, fontName, fontSize))
		{
			pRet->autorelease();
			return pRet;
		}
		CC_SAFE_DELETE(pRet);
		return NULL;
	}
	CCLabelTTF * CCLabelTTF::labelWithString(const char *label, const char *fontName, float fontSize)
	{
		CCLabelTTF *pRet = new CCLabelTTF();
		if(pRet && pRet->initWithString(label, fontName, fontSize))
		{
			pRet->autorelease();
			return pRet;
		}
		CC_SAFE_DELETE(pRet);
		return NULL;
	}

	bool CCLabelTTF::initWithString(const char *label, const CCSize& dimensions, CCTextAlignment alignment, const char *fontName, float fontSize)
	{
		CCAssert(label != NULL, "");
		if (CCSprite::init())
		{
			m_tDimensions = CCSizeMake( dimensions.width * CC_CONTENT_SCALE_FACTOR(), dimensions.height * CC_CONTENT_SCALE_FACTOR() );
			m_eAlignment = alignment;

            if (m_pFontName)
            {
                delete m_pFontName;
                m_pFontName = NULL;
            }
            m_pFontName = new std::string(fontName);

			m_fFontSize = fontSize * CC_CONTENT_SCALE_FACTOR();
			this->setString(label);
			return true;
		}
		return false;
	}
	bool CCLabelTTF::initWithString(const char *label, const char *fontName, float fontSize)
	{
		CCAssert(label != NULL, "");
		if (CCSprite::init())
		{
			m_tDimensions = CCSizeZero;

            if (m_pFontName)
            {
                delete m_pFontName;
                m_pFontName = NULL;
            }
            m_pFontName = new std::string(fontName);

			m_fFontSize = fontSize * CC_CONTENT_SCALE_FACTOR();
			this->setString(label);
			return true;
		}
		return false;
	}
	void CCLabelTTF::setString(const char *label)
	{
        if (m_pString)
        {
            delete m_pString;
            m_pString = NULL;
        }
        m_pString = new std::string(label);

		CCTexture2D *texture;
		if( CCSize::CCSizeEqualToSize( m_tDimensions, CCSizeZero ) )
		{
			texture = new CCTexture2D();
			texture->initWithString(label, m_pFontName->c_str(), m_fFontSize);
		}
		else
		{
			texture = new CCTexture2D();
			texture->initWithString(label, m_tDimensions, m_eAlignment, m_pFontName->c_str(), m_fFontSize);
		}
		this->setTexture(texture);
		texture->release();

        CCRect rect = CCRectZero;
		rect.size = m_pobTexture->getContentSize();
		this->setTextureRect(rect);
	}

	const char* CCLabelTTF::getString(void)
	{
		return m_pString->c_str();
	}

	char * CCLabelTTF::description()
	{
		char *ret = new char[100] ;
		sprintf(ret, "<CCLabelTTF | FontName = %s, FontSize = %.1f>", m_pFontName->c_str(), m_fFontSize);
		return ret;
	}
}// namespace cocos2d

license: mit


code:
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011      Zynga Inc.

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/

#include <stdarg.h>
#include "CCLayer.h"
#include "CCTouchDispatcher.h"
#include "CCKeypadDispatcher.h"
#include "CCAccelerometer.h"
#include "CCDirector.h"
#include "CCPointExtension.h"
#include "CCScriptSupport.h"

namespace   cocos2d {

// CCLayer
CCLayer::CCLayer()
:m_bIsTouchEnabled(false)
,m_bIsAccelerometerEnabled(false)
,m_bIsKeypadEnabled(false)
,m_pScriptHandlerEntry(NULL)
{
	setAnchorPoint(ccp(0.5f, 0.5f));
	m_bIsRelativeAnchorPoint = false;
}

CCLayer::~CCLayer()
{
    unregisterScriptTouchHandler();
}

bool CCLayer::init()
{
	bool bRet = false;
	do
	{
		CCDirector * pDirector;
		CC_BREAK_IF(!(pDirector = CCDirector::sharedDirector()));
		this->setContentSize(pDirector->getWinSize());
        m_bIsTouchEnabled = false;
        m_bIsAccelerometerEnabled = false;
		// success
		bRet = true;
	} while(0);
	return bRet;
}

CCLayer *CCLayer::node()
{
	CCLayer *pRet = new CCLayer();
	if (pRet && pRet->init())
	{
		pRet->autorelease();
		return pRet;
	}
    else
    {
	    CC_SAFE_DELETE(pRet)
	    return NULL;
    }
}

/// Touch and Accelerometer related

void CCLayer::registerWithTouchDispatcher()
{
    if (m_pScriptHandlerEntry)
    {
        if (m_pScriptHandlerEntry->getIsMultiTouches())
        {
            CCTouchDispatcher::sharedDispatcher()->addStandardDelegate(this, 0);
            LUALOG("[LUA] Add multi-touches event handler: %d", m_pScriptHandlerEntry->getHandler());
        }
        else
        {
            CCTouchDispatcher::sharedDispatcher()->addTargetedDelegate(this,
                                                                       m_pScriptHandlerEntry->getPriority(),
                                                                       m_pScriptHandlerEntry->getSwallowsTouches());
            LUALOG("[LUA] Add touch event handler: %d", m_pScriptHandlerEntry->getHandler());
        }
        return;
    }
	CCTouchDispatcher::sharedDispatcher()->addStandardDelegate(this,0);
}

void CCLayer::registerScriptTouchHandler(int nHandler, bool bIsMultiTouches, int nPriority, bool bSwallowsTouches)
{
    unregisterScriptTouchHandler();
    m_pScriptHandlerEntry = CCTouchScriptHandlerEntry::entryWithHandler(nHandler, bIsMultiTouches, nPriority, bSwallowsTouches);
    m_pScriptHandlerEntry->retain();
}

void CCLayer::unregisterScriptTouchHandler(void)
{
    if (m_pScriptHandlerEntry)
    {
        m_pScriptHandlerEntry->release();
        m_pScriptHandlerEntry = NULL;
    }
}

int CCLayer::excuteScriptTouchHandler(int nEventType, CCTouch *pTouch)
{
    return CCScriptEngineManager::sharedManager()->getScriptEngine()->executeTouchEvent(m_pScriptHandlerEntry->getHandler(), nEventType, pTouch);
}

int CCLayer::excuteScriptTouchHandler(int nEventType, CCSet *pTouches)
{
    return CCScriptEngineManager::sharedManager()->getScriptEngine()->executeTouchesEvent(m_pScriptHandlerEntry->getHandler(), nEventType, pTouches);
}

/// isTouchEnabled getter
bool CCLayer::getIsTouchEnabled()
{
	return m_bIsTouchEnabled;
}
/// isTouchEnabled setter
void CCLayer::setIsTouchEnabled(bool enabled)
{
	if (m_bIsTouchEnabled != enabled)
	{
		m_bIsTouchEnabled = enabled;
		if (m_bIsRunning)
		{
			if (enabled)
			{
				this->registerWithTouchDispatcher();
			}
			else
			{
				// have problems?
				CCTouchDispatcher::sharedDispatcher()->removeDelegate(this);
			}
		}
	}
}

/// isAccelerometerEnabled getter
bool CCLayer::getIsAccelerometerEnabled()
{
	return m_bIsAccelerometerEnabled;
}
/// isAccelerometerEnabled setter
void CCLayer::setIsAccelerometerEnabled(bool enabled)
{
    if (enabled != m_bIsAccelerometerEnabled)
    {
        m_bIsAccelerometerEnabled = enabled;

        if (m_bIsRunning)
        {
            if (enabled)
            {
                CCAccelerometer::sharedAccelerometer()->setDelegate(this);
            }
            else
            {
                CCAccelerometer::sharedAccelerometer()->setDelegate(NULL);
            }
        }
    }
}

/// isKeypadEnabled getter
bool CCLayer::getIsKeypadEnabled()
{
    return m_bIsKeypadEnabled;
}
/// isKeypadEnabled setter
void CCLayer::setIsKeypadEnabled(bool enabled)
{
    if (enabled != m_bIsKeypadEnabled)
    {
        m_bIsKeypadEnabled = enabled;

        if (m_bIsRunning)
        {
            if (enabled)
            {
                CCKeypadDispatcher::sharedDispatcher()->addDelegate(this);
            }
            else
            {
                CCKeypadDispatcher::sharedDispatcher()->removeDelegate(this);
            }
        }
    }
}

/// Callbacks
void CCLayer::onEnter()
{
	// register 'parent' nodes first
	// since events are propagated in reverse order
	if (m_bIsTouchEnabled)
	{
		this->registerWithTouchDispatcher();
	}

	// then iterate over all the children
	CCNode::onEnter();

    // add this layer to concern the Accelerometer Sensor
    if (m_bIsAccelerometerEnabled)
    {
        CCAccelerometer::sharedAccelerometer()->setDelegate(this);
    }

    // add this layer to concern the kaypad msg
    if (m_bIsKeypadEnabled)
    {
        CCKeypadDispatcher::sharedDispatcher()->addDelegate(this);
    }
}

void CCLayer::onExit()
{
	if( m_bIsTouchEnabled )
	{
		CCTouchDispatcher::sharedDispatcher()->removeDelegate(this);
        unregisterScriptTouchHandler();
	}

    // remove this layer from the delegates who concern Accelerometer Sensor
    if (m_bIsAccelerometerEnabled)
    {
        CCAccelerometer::sharedAccelerometer()->setDelegate(NULL);
    }

    // remove this layer from the delegates who concern the kaypad msg
    if (m_bIsKeypadEnabled)
    {
        CCKeypadDispatcher::sharedDispatcher()->removeDelegate(this);
    }

	CCNode::onExit();
}

void CCLayer::onEnterTransitionDidFinish()
{
    if (m_bIsAccelerometerEnabled)
    {
        CCAccelerometer::sharedAccelerometer()->setDelegate(this);
    }

    CCNode::onEnterTransitionDidFinish();
}

bool CCLayer::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)
{
    if (m_pScriptHandlerEntry)
    {
        return excuteScriptTouchHandler(CCTOUCHBEGAN, pTouch);
    }
    CC_UNUSED_PARAM(pTouch);
    CC_UNUSED_PARAM(pEvent);
	CCAssert(false, "Layer#ccTouchBegan override me");
	return true;
}

void CCLayer::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent) {
    if (m_pScriptHandlerEntry)
    {
        excuteScriptTouchHandler(CCTOUCHMOVED, pTouch);
        return;
    }
    CC_UNUSED_PARAM(pTouch);
    CC_UNUSED_PARAM(pEvent);
}

void CCLayer::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent) {
    if (m_pScriptHandlerEntry)
    {
        excuteScriptTouchHandler(CCTOUCHENDED, pTouch);
        return;
    }
    CC_UNUSED_PARAM(pTouch);
    CC_UNUSED_PARAM(pEvent);
}

void CCLayer::ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent) {
    if (m_pScriptHandlerEntry)
    {
        excuteScriptTouchHandler(CCTOUCHCANCELLED, pTouch);
        return;
    }
    CC_UNUSED_PARAM(pTouch);
    CC_UNUSED_PARAM(pEvent);
}

void CCLayer::ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent)
{
    if (m_pScriptHandlerEntry)
    {
        excuteScriptTouchHandler(CCTOUCHBEGAN, pTouches);
        return;
    }
    CC_UNUSED_PARAM(pTouches);
    CC_UNUSED_PARAM(pEvent);
}

void CCLayer::ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent)
{
    if (m_pScriptHandlerEntry)
    {
        excuteScriptTouchHandler(CCTOUCHMOVED, pTouches);
        return;
    }
    CC_UNUSED_PARAM(pTouches);
    CC_UNUSED_PARAM(pEvent);
}

void CCLayer::ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent)
{
    if (m_pScriptHandlerEntry)
    {
        excuteScriptTouchHandler(CCTOUCHENDED, pTouches);
        return;
    }
    CC_UNUSED_PARAM(pTouches);
    CC_UNUSED_PARAM(pEvent);
}

void CCLayer::ccTouchesCancelled(CCSet *pTouches, CCEvent *pEvent)
{
    if (m_pScriptHandlerEntry)
    {
        excuteScriptTouchHandler(CCTOUCHCANCELLED, pTouches);
        return;
    }
    CC_UNUSED_PARAM(pTouches);
    CC_UNUSED_PARAM(pEvent);
}

/// ColorLayer

CCLayerColor::CCLayerColor()
: m_cOpacity(0)
, m_tColor( ccc3(0,0,0) )
{
    // default blend function
	m_tBlendFunc.src = CC_BLEND_SRC;
	m_tBlendFunc.dst = CC_BLEND_DST;
}

CCLayerColor::~CCLayerColor()
{
}

// Opacity and RGB color protocol
/// opacity getter
GLubyte CCLayerColor::getOpacity()
{
	return m_cOpacity;
}
/// opacity setter
void CCLayerColor::setOpacity(GLubyte var)
{
	m_cOpacity = var;
	updateColor();
}

/// color getter
const ccColor3B& CCLayerColor::getColor()
{
	return m_tColor;
}

/// color setter
void CCLayerColor::setColor(const ccColor3B& var)
{
	m_tColor = var;
	updateColor();
}

/// blendFunc getter
ccBlendFunc CCLayerColor::getBlendFunc()
{
	return m_tBlendFunc;
}
/// blendFunc setter
void CCLayerColor::setBlendFunc(ccBlendFunc var)
{
	m_tBlendFunc = var;
}

CCLayerColor * CCLayerColor::layerWithColorWidthHeight(const ccColor4B& color, GLfloat width, GLfloat height)
{
	CCLayerColor * pLayer = new CCLayerColor();
	if( pLayer && pLayer->initWithColorWidthHeight(color,width,height))
	{
		pLayer->autorelease();
		return pLayer;
	}
	CC_SAFE_DELETE(pLayer);
	return NULL;
}
CCLayerColor * CCLayerColor::layerWithColor(const ccColor4B& color)
{
	CCLayerColor * pLayer = new CCLayerColor();
	if(pLayer && pLayer->initWithColor(color))
	{
		pLayer->autorelease();
		return pLayer;
	}
	CC_SAFE_DELETE(pLayer);
	return NULL;
}

bool CCLayerColor::initWithColorWidthHeight(const ccColor4B& color, GLfloat width, GLfloat height)
{
	// default blend function
	m_tBlendFunc.src = CC_BLEND_SRC;
	m_tBlendFunc.dst = CC_BLEND_DST;

	m_tColor.r = color.r;
	m_tColor.g = color.g;
	m_tColor.b = color.b;
	m_cOpacity = color.a;

	for (unsigned int i=0; i<sizeof(m_pSquareVertices) / sizeof(m_pSquareVertices[0]); i++ )
	{
		m_pSquareVertices[i].x = 0.0f;
        m_pSquareVertices[i].y = 0.0f;
	}

	this->updateColor();
	this->setContentSize(CCSizeMake(width,height));
	return true;
}

bool CCLayerColor::initWithColor(const ccColor4B& color)
{
	CCSize s = CCDirector::sharedDirector()->getWinSize();
	this->initWithColorWidthHeight(color, s.width, s.height);
	return true;
}

/// override contentSize
void CCLayerColor::setContentSize(const CCSize& size)
{
	m_pSquareVertices[1].x = size.width * CC_CONTENT_SCALE_FACTOR();
	m_pSquareVertices[2].y = size.height * CC_CONTENT_SCALE_FACTOR();
	m_pSquareVertices[3].x = size.width * CC_CONTENT_SCALE_FACTOR();
	m_pSquareVertices[3].y = size.height * CC_CONTENT_SCALE_FACTOR();

	CCLayer::setContentSize(size);
}

void CCLayerColor::changeWidthAndHeight(GLfloat w ,GLfloat h)
{
	this->setContentSize(CCSizeMake(w, h));
}

void CCLayerColor::changeWidth(GLfloat w)
{
	this->setContentSize(CCSizeMake(w, m_tContentSize.height));
}

void CCLayerColor::changeHeight(GLfloat h)
{
	this->setContentSize(CCSizeMake(m_tContentSize.width, h));
}

void CCLayerColor::updateColor()
{
	for( unsigned int i=0; i < 4; i++ )
	{
		m_pSquareColors[i].r = m_tColor.r;
		m_pSquareColors[i].g = m_tColor.g;
		m_pSquareColors[i].b = m_tColor.b;
		m_pSquareColors[i].a = m_cOpacity;
	}
}

void CCLayerColor::draw()
{
	CCLayer::draw();

	// Default GL states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY
	// Needed states: GL_VERTEX_ARRAY, GL_COLOR_ARRAY
	// Unneeded states: GL_TEXTURE_2D, GL_TEXTURE_COORD_ARRAY
	glDisableClientState(GL_TEXTURE_COORD_ARRAY);
	glDisable(GL_TEXTURE_2D);

	glVertexPointer(2, GL_FLOAT, 0, m_pSquareVertices);
	glColorPointer(4, GL_UNSIGNED_BYTE, 0, m_pSquareColors);

	bool newBlend = false;
	if( m_tBlendFunc.src != CC_BLEND_SRC || m_tBlendFunc.dst != CC_BLEND_DST ) {
		newBlend = true;
		glBlendFunc(m_tBlendFunc.src, m_tBlendFunc.dst);
	}
	else if( m_cOpacity != 255 ) {
		newBlend = true;
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	}

	glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

	if( newBlend )
		glBlendFunc(CC_BLEND_SRC, CC_BLEND_DST);

	// restore default GL state
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
	glEnable(GL_TEXTURE_2D);
}

//
// CCLayerGradient
//
CCLayerGradient* CCLayerGradient::layerWithColor(const ccColor4B& start, const ccColor4B& end)
{
    CCLayerGradient * pLayer = new CCLayerGradient();
    if( pLayer && pLayer->initWithColor(start, end))
    {
        pLayer->autorelease();
        return pLayer;
    }
    CC_SAFE_DELETE(pLayer);
    return NULL;
}

CCLayerGradient* CCLayerGradient::layerWithColor(const ccColor4B& start, const ccColor4B& end, const CCPoint& v)
{
    CCLayerGradient * pLayer = new CCLayerGradient();
    if( pLayer && pLayer->initWithColor(start, end, v))
    {
        pLayer->autorelease();
        return pLayer;
    }
    CC_SAFE_DELETE(pLayer);
    return NULL;
}

bool CCLayerGradient::initWithColor(const ccColor4B& start, const ccColor4B& end)
{
    return initWithColor(start, end, ccp(0, -1));
}

bool CCLayerGradient::initWithColor(const ccColor4B& start, const ccColor4B& end, const CCPoint& v)
{
    m_endColor.r  = end.r;
    m_endColor.g  = end.g;
    m_endColor.b  = end.b;

    m_cEndOpacity   = end.a;
    m_cStartOpacity	= start.a;
    m_AlongVector   = v;

    m_bCompressedInterpolation = true;

    return CCLayerColor::initWithColor(ccc4f(start.r, start.g, start.b, 255));
}

void CCLayerGradient::updateColor()
{
    CCLayerColor::updateColor();

    float h = ccpLength(m_AlongVector);
    if (h == 0)
        return;

    double c = sqrt(2.0);
    CCPoint u = ccp(m_AlongVector.x / h, m_AlongVector.y / h);

    // Compressed Interpolation mode
    if (m_bCompressedInterpolation)
    {
        float h2 = 1 / ( fabsf(u.x) + fabsf(u.y) );
        u = ccpMult(u, h2 * (float)c);
    }

    float opacityf = (float)m_cOpacity / 255.0f;

    ccColor4B S = {
        (unsigned char) m_tColor.r,
        (unsigned char) m_tColor.g,
        (unsigned char) m_tColor.b,
        (unsigned char) (m_cStartOpacity * opacityf)
    };

    ccColor4B E = {
        (unsigned char) m_endColor.r,
        (unsigned char) m_endColor.g,
        (unsigned char) m_endColor.b,
        (unsigned char) (m_cEndOpacity * opacityf)
    };

    // (-1, -1)
    m_pSquareColors[0].r = (GLubyte) (E.r + (S.r - E.r) * ((c + u.x + u.y) / (2.0f * c)));
    m_pSquareColors[0].g = (GLubyte) (E.g + (S.g - E.g) * ((c + u.x + u.y) / (2.0f * c)));
    m_pSquareColors[0].b = (GLubyte) (E.b + (S.b - E.b) * ((c + u.x + u.y) / (2.0f * c)));
    m_pSquareColors[0].a = (GLubyte) (E.a + (S.a - E.a) * ((c + u.x + u.y) / (2.0f * c)));
    // (1, -1)
    m_pSquareColors[1].r = (GLubyte) (E.r + (S.r - E.r) * ((c - u.x + u.y) / (2.0f * c)));
    m_pSquareColors[1].g = (GLubyte) (E.g + (S.g - E.g) * ((c - u.x + u.y) / (2.0f * c)));
    m_pSquareColors[1].b = (GLubyte) (E.b + (S.b - E.b) * ((c - u.x + u.y) / (2.0f * c)));
    m_pSquareColors[1].a = (GLubyte) (E.a + (S.a - E.a) * ((c - u.x + u.y) / (2.0f * c)));
    // (-1, 1)
    m_pSquareColors[2].r = (GLubyte) (E.r + (S.r - E.r) * ((c + u.x - u.y) / (2.0f * c)));
    m_pSquareColors[2].g = (GLubyte) (E.g + (S.g - E.g) * ((c + u.x - u.y) / (2.0f * c)));
    m_pSquareColors[2].b = (GLubyte) (E.b + (S.b - E.b) * ((c + u.x - u.y) / (2.0f * c)));
    m_pSquareColors[2].a = (GLubyte) (E.a + (S.a - E.a) * ((c + u.x - u.y) / (2.0f * c)));
    // (1, 1)
    m_pSquareColors[3].r = (GLubyte) (E.r + (S.r - E.r) * ((c - u.x - u.y) / (2.0f * c)));
    m_pSquareColors[3].g = (GLubyte) (E.g + (S.g - E.g) * ((c - u.x - u.y) / (2.0f * c)));
    m_pSquareColors[3].b = (GLubyte) (E.b + (S.b - E.b) * ((c - u.x - u.y) / (2.0f * c)));
    m_pSquareColors[3].a = (GLubyte) (E.a + (S.a - E.a) * ((c - u.x - u.y) / (2.0f * c)));
}

const ccColor3B& CCLayerGradient::getStartColor()
{
    return m_tColor;
}

void CCLayerGradient::setStartColor(const ccColor3B& color)
{
    setColor(color);
}

void CCLayerGradient::setEndColor(const ccColor3B& color)
{
    m_endColor = color;
    updateColor();
}

const ccColor3B& CCLayerGradient::getEndColor()
{
    return m_endColor;
}

void CCLayerGradient::setStartOpacity(GLubyte o)
{
    m_cStartOpacity = o;
    updateColor();
}

GLubyte CCLayerGradient::getStartOpacity()
{
    return m_cStartOpacity;
}

void CCLayerGradient::setEndOpacity(GLubyte o)
{
    m_cEndOpacity = o;
    updateColor();
}

GLubyte CCLayerGradient::getEndOpacity()
{
    return m_cEndOpacity;
}

void CCLayerGradient::setVector(const CCPoint& var)
{
    m_AlongVector = var;
    updateColor();
}

const CCPoint& CCLayerGradient::getVector()
{
    return m_AlongVector;
}

bool CCLayerGradient::getIsCompressedInterpolation()
{
    return m_bCompressedInterpolation;
}

void CCLayerGradient::setIsCompressedInterpolation(bool compress)
{
    m_bCompressedInterpolation = compress;
    updateColor();
}

/// MultiplexLayer

CCLayerMultiplex::CCLayerMultiplex()
: m_nEnabledLayer(0)
, m_pLayers(NULL)
{
}
CCLayerMultiplex::~CCLayerMultiplex()
{
	CC_SAFE_RELEASE(m_pLayers);
}

CCLayerMultiplex * CCLayerMultiplex::layerWithLayers(CCLayer * layer, ...)
{
	va_list args;
	va_start(args,layer);

	CCLayerMultiplex * pMultiplexLayer = new CCLayerMultiplex();
	if(pMultiplexLayer && pMultiplexLayer->initWithLayers(layer, args))
	{
		pMultiplexLayer->autorelease();
		va_end(args);
		return pMultiplexLayer;
	}
	va_end(args);
	CC_SAFE_DELETE(pMultiplexLayer);
	return NULL;
}

CCLayerMultiplex * CCLayerMultiplex::layerWithLayer(CCLayer* layer)
{
	CCLayerMultiplex * pMultiplexLayer = new CCLayerMultiplex();
	pMultiplexLayer->initWithLayer(layer);
	pMultiplexLayer->autorelease();
	return pMultiplexLayer;
}
void CCLayerMultiplex::addLayer(CCLayer* layer)
{
	CCAssert(m_pLayers, "");
	m_pLayers->addObject(layer);
}

bool CCLayerMultiplex::initWithLayer(CCLayer* layer)
{
	m_pLayers = new CCMutableArray<CCLayer*>(1);
	m_pLayers->addObject(layer);
	m_nEnabledLayer = 0;
	this->addChild(layer);
	return true;
}

bool CCLayerMultiplex::initWithLayers(CCLayer *layer, va_list params)
{
	m_pLayers = new CCMutableArray<CCLayer*>(5);
	//m_pLayers->retain();

	m_pLayers->addObject(layer);

	CCLayer *l = va_arg(params,CCLayer*);
	while( l ) {
		m_pLayers->addObject(l);
		l = va_arg(params,CCLayer*);
	}

	m_nEnabledLayer = 0;
	this->addChild(m_pLayers->getObjectAtIndex(m_nEnabledLayer));

	return true;
}

void CCLayerMultiplex::switchTo(unsigned int n)
{
	CCAssert( n < m_pLayers->count(), "Invalid index in MultiplexLayer switchTo message" );

	this->removeChild(m_pLayers->getObjectAtIndex(m_nEnabledLayer), true);

	m_nEnabledLayer = n;

	this->addChild(m_pLayers->getObjectAtIndex(n));
}

void CCLayerMultiplex::switchToAndReleaseMe(unsigned int n)
{
	CCAssert( n < m_pLayers->count(), "Invalid index in MultiplexLayer switchTo message" );

	this->removeChild(m_pLayers->getObjectAtIndex(m_nEnabledLayer), true);

	//[layers replaceObjectAtIndex:enabledLayer withObject:[NSNull null]];
	m_pLayers->replaceObjectAtIndex(m_nEnabledLayer, NULL);

	m_nEnabledLayer = n;

	this->addChild(m_pLayers->getObjectAtIndex(n));
}
}//namespace   cocos2d


code:
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011      Zynga Inc.

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/

#include "CCScene.h"
#include "CCPointExtension.h"
#include "CCDirector.h"

namespace   cocos2d {

CCScene::CCScene()
{
	m_bIsRelativeAnchorPoint = false;
	setAnchorPoint(ccp(0.5f, 0.5f));
}

CCScene::~CCScene()
{
}

bool CCScene::init()
{
	bool bRet = false;
 	do
 	{
 		CCDirector * pDirector;
 		CC_BREAK_IF( ! (pDirector = CCDirector::sharedDirector()) );
 		this->setContentSize(pDirector->getWinSize());
 		// success
 		bRet = true;
 	} while (0);
 	return bRet;
}

CCScene *CCScene::node()
{
	CCScene *pRet = new CCScene();
	if (pRet && pRet->init())
	{
		pRet->autorelease();
		return pRet;
	}
    else
    {
	    CC_SAFE_DELETE(pRet)
	    return NULL;
    }
}
}//namespace   cocos2d


code:
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011      Zynga Inc.

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/

#include "CCTransition.h"
#include "CCCamera.h"
#include "CCPointExtension.h"
#include "CCDirector.h"
#include "CCTouchDispatcher.h"
#include "CCActionInterval.h"
#include "CCActionInstant.h"
#include "CCActionEase.h"
#include "CCActionCamera.h"
#include "CCLayer.h"
#include "CCActionGrid.h"
#include "CCRenderTexture.h"
#include "CCActionTiledGrid.h"
namespace   cocos2d {

const unsigned int kSceneFade = 0xFADEFADE;

#define IMPLEMENT_TRANSITIONWITHDURATION(_Type)\
    _Type* _Type::transitionWithDuration(ccTime t, CCScene* scene)\
{\
    _Type* pScene = new _Type();\
	if(pScene && pScene->initWithDuration(t, scene)){\
    pScene->autorelease();\
	return pScene;}\
	CC_SAFE_DELETE(pScene);\
	return NULL;\
}

CCTransitionScene::CCTransitionScene()
{
}
CCTransitionScene::~CCTransitionScene()
{
	m_pInScene->release();
	m_pOutScene->release();
}

CCTransitionScene * CCTransitionScene::transitionWithDuration(ccTime t, CCScene *scene)
{
	CCTransitionScene * pScene = new CCTransitionScene();
	if(pScene && pScene->initWithDuration(t,scene))
	{
		pScene->autorelease();
		return pScene;
	}
	CC_SAFE_DELETE(pScene);
	return NULL;
}

bool CCTransitionScene::initWithDuration(ccTime t, CCScene *scene)
{
	CCAssert( scene != NULL, "Argument scene must be non-nil");

	if (CCScene::init())
	{
		m_fDuration = t;

		// retain
		m_pInScene = scene;
		m_pInScene->retain();
		m_pOutScene = CCDirector::sharedDirector()->getRunningScene();
		m_pOutScene->retain();

		CCAssert( m_pInScene != m_pOutScene, "Incoming scene must be different from the outgoing scene" );

		// disable events while transitions
		CCTouchDispatcher::sharedDispatcher()->setDispatchEvents(false);
		this->sceneOrder();

		return true;
	}
	else
	{
		return false;
	}
}

void CCTransitionScene::sceneOrder()
{
	m_bIsInSceneOnTop = true;
}

void CCTransitionScene::draw()
{
	CCScene::draw();

	if( m_bIsInSceneOnTop ) {
		m_pOutScene->visit();
		m_pInScene->visit();
	} else {
		m_pInScene->visit();
		m_pOutScene->visit();
	}
}

void CCTransitionScene::finish()
{
	// clean up
 	m_pInScene->setIsVisible(true);
 	m_pInScene->setPosition(ccp(0,0));
 	m_pInScene->setScale(1.0f);
 	m_pInScene->setRotation(0.0f);
 	m_pInScene->getCamera()->restore();

 	m_pOutScene->setIsVisible(false);
 	m_pOutScene->setPosition(ccp(0,0));
 	m_pOutScene->setScale(1.0f);
 	m_pOutScene->setRotation(0.0f);
 	m_pOutScene->getCamera()->restore();

	//[self schedule:@selector(setNewScene:) interval:0];
	this->schedule(schedule_selector(CCTransitionScene::setNewScene), 0);

}

void CCTransitionScene::setNewScene(ccTime dt)
{
    CC_UNUSED_PARAM(dt);
	// [self unschedule:_cmd];
	// "_cmd" is a local variable automatically defined in a method
	// that contains the selector for the method
	this->unschedule(schedule_selector(CCTransitionScene::setNewScene));
	CCDirector *director = CCDirector::sharedDirector();
	// Before replacing, save the "send cleanup to scene"
	m_bIsSendCleanupToScene = director->isSendCleanupToScene();
	director->replaceScene(m_pInScene);
	// enable events while transitions
	CCTouchDispatcher::sharedDispatcher()->setDispatchEvents(true);
	// issue #267
	m_pOutScene->setIsVisible(true);
}

void CCTransitionScene::hideOutShowIn()
{
	m_pInScene->setIsVisible(true);
	m_pOutScene->setIsVisible(false);
}

// custom onEnter
void CCTransitionScene::onEnter()
{
	CCScene::onEnter();
	m_pInScene->onEnter();
	// outScene should not receive the onEnter callback
}

// custom onExit
void CCTransitionScene::onExit()
{
	CCScene::onExit();
	m_pOutScene->onExit();

	// inScene should not receive the onExit callback
	// only the onEnterTransitionDidFinish
	m_pInScene->onEnterTransitionDidFinish();
}

// custom cleanup
void CCTransitionScene::cleanup()
{
	CCScene::cleanup();

	if( m_bIsSendCleanupToScene )
		m_pOutScene->cleanup();
}

//
// Oriented Transition
//
CCTransitionSceneOriented::CCTransitionSceneOriented()
{
}
CCTransitionSceneOriented::~CCTransitionSceneOriented()
{
}

CCTransitionSceneOriented * CCTransitionSceneOriented::transitionWithDuration(ccTime t, CCScene *scene, tOrientation orientation)
{
	CCTransitionSceneOriented * pScene = new CCTransitionSceneOriented();
	pScene->initWithDuration(t,scene,orientation);
	pScene->autorelease();
	return pScene;
}

bool CCTransitionSceneOriented::initWithDuration(ccTime t, CCScene *scene, tOrientation orientation)
{
	if ( CCTransitionScene::initWithDuration(t, scene) )
	{
		m_eOrientation = orientation;
	}
	return true;
}

//
// RotoZoom
//
CCTransitionRotoZoom::CCTransitionRotoZoom()
{
}
CCTransitionRotoZoom::~CCTransitionRotoZoom()
{
}

void CCTransitionRotoZoom:: onEnter()
{
	CCTransitionScene::onEnter();

	m_pInScene->setScale(0.001f);
	m_pOutScene->setScale(1.0f);

	m_pInScene->setAnchorPoint(ccp(0.5f, 0.5f));
	m_pOutScene->setAnchorPoint(ccp(0.5f, 0.5f));

	CCActionInterval *rotozoom = (CCActionInterval*)(CCSequence::actions
	(
		CCSpawn::actions
		(
			CCScaleBy::actionWithDuration(m_fDuration/2, 0.001f),
			CCRotateBy::actionWithDuration(m_fDuration/2, 360 * 2),
			NULL
		),
		CCDelayTime::actionWithDuration(m_fDuration/2),
		NULL
	));

	m_pOutScene->runAction(rotozoom);
	m_pInScene->runAction
	(
		CCSequence::actions
		(
			rotozoom->reverse(),
			CCCallFunc::actionWithTarget(this, callfunc_selector(CCTransitionScene::finish)),
			NULL
		)
	);
}

IMPLEMENT_TRANSITIONWITHDURATION(CCTransitionRotoZoom)

//
// JumpZoom
//
CCTransitionJumpZoom::CCTransitionJumpZoom()
{
}
CCTransitionJumpZoom::~CCTransitionJumpZoom()
{
}

void CCTransitionJumpZoom::onEnter()
{
	CCTransitionScene::onEnter();
	CCSize s = CCDirector::sharedDirector()->getWinSize();

	m_pInScene->setScale(0.5f);
	m_pInScene->setPosition(ccp(s.width, 0));
	m_pInScene->setAnchorPoint(ccp(0.5f, 0.5f));
	m_pOutScene->setAnchorPoint(ccp(0.5f, 0.5f));

	CCActionInterval *jump = CCJumpBy::actionWithDuration(m_fDuration/4, ccp(-s.width,0), s.width/4, 2);
	CCActionInterval *scaleIn = CCScaleTo::actionWithDuration(m_fDuration/4, 1.0f);
	CCActionInterval *scaleOut = CCScaleTo::actionWithDuration(m_fDuration/4, 0.5f);

	CCActionInterval *jumpZoomOut = (CCActionInterval*)(CCSequence::actions(scaleOut, jump, NULL));
	CCActionInterval *jumpZoomIn = (CCActionInterval*)(CCSequence::actions(jump, scaleIn, NULL));

	CCActionInterval *delay = CCDelayTime::actionWithDuration(m_fDuration/2);

	m_pOutScene->runAction(jumpZoomOut);
	m_pInScene->runAction
	(
		CCSequence::actions
		(
			delay,
			jumpZoomIn,
			CCCallFunc::actionWithTarget(this, callfunc_selector(CCTransitionScene::finish)),
			NULL
		)
	);
}

IMPLEMENT_TRANSITIONWITHDURATION(CCTransitionJumpZoom)

//
// MoveInL
//
CCTransitionMoveInL::CCTransitionMoveInL()
{
}
CCTransitionMoveInL::~CCTransitionMoveInL()
{
}

void CCTransitionMoveInL::onEnter()
{
	CCTransitionScene::onEnter();
	this->initScenes();

	CCActionInterval *a = this->action();

	m_pInScene->runAction
	(
		CCSequence::actions
		(
			this->easeActionWithAction(a),
			CCCallFunc::actionWithTarget(this, callfunc_selector(CCTransitionScene::finish)),
			NULL
		)
	);
}

CCActionInterval* CCTransitionMoveInL::action()
{
	return CCMoveTo::actionWithDuration(m_fDuration, ccp(0,0));
}

CCActionInterval* CCTransitionMoveInL::easeActionWithAction(CCActionInterval* action)
{
	return CCEaseOut::actionWithAction(action, 2.0f);
//	return [EaseElasticOut actionWithAction:action period:0.4f];
}

void CCTransitionMoveInL::initScenes()
{
	CCSize s = CCDirector::sharedDirector()->getWinSize();
	m_pInScene->setPosition( ccp(-s.width,0) );
}

IMPLEMENT_TRANSITIONWITHDURATION(CCTransitionMoveInL)

//
// MoveInR
//
CCTransitionMoveInR::CCTransitionMoveInR()
{
}
CCTransitionMoveInR::~CCTransitionMoveInR()
{
}

void CCTransitionMoveInR::initScenes()
{
	CCSize s = CCDirector::sharedDirector()->getWinSize();
	m_pInScene->setPosition( ccp(s.width,0) );
}

IMPLEMENT_TRANSITIONWITHDURATION(CCTransitionMoveInR)

//
// MoveInT
//
CCTransitionMoveInT::CCTransitionMoveInT()
{
}
CCTransitionMoveInT::~CCTransitionMoveInT()
{
}

void CCTransitionMoveInT::initScenes()
{
	CCSize s = CCDirector::sharedDirector()->getWinSize();
	m_pInScene->setPosition( ccp(0,s.height) );
}

IMPLEMENT_TRANSITIONWITHDURATION(CCTransitionMoveInT)

//
// MoveInB
//
CCTransitionMoveInB::CCTransitionMoveInB()
{
}
CCTransitionMoveInB::~CCTransitionMoveInB()
{
}

void CCTransitionMoveInB::initScenes()
{
	CCSize s = CCDirector::sharedDirector()->getWinSize();
	m_pInScene->setPosition( ccp(0,-s.height) );
}

IMPLEMENT_TRANSITIONWITHDURATION(CCTransitionMoveInB)

//
// SlideInL
//

// The adjust factor is needed to prevent issue #442
// One solution is to use DONT_RENDER_IN_SUBPIXELS images, but NO
// The other issue is that in some transitions (and I don't know why)
// the order should be reversed (In in top of Out or vice-versa).
#define ADJUST_FACTOR 0.5f
CCTransitionSlideInL::CCTransitionSlideInL()
{
}
CCTransitionSlideInL::~CCTransitionSlideInL()
{
}

void CCTransitionSlideInL::onEnter()
{
	CCTransitionScene::onEnter();
	this->initScenes();

	CCActionInterval *in = this->action();
	CCActionInterval *out = this->action();

	CCActionInterval* inAction = easeActionWithAction(in);
	CCActionInterval* outAction = (CCActionInterval*)CCSequence::actions
	(
		easeActionWithAction(out),
		CCCallFunc::actionWithTarget(this, callfunc_selector(CCTransitionScene::finish)),
		NULL
	);
	m_pInScene->runAction(inAction);
	m_pOutScene->runAction(outAction);
}

void CCTransitionSlideInL::sceneOrder()
{
	m_bIsInSceneOnTop = false;
}

void CCTransitionSlideInL:: initScenes()
{
	CCSize s = CCDirector::sharedDirector()->getWinSize();
	m_pInScene->setPosition( ccp(-(s.width-ADJUST_FACTOR),0) );
}

CCActionInterval* CCTransitionSlideInL::action()
{
	CCSize s = CCDirector::sharedDirector()->getWinSize();
	return CCMoveBy::actionWithDuration(m_fDuration, ccp(s.width-ADJUST_FACTOR,0));
}

CCActionInterval* CCTransitionSlideInL::easeActionWithAction(CCActionInterval* action)
{
	return CCEaseOut::actionWithAction(action, 2.0f);
//	return [EaseElasticOut actionWithAction:action period:0.4f];
}

IMPLEMENT_TRANSITIONWITHDURATION(CCTransitionSlideInL)

//
// SlideInR
//
CCTransitionSlideInR::CCTransitionSlideInR()
{
}
CCTransitionSlideInR::~CCTransitionSlideInR()
{
}

void CCTransitionSlideInR::sceneOrder()
{
	m_bIsInSceneOnTop = true;
}

void CCTransitionSlideInR::initScenes()
{
	CCSize s = CCDirector::sharedDirector()->getWinSize();
	m_pInScene->setPosition( ccp(s.width-ADJUST_FACTOR,0) );
}

CCActionInterval* CCTransitionSlideInR:: action()
{
	CCSize s = CCDirector::sharedDirector()->getWinSize();
	return CCMoveBy::actionWithDuration(m_fDuration, ccp(-(s.width-ADJUST_FACTOR),0));
}

IMPLEMENT_TRANSITIONWITHDURATION(CCTransitionSlideInR)

//
// SlideInT
//
CCTransitionSlideInT::CCTransitionSlideInT()
{
}
CCTransitionSlideInT::~CCTransitionSlideInT()
{
}

void CCTransitionSlideInT::sceneOrder()
{
	m_bIsInSceneOnTop = false;
}

void CCTransitionSlideInT::initScenes()
{
	CCSize s = CCDirector::sharedDirector()->getWinSize();
	m_pInScene->setPosition( ccp(0,s.height-ADJUST_FACTOR) );
}

CCActionInterval* CCTransitionSlideInT::action()
{
	CCSize s = CCDirector::sharedDirector()->getWinSize();
	return CCMoveBy::actionWithDuration(m_fDuration, ccp(0,-(s.height-ADJUST_FACTOR)));
}

IMPLEMENT_TRANSITIONWITHDURATION(CCTransitionSlideInT)

//
// SlideInB
//
CCTransitionSlideInB::CCTransitionSlideInB()
{
}
CCTransitionSlideInB::~CCTransitionSlideInB()
{
}

void CCTransitionSlideInB::sceneOrder()
{
	m_bIsInSceneOnTop = true;
}

void CCTransitionSlideInB:: initScenes()
{
	CCSize s = CCDirector::sharedDirector()->getWinSize();
	m_pInScene->setPosition( ccp(0,-(s.height-ADJUST_FACTOR)) );
}

CCActionInterval* CCTransitionSlideInB:: action()
{
	CCSize s = CCDirector::sharedDirector()->getWinSize();
	return CCMoveBy::actionWithDuration(m_fDuration, ccp(0,s.height-ADJUST_FACTOR));
}

IMPLEMENT_TRANSITIONWITHDURATION(CCTransitionSlideInB)

//
// ShrinkGrow Transition
//
CCTransitionShrinkGrow::CCTransitionShrinkGrow()
{
}
CCTransitionShrinkGrow::~CCTransitionShrinkGrow()
{
}

void CCTransitionShrinkGrow::onEnter()
{
	CCTransitionScene::onEnter();

	m_pInScene->setScale(0.001f);
	m_pOutScene->setScale(1.0f);

	m_pInScene->setAnchorPoint(ccp(2/3.0f,0.5f));
	m_pOutScene->setAnchorPoint(ccp(1/3.0f,0.5f));

	CCActionInterval* scaleOut = CCScaleTo::actionWithDuration(m_fDuration, 0.01f);
	CCActionInterval* scaleIn = CCScaleTo::actionWithDuration(m_fDuration, 1.0f);

	m_pInScene->runAction(this->easeActionWithAction(scaleIn));
	m_pOutScene->runAction
	(
		CCSequence::actions
		(
			this->easeActionWithAction(scaleOut),
			CCCallFunc::actionWithTarget(this, callfunc_selector(CCTransitionScene::finish)),
			NULL
		)
	);
}
CCActionInterval* CCTransitionShrinkGrow:: easeActionWithAction(CCActionInterval* action)
{
	return CCEaseOut::actionWithAction(action, 2.0f);
//	return [EaseElasticOut actionWithAction:action period:0.3f];
}

IMPLEMENT_TRANSITIONWITHDURATION(CCTransitionShrinkGrow)

//
// FlipX Transition
//
CCTransitionFlipX::CCTransitionFlipX()
{
}
CCTransitionFlipX::~CCTransitionFlipX()
{
}

void CCTransitionFlipX::onEnter()
{
	CCTransitionSceneOriented::onEnter();

	CCActionInterval *inA, *outA;
	m_pInScene->setIsVisible(false);

	float inDeltaZ, inAngleZ;
	float outDeltaZ, outAngleZ;

	if( m_eOrientation == kOrientationRightOver )
	{
		inDeltaZ = 90;
		inAngleZ = 270;
		outDeltaZ = 90;
		outAngleZ = 0;
	}
	else
	{
		inDeltaZ = -90;
		inAngleZ = 90;
		outDeltaZ = -90;
		outAngleZ = 0;
	}

	inA = (CCActionInterval*)CCSequence::actions
		(
			CCDelayTime::actionWithDuration(m_fDuration/2),
			CCShow::action(),
			CCOrbitCamera::actionWithDuration(m_fDuration/2, 1, 0, inAngleZ, inDeltaZ, 0, 0),
			CCCallFunc::actionWithTarget(this, callfunc_selector(CCTransitionScene::finish)),
			NULL
		);

	outA = (CCActionInterval *)CCSequence::actions
		(
			CCOrbitCamera::actionWithDuration(m_fDuration/2, 1, 0, outAngleZ, outDeltaZ, 0, 0),
			CCHide::action(),
			CCDelayTime::actionWithDuration(m_fDuration/2),
			NULL
		);

	m_pInScene->runAction(inA);
	m_pOutScene->runAction(outA);
}

CCTransitionFlipX* CCTransitionFlipX::transitionWithDuration(ccTime t, CCScene* s, tOrientation o)
{
    CCTransitionFlipX* pScene = new CCTransitionFlipX();
    pScene->initWithDuration(t, s, o);
    pScene->autorelease();

    return pScene;
}

//
// FlipY Transition
//
CCTransitionFlipY::CCTransitionFlipY()
{
}
CCTransitionFlipY::~CCTransitionFlipY()
{
}

void CCTransitionFlipY::onEnter()
{
	CCTransitionSceneOriented::onEnter();

	CCActionInterval *inA, *outA;
	m_pInScene->setIsVisible(false);

	float inDeltaZ, inAngleZ;
	float outDeltaZ, outAngleZ;

	if( m_eOrientation == kOrientationUpOver )
	{
		inDeltaZ = 90;
		inAngleZ = 270;
		outDeltaZ = 90;
		outAngleZ = 0;
	}
	else
	{
		inDeltaZ = -90;
		inAngleZ = 90;
		outDeltaZ = -90;
		outAngleZ = 0;
	}

	inA = (CCActionInterval*)CCSequence::actions
		(
			CCDelayTime::actionWithDuration(m_fDuration/2),
			CCShow::action(),
			CCOrbitCamera::actionWithDuration(m_fDuration/2, 1, 0, inAngleZ, inDeltaZ, 90, 0),
			CCCallFunc::actionWithTarget(this, callfunc_selector(CCTransitionScene::finish)),
			NULL
		);
	outA = (CCActionInterval*)CCSequence::actions
		(
			CCOrbitCamera::actionWithDuration(m_fDuration/2, 1, 0, outAngleZ, outDeltaZ, 90, 0),
			CCHide::action(),
			CCDelayTime::actionWithDuration(m_fDuration/2),
			NULL
		);

	m_pInScene->runAction(inA);
	m_pOutScene->runAction(outA);

}

CCTransitionFlipY* CCTransitionFlipY::transitionWithDuration(ccTime t, CCScene* s, tOrientation o)
{
    CCTransitionFlipY* pScene = new CCTransitionFlipY();
    pScene->initWithDuration(t, s, o);
    pScene->autorelease();

    return pScene;
}

//
// FlipAngular Transition
//
CCTransitionFlipAngular::CCTransitionFlipAngular()
{
}
CCTransitionFlipAngular::~CCTransitionFlipAngular()
{
}

void CCTransitionFlipAngular::onEnter()
{
	CCTransitionSceneOriented::onEnter();

	CCActionInterval *inA, *outA;
	m_pInScene->setIsVisible(false);

	float inDeltaZ, inAngleZ;
	float outDeltaZ, outAngleZ;

	if( m_eOrientation == kOrientationRightOver )
	{
		inDeltaZ = 90;
		inAngleZ = 270;
		outDeltaZ = 90;
		outAngleZ = 0;
	}
	else
	{
		inDeltaZ = -90;
		inAngleZ = 90;
		outDeltaZ = -90;
		outAngleZ = 0;
	}

	inA = (CCActionInterval *)CCSequence::actions
		(
			CCDelayTime::actionWithDuration(m_fDuration/2),
			CCShow::action(),
			CCOrbitCamera::actionWithDuration(m_fDuration/2, 1, 0, inAngleZ, inDeltaZ, -45, 0),
			CCCallFunc::actionWithTarget(this, callfunc_selector(CCTransitionScene::finish)),
			NULL
		);
	outA = (CCActionInterval *)CCSequence::actions
		(
			CCOrbitCamera::actionWithDuration(m_fDuration/2, 1, 0, outAngleZ, outDeltaZ, 45, 0),
			CCHide::action(),
			CCDelayTime::actionWithDuration(m_fDuration/2),
			NULL
		);

	m_pInScene->runAction(inA);
	m_pOutScene->runAction(outA);
}

CCTransitionFlipAngular* CCTransitionFlipAngular::transitionWithDuration(ccTime t, CCScene* s, tOrientation o)
{
    CCTransitionFlipAngular* pScene = new CCTransitionFlipAngular();
    pScene->initWithDuration(t, s, o);
    pScene->autorelease();

    return pScene;
}

//
// ZoomFlipX Transition
//
CCTransitionZoomFlipX::CCTransitionZoomFlipX()
{
}
CCTransitionZoomFlipX::~CCTransitionZoomFlipX()
{
}

void CCTransitionZoomFlipX::onEnter()
{
	CCTransitionSceneOriented::onEnter();

	CCActionInterval *inA, *outA;
	m_pInScene->setIsVisible(false);

	float inDeltaZ, inAngleZ;
	float outDeltaZ, outAngleZ;

	if( m_eOrientation == kOrientationRightOver ) {
		inDeltaZ = 90;
		inAngleZ = 270;
		outDeltaZ = 90;
		outAngleZ = 0;
	}
	else
	{
		inDeltaZ = -90;
		inAngleZ = 90;
		outDeltaZ = -90;
		outAngleZ = 0;
	}
	inA = (CCActionInterval *)CCSequence::actions
		(
			CCDelayTime::actionWithDuration(m_fDuration/2),
			CCSpawn::actions
			(
				CCOrbitCamera::actionWithDuration(m_fDuration/2, 1, 0, inAngleZ, inDeltaZ, 0, 0),
				CCScaleTo::actionWithDuration(m_fDuration/2, 1),
				CCShow::action(),
				NULL
			),
			CCCallFunc::actionWithTarget(this, callfunc_selector(CCTransitionScene::finish)),
			NULL
		);
	outA = (CCActionInterval *)CCSequence::actions
		(
			CCSpawn::actions
			(
				CCOrbitCamera::actionWithDuration(m_fDuration/2, 1, 0, outAngleZ, outDeltaZ, 0, 0),
				CCScaleTo::actionWithDuration(m_fDuration/2, 0.5f),
				NULL
			),
			CCHide::action(),
			CCDelayTime::actionWithDuration(m_fDuration/2),
			NULL
		);

	m_pInScene->setScale(0.5f);
	m_pInScene->runAction(inA);
	m_pOutScene->runAction(outA);
}

CCTransitionZoomFlipX* CCTransitionZoomFlipX::transitionWithDuration(ccTime t, CCScene* s, tOrientation o)
{
    CCTransitionZoomFlipX* pScene = new CCTransitionZoomFlipX();
    pScene->initWithDuration(t, s, o);
    pScene->autorelease();

    return pScene;
}

//
// ZoomFlipY Transition
//
CCTransitionZoomFlipY::CCTransitionZoomFlipY()
{
}
CCTransitionZoomFlipY::~CCTransitionZoomFlipY()
{
}

void CCTransitionZoomFlipY::onEnter()
{
	CCTransitionSceneOriented::onEnter();

	CCActionInterval *inA, *outA;
	m_pInScene->setIsVisible(false);

	float inDeltaZ, inAngleZ;
	float outDeltaZ, outAngleZ;

	if( m_eOrientation== kOrientationUpOver ) {
		inDeltaZ = 90;
		inAngleZ = 270;
		outDeltaZ = 90;
		outAngleZ = 0;
	} else {
		inDeltaZ = -90;
		inAngleZ = 90;
		outDeltaZ = -90;
		outAngleZ = 0;
	}

	inA = (CCActionInterval *)CCSequence::actions
		(
			CCDelayTime::actionWithDuration(m_fDuration/2),
			CCSpawn::actions
			(
				CCOrbitCamera::actionWithDuration(m_fDuration/2, 1, 0, inAngleZ, inDeltaZ, 90, 0),
				CCScaleTo::actionWithDuration(m_fDuration/2, 1),
				CCShow::action(),
				NULL
			),
			CCCallFunc::actionWithTarget(this, callfunc_selector(CCTransitionScene::finish)),
			NULL
		);

	outA = (CCActionInterval *)CCSequence::actions
		(
			CCSpawn::actions
			(
				CCOrbitCamera::actionWithDuration(m_fDuration/2, 1, 0, outAngleZ, outDeltaZ, 90, 0),
				CCScaleTo::actionWithDuration(m_fDuration/2, 0.5f),
				NULL
			),
			CCHide::action(),
			CCDelayTime::actionWithDuration(m_fDuration/2),
			NULL
		);

	m_pInScene->setScale(0.5f);
	m_pInScene->runAction(inA);
	m_pOutScene->runAction(outA);
}

CCTransitionZoomFlipY* CCTransitionZoomFlipY::transitionWithDuration(ccTime t, CCScene* s, tOrientation o)
{
    CCTransitionZoomFlipY* pScene = new CCTransitionZoomFlipY();
    pScene->initWithDuration(t, s, o);
    pScene->autorelease();

    return pScene;
}

//
// ZoomFlipAngular Transition
//
CCTransitionZoomFlipAngular::CCTransitionZoomFlipAngular()
{
}
CCTransitionZoomFlipAngular::~CCTransitionZoomFlipAngular()
{
}

void CCTransitionZoomFlipAngular::onEnter()
{
	CCTransitionSceneOriented::onEnter();

	CCActionInterval *inA, *outA;
	m_pInScene->setIsVisible(false);

	float inDeltaZ, inAngleZ;
	float outDeltaZ, outAngleZ;

	if( m_eOrientation == kOrientationRightOver ) {
		inDeltaZ = 90;
		inAngleZ = 270;
		outDeltaZ = 90;
		outAngleZ = 0;
	}
	else
	{
		inDeltaZ = -90;
		inAngleZ = 90;
		outDeltaZ = -90;
		outAngleZ = 0;
	}

	inA = (CCActionInterval *)CCSequence::actions
		(
			CCDelayTime::actionWithDuration(m_fDuration/2),
			CCSpawn::actions
			(
				CCOrbitCamera::actionWithDuration(m_fDuration/2, 1, 0, inAngleZ, inDeltaZ, -45, 0),
				CCScaleTo::actionWithDuration(m_fDuration/2, 1),
				CCShow::action(),
				NULL
			),
			CCShow::action(),
			CCCallFunc::actionWithTarget(this, callfunc_selector(CCTransitionScene::finish)),
			NULL
		);
	outA = (CCActionInterval *)CCSequence::actions
		(
			CCSpawn::actions
			(
				CCOrbitCamera::actionWithDuration(m_fDuration/2, 1, 0 , outAngleZ, outDeltaZ, 45, 0),
				CCScaleTo::actionWithDuration(m_fDuration/2, 0.5f),
				NULL
			),
			CCHide::action(),
			CCDelayTime::actionWithDuration(m_fDuration/2),
			NULL
		);

	m_pInScene->setScale(0.5f);
	m_pInScene->runAction(inA);
	m_pOutScene->runAction(outA);
}

CCTransitionZoomFlipAngular* CCTransitionZoomFlipAngular::transitionWithDuration(ccTime t, CCScene* s, tOrientation o)
{
    CCTransitionZoomFlipAngular* pScene = new CCTransitionZoomFlipAngular();
    pScene->initWithDuration(t, s, o);
    pScene->autorelease();

    return pScene;
}

//
// Fade Transition
//
CCTransitionFade::CCTransitionFade()
{
}
CCTransitionFade::~CCTransitionFade()
{
}

CCTransitionFade * CCTransitionFade::transitionWithDuration(ccTime duration, CCScene *scene, const ccColor3B& color)
{
	CCTransitionFade * pTransition = new CCTransitionFade();
	pTransition->initWithDuration(duration, scene, color);
	pTransition->autorelease();
	return pTransition;
}

bool CCTransitionFade::initWithDuration(ccTime duration, CCScene *scene, const ccColor3B& color)
{
	if (CCTransitionScene::initWithDuration(duration, scene))
	{
		m_tColor.r = color.r;
		m_tColor.g = color.g;
		m_tColor.b = color.b;
		m_tColor.a = 0;
	}
	return true;
}

bool CCTransitionFade::initWithDuration(ccTime t, CCScene *scene)
{
	this->initWithDuration(t, scene, ccBLACK);
	return true;
}

void CCTransitionFade :: onEnter()
{
	CCTransitionScene::onEnter();

	CCLayerColor* l = CCLayerColor::layerWithColor(m_tColor);
	m_pInScene->setIsVisible(false);

	addChild(l, 2, kSceneFade);
	CCNode* f = getChildByTag(kSceneFade);

	CCActionInterval* a = (CCActionInterval *)CCSequence::actions
		(
			CCFadeIn::actionWithDuration(m_fDuration/2),
			CCCallFunc::actionWithTarget(this, callfunc_selector(CCTransitionScene::hideOutShowIn)),//CCCallFunc::actionWithTarget:self selector:@selector(hideOutShowIn)],
			CCFadeOut::actionWithDuration(m_fDuration/2),
			CCCallFunc::actionWithTarget(this, callfunc_selector(CCTransitionScene::finish)), //:self selector:@selector(finish)],
			NULL
		);
	f->runAction(a);
}

void CCTransitionFade::onExit()
{
	CCTransitionScene::onExit();
	this->removeChildByTag(kSceneFade, false);
}

//
// Cross Fade Transition
//
CCTransitionCrossFade::CCTransitionCrossFade()
{
}
CCTransitionCrossFade::~CCTransitionCrossFade()
{
}

void CCTransitionCrossFade:: draw()
{
	// override draw since both scenes (textures) are rendered in 1 scene
}

void CCTransitionCrossFade::onEnter()
{
	CCTransitionScene::onEnter();

	// create a transparent color layer
	// in which we are going to add our rendertextures
	ccColor4B  color = {0,0,0,0};
	CCSize size = CCDirector::sharedDirector()->getWinSize();
	CCLayerColor* layer = CCLayerColor::layerWithColor(color);

	// create the first render texture for inScene
	CCRenderTexture* inTexture = CCRenderTexture::renderTextureWithWidthAndHeight((int)size.width, (int)size.height);

	if (NULL == inTexture)
	{
		return;
	}

	inTexture->getSprite()->setAnchorPoint( ccp(0.5f,0.5f) );
	inTexture->setPosition( ccp(size.width/2, size.height/2) );
	inTexture->setAnchorPoint( ccp(0.5f,0.5f) );

	// render inScene to its texturebuffer
	inTexture->begin();
	m_pInScene->visit();
	inTexture->end();

	// create the second render texture for outScene
	CCRenderTexture* outTexture = CCRenderTexture::renderTextureWithWidthAndHeight((int)size.width, (int)size.height);
	outTexture->getSprite()->setAnchorPoint( ccp(0.5f,0.5f) );
	outTexture->setPosition( ccp(size.width/2, size.height/2) );
	outTexture->setAnchorPoint( ccp(0.5f,0.5f) );

	// render outScene to its texturebuffer
	outTexture->begin();
	m_pOutScene->visit();
	outTexture->end();

	// create blend functions

	ccBlendFunc blend1 = {GL_ONE, GL_ONE}; // inScene will lay on background and will not be used with alpha
	ccBlendFunc blend2 = {GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA}; // we are going to blend outScene via alpha

	// set blendfunctions
	inTexture->getSprite()->setBlendFunc(blend1);
	outTexture->getSprite()->setBlendFunc(blend2);

	// add render textures to the layer
	layer->addChild(inTexture);
	layer->addChild(outTexture);

	// initial opacity:
	inTexture->getSprite()->setOpacity(255);
	outTexture->getSprite()->setOpacity(255);

	// create the blend action
	CCAction* layerAction = CCSequence::actions
	(
		CCFadeTo::actionWithDuration(m_fDuration, 0),
		CCCallFunc::actionWithTarget(this, callfunc_selector(CCTransitionScene::hideOutShowIn)),
		CCCallFunc::actionWithTarget(this, callfunc_selector(CCTransitionScene::finish)),
		NULL
	);

	// run the blend action
	outTexture->getSprite()->runAction( layerAction );

	// add the layer (which contains our two rendertextures) to the scene
	addChild(layer, 2, kSceneFade);
}

// clean up on exit
void CCTransitionCrossFade::onExit()
{
	// remove our layer and release all containing objects
	this->removeChildByTag(kSceneFade, false);
	CCTransitionScene::onExit();
}

CCTransitionCrossFade* CCTransitionCrossFade::transitionWithDuration(ccTime d, CCScene* s)
{
    CCTransitionCrossFade* Transition = new CCTransitionCrossFade();
    Transition->initWithDuration(d, s);
    Transition->autorelease();

    return Transition;
}

//
// TurnOffTilesTransition
//
CCTransitionTurnOffTiles::CCTransitionTurnOffTiles()
{
}
CCTransitionTurnOffTiles::~CCTransitionTurnOffTiles()
{
}

// override addScenes, and change the order
void CCTransitionTurnOffTiles::sceneOrder()
{
	m_bIsInSceneOnTop = false;
}

void CCTransitionTurnOffTiles::onEnter()
{
	CCTransitionScene::onEnter();
	CCSize s = CCDirector::sharedDirector()->getWinSize();
	float aspect = s.width / s.height;
	int x = (int)(12 * aspect);
	int y = 12;

	CCTurnOffTiles* toff = CCTurnOffTiles::actionWithSize( ccg(x,y), m_fDuration);
	CCActionInterval* action = easeActionWithAction(toff);
	m_pOutScene->runAction
	(
		CCSequence::actions
		(
			action,
			CCCallFunc::actionWithTarget(this, callfunc_selector(CCTransitionScene::finish)),
			CCStopGrid::action(),
			NULL
		)
	);
}

CCActionInterval* CCTransitionTurnOffTiles:: easeActionWithAction(CCActionInterval* action)
{
	return action;
}

IMPLEMENT_TRANSITIONWITHDURATION(CCTransitionTurnOffTiles)

//
// SplitCols Transition
//
CCTransitionSplitCols::CCTransitionSplitCols()
{
}
CCTransitionSplitCols::~CCTransitionSplitCols()
{
}

void CCTransitionSplitCols::onEnter()
{
	CCTransitionScene::onEnter();
	m_pInScene->setIsVisible(false);

	CCActionInterval* split = action();
	CCActionInterval* seq = (CCActionInterval*)CCSequence::actions
	(
		split,
		CCCallFunc::actionWithTarget(this, callfunc_selector(CCTransitionScene::hideOutShowIn)),
		split->reverse(),
		NULL
	);

	this->runAction
	(
		CCSequence::actions
		(
			easeActionWithAction(seq),
			CCCallFunc::actionWithTarget(this, callfunc_selector(CCTransitionScene::finish)),
			CCStopGrid::action(),
			NULL
		)
	);
}

CCActionInterval* CCTransitionSplitCols:: action()
{
	return CCSplitCols::actionWithCols(3, m_fDuration/2.0f);
}

CCActionInterval* CCTransitionSplitCols::easeActionWithAction(CCActionInterval * action)
{
	return CCEaseInOut::actionWithAction(action, 3.0f);
}

IMPLEMENT_TRANSITIONWITHDURATION(CCTransitionSplitCols)

//
// SplitRows Transition
//
CCTransitionSplitRows::CCTransitionSplitRows()
{
}
CCTransitionSplitRows::~CCTransitionSplitRows()
{
}

CCActionInterval* CCTransitionSplitRows::action()
{
	return CCSplitRows::actionWithRows(3, m_fDuration/2.0f);
}

IMPLEMENT_TRANSITIONWITHDURATION(CCTransitionSplitRows)

//
// FadeTR Transition
//
CCTransitionFadeTR::CCTransitionFadeTR()
{
}
CCTransitionFadeTR::~CCTransitionFadeTR()
{
}

void CCTransitionFadeTR::sceneOrder()
{
	m_bIsInSceneOnTop = false;
}

void CCTransitionFadeTR::onEnter()
{
	CCTransitionScene::onEnter();

	CCSize s = CCDirector::sharedDirector()->getWinSize();
	float aspect = s.width / s.height;
	int x = (int)(12 * aspect);
	int y = 12;

	CCActionInterval* action  = actionWithSize(ccg(x,y));

	m_pOutScene->runAction
	(
		CCSequence::actions
		(
			easeActionWithAction(action),
			CCCallFunc::actionWithTarget(this, callfunc_selector(CCTransitionScene::finish)),
			CCStopGrid::action(),
			NULL
		)
	);
}

CCActionInterval*  CCTransitionFadeTR::actionWithSize(const ccGridSize& size)
{
	return CCFadeOutTRTiles::actionWithSize(size, m_fDuration);
}

CCActionInterval* CCTransitionFadeTR:: easeActionWithAction(CCActionInterval* action)
{
	return action;
}

IMPLEMENT_TRANSITIONWITHDURATION(CCTransitionFadeTR)

//
// FadeBL Transition
//

CCTransitionFadeBL::CCTransitionFadeBL()
{
}
CCTransitionFadeBL::~CCTransitionFadeBL()
{
}

CCActionInterval*  CCTransitionFadeBL::actionWithSize(const ccGridSize& size)
{
	return CCFadeOutBLTiles::actionWithSize(size, m_fDuration);
}

IMPLEMENT_TRANSITIONWITHDURATION(CCTransitionFadeBL)

//
// FadeUp Transition
//
CCTransitionFadeUp::CCTransitionFadeUp()
{
}
CCTransitionFadeUp::~CCTransitionFadeUp()
{
}

CCActionInterval* CCTransitionFadeUp::actionWithSize(const ccGridSize& size)
{
	return CCFadeOutUpTiles::actionWithSize(size, m_fDuration);
}

IMPLEMENT_TRANSITIONWITHDURATION(CCTransitionFadeUp)

//
// FadeDown Transition
//
CCTransitionFadeDown::CCTransitionFadeDown()
{
}
CCTransitionFadeDown::~CCTransitionFadeDown()
{
}

CCActionInterval* CCTransitionFadeDown::actionWithSize(const ccGridSize& size)
{
	return CCFadeOutDownTiles::actionWithSize(size, m_fDuration);
}

IMPLEMENT_TRANSITIONWITHDURATION(CCTransitionFadeDown)

}//namespace   cocos2d


code:
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
Copyright (c) 2009      Sindesso Pty Ltd http://www.sindesso.com/

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/

#include "CCTransitionPageTurn.h"
#include "CCDirector.h"
#include "CCActionInterval.h"
#include "CCActionInstant.h"
#include "CCActionGrid.h"
#include "CCActionPageTurn3D.h"

namespace   cocos2d {

CCTransitionPageTurn::CCTransitionPageTurn()
{
}
CCTransitionPageTurn::~CCTransitionPageTurn()
{
}

/** creates a base transition with duration and incoming scene */
CCTransitionPageTurn * CCTransitionPageTurn::transitionWithDuration(ccTime t, CCScene *scene, bool backwards)
{
	CCTransitionPageTurn * pTransition = new CCTransitionPageTurn();
	pTransition->initWithDuration(t,scene,backwards);
	pTransition->autorelease();
	return pTransition;
}

/** initializes a transition with duration and incoming scene */
bool CCTransitionPageTurn::initWithDuration(ccTime t, CCScene *scene, bool backwards)
{
	// XXX: needed before [super init]
	m_bBack = backwards;

	if( CCTransitionScene::initWithDuration(t, scene) )
	{
		// do something
	}
	return true;
}

void CCTransitionPageTurn::sceneOrder()
{
	m_bIsInSceneOnTop = m_bBack;
}

void CCTransitionPageTurn::onEnter()
{
	CCTransitionScene::onEnter();
	CCSize s = CCDirector::sharedDirector()->getWinSize();
	int x,y;
	if( s.width > s.height)
	{
		x=16;
        y=12;
	}
	else
	{
		x=12;
        y=16;
	}

	CCActionInterval *action  = this->actionWithSize(ccg(x,y));

	if(! m_bBack )
	{
		m_pOutScene->runAction
		(
			CCSequence::actions
			(
				action,
				CCCallFunc::actionWithTarget(this, callfunc_selector(CCTransitionScene::finish)),
				CCStopGrid::action(),
				NULL
			)
		);
	}
	else
	{
		// to prevent initial flicker
		m_pInScene->setIsVisible(false);
		m_pInScene->runAction
		(
			CCSequence::actions
			(
			    CCShow::action(),
				action,
				CCCallFunc::actionWithTarget(this, callfunc_selector(CCTransitionScene::finish)),
				CCStopGrid::action(),
				NULL
			)
		);
	}
}

CCActionInterval* CCTransitionPageTurn:: actionWithSize(const ccGridSize& vector)
{
	if( m_bBack )
	{
		// Get hold of the PageTurn3DAction
		return CCReverseTime::actionWithAction
		(
			CCPageTurn3D::actionWithSize(vector, m_fDuration)
		);
	}
	else
	{
		// Get hold of the PageTurn3DAction
		return CCPageTurn3D::actionWithSize(vector, m_fDuration);
	}
}

}//namespace   cocos2d