code:
/****************************************************************************
 Copyright (c) 2010 cocos2d-x.org

 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 "CCCommon.h"

#include <stdarg.h>
#include <stdio.h>

#import <UIKit/UIAlert.h>

NS_CC_BEGIN;

void CCLog(const char * pszFormat, ...)
{
    printf("Cocos2d: ");
    char szBuf[kMaxLogLen];

    va_list ap;
    va_start(ap, pszFormat);
    vsprintf(szBuf, pszFormat, ap);
    va_end(ap);
    printf("%s", szBuf);
    printf("\n");
}

// ios no MessageBox, use CCLog instead
void CCMessageBox(const char * pszMsg, const char * pszTitle)
{
    NSString * title = (pszTitle) ? [NSString stringWithUTF8String : pszTitle] : nil;
    NSString * msg = (pszMsg) ? [NSString stringWithUTF8String : pszMsg] : nil;
    UIAlertView * messageBox = [[UIAlertView alloc] initWithTitle: title
                                                          message: msg
                                                         delegate: nil
                                                cancelButtonTitle: @"OK"
                                                otherButtonTitles: nil];
    [messageBox autorelease];
    [messageBox show];
}

NS_CC_END;


code:
/****************************************************************************
 Copyright (c) 2010 cocos2d-x.org

 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.
 ****************************************************************************/
#import <Foundation/Foundation.h>

@interface CCDirectorCaller : NSObject {
        id displayLink;
        int interval;
}
@property (readwrite) int interval;
-(void) startMainLoop;
-(void) doCaller: (id) sender;
-(void) setAnimationInterval:(double)interval;
+(id) sharedDirectorCaller;
+(void) destroy;
@end

license: mit


code:
/****************************************************************************
 Copyright (c) 2010 cocos2d-x.org

 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.
 ****************************************************************************/
#import <Foundation/Foundation.h>
#import "CCDirectorCaller.h"
#import "CCDirector.h"

static id s_sharedDirectorCaller;

@interface NSObject(CADisplayLink)
+(id) displayLinkWithTarget: (id)arg1 selector:(SEL)arg2;
-(void) addToRunLoop: (id)arg1 forMode: (id)arg2;
-(void) setFrameInterval: (int)interval;
-(void) invalidate;
@end

@implementation CCDirectorCaller

@synthesize interval;

+(id) sharedDirectorCaller
{
	if (s_sharedDirectorCaller == nil)
	{
		s_sharedDirectorCaller = [CCDirectorCaller new];
	}

	return s_sharedDirectorCaller;
}

+(void) destroy
{
	[s_sharedDirectorCaller release];
}

-(void) alloc
{
        interval = 1;
}

-(void) dealloc
{
	[displayLink release];
	[super dealloc];
}

-(void) startMainLoop
{
        // CCDirector::setAnimationInterval() is called, we should invalide it first
        [displayLink invalidate];
        displayLink = nil;

        displayLink = [NSClassFromString(@"CADisplayLink") displayLinkWithTarget:self selector:@selector(doCaller:)];
        [displayLink setFrameInterval: self.interval];
        [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}

-(void) setAnimationInterval:(double)intervalNew
{
        // CCDirector::setAnimationInterval() is called, we should invalide it first
        [displayLink invalidate];
        displayLink = nil;

        self.interval = 60.0 * intervalNew;

        displayLink = [NSClassFromString(@"CADisplayLink") displayLinkWithTarget:self selector:@selector(doCaller:)];
        [displayLink setFrameInterval: self.interval];
        [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}

-(void) doCaller: (id) sender
{
	cocos2d::CCDirector::sharedDirector()->mainLoop();
}

@end


code:
/****************************************************************************
Copyright (c) 2010 cocos2d-x.org

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.
****************************************************************************/

#ifndef __CC_EGLVIEW_IPHONE_H__
#define __CC_EGLVIEW_IPHONE_H__

#include "CCCommon.h"

namespace   cocos2d {
class CCSet;
class CCTouch;
class EGLTouchDelegate;
class CCSize;

class CC_DLL CCEGLView
{
public:
    CCEGLView();
   ~CCEGLView();

    CCSize  getSize();
    bool    isOpenGLReady();
    bool    canSetContentScaleFactor();
    bool    isIpad();
    void    setContentScaleFactor(float contentScaleFactor);

    // keep compatible
    void    release();
    void    setTouchDelegate(EGLTouchDelegate * pDelegate);
    void    swapBuffers();
    void    setViewPortInPoints(float x, float y, float w, float h);
    void    setScissorInPoints(float x, float y, float w, float h);

    void touchesBegan(CCSet *set);
    void touchesMoved(CCSet *set);
    void touchesEnded(CCSet *set);
    void touchesCancelled(CCSet *set);

    float getMainScreenScale();

    void setIMEKeyboardState(bool bOpen);

    static CCEGLView& sharedOpenGLView();

private:
    EGLTouchDelegate *m_pDelegate;
};

}   // end of namespace   cocos2d

#endif	// end of __CC_EGLVIEW_IPHONE_H__


code:
/****************************************************************************
Copyright (c) 2010 cocos2d-x.org

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 "EAGLView.h"
#include "CCDirectorCaller.h"
#include "CCEGLView_ios.h"
#include "CCSet.h"
#include "CCTouch.h"
#include "CCTouchDispatcher.h"

namespace cocos2d {

CCEGLView::CCEGLView()
: m_pDelegate(0)
{

}

CCEGLView::~CCEGLView()
{

}

cocos2d::CCSize  CCEGLView::getSize()
{
	cocos2d::CCSize size([[EAGLView sharedEGLView] getWidth], [[EAGLView sharedEGLView] getHeight]);
	return size;
}

bool CCEGLView::isIpad()
{
    return UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad;
}

bool CCEGLView::isOpenGLReady()
{
    return [EAGLView sharedEGLView] != NULL;
}

    bool CCEGLView::canSetContentScaleFactor()
    {
       return [[EAGLView sharedEGLView] respondsToSelector:@selector(setContentScaleFactor:)];
    }

    void CCEGLView::setContentScaleFactor(float contentScaleFactor)
    {
        UIView * view = [EAGLView sharedEGLView];
        view.contentScaleFactor = contentScaleFactor;
        [view setNeedsLayout];
    }

void CCEGLView::release()
{
	[CCDirectorCaller destroy];

	// destroy EAGLView
	[[EAGLView sharedEGLView] removeFromSuperview];
}

void CCEGLView::setTouchDelegate(EGLTouchDelegate * pDelegate)
{
    m_pDelegate = pDelegate;
}

void CCEGLView::swapBuffers()
{
	[[EAGLView sharedEGLView] swapBuffers];
}

void CCEGLView::touchesBegan(CCSet *set)
{
	if (m_pDelegate) {
		m_pDelegate->touchesBegan(set, NULL);
	}
}

void CCEGLView::touchesMoved(CCSet *set)
{
	if (m_pDelegate) {
		m_pDelegate->touchesMoved(set, NULL);
	}
}

void CCEGLView::touchesEnded(CCSet *set)
{
	if (m_pDelegate) {
		m_pDelegate->touchesEnded(set, NULL);
	}
}

void CCEGLView::touchesCancelled(CCSet *set)
{
	if (m_pDelegate) {
		m_pDelegate->touchesCancelled(set, NULL);
	}
}

void CCEGLView::setViewPortInPoints(float x, float y, float w, float h)
{
    glViewport((GLint)x, (GLint)y, (GLint)w, (GLint)h);
}

void CCEGLView::setScissorInPoints(float x, float y, float w, float h)
{
    glScissor((GLint)x, (GLint)y, (GLint)w, (GLint)h);
}

void CCEGLView::setIMEKeyboardState(bool bOpen)
{
    if (bOpen)
    {
        [[EAGLView sharedEGLView] becomeFirstResponder];
    }
    else
    {
        [[EAGLView sharedEGLView] resignFirstResponder];
    }
}

CCEGLView& CCEGLView::sharedOpenGLView()
{
    static CCEGLView instance;
    return instance;
}

float CCEGLView::getMainScreenScale()
{
    return [[UIScreen mainScreen] scale];
}

} // end of namespace cocos2d;


code:
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
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.
****************************************************************************/
#import <Foundation/Foundation.h>
#import <UIKit/UIDevice.h>

#include <string>
#include <stack>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xmlmemory.h>
#include "CCString.h"
#include "CCFileUtils.h"
#include "CCDirector.h"
#include "CCSAXParser.h"
#include "support/zip_support/unzip.h"
#include "ccTypes.h"

#define MAX_PATH 260

using namespace cocos2d;

static void static_addValueToCCDict(id key, id value, CCDictionary<std::string, CCObject*>* pDict);
static void static_addItemToCCArray(id item, CCMutableArray<CCObject*> *pArray);

static NSString *__suffixiPhoneRetinaDisplay =@"-hd";
static NSString *__suffixiPad =@"-ipad";
static NSString *__suffixiPadRetinaDisplay =@"-ipadhd";
static NSFileManager *__localFileManager= [[NSFileManager alloc] init];

// NSString *ccRemoveSuffixFromPath( NSString *suffix, NSString *path);

static NSString* removeSuffixFromPath(NSString *suffix, NSString *path)
{
    // quick return
	if( ! suffix || [suffix length] == 0 )
	{
		return path;
    }

	NSString *name = [path lastPathComponent];

	// check if path already has the suffix.
	if( [name rangeOfString:suffix].location != NSNotFound ) {

		CCLOG("cocos2d: Filename(%s) contains %s suffix. Removing it. See cocos2d issue #1040", [path UTF8String], [suffix UTF8String]);

		NSString *newLastname = [name stringByReplacingOccurrencesOfString:suffix withString:@""];

		NSString *pathWithoutLastname = [path stringByDeletingLastPathComponent];
		return [pathWithoutLastname stringByAppendingPathComponent:newLastname];
	}

	return path;
}

static NSString* getPathForSuffix(NSString *path, NSString *suffix)
{
    // quick return
	if( ! suffix || [suffix length] == 0 )
	{
		return path;
    }

	NSString *pathWithoutExtension = [path stringByDeletingPathExtension];
	NSString *name = [pathWithoutExtension lastPathComponent];

	// check if path already has the suffix.
	if( [name rangeOfString:suffix].location != NSNotFound ) {

		CCLOG("cocos2d: WARNING Filename(%s) already has the suffix %s. Using it.", [name UTF8String], [suffix UTF8String]);
		return path;
	}

	NSString *extension = [path pathExtension];

	if( [extension isEqualToString:@"ccz"] || [extension isEqualToString:@"gz"] )
	{
		// All ccz / gz files should be in the format filename.xxx.ccz
		// so we need to pull off the .xxx part of the extension as well
		extension = [NSString stringWithFormat:@"%@.%@", [pathWithoutExtension pathExtension], extension];
		pathWithoutExtension = [pathWithoutExtension stringByDeletingPathExtension];
	}

	NSString *newName = [pathWithoutExtension stringByAppendingString:suffix];
	newName = [newName stringByAppendingPathExtension:extension];

	if( [__localFileManager fileExistsAtPath:newName] )
		return newName;

	CCLOG("cocos2d: CCFileUtils: Warning file not found: %s", [[newName lastPathComponent] UTF8String] );

	return nil;
}

static void static_addItemToCCArray(id item, CCMutableArray<CCObject*> *pArray)
{
	// add string value into array
    if ([item isKindOfClass:[NSString class]]) {
        CCString* pValue = new CCString([item UTF8String]);

        pArray->addObject(pValue);
        pValue->release();
        return;
    }

	// add number value into array(such as int, float, bool and so on)
    if ([item isKindOfClass:[NSNumber class]]) {
        NSString* pStr = [item stringValue];
        CCString* pValue = new CCString([pStr UTF8String]);

        pArray->addObject(pValue);
        pValue->release();
        return;
    }

    // add dictionary value into array
    if ([item isKindOfClass:[NSDictionary class]]) {
        CCDictionary<std::string, CCObject*>* pDictItem = new CCDictionary<std::string, CCObject*>();
        for (id subKey in [item allKeys]) {
            id subValue = [item objectForKey:subKey];
            static_addValueToCCDict(subKey, subValue, pDictItem);
        }
        pArray->addObject(pDictItem);
        pDictItem->release();
        return;
    }

    // add array value into array
    if ([item isKindOfClass:[NSArray class]]) {
        CCMutableArray<CCObject*> *pArrayItem = new CCMutableArray<CCObject*>();
        for (id subItem in item) {
            static_addItemToCCArray(subItem, pArrayItem);
        }
        pArray->addObject(pArrayItem);
        pArrayItem->release();
        return;
    }
}

static void static_addValueToCCDict(id key, id value, CCDictionary<std::string, CCObject*>* pDict)
{
	// the key must be a string
    CCAssert([key isKindOfClass:[NSString class]], "The key should be a string!");
    std::string pKey = [key UTF8String];

	// the value is a new dictionary
    if ([value isKindOfClass:[NSDictionary class]]) {
        CCDictionary<std::string, CCObject*>* pSubDict = new CCDictionary<std::string, CCObject*>();
        for (id subKey in [value allKeys]) {
            id subValue = [value objectForKey:subKey];
            static_addValueToCCDict(subKey, subValue, pSubDict);
        }
        pDict->setObject(pSubDict, pKey);
        pSubDict->release();
        return;
    }

	// the value is a string
    if ([value isKindOfClass:[NSString class]]) {
        CCString* pValue = new CCString([value UTF8String]);

        pDict->setObject(pValue, pKey);
        pValue->release();
        return;
    }

	// the value is a number
    if ([value isKindOfClass:[NSNumber class]]) {
        NSString* pStr = [value stringValue];
        CCString* pValue = new CCString([pStr UTF8String]);

        pDict->setObject(pValue, pKey);
        pValue->release();
        return;
    }

	// the value is a array
    if ([value isKindOfClass:[NSArray class]]) {
        CCMutableArray<CCObject*> *pArray = new CCMutableArray<CCObject*>();
        for (id item in value) {
            static_addItemToCCArray(item, pArray);
        }
        pDict->setObject(pArray, pKey);
        pArray->release();
        return;
    }
}

namespace cocos2d {

    void CCFileUtils::setResourcePath(const char *pszResourcePath)
    {
        assert(0);
    }

    int CCFileUtils::ccLoadFileIntoMemory(const char *filename, unsigned char **out)
    {
        CCAssert( out, "ccLoadFileIntoMemory: invalid 'out' parameter");
        CCAssert( &*out, "ccLoadFileIntoMemory: invalid 'out' parameter");

        size_t size = 0;
        FILE *f = fopen(filename, "rb");
        if( !f ) {
            *out = NULL;
            return -1;
        }

        fseek(f, 0, SEEK_END);
        size = ftell(f);
        fseek(f, 0, SEEK_SET);

        *out = (unsigned char*)malloc(size);
        size_t read = fread(*out, 1, size, f);
        if( read != size ) {
            free(*out);
            *out = NULL;
            return -1;
        }

        fclose(f);

        return size;
    }

    std::string& CCFileUtils::removeSuffixFromFile(std::string& cpath )
    {
        NSString *ret = nil;
        NSString *path = [NSString stringWithUTF8String:cpath.c_str()];

	    if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad )
	    {
		    if( CC_CONTENT_SCALE_FACTOR() == 2 )
		    {
			    ret = removeSuffixFromPath(__suffixiPadRetinaDisplay, path);
			}
		    else
		    {
			    ret = removeSuffixFromPath(__suffixiPad, path);
			}
	    }
	    else
	    {
		    if( CC_CONTENT_SCALE_FACTOR() == 2 )
		    {
			    ret = removeSuffixFromPath(__suffixiPhoneRetinaDisplay, [NSString stringWithUTF8String:cpath.c_str()]);
			}
		    else
		    {
			    ret = path;
			}
	    }

	    cpath = [ret UTF8String];
        return cpath;
    }

    void CCFileUtils::setiPhoneRetinaDisplaySuffix(const char *suffix)
    {
        [__suffixiPhoneRetinaDisplay release];
	    __suffixiPhoneRetinaDisplay = [[NSString stringWithUTF8String:suffix] retain];
    }

    void CCFileUtils::setiPadSuffix(const char *suffix)
    {
        [__suffixiPad release];
	    __suffixiPad = [[NSString stringWithUTF8String:suffix] retain];
    }

    void CCFileUtils::setiPadRetinaDisplaySuffix(const char *suffix)
    {
        [__suffixiPadRetinaDisplay release];
	    __suffixiPadRetinaDisplay = [[NSString stringWithUTF8String:suffix] retain];
    }

    bool fileExistsAtPath(const char *cpath, const char *csuffix)
    {
        NSString *fullpath = nil;
        NSString *relPath = [NSString stringWithUTF8String:cpath];
        NSString *suffix = [NSString stringWithUTF8String:csuffix];

	    // only if it is not an absolute path
	    if( ! [relPath isAbsolutePath] ) {
		    // pathForResource also searches in .lproj directories. issue #1230
		    NSString *file = [relPath lastPathComponent];
		    NSString *imageDirectory = [relPath stringByDeletingLastPathComponent];

		    fullpath = [[NSBundle mainBundle] pathForResource:file
												   ofType:nil
											  inDirectory:imageDirectory];

	    }

	    if (fullpath == nil)
		    fullpath = relPath;

	    NSString *path = getPathForSuffix(fullpath, suffix);

	    return ( path != nil );
    }

    bool CCFileUtils::iPhoneRetinaDisplayFileExistsAtPath(const char *cpath)
    {
        return fileExistsAtPath(cpath, [__suffixiPhoneRetinaDisplay UTF8String]);
    }

    bool CCFileUtils::iPadFileExistsAtPath(const char *cpath)
    {
        return fileExistsAtPath(cpath, [__suffixiPad UTF8String]);
    }

    bool CCFileUtils::iPadRetinaDisplayFileExistsAtPath(const char *cpath)
    {
        return fileExistsAtPath(cpath, [__suffixiPadRetinaDisplay UTF8String]);
    }

    const char* CCFileUtils::fullPathFromRelativePath(const char *pszRelativePath)
    {
        ccResolutionType ignore;
        return fullPathFromRelativePath(pszRelativePath, &ignore);
    }

    const char* CCFileUtils::fullPathFromRelativePath(const char *pszRelativePath, ccResolutionType *pResolutionType)
    {
        CCAssert(pszRelativePath != NULL, "CCFileUtils: Invalid path");

	    NSString *fullpath = nil;
	    NSString *relPath = [NSString stringWithUTF8String:pszRelativePath];

	    // only if it is not an absolute path
	    if( ! [relPath isAbsolutePath] ) {

		    // pathForResource also searches in .lproj directories. issue #1230
		    NSString *file = [relPath lastPathComponent];
		    NSString *imageDirectory = [relPath stringByDeletingLastPathComponent];

		    fullpath = [[NSBundle mainBundle] pathForResource:file
												   ofType:nil
											  inDirectory:imageDirectory];

	    }

	    if (fullpath == nil)
	    {
		    fullpath = relPath;
		}

	    NSString *ret = nil;

	    // iPad?
	    if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
	    {
		    // Retina Display ?
		    if( CC_CONTENT_SCALE_FACTOR() == 2 ) {
			    ret = getPathForSuffix(fullpath, __suffixiPadRetinaDisplay);
			    *pResolutionType = kCCResolutioniPadRetinaDisplay;
		    }
		    else
		    {
			    ret = getPathForSuffix(fullpath, __suffixiPad);
			    *pResolutionType = kCCResolutioniPad;
		    }
	    }
	    // iPhone ?
	    else
	    {
		    // Retina Display ?
		    if( CC_CONTENT_SCALE_FACTOR() == 2 ) {
			    ret = getPathForSuffix(fullpath, __suffixiPhoneRetinaDisplay);
			    *pResolutionType = kCCResolutioniPhoneRetinaDisplay;
		    }
	    }

	    // If it is iPhone Non RetinaDisplay, or if the previous "getPath" failed, then use iPhone images.
	    if( ret == nil )
	    {
		    *pResolutionType = kCCResolutioniPhone;
		    ret = fullpath;
	    }

	    return [ret UTF8String];
    }

    const char *CCFileUtils::fullPathFromRelativeFile(const char *pszFilename, const char *pszRelativeFile)
    {
        std::string relativeFile = fullPathFromRelativePath(pszRelativeFile);
        CCString *pRet = new CCString();
        pRet->autorelease();
        pRet->m_sString = relativeFile.substr(0, relativeFile.rfind('/')+1);
        pRet->m_sString += pszFilename;
        return pRet->m_sString.c_str();
    }

    CCDictionary<std::string, CCObject*> *CCFileUtils::dictionaryWithContentsOfFile(const char *pFileName)
    {
        CCDictionary<std::string, CCObject*> *ret = dictionaryWithContentsOfFileThreadSafe(pFileName);
	      ret->autorelease();

	      return ret;
    }

    CCDictionary<std::string, CCObject*> *CCFileUtils::dictionaryWithContentsOfFileThreadSafe(const char *pFileName)
    {
        NSString* pPath = [NSString stringWithUTF8String:pFileName];
        NSDictionary* pDict = [NSDictionary dictionaryWithContentsOfFile:pPath];

        CCDictionary<std::string, CCObject*>* pRet = new CCDictionary<std::string, CCObject*>();
        for (id key in [pDict allKeys]) {
            id value = [pDict objectForKey:key];
            static_addValueToCCDict(key, value, pRet);
        }

        return pRet;
    }

    unsigned char* CCFileUtils::getFileData(const char* pszFileName, const char* pszMode, unsigned long * pSize)
    {
        unsigned char * pBuffer = NULL;

        do
        {
            // read the file from hardware
            FILE *fp = fopen(pszFileName, pszMode);
            CC_BREAK_IF(!fp);

            fseek(fp,0,SEEK_END);
            *pSize = ftell(fp);
            fseek(fp,0,SEEK_SET);
            pBuffer = new unsigned char[*pSize];
            *pSize = fread(pBuffer,sizeof(unsigned char), *pSize,fp);
            fclose(fp);
        } while (0);

        if (! pBuffer && getIsPopupNotify())
        {
            std::string title = "Notification";
            std::string msg = "Get data from file(";
            msg.append(pszFileName).append(") failed!");

            CCMessageBox(msg.c_str(), title.c_str());
        }
        return pBuffer;
    }
    void CCFileUtils::setResource(const char* pszZipFileName)
    {
        CCAssert(0, "Have not implement!");
    }

    // notification support when getFileData from a invalid file
    static bool s_bPopupNotify = true;

    void CCFileUtils::setIsPopupNotify(bool bNotify)
    {
        s_bPopupNotify = bNotify;
    }

    bool CCFileUtils::getIsPopupNotify()
    {
        return s_bPopupNotify;
    }

    std::string CCFileUtils::getWriteablePath()
    {
        // save to document folder
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        std::string strRet = [documentsDirectory UTF8String];
        strRet.append("/");
        return strRet;
    }

    unsigned char* CCFileUtils::getFileDataFromZip(const char* pszZipFilePath, const char* pszFileName, unsigned long * pSize)
    {
		    unsigned char * pBuffer = NULL;
		    unzFile pFile = NULL;
		    *pSize = 0;

		    do
		    {
		        CC_BREAK_IF(!pszZipFilePath || !pszFileName);
		        CC_BREAK_IF(strlen(pszZipFilePath) == 0);

		        pFile = unzOpen(pszZipFilePath);
		        CC_BREAK_IF(!pFile);

		        int nRet = unzLocateFile(pFile, pszFileName, 1);
		        CC_BREAK_IF(UNZ_OK != nRet);

		        char szFilePathA[260];
		        unz_file_info FileInfo;
		        nRet = unzGetCurrentFileInfo(pFile, &FileInfo, szFilePathA, sizeof(szFilePathA), NULL, 0, NULL, 0);
		        CC_BREAK_IF(UNZ_OK != nRet);

		        nRet = unzOpenCurrentFile(pFile);
		        CC_BREAK_IF(UNZ_OK != nRet);

		        pBuffer = new unsigned char[FileInfo.uncompressed_size];
		        int nSize = 0;
		        nSize = unzReadCurrentFile(pFile, pBuffer, FileInfo.uncompressed_size);
		        CCAssert(nSize == 0 || nSize == (int)FileInfo.uncompressed_size, "the file size is wrong");

		        *pSize = FileInfo.uncompressed_size;
		        unzCloseCurrentFile(pFile);
		    } while (0);

		    if (pFile)
		    {
		        unzClose(pFile);
		    }

				return pBuffer;
    }

}//namespace cocos2d


code:
/****************************************************************************
Copyright (c) 2010 cocos2d-x.org

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.
****************************************************************************/
#import "CCImage.h"
#import "CCFileUtils.h"
#import <string>

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

#if CC_FONT_LABEL_SUPPORT
// FontLabel support
#import "FontLabel/FontManager.h"
#import "FontLabel/FontLabelStringDrawing.h"
#endif// CC_FONT_LABEL_SUPPORT

typedef struct
{
    unsigned int height;
    unsigned int width;
    int         bitsPerComponent;
    bool        hasAlpha;
    bool        isPremultipliedAlpha;
    unsigned char*  data;
} tImageInfo;

static unsigned int nextPOT(unsigned int x)
{
    x = x - 1;
    x = x | (x >> 1);
    x = x | (x >> 2);
    x = x | (x >> 4);
    x = x | (x >> 8);
    x = x | (x >> 16);
    return x + 1;
}

typedef enum {
    kCCTexture2DPixelFormat_Automatic = 0,
        //! 32-bit texture: RGBA8888
    kCCTexture2DPixelFormat_RGBA8888,
        //! 24-bit texture: RGBA888
    kCCTexture2DPixelFormat_RGB888,
        //! 16-bit texture without Alpha channel
    kCCTexture2DPixelFormat_RGB565,
        //! 8-bit textures used as masks
    kCCTexture2DPixelFormat_A8,
        //! 16-bit textures: RGBA4444
    kCCTexture2DPixelFormat_RGBA4444,
        //! 16-bit textures: RGB5A1
    kCCTexture2DPixelFormat_RGB5A1,

        //! Default texture format: RGBA8888
    kCCTexture2DPixelFormat_Default = kCCTexture2DPixelFormat_RGBA8888,

        // backward compatibility stuff
    kTexture2DPixelFormat_Automatic = kCCTexture2DPixelFormat_Automatic,
    kTexture2DPixelFormat_RGBA8888 = kCCTexture2DPixelFormat_RGBA8888,
    kTexture2DPixelFormat_RGB888 = kCCTexture2DPixelFormat_RGB888,
    kTexture2DPixelFormat_RGB565 = kCCTexture2DPixelFormat_RGB565,
    kTexture2DPixelFormat_A8 = kCCTexture2DPixelFormat_A8,
    kTexture2DPixelFormat_RGBA4444 = kCCTexture2DPixelFormat_RGBA4444,
    kTexture2DPixelFormat_RGB5A1 = kCCTexture2DPixelFormat_RGB5A1,
    kTexture2DPixelFormat_Default = kCCTexture2DPixelFormat_Default

} CCTexture2DPixelFormat;

static bool _initPremultipliedATextureWithImage(CGImageRef image, NSUInteger POTWide, NSUInteger POTHigh, tImageInfo *pImageInfo)
{
    NSUInteger            i;
    CGContextRef        context = nil;
    unsigned char*        data = nil;;
    CGColorSpaceRef        colorSpace;
    unsigned char*        tempData;
    unsigned int*        inPixel32;
    unsigned short*        outPixel16;
    bool                hasAlpha;
    CGImageAlphaInfo    info;
    CGSize                imageSize;
    CCTexture2DPixelFormat    pixelFormat;

    info = CGImageGetAlphaInfo(image);
    hasAlpha = ((info == kCGImageAlphaPremultipliedLast) || (info == kCGImageAlphaPremultipliedFirst) || (info == kCGImageAlphaLast) || (info == kCGImageAlphaFirst) ? YES : NO);

    size_t bpp = CGImageGetBitsPerComponent(image);
    colorSpace = CGImageGetColorSpace(image);

    if(colorSpace)
    {
        if(hasAlpha || bpp >= 8)
        {
            pixelFormat = kCCTexture2DPixelFormat_Default;
        }
        else
        {
            pixelFormat = kCCTexture2DPixelFormat_RGB565;
        }
    }
    else
    {
        // NOTE: No colorspace means a mask image
        pixelFormat = kCCTexture2DPixelFormat_A8;
    }

    imageSize.width = CGImageGetWidth(image);
    imageSize.height = CGImageGetHeight(image);

    // Create the bitmap graphics context

    switch(pixelFormat)
    {
        case kCCTexture2DPixelFormat_RGBA8888:
        case kCCTexture2DPixelFormat_RGBA4444:
        case kCCTexture2DPixelFormat_RGB5A1:
            colorSpace = CGColorSpaceCreateDeviceRGB();
            data = new unsigned char[POTHigh * POTWide * 4];
            info = hasAlpha ? kCGImageAlphaPremultipliedLast : kCGImageAlphaNoneSkipLast;
            context = CGBitmapContextCreate(data, POTWide, POTHigh, 8, 4 * POTWide, colorSpace, info | kCGBitmapByteOrder32Big);
            CGColorSpaceRelease(colorSpace);
            break;

        case kCCTexture2DPixelFormat_RGB565:
            colorSpace = CGColorSpaceCreateDeviceRGB();
            data = new unsigned char[POTHigh * POTWide * 4];
            info = kCGImageAlphaNoneSkipLast;
            context = CGBitmapContextCreate(data, POTWide, POTHigh, 8, 4 * POTWide, colorSpace, info | kCGBitmapByteOrder32Big);
            CGColorSpaceRelease(colorSpace);
            break;
        case kCCTexture2DPixelFormat_A8:
            data = new unsigned char[POTHigh * POTWide];
            info = kCGImageAlphaOnly;
            context = CGBitmapContextCreate(data, POTWide, POTHigh, 8, POTWide, NULL, info);
            break;
        default:
            return false;
    }

    CGRect rect;
    rect.size.width = POTWide;
    rect.size.height = POTHigh;
    rect.origin.x = 0;
    rect.origin.y = 0;

    CGContextClearRect(context, rect);
    CGContextTranslateCTM(context, 0, POTHigh - imageSize.height);
    rect.size.width = CGImageGetWidth(image);
    rect.size.height = CGImageGetHeight(image);
    rect.origin.x = 0;
    rect.origin.y = 0;
    CGContextDrawImage(context, rect, image);

    // Repack the pixel data into the right format

    if(pixelFormat == kCCTexture2DPixelFormat_RGB565)
    {
        //Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGGBBBBB"
        tempData = new unsigned char[POTHigh * POTWide * 2];
        inPixel32 = (unsigned int*)data;
        outPixel16 = (unsigned short*)tempData;
        for(i = 0; i < POTWide * POTHigh; ++i, ++inPixel32)
        {
            *outPixel16++ = ((((*inPixel32 >> 0) & 0xFF) >> 3) << 11) | ((((*inPixel32 >> 8) & 0xFF) >> 2) << 5) | ((((*inPixel32 >> 16) & 0xFF) >> 3) << 0);
        }

        delete[] data;
        data = tempData;

    }
    else if (pixelFormat == kCCTexture2DPixelFormat_RGBA4444)
    {
        //Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRGGGGBBBBAAAA"
        tempData = new unsigned char[POTHigh * POTWide * 2];
        inPixel32 = (unsigned int*)data;
        outPixel16 = (unsigned short*)tempData;
        for(i = 0; i < POTWide * POTHigh; ++i, ++inPixel32)
        {
            *outPixel16++ =
            ((((*inPixel32 >> 0) & 0xFF) >> 4) << 12) | // R
            ((((*inPixel32 >> 8) & 0xFF) >> 4) << 8) | // G
            ((((*inPixel32 >> 16) & 0xFF) >> 4) << 4) | // B
            ((((*inPixel32 >> 24) & 0xFF) >> 4) << 0); // A
        }

        delete[] data;
        data = tempData;

    }
    else if (pixelFormat == kCCTexture2DPixelFormat_RGB5A1)
    {
        //Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGBBBBBA"
        tempData = new unsigned char[POTHigh * POTWide * 2];
        inPixel32 = (unsigned int*)data;
        outPixel16 = (unsigned short*)tempData;
        for(i = 0; i < POTWide * POTHigh; ++i, ++inPixel32)
        {
            *outPixel16++ =
            ((((*inPixel32 >> 0) & 0xFF) >> 3) << 11) | // R
            ((((*inPixel32 >> 8) & 0xFF) >> 3) << 6) | // G
            ((((*inPixel32 >> 16) & 0xFF) >> 3) << 1) | // B
            ((((*inPixel32 >> 24) & 0xFF) >> 7) << 0); // A
        }

        delete[] data;
        data = tempData;
    }

    // should be after calling super init
    pImageInfo->isPremultipliedAlpha = true;
    pImageInfo->hasAlpha = true;
    pImageInfo->bitsPerComponent = bpp;
    pImageInfo->width = imageSize.width;
    pImageInfo->height = imageSize.height;

    if (pImageInfo->data)
    {
        delete [] pImageInfo->data;
    }
    pImageInfo->data = data;

    CGContextRelease(context);
    return true;
}

static bool _initWithImage(CGImageRef CGImage, tImageInfo *pImageinfo)
{
    NSUInteger POTWide, POTHigh;

    if(CGImage == NULL)
    {
        return false;
    }

    POTWide = CGImageGetWidth(CGImage);
    POTHigh = CGImageGetHeight(CGImage);

    // always load premultiplied images
    _initPremultipliedATextureWithImage(CGImage, POTWide, POTHigh, pImageinfo);

    return true;
}

static bool _initWithFile(const char* path, tImageInfo *pImageinfo)
{
    CGImageRef                CGImage;
    UIImage                    *jpg;
    UIImage                    *png;
    bool            ret;

    // convert jpg to png before loading the texture

    NSString *fullPath = [NSString stringWithUTF8String:path];
    jpg = [[UIImage alloc] initWithContentsOfFile: fullPath];
    png = [[UIImage alloc] initWithData:UIImagePNGRepresentation(jpg)];
    CGImage = png.CGImage;

    ret = _initWithImage(CGImage, pImageinfo);

    [png release];
    [jpg release];

    return ret;
}

static bool _initWithData(void * pBuffer, int length, tImageInfo *pImageinfo)
{
    bool ret = false;

    if (pBuffer)
    {
        CGImageRef CGImage;
        NSData *data;

        data = [NSData dataWithBytes:pBuffer length:length];
        CGImage = [[UIImage imageWithData:data] CGImage];

        ret = _initWithImage(CGImage, pImageinfo);
    }

    return ret;
}

static bool _isValidFontName(const char *fontName)
{
    bool ret = false;

    NSString *fontNameNS = [NSString stringWithUTF8String:fontName];

    for (NSString *familiName in [UIFont familyNames])
    {
        if ([familiName isEqualToString:fontNameNS])
        {
            ret = true;
            goto out;
        }

        for(NSString *font in [UIFont fontNamesForFamilyName: familiName])
        {
            if ([font isEqualToString: fontNameNS])
            {
                ret = true;
                goto out;
            }
        }
    }

    out:
    return ret;
}

static CGSize _caculateStringSizeWithFontOrZFont(NSString *str, id font, CGSize *constrainSize, bool isZfont)
{
    NSArray *listItems = [str componentsSeparatedByString: @"\n"];
    CGSize dim = CGSizeZero;
    CGSize textRect = CGSizeZero;
    textRect.width = constrainSize->width > 0 ? constrainSize->width
                                              : 0x7fffffff;
    textRect.height = constrainSize->height > 0 ? constrainSize->height
                                              : 0x7fffffff;

    for (NSString *s in listItems)
    {
        CGSize tmp;
        if (isZfont)
        {
            tmp = [FontLabelStringDrawingHelper sizeWithZFont:str zfont:font constrainedToSize:textRect];
        }
        else
        {
           tmp = [s sizeWithFont:font constrainedToSize:textRect];
        }

        if (tmp.width > dim.width)
        {
           dim.width = tmp.width;
        }

        dim.height += tmp.height;
    }

    return dim;
}

static bool _initWithString(const char * pText, cocos2d::CCImage::ETextAlign eAlign, const char * pFontName, int nSize, tImageInfo* pInfo)
{
    bool bRet = false;
    do
    {
        CC_BREAK_IF(! pText || ! pInfo);

        NSString * str  = [NSString stringWithUTF8String:pText];
        NSString * fntName = [NSString stringWithUTF8String:pFontName];
        CGSize dim, constrainSize;
        constrainSize.width = pInfo->width;
        constrainSize.height = pInfo->height;

        // create the font
        id font;
        font = [UIFont fontWithName:fntName size:nSize];
        if (font)
        {
                dim = _caculateStringSizeWithFontOrZFont(str, font, &constrainSize, false);
        }

#if CC_FONT_LABEL_SUPPORT
	    if (! font)
	    {
		        font = [[FontManager sharedManager] zFontWithName:fntName pointSize:nSize];
		        if (font)
                {
                    //dim = [str sizeWithZFont:font];
                    dim =_caculateStringSizeWithFontOrZFont(str, font, &constrainSize, true);
                }
	    }
#endif // CC_FONT_LABEL_SUPPORT

        if (! font)
        {
                fntName = _isValidFontName(pFontName) ? fntName : @"MarkerFelt-Wide";
                font = [UIFont fontWithName:fntName size:nSize];

                if (! font)
                {
                        font = [UIFont systemFontOfSize:nSize];
                }

                if (font)
                {
                    dim = _caculateStringSizeWithFontOrZFont(str, font, &constrainSize, false);
                }
        }

        CC_BREAK_IF(! font);

        // compute start point
        int startH = 0;
        if (constrainSize.height > dim.height)
        {
            startH = (constrainSize.height - dim.height) / 2;
        }

        // adjust text rect
        if (constrainSize.width > 0 && constrainSize.width > dim.width)
        {
            dim.width = constrainSize.width;
        }
        if (constrainSize.height > 0 && constrainSize.height > dim.height)
        {
            dim.height = constrainSize.height;
        }

        unsigned char* data = new unsigned char[(int)(dim.width * dim.height * 4)];
        memset(data, 0, (int)(dim.width * dim.height * 4));

        // draw text
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        CGContextRef context = CGBitmapContextCreate(data, dim.width, dim.height, 8, dim.width * 4, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
        CGColorSpaceRelease(colorSpace);

		if (! context)
		{
		        delete[] data;
		        break;
		}

        CGContextSetRGBFillColor(context, 1, 1, 1, 1);
        CGContextTranslateCTM(context, 0.0f, dim.height);
        CGContextScaleCTM(context, 1.0f, -1.0f); //NOTE: NSString draws in UIKit referential i.e. renders upside-down compared to CGBitmapContext referential
        UIGraphicsPushContext(context);

        // measure text size with specified font and determine the rectangle to draw text in
        unsigned uHoriFlag = eAlign & 0x0f;
        UITextAlignment align = (2 == uHoriFlag) ? UITextAlignmentRight
                                : (3 == uHoriFlag) ? UITextAlignmentCenter
                                : UITextAlignmentLeft;

        // normal fonts
	if( [font isKindOfClass:[UIFont class] ] )
	{
		[str drawInRect:CGRectMake(0, startH, dim.width, dim.height) withFont:font lineBreakMode:UILineBreakModeWordWrap alignment:align];
	}

#if CC_FONT_LABEL_SUPPORT
	else // ZFont class
	{
		[FontLabelStringDrawingHelper drawInRect:str rect:CGRectMake(0, startH, dim.width, dim.height) withZFont:font lineBreakMode:UILineBreakModeWordWrap alignment:align];
	}
#endif

        UIGraphicsPopContext();

        CGContextRelease(context);

        // output params
        pInfo->data = data;
        pInfo->hasAlpha = true;
        pInfo->isPremultipliedAlpha = true;
        pInfo->bitsPerComponent = 8;
        pInfo->width = dim.width;
        pInfo->height = dim.height;
        bRet = true;
    } while (0);

    return bRet;
}

NS_CC_BEGIN;

CCImage::CCImage()
: m_nWidth(0)
, m_nHeight(0)
, m_nBitsPerComponent(0)
, m_pData(0)
, m_bHasAlpha(false)
, m_bPreMulti(false)
{

}

CCImage::~CCImage()
{
    CC_SAFE_DELETE_ARRAY(m_pData);
}

bool CCImage::initWithImageFile(const char * strPath, EImageFormat eImgFmt/* = eFmtPng*/)
{
    CCFileData data(CCFileUtils::fullPathFromRelativePath(strPath), "rb");
    return initWithImageData(data.getBuffer(), data.getSize(), eImgFmt);
}

bool CCImage::initWithImageFileThreadSafe(const char *fullpath, EImageFormat imageType)
{
	  CC_UNUSED_PARAM(imageType);
	  /*
	   * CCFileUtils::fullPathFromRelativePath() is not thread-safe, it use autorelease().
	   */
    CCFileData data(fullpath, "rb");
    return initWithImageData(data.getBuffer(), data.getSize(), imageType);
}

bool CCImage::initWithImageData(void * pData,
                                int nDataLen,
                                EImageFormat eFmt,
                                int nWidth,
                                int nHeight,
                                int nBitsPerComponent)
{
    bool bRet = false;
    tImageInfo info = {0};
    do
    {
        CC_BREAK_IF(! pData || nDataLen <= 0);
        if (eFmt == kFmtRawData)
        {
            bRet = _initWithRawData(pData, nDataLen, nWidth, nHeight, nBitsPerComponent);
        }
        else // init with png or jpg file data
        {
            bRet = _initWithData(pData, nDataLen, &info);
            if (bRet)
            {
                m_nHeight = (short)info.height;
                m_nWidth = (short)info.width;
                m_nBitsPerComponent = info.bitsPerComponent;
                m_bHasAlpha = info.hasAlpha;
                m_bPreMulti = info.isPremultipliedAlpha;
                m_pData = info.data;
            }
        }
    } while (0);

    return bRet;
}

bool CCImage::_initWithRawData(void *pData, int nDatalen, int nWidth, int nHeight, int nBitsPerComponent)
{
    bool bRet = false;
	do
	{
		CC_BREAK_IF(0 == nWidth || 0 == nHeight);

		m_nBitsPerComponent = nBitsPerComponent;
		m_nHeight   = (short)nHeight;
		m_nWidth    = (short)nWidth;
		m_bHasAlpha = true;

		// only RGBA8888 surported
		int nBytesPerComponent = 4;
		int nSize = nHeight * nWidth * nBytesPerComponent;
		m_pData = new unsigned char[nSize];
		CC_BREAK_IF(! m_pData);
		memcpy(m_pData, pData, nSize);

		bRet = true;
	} while (0);
	return bRet;
}

bool CCImage::_initWithJpgData(void *pData, int nDatalen)
{
    assert(0);
}

bool CCImage::_initWithPngData(void *pData, int nDatalen)
{
    assert(0);
}

bool CCImage::_saveImageToPNG(const char *pszFilePath, bool bIsToRGB)
{
    assert(0);
}

bool CCImage::_saveImageToJPG(const char *pszFilePath)
{
    assert(0);
}

bool CCImage::initWithString(
             const char * pText,
             int         nWidth /* = 0 */,
             int         nHeight /* = 0 */,
             ETextAlign eAlignMask /* = kAlignCenter */,
             const char * pFontName /* = nil */,
             int         nSize /* = 0 */)
{
    tImageInfo info = {0};
    info.width = nWidth;
    info.height = nHeight;

    if (! _initWithString(pText, eAlignMask, pFontName, nSize, &info))
    {
        return false;
    }
    m_nHeight = (short)info.height;
    m_nWidth = (short)info.width;
    m_nBitsPerComponent = info.bitsPerComponent;
    m_bHasAlpha = info.hasAlpha;
    m_bPreMulti = info.isPremultipliedAlpha;
    m_pData = info.data;

    return true;
}

bool CCImage::saveToFile(const char *pszFilePath, bool bIsToRGB)
{
	bool saveToPNG = false;
	bool needToCopyPixels = false;
	std::string filePath(pszFilePath);
	if (std::string::npos != filePath.find(".png"))
	{
	    saveToPNG = true;
	}

	int bitsPerComponent = 8;
	int bitsPerPixel = m_bHasAlpha ? 32 : 24;
	if ((! saveToPNG) || bIsToRGB)
	{
	    bitsPerPixel = 24;
	}

	int bytesPerRow	= (bitsPerPixel/8) * m_nWidth;
	int myDataLength = bytesPerRow * m_nHeight;

	unsigned char *pixels	= m_pData;

	// The data has alpha channel, and want to save it with an RGB png file,
    // or want to save as jpg,  remove the alpha channel.
	if ((saveToPNG && m_bHasAlpha && bIsToRGB)
       || (! saveToPNG))
	{
	    pixels = new unsigned char[myDataLength];

	    for (int i = 0; i < m_nHeight; ++i)
		{
			for (int j = 0; j < m_nWidth; ++j)
			{
				pixels[(i * m_nWidth + j) * 3] = m_pData[(i * m_nWidth + j) * 4];
				pixels[(i * m_nWidth + j) * 3 + 1] = m_pData[(i * m_nWidth + j) * 4 + 1];
				pixels[(i * m_nWidth + j) * 3 + 2] = m_pData[(i * m_nWidth + j) * 4 + 2];
			}
		}

	    needToCopyPixels = true;
	}

	// make data provider with data.
	CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
	if (saveToPNG && m_bHasAlpha && (! bIsToRGB))
	{
	    bitmapInfo |= kCGImageAlphaPremultipliedLast;
	}
	CGDataProviderRef provider		= CGDataProviderCreateWithData(NULL, pixels, myDataLength, NULL);
	CGColorSpaceRef colorSpaceRef	= CGColorSpaceCreateDeviceRGB();
	CGImageRef iref					= CGImageCreate(m_nWidth, m_nHeight,
														bitsPerComponent, bitsPerPixel, bytesPerRow,
														colorSpaceRef, bitmapInfo, provider,
														NULL, false,
														kCGRenderingIntentDefault);

	UIImage* image					= [[UIImage alloc] initWithCGImage:iref];

	CGImageRelease(iref);
	CGColorSpaceRelease(colorSpaceRef);
	CGDataProviderRelease(provider);

	NSData *data;

	if (saveToPNG)
	{
		data = UIImagePNGRepresentation(image);
	}
	else
	{
		data = UIImageJPEGRepresentation(image, 1.0f);
	}

	[data writeToFile:[NSString stringWithUTF8String:pszFilePath] atomically:YES];

	[image release];

	if (needToCopyPixels)
	{
	    delete [] pixels;
	}

	return true;
}

NS_CC_END;


code:
/****************************************************************************
Copyright (c) 2010 cocos2d-x.org

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 "CCLock.h"
namespace   cocos2d {

CCLock::CCLock(void)
{
}

CCLock::~CCLock(void)
{

}

void CCLock::lock(void)
{

}

void CCLock::unlock(void)
{

}
}//namespace   cocos2d


code:
/****************************************************************************
Copyright (c) 2010 cocos2d-x.org

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.
****************************************************************************/

#ifndef __PLATFORM_IPHONE_PLATFORM_CCLOCK_H__
#define __PLATFORM_IPHONE_PLATFORM_CCLOCK_H__

namespace   cocos2d {

class CCLock
{
public:
	CCLock(void);
	~CCLock(void);

	void lock(void);
	void unlock(void);
};
}//namespace   cocos2d

#endif // __PLATFORM_IPHONE_PLATFORM_CCLOCK_H__


code:
/****************************************************************************
Copyright (c) 2010 cocos2d-x.org

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.
****************************************************************************/
#import <UIKit/UIKit.h>
#include "CCThread.h"

NS_CC_BEGIN;

CCThread::~CCThread()
{
    [(id)m_pAutoreasePool release];
}

void CCThread::createAutoreleasePool()
{
    m_pAutoreasePool = [[NSAutoreleasePool alloc] init];
}

NS_CC_END;


code:
/*

===== IMPORTANT =====

This is sample code demonstrating API, technology or techniques in development.
Although this sample code has been reviewed for technical accuracy, it is not
final. Apple is supplying this information to help you plan for the adoption of
the technologies and programming interfaces described herein. This information
is subject to change, and software implemented based on this sample code should
be tested with final operating system software and final documentation. Newer
versions of this sample code may be provided with future seeds of the API or
technology. For information about updates to this and other developer
documentation, view the New & Updated sidebars in subsequent documentation
seeds.

=====================

File: EAGLView.h
Abstract: Convenience class that wraps the CAEAGLLayer from CoreAnimation into a
UIView subclass.

Version: 1.3

Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple Inc.
("Apple") in consideration of your agreement to the following terms, and your
use, installation, modification or redistribution of this Apple software
constitutes acceptance of these terms.  If you do not agree with these terms,
please do not use, install, modify or redistribute this Apple software.

In consideration of your agreement to abide by the following terms, and subject
to these terms, Apple grants you a personal, non-exclusive license, under
Apple's copyrights in this original Apple software (the "Apple Software"), to
use, reproduce, modify and redistribute the Apple Software, with or without
modifications, in source and/or binary forms; provided that if you redistribute
the Apple Software in its entirety and without modifications, you must retain
this notice and the following text and disclaimers in all such redistributions
of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may be used
to endorse or promote products derived from the Apple Software without specific
prior written permission from Apple.  Except as expressly stated in this notice,
no other rights or licenses, express or implied, are granted by Apple herein,
including but not limited to any patent rights that may be infringed by your
derivative works or by other works in which the Apple Software may be
incorporated.

The Apple Software is provided by Apple on an "AS IS" basis.  APPLE MAKES NO
WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
COMBINATION WITH YOUR PRODUCTS.

IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR
DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF
CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF
APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Copyright (C) 2008 Apple Inc. All Rights Reserved.

*/

#import <UIKit/UIKit.h>
#import <OpenGLES/EAGL.h>
#import <OpenGLES/EAGLDrawable.h>
#import <OpenGLES/ES1/gl.h>
#import <OpenGLES/ES1/glext.h>
#import <CoreFoundation/CoreFoundation.h>

#import "ESRenderer.h"

//CLASS INTERFACE:

/** EAGLView Class.
 * This class wraps the CAEAGLLayer from CoreAnimation into a convenient UIView subclass.
 * The view content is basically an EAGL surface you render your OpenGL scene into.
 * Note that setting the view non-opaque will only work if the EAGL surface has an alpha channel.
 */
@interface EAGLView : UIView <UIKeyInput, UITextInput>
{
    id						<ESRenderer> renderer_;
	EAGLContext				*context_; // weak ref

	NSString				*pixelformat_;
	GLuint					depthFormat_;
	BOOL					preserveBackbuffer_;

	CGSize					size_;
	BOOL					discardFramebufferSupported_;

	//fsaa addition
	BOOL					multisampling_;
	unsigned int               requestedSamples_;
@private
    CFMutableDictionaryRef  touchesIntergerDict;
    unsigned int               indexBitsUsed;
    NSString *              markedText_;
    CGRect                  caretRect_;
}

@property(nonatomic, readonly) UITextPosition *beginningOfDocument;
@property(nonatomic, readonly) UITextPosition *endOfDocument;
@property(nonatomic, assign) id<UITextInputDelegate> inputDelegate;
@property(nonatomic, readonly) UITextRange *markedTextRange;
@property (nonatomic, copy) NSDictionary *markedTextStyle;
@property(readwrite, copy) UITextRange *selectedTextRange;
@property(nonatomic, readonly) id<UITextInputTokenizer> tokenizer;

/** creates an initializes an EAGLView with a frame and 0-bit depth buffer, and a RGB565 color buffer */
+ (id) viewWithFrame:(CGRect)frame;
/** creates an initializes an EAGLView with a frame, a color buffer format, and 0-bit depth buffer */
+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format;
/** creates an initializes an EAGLView with a frame, a color buffer format, and a depth buffer format */
+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth;
/** creates an initializes an EAGLView with a frame, a color buffer format, a depth buffer format, a sharegroup, and multisamping */
+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegroup*)sharegroup multiSampling:(BOOL)multisampling numberOfSamples:(unsigned int)samples;

// get the view object
+(id) sharedEGLView;

/** Initializes an EAGLView with a frame and 0-bit depth buffer, and a RGB565 color buffer */
- (id) initWithFrame:(CGRect)frame; //These also set the current context
/** Initializes an EAGLView with a frame, a color buffer format, and 0-bit depth buffer */
- (id) initWithFrame:(CGRect)frame pixelFormat:(NSString*)format;
/** Initializes an EAGLView with a frame, a color buffer format, a depth buffer format, a sharegroup and multisampling support */
- (id) initWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegroup*)sharegroup multiSampling:(BOOL)sampling numberOfSamples:(unsigned int)nSamples;

/** pixel format: it could be RGBA8 (32-bit) or RGB565 (16-bit) */
@property(nonatomic,readonly) NSString* pixelFormat;
/** depth format of the render buffer: 0, 16 or 24 bits*/
@property(nonatomic,readonly) GLuint depthFormat;

/** returns surface size in pixels */
@property(nonatomic,readonly) CGSize surfaceSize;

/** OpenGL context */
@property(nonatomic,readonly) EAGLContext *context;

@property(nonatomic,readwrite) BOOL multiSampling;

@property(readonly) CFMutableDictionaryRef touchesIntergerDict;
@property(readwrite) unsigned int indexBitsUsed;

/** EAGLView uses double-buffer. This method swaps the buffers */
-(void) swapBuffers;

- (CGRect) convertRectFromViewToSurface:(CGRect)rect;
- (CGPoint) convertPointFromViewToSurface:(CGPoint)point;

-(int) getWidth;
-(int) getHeight;
-(int) getUnUsedIndex;
-(void) removeUsedIndexBit:(int) index;

@end


code:
/*

===== IMPORTANT =====

This is sample code demonstrating API, technology or techniques in development.
Although this sample code has been reviewed for technical accuracy, it is not
final. Apple is supplying this information to help you plan for the adoption of
the technologies and programming interfaces described herein. This information
is subject to change, and software implemented based on this sample code should
be tested with final operating system software and final documentation. Newer
versions of this sample code may be provided with future seeds of the API or
technology. For information about updates to this and other developer
documentation, view the New & Updated sidebars in subsequent documentation
seeds.

=====================

File: EAGLView.m
Abstract: Convenience class that wraps the CAEAGLLayer from CoreAnimation into a
UIView subclass.

Version: 1.3

Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple Inc.
("Apple") in consideration of your agreement to the following terms, and your
use, installation, modification or redistribution of this Apple software
constitutes acceptance of these terms.  If you do not agree with these terms,
please do not use, install, modify or redistribute this Apple software.

In consideration of your agreement to abide by the following terms, and subject
to these terms, Apple grants you a personal, non-exclusive license, under
Apple's copyrights in this original Apple software (the "Apple Software"), to
use, reproduce, modify and redistribute the Apple Software, with or without
modifications, in source and/or binary forms; provided that if you redistribute
the Apple Software in its entirety and without modifications, you must retain
this notice and the following text and disclaimers in all such redistributions
of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may be used
to endorse or promote products derived from the Apple Software without specific
prior written permission from Apple.  Except as expressly stated in this notice,
no other rights or licenses, express or implied, are granted by Apple herein,
including but not limited to any patent rights that may be infringed by your
derivative works or by other works in which the Apple Software may be
incorporated.

The Apple Software is provided by Apple on an "AS IS" basis.  APPLE MAKES NO
WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
COMBINATION WITH YOUR PRODUCTS.

IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR
DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF
CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF
APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Copyright (C) 2008 Apple Inc. All Rights Reserved.

*/

#import <QuartzCore/QuartzCore.h>

#import "EAGLView.h"
#import "ES1Renderer.h"
#import "CCDirector.h"
#import "CCSet.h"
#import "CCTouch.h"
#import "CCIMEDispatcher.h"
#import "OpenGL_Internal.h"

//CLASS IMPLEMENTATIONS:

#define MAX_TOUCHES     11

static EAGLView *view;
static cocos2d::CCTouch *s_pTouches[MAX_TOUCHES];

@interface EAGLView (Private)
- (BOOL) setupSurfaceWithSharegroup:(EAGLSharegroup*)sharegroup;
- (unsigned int) convertPixelFormat:(NSString*) pixelFormat;
@end

@implementation EAGLView

@synthesize surfaceSize=size_;
@synthesize pixelFormat=pixelformat_, depthFormat=depthFormat_;
@synthesize context=context_;
@synthesize touchesIntergerDict;
@synthesize indexBitsUsed;
@synthesize multiSampling=multiSampling_;

+ (Class) layerClass
{
	return [CAEAGLLayer class];
}

+ (id) viewWithFrame:(CGRect)frame
{
	return [[[self alloc] initWithFrame:frame] autorelease];
}

+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format
{
	return [[[self alloc]initWithFrame:frame pixelFormat:format] autorelease];
}

+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth
{
	return [[[self alloc] initWithFrame:frame pixelFormat:format depthFormat:depth preserveBackbuffer:NO sharegroup:nil multiSampling:NO numberOfSamples:0] autorelease];
}

+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegroup*)sharegroup multiSampling:(BOOL)multisampling numberOfSamples:(unsigned int)samples
{
	return [[[self alloc]initWithFrame:frame pixelFormat:format depthFormat:depth preserveBackbuffer:retained sharegroup:sharegroup multiSampling:multisampling numberOfSamples:samples] autorelease];
}

+ (id) sharedEGLView
{
	return view;
}

- (id) initWithFrame:(CGRect)frame
{
	return [self initWithFrame:frame pixelFormat:kEAGLColorFormatRGB565 depthFormat:0 preserveBackbuffer:NO sharegroup:nil multiSampling:NO numberOfSamples:0];
}

- (id) initWithFrame:(CGRect)frame pixelFormat:(NSString*)format
{
	return [self initWithFrame:frame pixelFormat:format depthFormat:0 preserveBackbuffer:NO sharegroup:nil multiSampling:NO numberOfSamples:0];
}

- (id) initWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegroup*)sharegroup multiSampling:(BOOL)sampling numberOfSamples:(unsigned int)nSamples;
{
	if((self = [super initWithFrame:frame]))
	{
		pixelformat_ = format;
		depthFormat_ = depth;
		multiSampling_ = sampling;
		requestedSamples_ = nSamples;
		preserveBackbuffer_ = retained;
		markedText_ = nil;
		if( ! [self setupSurfaceWithSharegroup:sharegroup] ) {
			[self release];
			return nil;
		}
        touchesIntergerDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 4, NULL, NULL);
        indexBitsUsed = 0x00000000;

        view = self;
	}

	return self;
}

-(id) initWithCoder:(NSCoder *)aDecoder
{
	if( (self = [super initWithCoder:aDecoder]) ) {

		CAEAGLLayer*			eaglLayer = (CAEAGLLayer*)[self layer];

		pixelformat_ = kEAGLColorFormatRGB565;
		depthFormat_ = 0; // GL_DEPTH_COMPONENT24_OES;
		multiSampling_= NO;
		requestedSamples_ = 0;
		size_ = [eaglLayer bounds].size;
		markedText_ = nil;

		if( ! [self setupSurfaceWithSharegroup:nil] ) {
			[self release];
			return nil;
		}
    }

	view = self;
    return self;
}

- (void)didMoveToWindow;
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onUIKeyboardNotification:)
                                                 name:UIKeyboardWillShowNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onUIKeyboardNotification:)
                                                 name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onUIKeyboardNotification:)
                                                 name:UIKeyboardWillHideNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onUIKeyboardNotification:)
                                                 name:UIKeyboardDidHideNotification object:nil];
}

-(int) getWidth
{
	CGSize bound = [self bounds].size;
	return bound.width;
}

-(int) getHeight
{
	CGSize bound = [self bounds].size;
	return bound.height;
}

-(int) getUnUsedIndex
{
    int i;
    int temp = indexBitsUsed;

    for (i = 0; i < MAX_TOUCHES; i++) {
        if (! (temp & 0x00000001)) {
            indexBitsUsed |= (1 <<  i);
            return i;
        }

        temp >>= 1;
    }

    // all bits are used
    return -1;
}

-(void) removeUsedIndexBit:(int) index
{
   if (index < 0 || index >= MAX_TOUCHES) {
       return;
   }

    unsigned int temp = 1 << index;
    temp = ~temp;
    indexBitsUsed &= temp;
}

-(BOOL) setupSurfaceWithSharegroup:(EAGLSharegroup*)sharegroup
{
	CAEAGLLayer *eaglLayer = (CAEAGLLayer *)self.layer;

	eaglLayer.opaque = YES;
	eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys:
									[NSNumber numberWithBool:preserveBackbuffer_], kEAGLDrawablePropertyRetainedBacking,
									pixelformat_, kEAGLDrawablePropertyColorFormat, nil];

	renderer_ = [[ES1Renderer alloc] initWithDepthFormat:depthFormat_
										 withPixelFormat:[self convertPixelFormat:pixelformat_]
										  withSharegroup:sharegroup
									   withMultiSampling:multiSampling_
									 withNumberOfSamples:requestedSamples_];
	if (!renderer_)
		return NO;

	context_ = [renderer_ context];
	[context_ renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:eaglLayer];

	//discardFramebufferSupported_ = [[CCConfiguration sharedConfiguration] supportsDiscardFramebuffer];

	return YES;
}

- (void) dealloc
{
    CFRelease(touchesIntergerDict);
	[renderer_ release];
	[super dealloc];
}

- (void) layoutSubviews
{
    [renderer_ resizeFromLayer:(CAEAGLLayer*)self.layer];
	size_ = [renderer_ backingSize];

	// Issue #914 #924
// 	CCDirector *director = [CCDirector sharedDirector];
// 	[director reshapeProjection:size_];
    cocos2d::CCSize size;
    size.width = size_.width;
    size.height = size_.height;
    cocos2d::CCDirector::sharedDirector()->reshapeProjection(size);

	// Avoid flicker. Issue #350
	//[director performSelectorOnMainThread:@selector(drawScene) withObject:nil waitUntilDone:YES];
	cocos2d::CCDirector::sharedDirector()->drawScene();
}

- (void) swapBuffers
{
	// IMPORTANT:
	// - preconditions
	//	-> context_ MUST be the OpenGL context
	//	-> renderbuffer_ must be the the RENDER BUFFER

#ifdef __IPHONE_4_0

	if (multiSampling_)
	{
		/* Resolve from msaaFramebuffer to resolveFramebuffer */
		//glDisable(GL_SCISSOR_TEST);
		glBindFramebufferOES(GL_READ_FRAMEBUFFER_APPLE, [renderer_ msaaFrameBuffer]);
		glBindFramebufferOES(GL_DRAW_FRAMEBUFFER_APPLE, [renderer_ defaultFrameBuffer]);
		glResolveMultisampleFramebufferAPPLE();
	}

	if( discardFramebufferSupported_)
	{
		if (multiSampling_)
		{
			if (depthFormat_)
			{
				GLenum attachments[] = {GL_COLOR_ATTACHMENT0_OES, GL_DEPTH_ATTACHMENT_OES};
				glDiscardFramebufferEXT(GL_READ_FRAMEBUFFER_APPLE, 2, attachments);
			}
			else
			{
				GLenum attachments[] = {GL_COLOR_ATTACHMENT0_OES};
				glDiscardFramebufferEXT(GL_READ_FRAMEBUFFER_APPLE, 1, attachments);
			}

			glBindRenderbufferOES(GL_RENDERBUFFER_OES, [renderer_ colorRenderBuffer]);

		}

		// not MSAA
		else if (depthFormat_ ) {
			GLenum attachments[] = { GL_DEPTH_ATTACHMENT_OES};
			glDiscardFramebufferEXT(GL_FRAMEBUFFER_OES, 1, attachments);
		}
	}

#endif // __IPHONE_4_0

 	if(![context_ presentRenderbuffer:GL_RENDERBUFFER_OES])
        {
// 		CCLOG(@"cocos2d: Failed to swap renderbuffer in %s\n", __FUNCTION__);
        }

#if COCOS2D_DEBUG
	CHECK_GL_ERROR();
#endif

	// We can safely re-bind the framebuffer here, since this will be the
	// 1st instruction of the new main loop
	if( multiSampling_ )
		glBindFramebufferOES(GL_FRAMEBUFFER_OES, [renderer_ msaaFrameBuffer]);
}

- (unsigned int) convertPixelFormat:(NSString*) pixelFormat
{
	// define the pixel format
	GLenum pFormat;

	if([pixelFormat isEqualToString:@"EAGLColorFormat565"])
		pFormat = GL_RGB565_OES;
	else
		pFormat = GL_RGBA8_OES;

	return pFormat;
}

#pragma mark EAGLView - Point conversion

- (CGPoint) convertPointFromViewToSurface:(CGPoint)point
{
	CGRect bounds = [self bounds];

        CGPoint ret;
        ret.x = (point.x - bounds.origin.x) / bounds.size.width * size_.width;
        ret.y =  (point.y - bounds.origin.y) / bounds.size.height * size_.height;

        return ret;
}

- (CGRect) convertRectFromViewToSurface:(CGRect)rect
{
	CGRect bounds = [self bounds];

        CGRect ret;
        ret.origin.x = (rect.origin.x - bounds.origin.x) / bounds.size.width * size_.width;
        ret.origin.y = (rect.origin.y - bounds.origin.y) / bounds.size.height * size_.height;
        ret.size.width = rect.size.width / bounds.size.width * size_.width;
        ret.size.height = rect.size.height / bounds.size.height * size_.height;

        return ret;
}

// Pass the touches to the superview
#pragma mark EAGLView - Touch Delegate

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
	cocos2d::CCSet set;
    cocos2d::CCTouch *pTouch;

	for (UITouch *touch in touches) {
        NSNumber *index = (NSNumber*)CFDictionaryGetValue(touchesIntergerDict, touch);
        int unUsedIndex = 0;

        // it is a new touch
        if (! index) {
            unUsedIndex = [self getUnUsedIndex];

            // The touches is more than MAX_TOUCHES ?
            if (unUsedIndex == -1) {
                return;
            }

            pTouch = s_pTouches[unUsedIndex] = new cocos2d::CCTouch();
            float x = [touch locationInView: [touch view]].x;
            float y = [touch locationInView: [touch view]].y;
            pTouch->SetTouchInfo(x, y);

            CFDictionaryAddValue(touchesIntergerDict, touch, [NSNumber numberWithInt:unUsedIndex]);

            set.addObject(pTouch);
        }

	}

    if (set.count() == 0)
        return;

	cocos2d::CCDirector::sharedDirector()->getOpenGLView()->touchesBegan(&set);
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
	cocos2d::CCSet set;
	for (UITouch *touch in touches) {
		NSNumber *index = (NSNumber*)CFDictionaryGetValue(touchesIntergerDict, touch);
                if (! index) {
                    // if the index doesn't exist, it is an error
                    return;
                }

                cocos2d::CCTouch *pTouch = s_pTouches[[index intValue]];
                if (! pTouch) {
                    // if the pTouch is null, it is an error
                    return;
                }

		float x = [touch locationInView: [touch view]].x;
		float y = [touch locationInView: [touch view]].y;
		pTouch->SetTouchInfo(x, y);

		set.addObject(pTouch);
	}

	cocos2d::CCDirector::sharedDirector()->getOpenGLView()->touchesMoved(&set);
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
	cocos2d::CCSet set;
	for (UITouch *touch in touches) {
            NSNumber *index = (NSNumber*)CFDictionaryGetValue(touchesIntergerDict, touch);
            if (! index) {
                // if the index doesn't exist, it is an error
                return;
            }

                cocos2d::CCTouch *pTouch = s_pTouches[[index intValue]];
                if (! pTouch) {
                    // if the pTouch is null, it is an error
                    return;
                }

		float x = [touch locationInView: [touch view]].x;
		float y = [touch locationInView: [touch view]].y;
		pTouch->SetTouchInfo(x, y);

		set.addObject(pTouch);
                CFDictionaryRemoveValue(touchesIntergerDict, touch);
                pTouch->release();
                s_pTouches[[index intValue]] = NULL;
                [self removeUsedIndexBit:[index intValue]];
	}

	cocos2d::CCDirector::sharedDirector()->getOpenGLView()->touchesEnded(&set);
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
	cocos2d::CCSet set;
	for (UITouch *touch in touches) {
            NSNumber *index = (NSNumber*)CFDictionaryGetValue(touchesIntergerDict, touch);
            if (! index) {
                // if the index doesn't exist, it is an error
                return;
            }

                cocos2d::CCTouch *pTouch = s_pTouches[[index intValue]];
                if (! pTouch) {
                    // if the pTouch is null, it is an error
                    return;
                }

		float x = [touch locationInView: [touch view]].x;
		float y = [touch locationInView: [touch view]].y;
		pTouch->SetTouchInfo(x, y);

		set.addObject(pTouch);
                CFDictionaryRemoveValue(touchesIntergerDict, touch);
                pTouch->release();
                s_pTouches[[index intValue]] = NULL;
                [self removeUsedIndexBit:[index intValue]];
	}

	cocos2d::CCDirector::sharedDirector()->getOpenGLView()->touchesCancelled(&set);
}

#pragma mark -
#pragma mark UIView - Responder

- (BOOL)canBecomeFirstResponder
{
	if (nil != markedText_) {
		[markedText_ release];
	}
    markedText_ = nil;
    return YES;
}

#pragma mark -
#pragma mark UIKeyInput protocol

- (BOOL)hasText
{
    return NO;
}

- (void)insertText:(NSString *)text
{
	if (nil != markedText_) {
		[markedText_ release];
		markedText_ = nil;
	}
    const char * pszText = [text cStringUsingEncoding:NSUTF8StringEncoding];
    cocos2d::CCIMEDispatcher::sharedDispatcher()->dispatchInsertText(pszText, strlen(pszText));
}

- (void)deleteBackward
{
	if (nil != markedText_) {
		[markedText_ release];
		markedText_ = nil;
	}
    cocos2d::CCIMEDispatcher::sharedDispatcher()->dispatchDeleteBackward();
}

#pragma mark -
#pragma mark UITextInputTrait protocol

-(UITextAutocapitalizationType) autocapitalizationType
{
    return UITextAutocapitalizationTypeNone;
}

#pragma mark -
#pragma mark UITextInput protocol

#pragma mark UITextInput - properties

@synthesize beginningOfDocument;
@synthesize endOfDocument;
@synthesize inputDelegate;
@synthesize markedTextRange;
@synthesize markedTextStyle;
// @synthesize selectedTextRange;       // must implement
@synthesize tokenizer;

/* Text may have a selection, either zero-length (a caret) or ranged.  Editing operations are
 * always performed on the text from this selection.  nil corresponds to no selection. */
- (void)setSelectedTextRange:(UITextRange *)aSelectedTextRange;
{
    CCLOG("UITextRange:setSelectedTextRange");
}
- (UITextRange *)selectedTextRange;
{
	return [[[UITextRange alloc] init] autorelease];
}

#pragma mark UITextInput - Replacing and Returning Text

- (NSString *)textInRange:(UITextRange *)range;
{
    CCLOG("textInRange");
	return @"";
}
- (void)replaceRange:(UITextRange *)range withText:(NSString *)theText;
{
    CCLOG("replaceRange");
}

#pragma mark UITextInput - Working with Marked and Selected Text

/* If text can be selected, it can be marked. Marked text represents provisionally
 * inserted text that has yet to be confirmed by the user.  It requires unique visual
 * treatment in its display.  If there is any marked text, the selection, whether a
 * caret or an extended range, always resides witihin.
 *
 * Setting marked text either replaces the existing marked text or, if none is present,
 * inserts it from the current selection. */

- (void)setMarkedTextRange:(UITextRange *)markedTextRange;
{
    CCLOG("setMarkedTextRange");
}

- (UITextRange *)markedTextRange;
{
    CCLOG("markedTextRange");
	return nil; // Nil if no marked text.
}
- (void)setMarkedTextStyle:(NSDictionary *)markedTextStyle;
{
    CCLOG("setMarkedTextStyle");

}
- (NSDictionary *)markedTextStyle;
{
    CCLOG("markedTextStyle");
	return nil;
}
- (void)setMarkedText:(NSString *)markedText selectedRange:(NSRange)selectedRange;
{
    CCLOG("setMarkedText");
	if (markedText == markedText_) {
		return;
	}
	if (nil != markedText_) {
		[markedText_ release];
	}
    markedText_ = markedText;
	[markedText_ retain];
}
- (void)unmarkText;
{
    CCLOG("unmarkText");
    if (nil == markedText_)
    {
        return;
    }
    const char * pszText = [markedText_ cStringUsingEncoding:NSUTF8StringEncoding];
    cocos2d::CCIMEDispatcher::sharedDispatcher()->dispatchInsertText(pszText, strlen(pszText));
	[markedText_ release];
    markedText_ = nil;
}

#pragma mark Methods for creating ranges and positions.

- (UITextRange *)textRangeFromPosition:(UITextPosition *)fromPosition toPosition:(UITextPosition *)toPosition;
{
    CCLOG("textRangeFromPosition");
	return nil;
}
- (UITextPosition *)positionFromPosition:(UITextPosition *)position offset:(NSInteger)offset;
{
    CCLOG("positionFromPosition");
	return nil;
}
- (UITextPosition *)positionFromPosition:(UITextPosition *)position inDirection:(UITextLayoutDirection)direction offset:(NSInteger)offset;
{
    CCLOG("positionFromPosition");
	return nil;
}

/* Simple evaluation of positions */
- (NSComparisonResult)comparePosition:(UITextPosition *)position toPosition:(UITextPosition *)other;
{
    CCLOG("comparePosition");
	return 0;
}
- (NSInteger)offsetFromPosition:(UITextPosition *)from toPosition:(UITextPosition *)toPosition;
{
    CCLOG("offsetFromPosition");
	return 0;
}

- (UITextPosition *)positionWithinRange:(UITextRange *)range farthestInDirection:(UITextLayoutDirection)direction;
{
    CCLOG("positionWithinRange");
	return nil;
}
- (UITextRange *)characterRangeByExtendingPosition:(UITextPosition *)position inDirection:(UITextLayoutDirection)direction;
{
    CCLOG("characterRangeByExtendingPosition");
	return nil;
}

#pragma mark Writing direction

- (UITextWritingDirection)baseWritingDirectionForPosition:(UITextPosition *)position inDirection:(UITextStorageDirection)direction;
{
    CCLOG("baseWritingDirectionForPosition");
	return UITextWritingDirectionNatural;
}
- (void)setBaseWritingDirection:(UITextWritingDirection)writingDirection forRange:(UITextRange *)range;
{
    CCLOG("setBaseWritingDirection");
}

#pragma mark Geometry

/* Geometry used to provide, for example, a correction rect. */
- (CGRect)firstRectForRange:(UITextRange *)range;
{
    CCLOG("firstRectForRange");
	return CGRectNull;
}
- (CGRect)caretRectForPosition:(UITextPosition *)position;
{
	CCLOG("caretRectForPosition");
	return caretRect_;
}

#pragma mark Hit testing

/* JS - Find the closest position to a given point */
- (UITextPosition *)closestPositionToPoint:(CGPoint)point;
{
    CCLOG("closestPositionToPoint");
	return nil;
}
- (UITextPosition *)closestPositionToPoint:(CGPoint)point withinRange:(UITextRange *)range;
{
    CCLOG("closestPositionToPoint");
	return nil;
}
- (UITextRange *)characterRangeAtPoint:(CGPoint)point;
{
    CCLOG("characterRangeAtPoint");
	return nil;
}

#pragma mark -
#pragma mark UIKeyboard notification

- (void)onUIKeyboardNotification:(NSNotification *)notif;
{
    NSString * type = notif.name;

    NSDictionary* info = [notif userInfo];
    CGRect begin = [self convertRect:
                    [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue]
                            fromView:self];
    CGRect end = [self convertRect:
                  [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue]
                          fromView:self];
    double aniDuration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    CGSize viewSize = self.frame.size;
    CGFloat tmp;

    switch ([[UIApplication sharedApplication] statusBarOrientation])
    {
        case UIInterfaceOrientationPortrait:
            begin.origin.y = viewSize.height - begin.origin.y - begin.size.height;
            end.origin.y = viewSize.height - end.origin.y - end.size.height;
            break;

        case UIInterfaceOrientationPortraitUpsideDown:
            begin.origin.x = viewSize.width - (begin.origin.x + begin.size.width);
            end.origin.x = viewSize.width - (end.origin.x + end.size.width);
            break;

        case UIInterfaceOrientationLandscapeLeft:
            tmp = begin.size.width;
            begin.size.width = begin.size.height;
            begin.size.height = tmp;
            tmp = end.size.width;
            end.size.width = end.size.height;
            end.size.height = tmp;
            tmp = viewSize.width;
            viewSize.width = viewSize.height;
            viewSize.height = tmp;

            tmp = begin.origin.x;
            begin.origin.x = begin.origin.y;
            begin.origin.y = viewSize.height - tmp - begin.size.height;
            tmp = end.origin.x;
            end.origin.x = end.origin.y;
            end.origin.y = viewSize.height - tmp - end.size.height;
            break;

        case UIInterfaceOrientationLandscapeRight:
            tmp = begin.size.width;
            begin.size.width = begin.size.height;
            begin.size.height = tmp;
            tmp = end.size.width;
            end.size.width = end.size.height;
            end.size.height = tmp;
            tmp = viewSize.width;
            viewSize.width = viewSize.height;
            viewSize.height = tmp;

            tmp = begin.origin.x;
            begin.origin.x = begin.origin.y;
            begin.origin.y = tmp;
            tmp = end.origin.x;
            end.origin.x = end.origin.y;
            end.origin.y = tmp;
            break;

        default:
            break;
    }
    cocos2d::CCIMEKeyboardNotificationInfo notiInfo;
    notiInfo.begin = cocos2d::CCRect(begin.origin.x,
                                     begin.origin.y,
                                     begin.size.width,
                                     begin.size.height);
    notiInfo.end = cocos2d::CCRect(end.origin.x,
                                   end.origin.y,
                                   end.size.width,
                                   end.size.height);
    notiInfo.duration = (float)aniDuration;
    cocos2d::CCIMEDispatcher* dispatcher = cocos2d::CCIMEDispatcher::sharedDispatcher();
    if (UIKeyboardWillShowNotification == type)
    {
        dispatcher->dispatchKeyboardWillShow(notiInfo);
    }
    else if (UIKeyboardDidShowNotification == type)
    {
		//CGSize screenSize = self.window.screen.bounds.size;
        dispatcher->dispatchKeyboardDidShow(notiInfo);
        caretRect_ = end;
        caretRect_.origin.y = viewSize.height - (caretRect_.origin.y + caretRect_.size.height + [UIFont smallSystemFontSize]);
        caretRect_.size.height = 0;
    }
    else if (UIKeyboardWillHideNotification == type)
    {
        dispatcher->dispatchKeyboardWillHide(notiInfo);
    }
    else if (UIKeyboardDidHideNotification == type)
    {
        caretRect_ = CGRectZero;
        dispatcher->dispatchKeyboardDidHide(notiInfo);
    }
}
@end


code:
/*
 * cocos2d for iPhone: http://www.cocos2d-iphone.org
 *
 * Copyright (c) 2010 Ricardo Quesada
 * Copyright (c) 2011 Zynga Inc.
 *
 * 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.
 *
 *
 * File autogenerated with Xcode. Adapted for cocos2d needs.
 */

// Only compile this code on iOS. These files should NOT be included on your Mac project.
// But in case they are included, it won't be compiled.
#import <Availability.h>
#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED

#import "ESRenderer.h"

#import <OpenGLES/ES1/gl.h>
#import <OpenGLES/ES1/glext.h>

@interface ES1Renderer : NSObject <ESRenderer>
{
    // The pixel dimensions of the CAEAGLLayer
    GLint backingWidth_;
    GLint backingHeight_;

	unsigned int	samplesToUse_;
	BOOL			multiSampling_;

	unsigned int	depthFormat_;
	unsigned int	pixelFormat_;

	// The OpenGL ES names for the framebuffer and renderbuffer used to render to this view
    GLuint defaultFramebuffer_;
	GLuint colorRenderbuffer_;
	GLuint depthBuffer_;

	//buffers for MSAA
	GLuint msaaFramebuffer_;
	GLuint msaaColorbuffer_;

	EAGLContext *context_;
}

/** EAGLContext */
@property (nonatomic,readonly) EAGLContext* context;

- (BOOL)resizeFromLayer:(CAEAGLLayer *)layer;

@end

#endif // __IPHONE_OS_VERSION_MAX_ALLOWED


code:
/*
 * cocos2d for iPhone: http://www.cocos2d-iphone.org
 *
 * Copyright (c) 2010 Ricardo Quesada
 * Copyright (c) 2011 Zynga Inc.
 *
 * 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.
 *
 *
 * File autogenerated with Xcode. Adapted for cocos2d needs.
 */

// Only compile this code on iOS. These files should NOT be included on your Mac project.
// But in case they are included, it won't be compiled.
#import <Availability.h>
#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED

#import "ES1Renderer.h"
#import "OpenGL_Internal.h"
//#import "ccMacros.h"

@interface ES1Renderer (private)

- (GLenum) convertPixelFormat:(int) pixelFormat;

@end

@implementation ES1Renderer

@synthesize context=context_;

- (id) initWithDepthFormat:(unsigned int)depthFormat withPixelFormat:(unsigned int)pixelFormat withSharegroup:(EAGLSharegroup*)sharegroup withMultiSampling:(BOOL) multiSampling withNumberOfSamples:(unsigned int) requestedSamples
{
    if ((self = [super init]))
    {
		if ( sharegroup == nil )
		{
			context_ = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1];
		}
		else
		{
			context_ = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1 sharegroup:sharegroup];
		}

        if (!context_ || ![EAGLContext setCurrentContext:context_])
        {
            [self release];
            return nil;
        }

        // Create default framebuffer object. The backing will be allocated for the current layer in -resizeFromLayer
        glGenFramebuffersOES(1, &defaultFramebuffer_);
		NSAssert( defaultFramebuffer_, @"Can't create default frame buffer");
        glGenRenderbuffersOES(1, &colorRenderbuffer_);
		NSAssert( colorRenderbuffer_, @"Can't create default render buffer");

        glBindFramebufferOES(GL_FRAMEBUFFER_OES, defaultFramebuffer_);
        glBindRenderbufferOES(GL_RENDERBUFFER_OES, colorRenderbuffer_);
        glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorRenderbuffer_);

		depthFormat_ = depthFormat;

		if( depthFormat_ ) {
//			glGenRenderbuffersOES(1, &depthBuffer_);
//			glBindRenderbufferOES(GL_RENDERBUFFER_OES, depthBuffer_);
//			glRenderbufferStorageOES(GL_RENDERBUFFER_OES, depthFormat_, 100, 100);
//			glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBuffer_);

			// default buffer
//			glBindRenderbufferOES(GL_RENDERBUFFER_OES, colorRenderbuffer_);
		}

		pixelFormat_ = pixelFormat;
		multiSampling_ = multiSampling;
		if (multiSampling_)
		{
			GLint maxSamplesAllowed;
			glGetIntegerv(GL_MAX_SAMPLES_APPLE, &maxSamplesAllowed);
			samplesToUse_ = MIN(maxSamplesAllowed,requestedSamples);

			/* Create the MSAA framebuffer (offscreen) */
			glGenFramebuffersOES(1, &msaaFramebuffer_);
			glBindFramebufferOES(GL_FRAMEBUFFER_OES, msaaFramebuffer_);

		}

		CHECK_GL_ERROR();
    }

    return self;
}

- (BOOL)resizeFromLayer:(CAEAGLLayer *)layer
{
    // Allocate color buffer backing based on the current layer size

    glBindRenderbufferOES(GL_RENDERBUFFER_OES, colorRenderbuffer_);

	if (![context_ renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:layer])
	{
		NSLog(@"failed to call context");
	}

    glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth_);
    glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight_);

	NSLog(@"cocos2d: surface size: %dx%d", (int)backingWidth_, (int)backingHeight_);

	if (multiSampling_)
	{

		if ( msaaColorbuffer_) {
			glDeleteRenderbuffersOES(1, &msaaColorbuffer_);
			msaaColorbuffer_ = 0;
		}

		/* Create the offscreen MSAA color buffer.
		 After rendering, the contents of this will be blitted into ColorRenderbuffer */

		//msaaFrameBuffer needs to be binded
		glBindFramebufferOES(GL_FRAMEBUFFER_OES, msaaFramebuffer_);
		glGenRenderbuffersOES(1, &msaaColorbuffer_);
		glBindRenderbufferOES(GL_RENDERBUFFER_OES, msaaColorbuffer_);
		glRenderbufferStorageMultisampleAPPLE(GL_RENDERBUFFER_OES, samplesToUse_,pixelFormat_ , backingWidth_, backingHeight_);
		glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, msaaColorbuffer_);

		if (glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES)
		{
			NSLog(@"Failed to make complete framebuffer object %x", glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES));
			return NO;
		}
	}

	if (depthFormat_)
	{
		if( ! depthBuffer_ )
			glGenRenderbuffersOES(1, &depthBuffer_);

		glBindRenderbufferOES(GL_RENDERBUFFER_OES, depthBuffer_);
		if( multiSampling_ )
			glRenderbufferStorageMultisampleAPPLE(GL_RENDERBUFFER_OES, samplesToUse_, depthFormat_,backingWidth_, backingHeight_);
		else
			glRenderbufferStorageOES(GL_RENDERBUFFER_OES, depthFormat_, backingWidth_, backingHeight_);
		glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBuffer_);

		// bind color buffer
		glBindRenderbufferOES(GL_RENDERBUFFER_OES, colorRenderbuffer_);
	}

	glBindFramebufferOES(GL_FRAMEBUFFER_OES, defaultFramebuffer_);

	if (glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES)
	{
		NSLog(@"Failed to make complete framebuffer object %x", glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES));
		return NO;
	}

	CHECK_GL_ERROR();

    return YES;
}

-(CGSize) backingSize
{
	return CGSizeMake( backingWidth_, backingHeight_);
}

- (NSString*) description
{
	return [NSString stringWithFormat:@"<%@ = %08X | size = %ix%i>", [self class], self, backingWidth_, backingHeight_];
}

- (void)dealloc
{
	NSLog(@"cocos2d: deallocing %@", self);

    // Tear down GL
    if(defaultFramebuffer_)
    {
        glDeleteFramebuffersOES(1, &defaultFramebuffer_);
        defaultFramebuffer_ = 0;
    }

    if(colorRenderbuffer_)
    {
        glDeleteRenderbuffersOES(1, &colorRenderbuffer_);
        colorRenderbuffer_ = 0;
    }

	if( depthBuffer_ )
	{
		glDeleteRenderbuffersOES(1, &depthBuffer_);
		depthBuffer_ = 0;
	}

	if ( msaaColorbuffer_)
	{
		glDeleteRenderbuffersOES(1, &msaaColorbuffer_);
		msaaColorbuffer_ = 0;
	}

	if ( msaaFramebuffer_)
	{
		glDeleteRenderbuffersOES(1, &msaaFramebuffer_);
		msaaFramebuffer_ = 0;
	}

    // Tear down context
    if ([EAGLContext currentContext] == context_)
        [EAGLContext setCurrentContext:nil];

    [context_ release];
    context_ = nil;

    [super dealloc];
}

- (unsigned int) colorRenderBuffer
{
	return colorRenderbuffer_;
}

- (unsigned int) defaultFrameBuffer
{
	return defaultFramebuffer_;
}

- (unsigned int) msaaFrameBuffer
{
	return msaaFramebuffer_;
}

- (unsigned int) msaaColorBuffer
{
	return msaaColorbuffer_;
}

@end

#endif // __IPHONE_OS_VERSION_MAX_ALLOWED