mirror of https://github.com/axmolengine/axmol.git
Merge remote branch 'upstream/gles20' into gles20
This commit is contained in:
commit
a2e1400402
|
@ -4,3 +4,6 @@
|
|||
[submodule "scripting/javascript/bindings/generated"]
|
||||
path = scripting/javascript/bindings/generated
|
||||
url = git://github.com/folecr/cocos2dx-autogen-bindings.git
|
||||
[submodule "samples/TestJavascript/cocos2d-html5-tests"]
|
||||
path = samples/TestJavascript/cocos2d-html5-tests
|
||||
url = https://github.com/cocos2d/cocos2d-html5-tests.git
|
||||
|
|
|
@ -53,6 +53,12 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestLua", "samples\TestLua\
|
|||
{F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} = {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MoonWarriors", "samples\MoonWarriors\proj.win32\MoonWarriors.vcproj", "{A0EA54FA-6F12-45EC-AD5C-D139AA3CD528}"
|
||||
ProjectSection(ProjectDependencies) = postProject
|
||||
{98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} = {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}
|
||||
{F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} = {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(DPCodeReviewSolutionGUID) = preSolution
|
||||
DPCodeReviewSolutionGUID = {00000000-0000-0000-0000-000000000000}
|
||||
|
@ -106,6 +112,10 @@ Global
|
|||
{B53D3C68-96DA-4806-BB26-94888B52191A}.Debug|Win32.Build.0 = Debug|Win32
|
||||
{B53D3C68-96DA-4806-BB26-94888B52191A}.Release|Win32.ActiveCfg = Release|Win32
|
||||
{B53D3C68-96DA-4806-BB26-94888B52191A}.Release|Win32.Build.0 = Release|Win32
|
||||
{A0EA54FA-6F12-45EC-AD5C-D139AA3CD528}.Debug|Win32.ActiveCfg = Debug|Win32
|
||||
{A0EA54FA-6F12-45EC-AD5C-D139AA3CD528}.Debug|Win32.Build.0 = Debug|Win32
|
||||
{A0EA54FA-6F12-45EC-AD5C-D139AA3CD528}.Release|Win32.ActiveCfg = Release|Win32
|
||||
{A0EA54FA-6F12-45EC-AD5C-D139AA3CD528}.Release|Win32.Build.0 = Release|Win32
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
|
|
@ -35,6 +35,8 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestLua", "samples\TestLua\
|
|||
{F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} = {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MoonWarriors", "samples\MoonWarriors\proj.win32\MoonWarriors.vcxproj", "{1DB7C0FC-46FF-4A1B-82E0-C6244EEEC4C2}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(DPCodeReviewSolutionGUID) = preSolution
|
||||
DPCodeReviewSolutionGUID = {00000000-0000-0000-0000-000000000000}
|
||||
|
@ -88,6 +90,10 @@ Global
|
|||
{4E6A7A0E-DDD8-4BAA-8B22-C964069364ED}.Debug|Win32.Build.0 = Debug|Win32
|
||||
{4E6A7A0E-DDD8-4BAA-8B22-C964069364ED}.Release|Win32.ActiveCfg = Release|Win32
|
||||
{4E6A7A0E-DDD8-4BAA-8B22-C964069364ED}.Release|Win32.Build.0 = Release|Win32
|
||||
{1DB7C0FC-46FF-4A1B-82E0-C6244EEEC4C2}.Debug|Win32.ActiveCfg = Debug|Win32
|
||||
{1DB7C0FC-46FF-4A1B-82E0-C6244EEEC4C2}.Debug|Win32.Build.0 = Debug|Win32
|
||||
{1DB7C0FC-46FF-4A1B-82E0-C6244EEEC4C2}.Release|Win32.ActiveCfg = Release|Win32
|
||||
{1DB7C0FC-46FF-4A1B-82E0-C6244EEEC4C2}.Release|Win32.Build.0 = Release|Win32
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
|
|
@ -136,7 +136,6 @@ bool CCDirector::init(void)
|
|||
m_pobOpenGLView = NULL;
|
||||
|
||||
m_fContentScaleFactor = 1.0f;
|
||||
m_bIsContentScaleSupported = false;
|
||||
|
||||
// scheduler
|
||||
m_pScheduler = new CCScheduler();
|
||||
|
@ -314,12 +313,7 @@ void CCDirector::setOpenGLView(CCEGLView *pobOpenGLView)
|
|||
|
||||
CHECK_GL_ERROR_DEBUG();
|
||||
|
||||
if (m_fContentScaleFactor != 1)
|
||||
{
|
||||
updateContentScaleFactor();
|
||||
}
|
||||
|
||||
m_pobOpenGLView->setTouchDelegate(m_pTouchDispatcher);
|
||||
m_pobOpenGLView->setTouchDelegate(m_pTouchDispatcher);
|
||||
m_pTouchDispatcher->setDispatchEvents(true);
|
||||
}
|
||||
}
|
||||
|
@ -331,12 +325,11 @@ void CCDirector::setNextDeltaTimeZero(bool bNextDeltaTimeZero)
|
|||
|
||||
void CCDirector::setProjection(ccDirectorProjection kProjection)
|
||||
{
|
||||
CCSize size = m_obWinSizeInPixels;
|
||||
CCSize sizePoint = m_obWinSizeInPoints;
|
||||
CCSize size = m_obWinSizeInPoints;
|
||||
|
||||
if (m_pobOpenGLView)
|
||||
{
|
||||
m_pobOpenGLView->setViewPortInPoints(0, 0, sizePoint.width, sizePoint.height);
|
||||
m_pobOpenGLView->setViewPortInPoints(0, 0, size.width, size.height);
|
||||
}
|
||||
|
||||
switch (kProjection)
|
||||
|
@ -346,7 +339,7 @@ void CCDirector::setProjection(ccDirectorProjection kProjection)
|
|||
kmGLMatrixMode(KM_GL_PROJECTION);
|
||||
kmGLLoadIdentity();
|
||||
kmMat4 orthoMatrix;
|
||||
kmMat4OrthographicProjection(&orthoMatrix, 0, size.width / CC_CONTENT_SCALE_FACTOR(), 0, size.height / CC_CONTENT_SCALE_FACTOR(), -1024, 1024 );
|
||||
kmMat4OrthographicProjection(&orthoMatrix, 0, size.width, 0, size.height, -1024, 1024 );
|
||||
kmGLMultMatrix(&orthoMatrix);
|
||||
kmGLMatrixMode(KM_GL_MODELVIEW);
|
||||
kmGLLoadIdentity();
|
||||
|
@ -371,8 +364,8 @@ void CCDirector::setProjection(ccDirectorProjection kProjection)
|
|||
kmGLMatrixMode(KM_GL_MODELVIEW);
|
||||
kmGLLoadIdentity();
|
||||
kmVec3 eye, center, up;
|
||||
kmVec3Fill( &eye, sizePoint.width/2, sizePoint.height/2, zeye );
|
||||
kmVec3Fill( ¢er, sizePoint.width/2, sizePoint.height/2, 0.0f );
|
||||
kmVec3Fill( &eye, size.width/2, size.height/2, zeye );
|
||||
kmVec3Fill( ¢er, size.width/2, size.height/2, 0.0f );
|
||||
kmVec3Fill( &up, 0.0f, 1.0f, 0.0f);
|
||||
kmMat4LookAt(&matrixLookup, &eye, ¢er, &up);
|
||||
kmGLMultMatrix(&matrixLookup);
|
||||
|
@ -404,7 +397,7 @@ void CCDirector::purgeCachedData(void)
|
|||
|
||||
float CCDirector::getZEye(void)
|
||||
{
|
||||
return (m_obWinSizeInPixels.height / 1.1566f / CC_CONTENT_SCALE_FACTOR());
|
||||
return (m_obWinSizeInPoints.height / 1.1566f);
|
||||
}
|
||||
|
||||
void CCDirector::setAlphaBlending(bool bOn)
|
||||
|
@ -805,38 +798,6 @@ void CCDirector::createStatsLabel()
|
|||
* mobile platforms specific functions
|
||||
**************************************************/
|
||||
|
||||
void CCDirector::updateContentScaleFactor()
|
||||
{
|
||||
m_bIsContentScaleSupported = m_pobOpenGLView->setContentScaleFactor(m_fContentScaleFactor);
|
||||
}
|
||||
|
||||
bool CCDirector::enableRetinaDisplay(bool enabled)
|
||||
{
|
||||
// Already enabled?
|
||||
if (enabled && m_fContentScaleFactor == 2)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
// Already disabled?
|
||||
if (!enabled && m_fContentScaleFactor == 1)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (! m_pobOpenGLView->enableRetina())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
float newScale = (float)(enabled ? 2 : 1);
|
||||
setContentScaleFactor(newScale);
|
||||
|
||||
createStatsLabel();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
float CCDirector::getContentScaleFactor(void)
|
||||
{
|
||||
return m_fContentScaleFactor;
|
||||
|
@ -847,15 +808,6 @@ void CCDirector::setContentScaleFactor(float scaleFactor)
|
|||
if (scaleFactor != m_fContentScaleFactor)
|
||||
{
|
||||
m_fContentScaleFactor = scaleFactor;
|
||||
m_obWinSizeInPixels = CCSizeMake(m_obWinSizeInPoints.width * scaleFactor, m_obWinSizeInPoints.height * scaleFactor);
|
||||
|
||||
if (m_pobOpenGLView)
|
||||
{
|
||||
updateContentScaleFactor();
|
||||
}
|
||||
|
||||
// update projection
|
||||
setProjection(m_eProjection);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -159,8 +159,6 @@ public:
|
|||
*/
|
||||
CCNode* getNotificationNode();
|
||||
void setNotificationNode(CCNode *node);
|
||||
|
||||
bool enableRetinaDisplay(bool bEnabelRetina);
|
||||
|
||||
// window size
|
||||
|
||||
|
@ -330,8 +328,6 @@ protected:
|
|||
void purgeDirector();
|
||||
bool m_bPurgeDirecotorInNextLoop; // this flag will be set to true in end()
|
||||
|
||||
void updateContentScaleFactor(void);
|
||||
|
||||
void setNextScene(void);
|
||||
|
||||
void showStats();
|
||||
|
@ -408,9 +404,6 @@ protected:
|
|||
|
||||
/* Projection protocol delegate */
|
||||
CCDirectorDelegate *m_pProjectionDelegate;
|
||||
|
||||
/* contentScaleFactor could be simulated */
|
||||
bool m_bIsContentScaleSupported;
|
||||
|
||||
// CCEGLViewProtocol will recreate stats labels to fit visible rect
|
||||
friend class CCEGLViewProtocol;
|
||||
|
|
|
@ -50,7 +50,7 @@ void CCAutoreleasePool::addObject(CCObject* pObject)
|
|||
|
||||
void CCAutoreleasePool::removeObject(CCObject* pObject)
|
||||
{
|
||||
for (int i = 0; i < pObject->m_uAutoReleaseCount; ++i)
|
||||
for (unsigned int i = 0; i < pObject->m_uAutoReleaseCount; ++i)
|
||||
{
|
||||
m_pManagedObjectArray->removeObject(pObject, false);
|
||||
}
|
||||
|
|
|
@ -233,7 +233,7 @@ THE SOFTWARE.
|
|||
|
||||
NS_CC_BEGIN
|
||||
|
||||
const char* cocos2dVersion();
|
||||
CC_DLL const char* cocos2dVersion();
|
||||
|
||||
NS_CC_END
|
||||
|
||||
|
|
|
@ -95,19 +95,22 @@ CCLabelAtlas* CCLabelAtlas::create(const char *string, const char *fntFile)
|
|||
|
||||
bool CCLabelAtlas::initWithString(const char *theString, const char *fntFile)
|
||||
{
|
||||
CCDictionary *dict = CCDictionary::createWithContentsOfFile(CCFileUtils::sharedFileUtils()->fullPathFromRelativePath(fntFile));
|
||||
|
||||
CCAssert(((CCString*)dict->objectForKey("version"))->intValue() == 1, "Unsupported version. Upgrade cocos2d version");
|
||||
std::string pathStr = CCFileUtils::sharedFileUtils()->fullPathFromRelativePath(fntFile);
|
||||
std::string relPathStr = pathStr.substr(0, pathStr.find_last_of("/"))+"/";
|
||||
CCDictionary *dict = CCDictionary::createWithContentsOfFile(pathStr.c_str());
|
||||
|
||||
CCAssert(((CCString*)dict->objectForKey("version"))->intValue() == 1, "Unsupported version. Upgrade cocos2d version");
|
||||
|
||||
CCString *textureFilename = (CCString*)dict->objectForKey("textureFilename");
|
||||
unsigned int width = ((CCString*)dict->objectForKey("itemWidth"))->intValue() / CC_CONTENT_SCALE_FACTOR();
|
||||
unsigned int height = ((CCString*)dict->objectForKey("itemHeight"))->intValue() / CC_CONTENT_SCALE_FACTOR();
|
||||
unsigned int startChar = ((CCString*)dict->objectForKey("firstChar"))->intValue();
|
||||
|
||||
std::string texturePathStr = relPathStr + ((CCString*)dict->objectForKey("textureFilename"))->getCString();
|
||||
CCString *textureFilename = CCString::create(texturePathStr);
|
||||
unsigned int width = ((CCString*)dict->objectForKey("itemWidth"))->intValue() / CC_CONTENT_SCALE_FACTOR();
|
||||
unsigned int height = ((CCString*)dict->objectForKey("itemHeight"))->intValue() / CC_CONTENT_SCALE_FACTOR();
|
||||
unsigned int startChar = ((CCString*)dict->objectForKey("firstChar"))->intValue();
|
||||
|
||||
|
||||
this->initWithString(theString, textureFilename->getCString(), width, height, startChar);
|
||||
this->initWithString(theString, textureFilename->getCString(), width, height, startChar);
|
||||
|
||||
return true;
|
||||
return true;
|
||||
}
|
||||
|
||||
//CCLabelAtlas - Atlas generation
|
||||
|
|
|
@ -49,6 +49,7 @@ CCRenderTexture::CCRenderTexture()
|
|||
, m_uDepthRenderBufffer(0)
|
||||
, m_nOldFBO(0)
|
||||
, m_pTexture(0)
|
||||
, m_pTextureCopy(0)
|
||||
, m_pUITextureImage(NULL)
|
||||
, m_ePixelFormat(kCCTexture2DPixelFormat_RGBA8888)
|
||||
{
|
||||
|
@ -62,6 +63,8 @@ CCRenderTexture::CCRenderTexture()
|
|||
|
||||
CCRenderTexture::~CCRenderTexture()
|
||||
{
|
||||
CC_SAFE_RELEASE(m_pTextureCopy);
|
||||
|
||||
glDeleteFramebuffers(1, &m_uFBO);
|
||||
if (m_uDepthRenderBufffer)
|
||||
{
|
||||
|
@ -168,10 +171,11 @@ bool CCRenderTexture::initWithWidthAndHeight(int w, int h, CCTexture2DPixelForma
|
|||
CCAssert(m_ePixelFormat != kCCTexture2DPixelFormat_A8, "only RGB and RGBA formats are valid for a render texture");
|
||||
|
||||
bool bRet = false;
|
||||
void *data = NULL;
|
||||
do
|
||||
{
|
||||
w *= (int)CC_CONTENT_SCALE_FACTOR();
|
||||
h *= (int)CC_CONTENT_SCALE_FACTOR();
|
||||
w = (int)(w * CC_CONTENT_SCALE_FACTOR());
|
||||
h = (int)(h * CC_CONTENT_SCALE_FACTOR());
|
||||
|
||||
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &m_nOldFBO);
|
||||
|
||||
|
@ -179,30 +183,47 @@ bool CCRenderTexture::initWithWidthAndHeight(int w, int h, CCTexture2DPixelForma
|
|||
unsigned int powW = 0;
|
||||
unsigned int powH = 0;
|
||||
|
||||
if( CCConfiguration::sharedConfiguration()->supportsNPOT() ) {
|
||||
if (CCConfiguration::sharedConfiguration()->supportsNPOT())
|
||||
{
|
||||
powW = w;
|
||||
powH = h;
|
||||
} else {
|
||||
}
|
||||
else
|
||||
{
|
||||
powW = ccNextPOT(w);
|
||||
powH = ccNextPOT(h);
|
||||
}
|
||||
|
||||
void *data = malloc((int)(powW * powH * 4));
|
||||
data = malloc((int)(powW * powH * 4));
|
||||
CC_BREAK_IF(! data);
|
||||
|
||||
memset(data, 0, (int)(powW * powH * 4));
|
||||
m_ePixelFormat = eFormat;
|
||||
|
||||
m_pTexture = new CCTexture2D();
|
||||
if (m_pTexture) {
|
||||
m_pTexture->initWithData(data, (CCTexture2DPixelFormat)m_ePixelFormat, powW, powH, CCSizeMake((float)w, (float)h));
|
||||
free( data );
|
||||
} else {
|
||||
free( data ); // ScopeGuard (a simulated Finally clause) would be more elegant.
|
||||
break;
|
||||
if (m_pTexture)
|
||||
{
|
||||
m_pTexture->initWithData(data, (CCTexture2DPixelFormat)m_ePixelFormat, powW, powH, CCSizeMake((float)w, (float)h));
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
GLint oldRBO;
|
||||
glGetIntegerv(GL_RENDERBUFFER_BINDING, &oldRBO);
|
||||
|
||||
if (CCConfiguration::sharedConfiguration()->checkForGLExtension("GL_QCOM"))
|
||||
{
|
||||
m_pTextureCopy = new CCTexture2D();
|
||||
if (m_pTextureCopy)
|
||||
{
|
||||
m_pTextureCopy->initWithData(data, (CCTexture2DPixelFormat)m_ePixelFormat, powW, powH, CCSizeMake((float)w, (float)h));
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// generate FBO
|
||||
glGenFramebuffers(1, &m_uFBO);
|
||||
|
@ -221,10 +242,11 @@ bool CCRenderTexture::initWithWidthAndHeight(int w, int h, CCTexture2DPixelForma
|
|||
|
||||
// if depth format is the one with stencil part, bind same render buffer as stencil attachment
|
||||
if (uDepthStencilFormat == CC_GL_DEPTH24_STENCIL8)
|
||||
{
|
||||
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, m_uDepthRenderBufffer);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// check if it worked (probably worth doing :) )
|
||||
CCAssert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE, "Could not attach texture to framebuffer");
|
||||
|
||||
|
@ -243,8 +265,10 @@ bool CCRenderTexture::initWithWidthAndHeight(int w, int h, CCTexture2DPixelForma
|
|||
glBindFramebuffer(GL_FRAMEBUFFER, m_nOldFBO);
|
||||
bRet = true;
|
||||
} while (0);
|
||||
return bRet;
|
||||
|
||||
CC_SAFE_FREE(data);
|
||||
|
||||
return bRet;
|
||||
}
|
||||
|
||||
void CCRenderTexture::begin()
|
||||
|
@ -271,6 +295,17 @@ void CCRenderTexture::begin()
|
|||
|
||||
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &m_nOldFBO);
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, m_uFBO);
|
||||
|
||||
/* Certain Qualcomm Andreno gpu's will retain data in memory after a frame buffer switch which corrupts the render to the texture. The solution is to clear the frame buffer before rendering to the texture. However, calling glClear has the unintended result of clearing the current texture. Create a temporary texture to overcome this. At the end of CCRenderTexture::begin(), switch the attached texture to the second one, call glClear, and then switch back to the original texture. This solution is unnecessary for other devices as they don't have the same issue with switching frame buffers.
|
||||
*/
|
||||
if (CCConfiguration::sharedConfiguration()->checkForGLExtension("GL_QCOM"))
|
||||
{
|
||||
// -- bind a temporary texture so we can clear the render buffer without losing our texture
|
||||
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_pTextureCopy->getName(), 0);
|
||||
CHECK_GL_ERROR_DEBUG();
|
||||
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
|
||||
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_pTexture->getName(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
void CCRenderTexture::beginWithClear(float r, float g, float b, float a)
|
||||
|
@ -444,7 +479,6 @@ CCImage* CCRenderTexture::newCCImage()
|
|||
{
|
||||
CC_BREAK_IF(! (pBuffer = new GLubyte[nSavedBufferWidth * nSavedBufferHeight * 4]));
|
||||
|
||||
|
||||
if(! (pTempData = new GLubyte[nSavedBufferWidth * nSavedBufferHeight * 4]))
|
||||
{
|
||||
delete[] pBuffer;
|
||||
|
@ -462,8 +496,8 @@ CCImage* CCRenderTexture::newCCImage()
|
|||
for (int i = 0; i < nSavedBufferHeight; ++i)
|
||||
{
|
||||
memcpy(&pBuffer[i * nSavedBufferWidth * 4],
|
||||
&pTempData[(nSavedBufferHeight - i - 1) * nSavedBufferWidth * 4],
|
||||
nSavedBufferWidth * 4);
|
||||
&pTempData[(nSavedBufferHeight - i - 1) * nSavedBufferWidth * 4],
|
||||
nSavedBufferWidth * 4);
|
||||
}
|
||||
|
||||
pImage->initWithImageData(pBuffer, nSavedBufferWidth * nSavedBufferHeight * 4, CCImage::kFmtRawData, nSavedBufferWidth, nSavedBufferHeight, 8);
|
||||
|
|
|
@ -147,6 +147,7 @@ protected:
|
|||
GLuint m_uDepthRenderBufffer;
|
||||
GLint m_nOldFBO;
|
||||
CCTexture2D* m_pTexture;
|
||||
CCTexture2D* m_pTextureCopy; // a copy of m_pTexture
|
||||
CCImage* m_pUITextureImage;
|
||||
GLenum m_ePixelFormat;
|
||||
};
|
||||
|
|
|
@ -46,7 +46,6 @@ CCEGLViewProtocol::CCEGLViewProtocol()
|
|||
: m_pDelegate(NULL)
|
||||
, m_fScaleY(1.0f)
|
||||
, m_fScaleX(1.0f)
|
||||
, m_bIsRetinaEnabled(false)
|
||||
, m_eResolutionPolicy(kResolutionUnKnown)
|
||||
{
|
||||
}
|
||||
|
@ -58,7 +57,6 @@ CCEGLViewProtocol::~CCEGLViewProtocol()
|
|||
|
||||
void CCEGLViewProtocol::setDesignResolutionSize(float width, float height, ResolutionPolicy resolutionPolicy)
|
||||
{
|
||||
CCAssert(m_bIsRetinaEnabled == false, "can not enable retina while set design resolution size!");
|
||||
CCAssert(resolutionPolicy != kResolutionUnKnown, "should set resolutionPolicy");
|
||||
|
||||
if (width == 0.0f || height == 0.0f)
|
||||
|
@ -93,15 +91,11 @@ void CCEGLViewProtocol::setDesignResolutionSize(float width, float height, Resol
|
|||
|
||||
// reset director's member variables to fit visible rect
|
||||
CCDirector::sharedDirector()->createStatsLabel();
|
||||
CCDirector::sharedDirector()->m_obWinSizeInPoints = CCDirector::sharedDirector()->m_obWinSizeInPixels = getSize();
|
||||
CCDirector::sharedDirector()->m_obWinSizeInPoints = getSize();
|
||||
CCDirector::sharedDirector()->m_obWinSizeInPixels = CCSizeMake(m_obDesignResolutionSize.width*CC_CONTENT_SCALE_FACTOR(), m_obDesignResolutionSize.height*CC_CONTENT_SCALE_FACTOR());
|
||||
CCDirector::sharedDirector()->setGLDefaultValues();
|
||||
}
|
||||
|
||||
bool CCEGLViewProtocol::enableRetina()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
const CCSize& CCEGLViewProtocol::getSize() const
|
||||
{
|
||||
return m_obDesignResolutionSize;
|
||||
|
@ -147,12 +141,6 @@ void CCEGLViewProtocol::setTouchDelegate(EGLTouchDelegate * pDelegate)
|
|||
m_pDelegate = pDelegate;
|
||||
}
|
||||
|
||||
bool CCEGLViewProtocol::setContentScaleFactor(float contentScaleFactor)
|
||||
{
|
||||
m_fScaleX = m_fScaleY = contentScaleFactor;
|
||||
return false;
|
||||
}
|
||||
|
||||
void CCEGLViewProtocol::setViewPortInPoints(float x , float y , float w , float h)
|
||||
{
|
||||
glViewport((GLint)(x * m_fScaleX + m_obViewPortRect.origin.x),
|
||||
|
@ -206,18 +194,8 @@ void CCEGLViewProtocol::handleTouchesBegin(int num, int ids[], float xs[], float
|
|||
}
|
||||
|
||||
CCTouch* pTouch = s_pTouches[nUnusedIndex] = new CCTouch();
|
||||
if (m_bIsRetinaEnabled)
|
||||
{
|
||||
// on iOS, though retina is enabled, the value got from os is also
|
||||
// relative to its original size
|
||||
pTouch->setTouchInfo(nUnusedIndex, (x - m_obViewPortRect.origin.x),
|
||||
(y - m_obViewPortRect.origin.y));
|
||||
}
|
||||
else
|
||||
{
|
||||
pTouch->setTouchInfo(nUnusedIndex, (x - m_obViewPortRect.origin.x) / m_fScaleX,
|
||||
pTouch->setTouchInfo(nUnusedIndex, (x - m_obViewPortRect.origin.x) / m_fScaleX,
|
||||
(y - m_obViewPortRect.origin.y) / m_fScaleY);
|
||||
}
|
||||
|
||||
//CCLOG("x = %f y = %f", pTouch->getLocationInView().x, pTouch->getLocationInView().y);
|
||||
|
||||
|
@ -256,16 +234,8 @@ void CCEGLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float
|
|||
CCTouch* pTouch = s_pTouches[pIndex->getValue()];
|
||||
if (pTouch)
|
||||
{
|
||||
if (m_bIsRetinaEnabled)
|
||||
{
|
||||
pTouch->setTouchInfo(pIndex->getValue(), (x - m_obViewPortRect.origin.x),
|
||||
(y - m_obViewPortRect.origin.y));
|
||||
}
|
||||
else
|
||||
{
|
||||
pTouch->setTouchInfo(pIndex->getValue(), (x - m_obViewPortRect.origin.x) / m_fScaleX,
|
||||
(y - m_obViewPortRect.origin.y) / m_fScaleY);
|
||||
}
|
||||
pTouch->setTouchInfo(pIndex->getValue(), (x - m_obViewPortRect.origin.x) / m_fScaleX,
|
||||
(y - m_obViewPortRect.origin.y) / m_fScaleY);
|
||||
|
||||
set.addObject(pTouch);
|
||||
}
|
||||
|
@ -305,17 +275,8 @@ void CCEGLViewProtocol::getSetOfTouchesEndOrCancel(CCSet& set, int num, int ids[
|
|||
if (pTouch)
|
||||
{
|
||||
CCLOGINFO("Ending touches with id: %d, x=%f, y=%f", id, x, y);
|
||||
|
||||
if (m_bIsRetinaEnabled)
|
||||
{
|
||||
pTouch->setTouchInfo(pIndex->getValue(), (x - m_obViewPortRect.origin.x),
|
||||
(y - m_obViewPortRect.origin.y));
|
||||
}
|
||||
else
|
||||
{
|
||||
pTouch->setTouchInfo(pIndex->getValue(), (x - m_obViewPortRect.origin.x) / m_fScaleX,
|
||||
(y - m_obViewPortRect.origin.y) / m_fScaleY);
|
||||
}
|
||||
pTouch->setTouchInfo(pIndex->getValue(), (x - m_obViewPortRect.origin.x) / m_fScaleX,
|
||||
(y - m_obViewPortRect.origin.y) / m_fScaleY);
|
||||
|
||||
set.addObject(pTouch);
|
||||
|
||||
|
@ -371,9 +332,4 @@ float CCEGLViewProtocol::getScaleY() const
|
|||
return m_fScaleY;
|
||||
}
|
||||
|
||||
bool CCEGLViewProtocol::isRetinaEnabled() const
|
||||
{
|
||||
return m_bIsRetinaEnabled;
|
||||
}
|
||||
|
||||
NS_CC_END
|
||||
|
|
|
@ -5,16 +5,16 @@
|
|||
|
||||
enum ResolutionPolicy
|
||||
{
|
||||
// The entire application is visible in the specified area without trying to preserve the original aspect ratio.
|
||||
// The entire application is visible in the specified area without trying to preserve the original aspect ratio.
|
||||
// Distortion can occur, and the application may appear stretched or compressed.
|
||||
kResolutionExactFit,
|
||||
// The entire application fills the specified area, without distortion but possibly with some cropping,
|
||||
// The entire application fills the specified area, without distortion but possibly with some cropping,
|
||||
// while maintaining the original aspect ratio of the application.
|
||||
kResolutionNoBorder,
|
||||
// The entire application is visible in the specified area without distortion while maintaining the original
|
||||
// The entire application is visible in the specified area without distortion while maintaining the original
|
||||
// aspect ratio of the application. Borders can appear on two sides of the application.
|
||||
kResolutionShowAll,
|
||||
|
||||
|
||||
kResolutionUnKnown,
|
||||
};
|
||||
|
||||
|
@ -38,45 +38,45 @@ public:
|
|||
|
||||
/** Force destroying EGL view, subclass must implement this method. */
|
||||
virtual void end() = 0;
|
||||
|
||||
|
||||
/** Get whether opengl render system is ready, subclass must implement this method. */
|
||||
virtual bool isOpenGLReady() = 0;
|
||||
|
||||
|
||||
/** Exchanges the front and back buffers, subclass must implement this method. */
|
||||
virtual void swapBuffers() = 0;
|
||||
|
||||
|
||||
/** Open or close IME keyboard , subclass must implement this method. */
|
||||
virtual void setIMEKeyboardState(bool bOpen) = 0;
|
||||
|
||||
/**
|
||||
/**
|
||||
* Get design resolution size.
|
||||
* If setDesignResolutionSize wasn't invoked, the result of this function return is the same as 'getFrameSize'
|
||||
*/
|
||||
|
||||
virtual const CCSize& getSize() const;
|
||||
|
||||
|
||||
/**
|
||||
* Get the frame size of EGL view.
|
||||
* In general, it returns the screen size since the EGL view is a fullscreen view.
|
||||
*/
|
||||
virtual const CCSize& getFrameSize() const;
|
||||
|
||||
|
||||
/**
|
||||
* Set the frame size of EGL view.
|
||||
*/
|
||||
virtual void setFrameSize(float width, float height);
|
||||
|
||||
|
||||
/**
|
||||
* Get the visible area size of opengl viewport.
|
||||
*/
|
||||
virtual CCSize getVisibleSize() const;
|
||||
|
||||
|
||||
/**
|
||||
* Get the visible origin point of opengl viewport.
|
||||
*/
|
||||
virtual CCPoint getVisibleOrigin() const;
|
||||
|
||||
/**
|
||||
|
||||
/**
|
||||
* Set the design resolution size.
|
||||
* Behavior undefined when enableRetina == true.
|
||||
* @param width Design resolution width.
|
||||
|
@ -87,35 +87,23 @@ public:
|
|||
* [3] kCCResolutionShowAll Full screen with black border: if the design resolution ratio of width to height is different from the screen resolution ratio, two black borders will be shown.
|
||||
*/
|
||||
virtual void setDesignResolutionSize(float width, float height, ResolutionPolicy resolutionPolicy);
|
||||
|
||||
|
||||
/** Set touch delegate */
|
||||
virtual void setTouchDelegate(EGLTouchDelegate * pDelegate);
|
||||
|
||||
/**
|
||||
* Set content scale factor.
|
||||
* @return If the return value is true, the platform supports retina display mode.
|
||||
*/
|
||||
virtual bool setContentScaleFactor(float contentScaleFactor);
|
||||
|
||||
|
||||
/**
|
||||
* Set opengl view port rectangle with points.
|
||||
*/
|
||||
virtual void setViewPortInPoints(float x , float y , float w , float h);
|
||||
|
||||
|
||||
/**
|
||||
* Set Scissor rectangle with points.
|
||||
*/
|
||||
virtual void setScissorInPoints(float x , float y , float w , float h);
|
||||
|
||||
virtual void setViewName(const char* pszViewName);
|
||||
virtual void setViewName(const char* pszViewName);
|
||||
|
||||
const char* getViewName();
|
||||
|
||||
/**
|
||||
* Enable retina mode.
|
||||
* You can't use it with setDesignResolutionSize
|
||||
*/
|
||||
virtual bool enableRetina();
|
||||
const char* getViewName();
|
||||
|
||||
/** Touch events are handled by default; if you want to customize your handlers, please override these functions: */
|
||||
virtual void handleTouchesBegin(int num, int ids[], float xs[], float ys[]);
|
||||
|
@ -127,24 +115,19 @@ public:
|
|||
* Get the opengl view port rectangle.
|
||||
*/
|
||||
const CCRect& getViewPortRect() const;
|
||||
|
||||
|
||||
/**
|
||||
* Get scale factor of the horizontal direction.
|
||||
*/
|
||||
float getScaleX() const;
|
||||
|
||||
|
||||
/**
|
||||
* Get scale factor of the vertical direction.
|
||||
*/
|
||||
float getScaleY() const;
|
||||
|
||||
/**
|
||||
* Get retina mode status (on if true).
|
||||
*/
|
||||
bool isRetinaEnabled() const;
|
||||
private:
|
||||
void getSetOfTouchesEndOrCancel(CCSet& set, int num, int ids[], float xs[], float ys[]);
|
||||
|
||||
|
||||
protected:
|
||||
EGLTouchDelegate* m_pDelegate;
|
||||
|
||||
|
@ -156,11 +139,10 @@ protected:
|
|||
CCRect m_obViewPortRect;
|
||||
// the view name
|
||||
char m_szViewName[50];
|
||||
|
||||
|
||||
float m_fScaleX;
|
||||
float m_fScaleY;
|
||||
ResolutionPolicy m_eResolutionPolicy;
|
||||
bool m_bIsRetinaEnabled;
|
||||
};
|
||||
|
||||
// end of platform group
|
||||
|
|
|
@ -28,6 +28,7 @@ import java.util.HashMap;
|
|||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.concurrent.Semaphore;
|
||||
|
||||
import android.content.Context;
|
||||
import android.media.AudioManager;
|
||||
|
@ -56,6 +57,11 @@ public class Cocos2dxSound {
|
|||
private final HashMap<String, ArrayList<Integer>> mPathStreamIDsMap = new HashMap<String, ArrayList<Integer>>();
|
||||
|
||||
private final HashMap<String, Integer> mPathSoundIDMap = new HashMap<String, Integer>();
|
||||
|
||||
private final ArrayList<SoundInfoForLoadedCompleted> mEffecToPlayWhenLoadedArray = new ArrayList<SoundInfoForLoadedCompleted>();
|
||||
|
||||
private int mStreamIdSyn;
|
||||
private Semaphore mSemaphore;
|
||||
|
||||
private static final int MAX_SIMULTANEOUS_STREAMS_DEFAULT = 5;
|
||||
private static final float SOUND_RATE = 1.0f;
|
||||
|
@ -77,9 +83,12 @@ public class Cocos2dxSound {
|
|||
|
||||
private void initData() {
|
||||
this.mSoundPool = new SoundPool(Cocos2dxSound.MAX_SIMULTANEOUS_STREAMS_DEFAULT, AudioManager.STREAM_MUSIC, Cocos2dxSound.SOUND_QUALITY);
|
||||
|
||||
this.mSoundPool.setOnLoadCompleteListener(new OnLoadCompletedListener());
|
||||
|
||||
this.mLeftVolume = 0.5f;
|
||||
this.mRightVolume = 0.5f;
|
||||
|
||||
this.mSemaphore = new Semaphore(0, true);
|
||||
}
|
||||
|
||||
// ===========================================================
|
||||
|
@ -127,15 +136,7 @@ public class Cocos2dxSound {
|
|||
|
||||
if (soundID != null) {
|
||||
// play sound
|
||||
streamID = this.mSoundPool.play(soundID.intValue(), this.mLeftVolume, this.mRightVolume, Cocos2dxSound.SOUND_PRIORITY, pLoop ? -1 : 0, Cocos2dxSound.SOUND_RATE);
|
||||
|
||||
// record stream id
|
||||
ArrayList<Integer> streamIDs = this.mPathStreamIDsMap.get(pPath);
|
||||
if (streamIDs == null) {
|
||||
streamIDs = new ArrayList<Integer>();
|
||||
this.mPathStreamIDsMap.put(pPath, streamIDs);
|
||||
}
|
||||
streamIDs.add(streamID);
|
||||
streamID = this.doPlayEffect(pPath, soundID.intValue(), pLoop);
|
||||
} else {
|
||||
// the effect is not prepared
|
||||
soundID = this.preloadEffect(pPath);
|
||||
|
@ -143,16 +144,21 @@ public class Cocos2dxSound {
|
|||
// can not preload effect
|
||||
return Cocos2dxSound.INVALID_SOUND_ID;
|
||||
}
|
||||
|
||||
/*
|
||||
* Someone reports that, it can not play effect for the first time.
|
||||
* If you are lucky to meet it. There are two ways to resolve it. 1.
|
||||
* Add some delay here. I don't know how long it is, so I don't add
|
||||
* it here. 2. If you use 2.2(API level 8), you can call
|
||||
* SoundPool.setOnLoadCompleteListener() to play the effect. Because
|
||||
* the method is supported from 2.2, so I can't use it here.
|
||||
*/
|
||||
this.playEffect(pPath, pLoop);
|
||||
|
||||
// only allow one playEffect at a time, or the semaphore will not work correctly
|
||||
synchronized(this.mSoundPool) {
|
||||
// add this effect into mEffecToPlayWhenLoadedArray, and it will be played when loaded completely
|
||||
mEffecToPlayWhenLoadedArray.add(new SoundInfoForLoadedCompleted(pPath, soundID.intValue(), pLoop));
|
||||
|
||||
try {
|
||||
// wait OnloadedCompleteListener to set streamID
|
||||
this.mSemaphore.acquire();
|
||||
|
||||
streamID = this.mStreamIdSyn;
|
||||
} catch(Exception e) {
|
||||
return Cocos2dxSound.INVALID_SOUND_ID;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return streamID;
|
||||
|
@ -183,8 +189,17 @@ public class Cocos2dxSound {
|
|||
}
|
||||
|
||||
public void resumeAllEffects() {
|
||||
// autoPause() is available since level 8
|
||||
this.mSoundPool.autoResume();
|
||||
// can not only invoke SoundPool.autoResume() here, because
|
||||
// it only resumes all effects paused by pauseAllEffects()
|
||||
if (!this.mPathStreamIDsMap.isEmpty()) {
|
||||
final Iterator<Entry<String, ArrayList<Integer>>> iter = this.mPathStreamIDsMap.entrySet().iterator();
|
||||
while (iter.hasNext()) {
|
||||
final Entry<String, ArrayList<Integer>> entry = iter.next();
|
||||
for (final int pStreamID : entry.getValue()) {
|
||||
this.mSoundPool.resume(pStreamID);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
|
@ -235,9 +250,12 @@ public class Cocos2dxSound {
|
|||
this.mSoundPool.release();
|
||||
this.mPathStreamIDsMap.clear();
|
||||
this.mPathSoundIDMap.clear();
|
||||
this.mEffecToPlayWhenLoadedArray.clear();
|
||||
|
||||
this.mLeftVolume = 0.5f;
|
||||
this.mRightVolume = 0.5f;
|
||||
|
||||
this.initData();
|
||||
}
|
||||
|
||||
public int createSoundIDFromAsset(final String pPath) {
|
||||
|
@ -256,8 +274,62 @@ public class Cocos2dxSound {
|
|||
|
||||
return soundID;
|
||||
}
|
||||
|
||||
private int doPlayEffect(final String pPath, final int soundId, final boolean pLoop) {
|
||||
// play sound
|
||||
int streamID = this.mSoundPool.play(soundId, this.mLeftVolume, this.mRightVolume, Cocos2dxSound.SOUND_PRIORITY, pLoop ? -1 : 0, Cocos2dxSound.SOUND_RATE);
|
||||
|
||||
// record stream id
|
||||
ArrayList<Integer> streamIDs = this.mPathStreamIDsMap.get(pPath);
|
||||
if (streamIDs == null) {
|
||||
streamIDs = new ArrayList<Integer>();
|
||||
this.mPathStreamIDsMap.put(pPath, streamIDs);
|
||||
}
|
||||
streamIDs.add(streamID);
|
||||
|
||||
return streamID;
|
||||
}
|
||||
|
||||
// ===========================================================
|
||||
// Inner and Anonymous Classes
|
||||
// ===========================================================
|
||||
|
||||
public class SoundInfoForLoadedCompleted {
|
||||
public int soundID;
|
||||
public boolean isLoop;
|
||||
public String path;
|
||||
|
||||
public SoundInfoForLoadedCompleted(String path, int soundId, boolean isLoop) {
|
||||
this.path = path;
|
||||
this.soundID = soundId;
|
||||
this.isLoop = isLoop;
|
||||
}
|
||||
}
|
||||
|
||||
public class OnLoadCompletedListener implements SoundPool.OnLoadCompleteListener {
|
||||
|
||||
@Override
|
||||
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
|
||||
if (status == 0)
|
||||
{
|
||||
// only play effect that are in mEffecToPlayWhenLoadedArray
|
||||
for ( SoundInfoForLoadedCompleted info : mEffecToPlayWhenLoadedArray) {
|
||||
if (sampleId == info.soundID) {
|
||||
// set the stream id which will be returned by playEffect()
|
||||
mStreamIdSyn = doPlayEffect(info.path, info.soundID, info.isLoop);
|
||||
|
||||
// remove it from array, because we will break here
|
||||
// so it is safe to do
|
||||
mEffecToPlayWhenLoadedArray.remove(info);
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
mStreamIdSyn = Cocos2dxSound.INVALID_SOUND_ID;
|
||||
}
|
||||
|
||||
mSemaphore.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -40,7 +40,6 @@ public:
|
|||
|
||||
virtual bool isOpenGLReady();
|
||||
virtual bool setContentScaleFactor(float contentScaleFactor);
|
||||
virtual bool enableRetina();
|
||||
|
||||
// keep compatible
|
||||
virtual void end();
|
||||
|
|
|
@ -49,34 +49,11 @@ bool CCEGLView::isOpenGLReady()
|
|||
bool CCEGLView::setContentScaleFactor(float contentScaleFactor)
|
||||
{
|
||||
assert(m_eResolutionPolicy == kResolutionUnKnown); // cannot enable retina mode
|
||||
|
||||
if ([[EAGLView sharedEGLView] respondsToSelector:@selector(setContentScaleFactor:)])
|
||||
{
|
||||
UIView * view = [EAGLView sharedEGLView];
|
||||
view.contentScaleFactor = contentScaleFactor;
|
||||
[view setNeedsLayout];
|
||||
|
||||
m_fScaleX = m_fScaleY = contentScaleFactor;
|
||||
[[EAGLView sharedEGLView] setNeedsLayout];
|
||||
|
||||
m_fScaleX = m_fScaleY = contentScaleFactor;
|
||||
m_bIsRetinaEnabled = true;
|
||||
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool CCEGLView::enableRetina()
|
||||
{
|
||||
bool ret = true;
|
||||
|
||||
// can set content scale factor?
|
||||
ret &= [[EAGLView sharedEGLView] respondsToSelector:@selector(setContentScaleFactor:)];
|
||||
// SD device?
|
||||
ret &= ([[UIScreen mainScreen] scale] != 1.0f);
|
||||
|
||||
return ret;
|
||||
return true;
|
||||
}
|
||||
|
||||
void CCEGLView::end()
|
||||
|
|
|
@ -28,10 +28,6 @@ THE SOFTWARE.
|
|||
#import <Foundation/Foundation.h>
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
// FontLabel support
|
||||
#import "FontLabel/FontManager.h"
|
||||
#import "FontLabel/FontLabelStringDrawing.h"
|
||||
|
||||
typedef struct
|
||||
{
|
||||
unsigned int height;
|
||||
|
@ -171,7 +167,7 @@ static bool _isValidFontName(const char *fontName)
|
|||
return ret;
|
||||
}
|
||||
|
||||
static CGSize _calculateStringSizeWithFontOrZFont(NSString *str, id font, CGSize *constrainSize, bool isZfont)
|
||||
static CGSize _calculateStringSize(NSString *str, id font, CGSize *constrainSize)
|
||||
{
|
||||
NSArray *listItems = [str componentsSeparatedByString: @"\n"];
|
||||
CGSize dim = CGSizeZero;
|
||||
|
@ -184,15 +180,7 @@ static CGSize _calculateStringSizeWithFontOrZFont(NSString *str, id font, CGSize
|
|||
|
||||
for (NSString *s in listItems)
|
||||
{
|
||||
CGSize tmp;
|
||||
if (isZfont)
|
||||
{
|
||||
tmp = [FontLabelStringDrawingHelper sizeWithZFont:s zfont:font constrainedToSize:textRect];
|
||||
}
|
||||
else
|
||||
{
|
||||
tmp = [s sizeWithFont:font constrainedToSize:textRect];
|
||||
}
|
||||
CGSize tmp = [s sizeWithFont:font constrainedToSize:textRect];
|
||||
|
||||
if (tmp.width > dim.width)
|
||||
{
|
||||
|
@ -228,19 +216,9 @@ static bool _initWithString(const char * pText, cocos2d::CCImage::ETextAlign eAl
|
|||
font = [UIFont fontWithName:fntName size:nSize];
|
||||
if (font)
|
||||
{
|
||||
dim = _calculateStringSizeWithFontOrZFont(str, font, &constrainSize, false);
|
||||
dim = _calculateStringSize(str, font, &constrainSize);
|
||||
}
|
||||
|
||||
if (! font)
|
||||
{
|
||||
font = [[FontManager sharedManager] zFontWithName:fntName pointSize:nSize];
|
||||
if (font)
|
||||
{
|
||||
dim =_calculateStringSizeWithFontOrZFont(str, font, &constrainSize, true);
|
||||
}
|
||||
}
|
||||
|
||||
if (! font)
|
||||
else
|
||||
{
|
||||
fntName = _isValidFontName(pFontName) ? fntName : @"MarkerFelt-Wide";
|
||||
font = [UIFont fontWithName:fntName size:nSize];
|
||||
|
@ -252,7 +230,7 @@ static bool _initWithString(const char * pText, cocos2d::CCImage::ETextAlign eAl
|
|||
|
||||
if (font)
|
||||
{
|
||||
dim = _calculateStringSizeWithFontOrZFont(str, font, &constrainSize, false);
|
||||
dim = _calculateStringSize(str, font, &constrainSize);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -314,6 +292,7 @@ static bool _initWithString(const char * pText, cocos2d::CCImage::ETextAlign eAl
|
|||
: UITextAlignmentLeft);
|
||||
|
||||
// normal fonts
|
||||
/*
|
||||
if( [font isKindOfClass:[UIFont class] ] )
|
||||
{
|
||||
[str drawInRect:CGRectMake(0, startH, dim.width, dim.height) withFont:font lineBreakMode:(UILineBreakMode)UILineBreakModeWordWrap alignment:align];
|
||||
|
@ -322,6 +301,8 @@ static bool _initWithString(const char * pText, cocos2d::CCImage::ETextAlign eAl
|
|||
{
|
||||
[FontLabelStringDrawingHelper drawInRect:str rect:CGRectMake(0, startH, dim.width, dim.height) withZFont:font lineBreakMode:(UILineBreakMode)UILineBreakModeWordWrap alignment:align];
|
||||
}
|
||||
*/
|
||||
[str drawInRect:CGRectMake(0, startH, dim.width, dim.height) withFont:font lineBreakMode:(UILineBreakMode)UILineBreakModeWordWrap alignment:align];
|
||||
|
||||
UIGraphicsPopContext();
|
||||
|
||||
|
|
|
@ -151,6 +151,11 @@ static EAGLView *view = 0;
|
|||
|
||||
originalRect_ = self.frame;
|
||||
self.keyboardShowNotification = nil;
|
||||
|
||||
if ([view respondsToSelector:@selector(setContentScaleFactor:)])
|
||||
{
|
||||
view.contentScaleFactor = [[UIScreen mainScreen] scale];
|
||||
}
|
||||
}
|
||||
|
||||
return self;
|
||||
|
@ -200,13 +205,13 @@ static EAGLView *view = 0;
|
|||
-(int) getWidth
|
||||
{
|
||||
CGSize bound = [self bounds].size;
|
||||
return bound.width;
|
||||
return bound.width * self.contentScaleFactor;
|
||||
}
|
||||
|
||||
-(int) getHeight
|
||||
{
|
||||
CGSize bound = [self bounds].size;
|
||||
return bound.height;
|
||||
return bound.height * self.contentScaleFactor;
|
||||
}
|
||||
|
||||
|
||||
|
@ -401,8 +406,8 @@ static EAGLView *view = 0;
|
|||
int i = 0;
|
||||
for (UITouch *touch in touches) {
|
||||
ids[i] = (int)touch;
|
||||
xs[i] = [touch locationInView: [touch view]].x;
|
||||
ys[i] = [touch locationInView: [touch view]].y;
|
||||
xs[i] = [touch locationInView: [touch view]].x * view.contentScaleFactor;;
|
||||
ys[i] = [touch locationInView: [touch view]].y * view.contentScaleFactor;;
|
||||
++i;
|
||||
}
|
||||
cocos2d::CCEGLView::sharedOpenGLView()->handleTouchesBegin(i, ids, xs, ys);
|
||||
|
@ -421,8 +426,8 @@ static EAGLView *view = 0;
|
|||
int i = 0;
|
||||
for (UITouch *touch in touches) {
|
||||
ids[i] = (int)touch;
|
||||
xs[i] = [touch locationInView: [touch view]].x;
|
||||
ys[i] = [touch locationInView: [touch view]].y;
|
||||
xs[i] = [touch locationInView: [touch view]].x * view.contentScaleFactor;;
|
||||
ys[i] = [touch locationInView: [touch view]].y * view.contentScaleFactor;;
|
||||
++i;
|
||||
}
|
||||
cocos2d::CCEGLView::sharedOpenGLView()->handleTouchesMove(i, ids, xs, ys);
|
||||
|
@ -442,8 +447,8 @@ static EAGLView *view = 0;
|
|||
int i = 0;
|
||||
for (UITouch *touch in touches) {
|
||||
ids[i] = (int)touch;
|
||||
xs[i] = [touch locationInView: [touch view]].x;
|
||||
ys[i] = [touch locationInView: [touch view]].y;
|
||||
xs[i] = [touch locationInView: [touch view]].x * view.contentScaleFactor;;
|
||||
ys[i] = [touch locationInView: [touch view]].y * view.contentScaleFactor;;
|
||||
++i;
|
||||
}
|
||||
cocos2d::CCEGLView::sharedOpenGLView()->handleTouchesEnd(i, ids, xs, ys);
|
||||
|
@ -463,8 +468,8 @@ static EAGLView *view = 0;
|
|||
int i = 0;
|
||||
for (UITouch *touch in touches) {
|
||||
ids[i] = (int)touch;
|
||||
xs[i] = [touch locationInView: [touch view]].x;
|
||||
ys[i] = [touch locationInView: [touch view]].y;
|
||||
xs[i] = [touch locationInView: [touch view]].x * view.contentScaleFactor;;
|
||||
ys[i] = [touch locationInView: [touch view]].y * view.contentScaleFactor;;
|
||||
++i;
|
||||
}
|
||||
cocos2d::CCEGLView::sharedOpenGLView()->handleTouchesCancel(i, ids, xs, ys);
|
||||
|
@ -786,6 +791,32 @@ static EAGLView *view = 0;
|
|||
break;
|
||||
}
|
||||
|
||||
float scaleX = cocos2d::CCEGLView::sharedOpenGLView()->getScaleX();
|
||||
float scaleY = cocos2d::CCEGLView::sharedOpenGLView()->getScaleY();
|
||||
|
||||
|
||||
if (self.contentScaleFactor == 2.0f)
|
||||
{
|
||||
// Convert to pixel coordinate
|
||||
|
||||
begin = CGRectApplyAffineTransform(begin, CGAffineTransformScale(CGAffineTransformIdentity, 2.0f, 2.0f));
|
||||
end = CGRectApplyAffineTransform(end, CGAffineTransformScale(CGAffineTransformIdentity, 2.0f, 2.0f));
|
||||
}
|
||||
|
||||
float offestY = cocos2d::CCEGLView::sharedOpenGLView()->getViewPortRect().origin.y;
|
||||
CCLOG("offestY = %f", offestY);
|
||||
if (offestY < 0.0f)
|
||||
{
|
||||
begin.origin.y += offestY;
|
||||
begin.size.height -= offestY;
|
||||
end.size.height -= offestY;
|
||||
}
|
||||
|
||||
// Convert to desigin coordinate
|
||||
begin = CGRectApplyAffineTransform(begin, CGAffineTransformScale(CGAffineTransformIdentity, 1.0f/scaleX, 1.0f/scaleY));
|
||||
end = CGRectApplyAffineTransform(end, CGAffineTransformScale(CGAffineTransformIdentity, 1.0f/scaleX, 1.0f/scaleY));
|
||||
|
||||
|
||||
cocos2d::CCIMEKeyboardNotificationInfo notiInfo;
|
||||
notiInfo.begin = cocos2d::CCRect(begin.origin.x,
|
||||
begin.origin.y,
|
||||
|
@ -797,31 +828,6 @@ static EAGLView *view = 0;
|
|||
end.size.height);
|
||||
notiInfo.duration = (float)aniDuration;
|
||||
|
||||
float offestY = cocos2d::CCEGLView::sharedOpenGLView()->getViewPortRect().origin.y;
|
||||
|
||||
if (offestY > 0.0f)
|
||||
{
|
||||
notiInfo.begin.origin.y += offestY;
|
||||
notiInfo.begin.size.height -= offestY;
|
||||
notiInfo.end.size.height -= offestY;
|
||||
}
|
||||
|
||||
if (!cocos2d::CCEGLView::sharedOpenGLView()->isRetinaEnabled())
|
||||
{
|
||||
float scaleX = cocos2d::CCEGLView::sharedOpenGLView()->getScaleX();
|
||||
float scaleY = cocos2d::CCEGLView::sharedOpenGLView()->getScaleY();
|
||||
|
||||
notiInfo.begin.origin.x /= scaleX;
|
||||
notiInfo.begin.origin.y /= scaleY;
|
||||
notiInfo.begin.size.width /= scaleX;
|
||||
notiInfo.begin.size.height /= scaleY;
|
||||
|
||||
notiInfo.end.origin.x /= scaleX;
|
||||
notiInfo.end.origin.y /= scaleY;
|
||||
notiInfo.end.size.width /= scaleX;
|
||||
notiInfo.end.size.height /= scaleY;
|
||||
}
|
||||
|
||||
cocos2d::CCIMEDispatcher* dispatcher = cocos2d::CCIMEDispatcher::sharedDispatcher();
|
||||
if (UIKeyboardWillShowNotification == type)
|
||||
{
|
||||
|
@ -856,13 +862,15 @@ static EAGLView *view = 0;
|
|||
[UIView setAnimationDuration:duration];
|
||||
[UIView setAnimationBeginsFromCurrentState:YES];
|
||||
|
||||
// NSLog(@"[animation] dis = %f\n", dis);
|
||||
//NSLog(@"[animation] dis = %f, scale = %f \n", dis, cocos2d::CCEGLView::sharedOpenGLView()->getScaleY());
|
||||
|
||||
if (dis < 0.0f) dis = 0.0f;
|
||||
|
||||
if (!cocos2d::CCEGLView::sharedOpenGLView()->isRetinaEnabled())
|
||||
dis *= cocos2d::CCEGLView::sharedOpenGLView()->getScaleY();
|
||||
|
||||
if (self.contentScaleFactor == 2.0f)
|
||||
{
|
||||
dis *= cocos2d::CCEGLView::sharedOpenGLView()->getScaleY();
|
||||
dis /= 2.0f;
|
||||
}
|
||||
|
||||
switch ([[UIApplication sharedApplication] statusBarOrientation])
|
||||
|
|
|
@ -1,44 +0,0 @@
|
|||
//
|
||||
// FontLabel.h
|
||||
// FontLabel
|
||||
//
|
||||
// Created by Kevin Ballard on 5/8/09.
|
||||
// Copyright © 2009 Zynga Game Networks
|
||||
//
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
@class ZFont;
|
||||
@class ZAttributedString;
|
||||
|
||||
@interface FontLabel : UILabel {
|
||||
void *reserved; // works around a bug in UILabel
|
||||
ZFont *zFont;
|
||||
ZAttributedString *zAttributedText;
|
||||
}
|
||||
@property (nonatomic, setter=setCGFont:) CGFontRef cgFont __AVAILABILITY_INTERNAL_DEPRECATED;
|
||||
@property (nonatomic, assign) CGFloat pointSize __AVAILABILITY_INTERNAL_DEPRECATED;
|
||||
@property (nonatomic, retain, setter=setZFont:) ZFont *zFont;
|
||||
// if attributedText is nil, fall back on using the inherited UILabel properties
|
||||
// if attributedText is non-nil, the font/text/textColor
|
||||
// in addition, adjustsFontSizeToFitWidth does not work with attributed text
|
||||
@property (nonatomic, copy) ZAttributedString *zAttributedText;
|
||||
// -initWithFrame:fontName:pointSize: uses FontManager to look up the font name
|
||||
- (id)initWithFrame:(CGRect)frame fontName:(NSString *)fontName pointSize:(CGFloat)pointSize;
|
||||
- (id)initWithFrame:(CGRect)frame zFont:(ZFont *)font;
|
||||
- (id)initWithFrame:(CGRect)frame font:(CGFontRef)font pointSize:(CGFloat)pointSize __AVAILABILITY_INTERNAL_DEPRECATED;
|
||||
@end
|
|
@ -1,197 +0,0 @@
|
|||
//
|
||||
// FontLabel.m
|
||||
// FontLabel
|
||||
//
|
||||
// Created by Kevin Ballard on 5/8/09.
|
||||
// Copyright © 2009 Zynga Game Networks
|
||||
//
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
#import "FontLabel.h"
|
||||
#import "FontManager.h"
|
||||
#import "FontLabelStringDrawing.h"
|
||||
#import "ZFont.h"
|
||||
|
||||
@interface ZFont (ZFontPrivate)
|
||||
@property (nonatomic, readonly) CGFloat ratio;
|
||||
@end
|
||||
|
||||
@implementation FontLabel
|
||||
@synthesize zFont;
|
||||
@synthesize zAttributedText;
|
||||
|
||||
- (id)initWithFrame:(CGRect)frame fontName:(NSString *)fontName pointSize:(CGFloat)pointSize {
|
||||
return [self initWithFrame:frame zFont:[[FontManager sharedManager] zFontWithName:fontName pointSize:pointSize]];
|
||||
}
|
||||
|
||||
- (id)initWithFrame:(CGRect)frame zFont:(ZFont *)font {
|
||||
if ((self = [super initWithFrame:frame])) {
|
||||
zFont = [font retain];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (id)initWithFrame:(CGRect)frame font:(CGFontRef)font pointSize:(CGFloat)pointSize {
|
||||
return [self initWithFrame:frame zFont:[ZFont fontWithCGFont:font size:pointSize]];
|
||||
}
|
||||
|
||||
- (CGFontRef)cgFont {
|
||||
return self.zFont.cgFont;
|
||||
}
|
||||
|
||||
- (void)setCGFont:(CGFontRef)font {
|
||||
if (self.zFont.cgFont != font) {
|
||||
self.zFont = [ZFont fontWithCGFont:font size:self.zFont.pointSize];
|
||||
}
|
||||
}
|
||||
|
||||
- (CGFloat)pointSize {
|
||||
return self.zFont.pointSize;
|
||||
}
|
||||
|
||||
- (void)setPointSize:(CGFloat)pointSize {
|
||||
if (self.zFont.pointSize != pointSize) {
|
||||
self.zFont = [ZFont fontWithCGFont:self.zFont.cgFont size:pointSize];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setZAttributedText:(ZAttributedString *)attStr {
|
||||
if (zAttributedText != attStr) {
|
||||
[zAttributedText release];
|
||||
zAttributedText = [attStr copy];
|
||||
[self setNeedsDisplay];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)drawTextInRect:(CGRect)rect {
|
||||
if (self.zFont == NULL && self.zAttributedText == nil) {
|
||||
[super drawTextInRect:rect];
|
||||
return;
|
||||
}
|
||||
|
||||
if (self.zAttributedText == nil) {
|
||||
// this method is documented as setting the text color for us, but that doesn't appear to be the case
|
||||
if (self.highlighted) {
|
||||
[(self.highlightedTextColor ?: [UIColor whiteColor]) setFill];
|
||||
} else {
|
||||
[(self.textColor ?: [UIColor blackColor]) setFill];
|
||||
}
|
||||
|
||||
ZFont *actualFont = self.zFont;
|
||||
CGSize origSize = rect.size;
|
||||
if (self.numberOfLines == 1) {
|
||||
origSize.height = actualFont.leading;
|
||||
CGPoint point = CGPointMake(rect.origin.x,
|
||||
rect.origin.y + roundf(((rect.size.height - actualFont.leading) / 2.0f)));
|
||||
CGSize size = [self.text sizeWithZFont:actualFont];
|
||||
if (self.adjustsFontSizeToFitWidth && self.minimumFontSize < actualFont.pointSize) {
|
||||
if (size.width > origSize.width) {
|
||||
CGFloat desiredRatio = (origSize.width * actualFont.ratio) / size.width;
|
||||
CGFloat desiredPointSize = desiredRatio * actualFont.pointSize / actualFont.ratio;
|
||||
actualFont = [actualFont fontWithSize:MAX(MAX(desiredPointSize, self.minimumFontSize), 1.0f)];
|
||||
size = [self.text sizeWithZFont:actualFont];
|
||||
}
|
||||
if (!CGSizeEqualToSize(origSize, size)) {
|
||||
switch (self.baselineAdjustment) {
|
||||
case UIBaselineAdjustmentAlignCenters:
|
||||
point.y += roundf((origSize.height - size.height) / 2.0f);
|
||||
break;
|
||||
case UIBaselineAdjustmentAlignBaselines:
|
||||
point.y += (self.zFont.ascender - actualFont.ascender);
|
||||
break;
|
||||
case UIBaselineAdjustmentNone:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
size.width = MIN(size.width, origSize.width);
|
||||
// adjust the point for alignment
|
||||
switch (self.textAlignment) {
|
||||
case UITextAlignmentLeft:
|
||||
break;
|
||||
case UITextAlignmentCenter:
|
||||
point.x += (origSize.width - size.width) / 2.0f;
|
||||
break;
|
||||
case UITextAlignmentRight:
|
||||
point.x += origSize.width - size.width;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
[self.text drawAtPoint:point forWidth:size.width withZFont:actualFont lineBreakMode:self.lineBreakMode];
|
||||
} else {
|
||||
CGSize size = [self.text sizeWithZFont:actualFont constrainedToSize:origSize lineBreakMode:self.lineBreakMode numberOfLines:self.numberOfLines];
|
||||
CGPoint point = rect.origin;
|
||||
point.y += roundf((rect.size.height - size.height) / 2.0f);
|
||||
rect = (CGRect){point, CGSizeMake(rect.size.width, size.height)};
|
||||
[self.text drawInRect:rect withZFont:actualFont lineBreakMode:self.lineBreakMode alignment:self.textAlignment numberOfLines:self.numberOfLines];
|
||||
}
|
||||
} else {
|
||||
ZAttributedString *attStr = self.zAttributedText;
|
||||
if (self.highlighted) {
|
||||
// modify the string to change the base color
|
||||
ZMutableAttributedString *mutStr = [[attStr mutableCopy] autorelease];
|
||||
NSRange activeRange = NSMakeRange(0, attStr.length);
|
||||
while (activeRange.length > 0) {
|
||||
NSRange effective;
|
||||
UIColor *color = [attStr attribute:ZForegroundColorAttributeName atIndex:activeRange.location
|
||||
longestEffectiveRange:&effective inRange:activeRange];
|
||||
if (color == nil) {
|
||||
[mutStr addAttribute:ZForegroundColorAttributeName value:[UIColor whiteColor] range:effective];
|
||||
}
|
||||
activeRange.location += effective.length, activeRange.length -= effective.length;
|
||||
}
|
||||
attStr = mutStr;
|
||||
}
|
||||
CGSize size = [attStr sizeConstrainedToSize:rect.size lineBreakMode:self.lineBreakMode numberOfLines:self.numberOfLines];
|
||||
CGPoint point = rect.origin;
|
||||
point.y += roundf((rect.size.height - size.height) / 2.0f);
|
||||
rect = (CGRect){point, CGSizeMake(rect.size.width, size.height)};
|
||||
[attStr drawInRect:rect withLineBreakMode:self.lineBreakMode alignment:self.textAlignment numberOfLines:self.numberOfLines];
|
||||
}
|
||||
}
|
||||
|
||||
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {
|
||||
if (self.zFont == NULL && self.zAttributedText == nil) {
|
||||
return [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
|
||||
}
|
||||
|
||||
if (numberOfLines == 1) {
|
||||
// if numberOfLines == 1 we need to use the version that converts spaces
|
||||
CGSize size;
|
||||
if (self.zAttributedText == nil) {
|
||||
size = [self.text sizeWithZFont:self.zFont];
|
||||
} else {
|
||||
size = [self.zAttributedText size];
|
||||
}
|
||||
bounds.size.width = MIN(bounds.size.width, size.width);
|
||||
bounds.size.height = MIN(bounds.size.height, size.height);
|
||||
} else {
|
||||
if (numberOfLines > 0) bounds.size.height = MIN(bounds.size.height, self.zFont.leading * numberOfLines);
|
||||
if (self.zAttributedText == nil) {
|
||||
bounds.size = [self.text sizeWithZFont:self.zFont constrainedToSize:bounds.size lineBreakMode:self.lineBreakMode];
|
||||
} else {
|
||||
bounds.size = [self.zAttributedText sizeConstrainedToSize:bounds.size lineBreakMode:self.lineBreakMode];
|
||||
}
|
||||
}
|
||||
return bounds;
|
||||
}
|
||||
|
||||
- (void)dealloc {
|
||||
[zFont release];
|
||||
[zAttributedText release];
|
||||
[super dealloc];
|
||||
}
|
||||
@end
|
|
@ -1,82 +0,0 @@
|
|||
//
|
||||
// FontLabelStringDrawing.h
|
||||
// FontLabel
|
||||
//
|
||||
// Created by Kevin Ballard on 5/5/09.
|
||||
// Copyright © 2009 Zynga Game Networks
|
||||
// Copyright (c) 2011 cocos2d-x.org
|
||||
//
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
#import "ZAttributedString.h"
|
||||
|
||||
@class ZFont;
|
||||
|
||||
@interface NSString (FontLabelStringDrawing)
|
||||
// CGFontRef-based methods
|
||||
- (CGSize)sizeWithCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize __AVAILABILITY_INTERNAL_DEPRECATED;
|
||||
- (CGSize)sizeWithCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize constrainedToSize:(CGSize)size __AVAILABILITY_INTERNAL_DEPRECATED;
|
||||
- (CGSize)sizeWithCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize constrainedToSize:(CGSize)size
|
||||
lineBreakMode:(UILineBreakMode)lineBreakMode __AVAILABILITY_INTERNAL_DEPRECATED;
|
||||
- (CGSize)drawAtPoint:(CGPoint)point withCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize __AVAILABILITY_INTERNAL_DEPRECATED;
|
||||
- (CGSize)drawInRect:(CGRect)rect withCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize __AVAILABILITY_INTERNAL_DEPRECATED;
|
||||
- (CGSize)drawInRect:(CGRect)rect withCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize
|
||||
lineBreakMode:(UILineBreakMode)lineBreakMode __AVAILABILITY_INTERNAL_DEPRECATED;
|
||||
- (CGSize)drawInRect:(CGRect)rect withCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize
|
||||
lineBreakMode:(UILineBreakMode)lineBreakMode alignment:(UITextAlignment)alignment __AVAILABILITY_INTERNAL_DEPRECATED;
|
||||
|
||||
// ZFont-based methods
|
||||
- (CGSize)sizeWithZFont:(ZFont *)font;
|
||||
- (CGSize)sizeWithZFont:(ZFont *)font constrainedToSize:(CGSize)size;
|
||||
- (CGSize)sizeWithZFont:(ZFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode;
|
||||
- (CGSize)sizeWithZFont:(ZFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode
|
||||
numberOfLines:(NSUInteger)numberOfLines;
|
||||
- (CGSize)drawAtPoint:(CGPoint)point withZFont:(ZFont *)font;
|
||||
- (CGSize)drawAtPoint:(CGPoint)point forWidth:(CGFloat)width withZFont:(ZFont *)font lineBreakMode:(UILineBreakMode)lineBreakMode;
|
||||
- (CGSize)drawInRect:(CGRect)rect withZFont:(ZFont *)font;
|
||||
- (CGSize)drawInRect:(CGRect)rect withZFont:(ZFont *)font lineBreakMode:(UILineBreakMode)lineBreakMode;
|
||||
- (CGSize)drawInRect:(CGRect)rect withZFont:(ZFont *)font lineBreakMode:(UILineBreakMode)lineBreakMode
|
||||
alignment:(UITextAlignment)alignment;
|
||||
- (CGSize)drawInRect:(CGRect)rect withZFont:(ZFont *)font lineBreakMode:(UILineBreakMode)lineBreakMode
|
||||
alignment:(UITextAlignment)alignment numberOfLines:(NSUInteger)numberOfLines;
|
||||
@end
|
||||
|
||||
@interface ZAttributedString (ZAttributedStringDrawing)
|
||||
- (CGSize)size;
|
||||
- (CGSize)sizeConstrainedToSize:(CGSize)size;
|
||||
- (CGSize)sizeConstrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode;
|
||||
- (CGSize)sizeConstrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode
|
||||
numberOfLines:(NSUInteger)numberOfLines;
|
||||
- (CGSize)drawAtPoint:(CGPoint)point;
|
||||
- (CGSize)drawAtPoint:(CGPoint)point forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode;
|
||||
- (CGSize)drawInRect:(CGRect)rect;
|
||||
- (CGSize)drawInRect:(CGRect)rect withLineBreakMode:(UILineBreakMode)lineBreakMode;
|
||||
- (CGSize)drawInRect:(CGRect)rect withLineBreakMode:(UILineBreakMode)lineBreakMode alignment:(UITextAlignment)alignment;
|
||||
- (CGSize)drawInRect:(CGRect)rect withLineBreakMode:(UILineBreakMode)lineBreakMode alignment:(UITextAlignment)alignment
|
||||
numberOfLines:(NSUInteger)numberOfLines;
|
||||
@end
|
||||
|
||||
// This class is used to invoke in .mm file.
|
||||
// Can not invoke FontLabelStringDrawing directly in .mm.
|
||||
// It seems that, in .mm it can not support category.
|
||||
@interface FontLabelStringDrawingHelper : NSObject {
|
||||
}
|
||||
+ (CGSize)sizeWithZFont:(NSString*)string zfont:(ZFont *)font;
|
||||
+ (CGSize)sizeWithZFont:(NSString *)string zfont:(ZFont *)font constrainedToSize:(CGSize)size;
|
||||
+ (CGSize)drawInRect:(NSString*)string rect:(CGRect)rect withZFont:(ZFont *)font
|
||||
lineBreakMode:(UILineBreakMode)lineBreakMode
|
||||
alignment:(UITextAlignment)alignment;
|
||||
@end
|
|
@ -1,916 +0,0 @@
|
|||
//
|
||||
// FontLabelStringDrawing.m
|
||||
// FontLabel
|
||||
//
|
||||
// Created by Kevin Ballard on 5/5/09.
|
||||
// Copyright © 2009 Zynga Game Networks
|
||||
// Copyright (c) 2011 cocos2d-x.org
|
||||
//
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
#import "FontLabelStringDrawing.h"
|
||||
#import "ZFont.h"
|
||||
#import "ZAttributedStringPrivate.h"
|
||||
|
||||
@interface ZFont (ZFontPrivate)
|
||||
@property (nonatomic, readonly) CGFloat ratio;
|
||||
@end
|
||||
|
||||
#define kUnicodeHighSurrogateStart 0xD800
|
||||
#define kUnicodeHighSurrogateEnd 0xDBFF
|
||||
#define kUnicodeHighSurrogateMask kUnicodeHighSurrogateStart
|
||||
#define kUnicodeLowSurrogateStart 0xDC00
|
||||
#define kUnicodeLowSurrogateEnd 0xDFFF
|
||||
#define kUnicodeLowSurrogateMask kUnicodeLowSurrogateStart
|
||||
#define kUnicodeSurrogateTypeMask 0xFC00
|
||||
#define UnicharIsHighSurrogate(c) ((c & kUnicodeSurrogateTypeMask) == kUnicodeHighSurrogateMask)
|
||||
#define UnicharIsLowSurrogate(c) ((c & kUnicodeSurrogateTypeMask) == kUnicodeLowSurrogateMask)
|
||||
#define ConvertSurrogatePairToUTF32(high, low) ((UInt32)((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000))
|
||||
|
||||
typedef enum {
|
||||
kFontTableFormat4 = 4,
|
||||
kFontTableFormat12 = 12,
|
||||
} FontTableFormat;
|
||||
|
||||
typedef struct fontTable {
|
||||
NSUInteger retainCount;
|
||||
CFDataRef cmapTable;
|
||||
FontTableFormat format;
|
||||
union {
|
||||
struct {
|
||||
UInt16 segCountX2;
|
||||
UInt16 *endCodes;
|
||||
UInt16 *startCodes;
|
||||
UInt16 *idDeltas;
|
||||
UInt16 *idRangeOffsets;
|
||||
} format4;
|
||||
struct {
|
||||
UInt32 nGroups;
|
||||
struct {
|
||||
UInt32 startCharCode;
|
||||
UInt32 endCharCode;
|
||||
UInt32 startGlyphCode;
|
||||
} *groups;
|
||||
} format12;
|
||||
} cmap;
|
||||
} fontTable;
|
||||
|
||||
static FontTableFormat supportedFormats[] = { kFontTableFormat4, kFontTableFormat12 };
|
||||
static size_t supportedFormatsCount = sizeof(supportedFormats) / sizeof(FontTableFormat);
|
||||
|
||||
static fontTable *newFontTable(CFDataRef cmapTable, FontTableFormat format) {
|
||||
fontTable *table = (struct fontTable *)malloc(sizeof(struct fontTable));
|
||||
table->retainCount = 1;
|
||||
table->cmapTable = CFRetain(cmapTable);
|
||||
table->format = format;
|
||||
return table;
|
||||
}
|
||||
|
||||
static fontTable *retainFontTable(fontTable *table) {
|
||||
if (table != NULL) {
|
||||
table->retainCount++;
|
||||
}
|
||||
return table;
|
||||
}
|
||||
|
||||
static void releaseFontTable(fontTable *table) {
|
||||
if (table != NULL) {
|
||||
if (table->retainCount <= 1) {
|
||||
CFRelease(table->cmapTable);
|
||||
free(table);
|
||||
} else {
|
||||
table->retainCount--;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static const void *fontTableRetainCallback(CFAllocatorRef allocator, const void *value) {
|
||||
return retainFontTable((fontTable *)value);
|
||||
}
|
||||
|
||||
static void fontTableReleaseCallback(CFAllocatorRef allocator, const void *value) {
|
||||
releaseFontTable((fontTable *)value);
|
||||
}
|
||||
|
||||
static const CFDictionaryValueCallBacks kFontTableDictionaryValueCallBacks = {
|
||||
.version = 0,
|
||||
.retain = &fontTableRetainCallback,
|
||||
.release = &fontTableReleaseCallback,
|
||||
.copyDescription = NULL,
|
||||
.equal = NULL
|
||||
};
|
||||
|
||||
// read the cmap table from the font
|
||||
// we only know how to understand some of the table formats at the moment
|
||||
static fontTable *readFontTableFromCGFont(CGFontRef font) {
|
||||
CFDataRef cmapTable = CGFontCopyTableForTag(font, 'cmap');
|
||||
NSCAssert1(cmapTable != NULL, @"CGFontCopyTableForTag returned NULL for 'cmap' tag in font %@",
|
||||
(font ? [(id)CFCopyDescription(font) autorelease] : @"(null)"));
|
||||
const UInt8 * const bytes = CFDataGetBytePtr(cmapTable);
|
||||
NSCAssert1(OSReadBigInt16(bytes, 0) == 0, @"cmap table for font %@ has bad version number",
|
||||
(font ? [(id)CFCopyDescription(font) autorelease] : @"(null)"));
|
||||
UInt16 numberOfSubtables = OSReadBigInt16(bytes, 2);
|
||||
const UInt8 *unicodeSubtable = NULL;
|
||||
//UInt16 unicodeSubtablePlatformID;
|
||||
UInt16 unicodeSubtablePlatformSpecificID;
|
||||
FontTableFormat unicodeSubtableFormat;
|
||||
const UInt8 * const encodingSubtables = &bytes[4];
|
||||
for (UInt16 i = 0; i < numberOfSubtables; i++) {
|
||||
const UInt8 * const encodingSubtable = &encodingSubtables[8 * i];
|
||||
UInt16 platformID = OSReadBigInt16(encodingSubtable, 0);
|
||||
UInt16 platformSpecificID = OSReadBigInt16(encodingSubtable, 2);
|
||||
// find the best subtable
|
||||
// best is defined by a combination of encoding and format
|
||||
// At the moment we only support format 4, so ignore all other format tables
|
||||
// We prefer platformID == 0, but we will also accept Microsoft's unicode format
|
||||
if (platformID == 0 || (platformID == 3 && platformSpecificID == 1)) {
|
||||
BOOL preferred = NO;
|
||||
if (unicodeSubtable == NULL) {
|
||||
preferred = YES;
|
||||
} else if (platformID == 0 && platformSpecificID > unicodeSubtablePlatformSpecificID) {
|
||||
preferred = YES;
|
||||
}
|
||||
if (preferred) {
|
||||
UInt32 offset = OSReadBigInt32(encodingSubtable, 4);
|
||||
const UInt8 *subtable = &bytes[offset];
|
||||
UInt16 format = OSReadBigInt16(subtable, 0);
|
||||
for (size_t i = 0; i < supportedFormatsCount; i++) {
|
||||
if (format == supportedFormats[i]) {
|
||||
if (format >= 8) {
|
||||
// the version is a fixed-point
|
||||
UInt16 formatFrac = OSReadBigInt16(subtable, 2);
|
||||
if (formatFrac != 0) {
|
||||
// all the current formats with a Fixed version are always *.0
|
||||
continue;
|
||||
}
|
||||
}
|
||||
unicodeSubtable = subtable;
|
||||
//unicodeSubtablePlatformID = platformID;
|
||||
unicodeSubtablePlatformSpecificID = platformSpecificID;
|
||||
unicodeSubtableFormat = format;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fontTable *table = NULL;
|
||||
if (unicodeSubtable != NULL) {
|
||||
table = newFontTable(cmapTable, unicodeSubtableFormat);
|
||||
switch (unicodeSubtableFormat) {
|
||||
case kFontTableFormat4:
|
||||
// subtable format 4
|
||||
//UInt16 length = OSReadBigInt16(unicodeSubtable, 2);
|
||||
//UInt16 language = OSReadBigInt16(unicodeSubtable, 4);
|
||||
table->cmap.format4.segCountX2 = OSReadBigInt16(unicodeSubtable, 6);
|
||||
//UInt16 searchRange = OSReadBigInt16(unicodeSubtable, 8);
|
||||
//UInt16 entrySelector = OSReadBigInt16(unicodeSubtable, 10);
|
||||
//UInt16 rangeShift = OSReadBigInt16(unicodeSubtable, 12);
|
||||
table->cmap.format4.endCodes = (UInt16*)&unicodeSubtable[14];
|
||||
table->cmap.format4.startCodes = (UInt16*)&((UInt8*)table->cmap.format4.endCodes)[table->cmap.format4.segCountX2+2];
|
||||
table->cmap.format4.idDeltas = (UInt16*)&((UInt8*)table->cmap.format4.startCodes)[table->cmap.format4.segCountX2];
|
||||
table->cmap.format4.idRangeOffsets = (UInt16*)&((UInt8*)table->cmap.format4.idDeltas)[table->cmap.format4.segCountX2];
|
||||
//UInt16 *glyphIndexArray = &idRangeOffsets[segCountX2];
|
||||
break;
|
||||
case kFontTableFormat12:
|
||||
table->cmap.format12.nGroups = OSReadBigInt32(unicodeSubtable, 12);
|
||||
table->cmap.format12.groups = (void *)&unicodeSubtable[16];
|
||||
break;
|
||||
default:
|
||||
releaseFontTable(table);
|
||||
table = NULL;
|
||||
}
|
||||
}
|
||||
CFRelease(cmapTable);
|
||||
return table;
|
||||
}
|
||||
|
||||
// outGlyphs must be at least size n
|
||||
static void mapCharactersToGlyphsInFont(const fontTable *table, unichar characters[], size_t charLen, CGGlyph outGlyphs[], size_t *outGlyphLen) {
|
||||
if (table != NULL) {
|
||||
NSUInteger j = 0;
|
||||
switch (table->format) {
|
||||
case kFontTableFormat4: {
|
||||
for (NSUInteger i = 0; i < charLen; i++, j++) {
|
||||
unichar c = characters[i];
|
||||
UInt16 segOffset;
|
||||
BOOL foundSegment = NO;
|
||||
for (segOffset = 0; segOffset < table->cmap.format4.segCountX2; segOffset += 2) {
|
||||
UInt16 endCode = OSReadBigInt16(table->cmap.format4.endCodes, segOffset);
|
||||
if (endCode >= c) {
|
||||
foundSegment = YES;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!foundSegment) {
|
||||
// no segment
|
||||
// this is an invalid font
|
||||
outGlyphs[j] = 0;
|
||||
} else {
|
||||
UInt16 startCode = OSReadBigInt16(table->cmap.format4.startCodes, segOffset);
|
||||
if (!(startCode <= c)) {
|
||||
// the code falls in a hole between segments
|
||||
outGlyphs[j] = 0;
|
||||
} else {
|
||||
UInt16 idRangeOffset = OSReadBigInt16(table->cmap.format4.idRangeOffsets, segOffset);
|
||||
if (idRangeOffset == 0) {
|
||||
UInt16 idDelta = OSReadBigInt16(table->cmap.format4.idDeltas, segOffset);
|
||||
outGlyphs[j] = (c + idDelta) % 65536;
|
||||
} else {
|
||||
// use the glyphIndexArray
|
||||
UInt16 glyphOffset = idRangeOffset + 2 * (c - startCode);
|
||||
outGlyphs[j] = OSReadBigInt16(&((UInt8*)table->cmap.format4.idRangeOffsets)[segOffset], glyphOffset);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case kFontTableFormat12: {
|
||||
UInt32 lastSegment = UINT32_MAX;
|
||||
for (NSUInteger i = 0; i < charLen; i++, j++) {
|
||||
unichar c = characters[i];
|
||||
UInt32 c32 = c;
|
||||
if (UnicharIsHighSurrogate(c)) {
|
||||
if (i+1 < charLen) { // do we have another character after this one?
|
||||
unichar cc = characters[i+1];
|
||||
if (UnicharIsLowSurrogate(cc)) {
|
||||
c32 = ConvertSurrogatePairToUTF32(c, cc);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Start the heuristic search
|
||||
// If this is an ASCII char, just do a linear search
|
||||
// Otherwise do a hinted, modified binary search
|
||||
// Start the first pivot at the last range found
|
||||
// And when moving the pivot, limit the movement by increasing
|
||||
// powers of two. This should help with locality
|
||||
__typeof__(table->cmap.format12.groups[0]) *foundGroup = NULL;
|
||||
if (c32 <= 0x7F) {
|
||||
// ASCII
|
||||
for (UInt32 idx = 0; idx < table->cmap.format12.nGroups; idx++) {
|
||||
__typeof__(table->cmap.format12.groups[idx]) *group = &table->cmap.format12.groups[idx];
|
||||
if (c32 < OSSwapBigToHostInt32(group->startCharCode)) {
|
||||
// we've fallen into a hole
|
||||
break;
|
||||
} else if (c32 <= OSSwapBigToHostInt32(group->endCharCode)) {
|
||||
// this is the range
|
||||
foundGroup = group;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// heuristic search
|
||||
UInt32 maxJump = (lastSegment == UINT32_MAX ? UINT32_MAX / 2 : 8);
|
||||
UInt32 lowIdx = 0, highIdx = table->cmap.format12.nGroups; // highIdx is the first invalid idx
|
||||
UInt32 pivot = (lastSegment == UINT32_MAX ? lowIdx + (highIdx - lowIdx) / 2 : lastSegment);
|
||||
while (highIdx > lowIdx) {
|
||||
__typeof__(table->cmap.format12.groups[pivot]) *group = &table->cmap.format12.groups[pivot];
|
||||
if (c32 < OSSwapBigToHostInt32(group->startCharCode)) {
|
||||
highIdx = pivot;
|
||||
} else if (c32 > OSSwapBigToHostInt32(group->endCharCode)) {
|
||||
lowIdx = pivot + 1;
|
||||
} else {
|
||||
// we've hit the range
|
||||
foundGroup = group;
|
||||
break;
|
||||
}
|
||||
if (highIdx - lowIdx > maxJump * 2) {
|
||||
if (highIdx == pivot) {
|
||||
pivot -= maxJump;
|
||||
} else {
|
||||
pivot += maxJump;
|
||||
}
|
||||
maxJump *= 2;
|
||||
} else {
|
||||
pivot = lowIdx + (highIdx - lowIdx) / 2;
|
||||
}
|
||||
}
|
||||
if (foundGroup != NULL) lastSegment = pivot;
|
||||
}
|
||||
if (foundGroup == NULL) {
|
||||
outGlyphs[j] = 0;
|
||||
} else {
|
||||
outGlyphs[j] = (CGGlyph)(OSSwapBigToHostInt32(foundGroup->startGlyphCode) +
|
||||
(c32 - OSSwapBigToHostInt32(foundGroup->startCharCode)));
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (outGlyphLen != NULL) *outGlyphLen = j;
|
||||
} else {
|
||||
// we have no table, so just null out the glyphs
|
||||
bzero(outGlyphs, charLen*sizeof(CGGlyph));
|
||||
if (outGlyphLen != NULL) *outGlyphLen = 0;
|
||||
}
|
||||
}
|
||||
|
||||
static BOOL mapGlyphsToAdvancesInFont(ZFont *font, size_t n, CGGlyph glyphs[], CGFloat outAdvances[]) {
|
||||
int advances[n];
|
||||
if (CGFontGetGlyphAdvances(font.cgFont, glyphs, n, advances)) {
|
||||
CGFloat ratio = font.ratio;
|
||||
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
outAdvances[i] = advances[i]*ratio;
|
||||
}
|
||||
return YES;
|
||||
} else {
|
||||
bzero(outAdvances, n*sizeof(CGFloat));
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
static id getValueOrDefaultForRun(ZAttributeRun *run, NSString *key) {
|
||||
id value = [run.attributes objectForKey:key];
|
||||
if (value == nil) {
|
||||
static NSDictionary *defaultValues = nil;
|
||||
if (defaultValues == nil) {
|
||||
defaultValues = [[NSDictionary alloc] initWithObjectsAndKeys:
|
||||
[ZFont fontWithUIFont:[UIFont systemFontOfSize:12]], ZFontAttributeName,
|
||||
[UIColor blackColor], ZForegroundColorAttributeName,
|
||||
[UIColor clearColor], ZBackgroundColorAttributeName,
|
||||
[NSNumber numberWithInt:ZUnderlineStyleNone], ZUnderlineStyleAttributeName,
|
||||
nil];
|
||||
}
|
||||
value = [defaultValues objectForKey:key];
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
static void readRunInformation(NSArray *attributes, NSUInteger len, CFMutableDictionaryRef fontTableMap,
|
||||
NSUInteger index, ZAttributeRun **currentRun, NSUInteger *nextRunStart,
|
||||
ZFont **currentFont, fontTable **currentTable) {
|
||||
*currentRun = [attributes objectAtIndex:index];
|
||||
*nextRunStart = ([attributes count] > index+1 ? [[attributes objectAtIndex:index+1] index] : len);
|
||||
*currentFont = getValueOrDefaultForRun(*currentRun, ZFontAttributeName);
|
||||
if (!CFDictionaryGetValueIfPresent(fontTableMap, (*currentFont).cgFont, (const void **)currentTable)) {
|
||||
*currentTable = readFontTableFromCGFont((*currentFont).cgFont);
|
||||
CFDictionarySetValue(fontTableMap, (*currentFont).cgFont, *currentTable);
|
||||
releaseFontTable(*currentTable);
|
||||
}
|
||||
}
|
||||
|
||||
static CGSize drawOrSizeTextConstrainedToSize(BOOL performDraw, NSString *string, NSArray *attributes, CGSize constrainedSize, NSUInteger maxLines,
|
||||
UILineBreakMode lineBreakMode, UITextAlignment alignment, BOOL ignoreColor) {
|
||||
NSUInteger len = [string length];
|
||||
NSUInteger idx = 0;
|
||||
CGPoint drawPoint = CGPointZero;
|
||||
CGSize retValue = CGSizeZero;
|
||||
CGContextRef ctx = (performDraw ? UIGraphicsGetCurrentContext() : NULL);
|
||||
|
||||
BOOL convertNewlines = (maxLines == 1);
|
||||
|
||||
// Extract the characters from the string
|
||||
// Convert newlines to spaces if necessary
|
||||
unichar *characters = (unichar *)malloc(sizeof(unichar) * len);
|
||||
if (convertNewlines) {
|
||||
NSCharacterSet *charset = [NSCharacterSet newlineCharacterSet];
|
||||
NSRange range = NSMakeRange(0, len);
|
||||
size_t cIdx = 0;
|
||||
while (range.length > 0) {
|
||||
NSRange newlineRange = [string rangeOfCharacterFromSet:charset options:0 range:range];
|
||||
if (newlineRange.location == NSNotFound) {
|
||||
[string getCharacters:&characters[cIdx] range:range];
|
||||
cIdx += range.length;
|
||||
break;
|
||||
} else {
|
||||
NSUInteger delta = newlineRange.location - range.location;
|
||||
if (newlineRange.location > range.location) {
|
||||
[string getCharacters:&characters[cIdx] range:NSMakeRange(range.location, delta)];
|
||||
}
|
||||
cIdx += delta;
|
||||
characters[cIdx] = (unichar)' ';
|
||||
cIdx++;
|
||||
delta += newlineRange.length;
|
||||
range.location += delta, range.length -= delta;
|
||||
if (newlineRange.length == 1 && range.length >= 1 &&
|
||||
[string characterAtIndex:newlineRange.location] == (unichar)'\r' &&
|
||||
[string characterAtIndex:range.location] == (unichar)'\n') {
|
||||
// CRLF sequence, skip the LF
|
||||
range.location += 1, range.length -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
len = cIdx;
|
||||
} else {
|
||||
[string getCharacters:characters range:NSMakeRange(0, len)];
|
||||
}
|
||||
|
||||
// Create storage for glyphs and advances
|
||||
CGGlyph *glyphs;
|
||||
CGFloat *advances;
|
||||
{
|
||||
NSUInteger maxRunLength = 0;
|
||||
ZAttributeRun *a = [attributes objectAtIndex:0];
|
||||
for (NSUInteger i = 1; i < [attributes count]; i++) {
|
||||
ZAttributeRun *b = [attributes objectAtIndex:i];
|
||||
maxRunLength = MAX(maxRunLength, b.index - a.index);
|
||||
a = b;
|
||||
}
|
||||
maxRunLength = MAX(maxRunLength, len - a.index);
|
||||
maxRunLength++; // for a potential ellipsis
|
||||
glyphs = (CGGlyph *)malloc(sizeof(CGGlyph) * maxRunLength);
|
||||
advances = (CGFloat *)malloc(sizeof(CGFloat) * maxRunLength);
|
||||
}
|
||||
|
||||
// Use this table to cache all fontTable objects
|
||||
CFMutableDictionaryRef fontTableMap = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks,
|
||||
&kFontTableDictionaryValueCallBacks);
|
||||
|
||||
// Fetch initial style values
|
||||
NSUInteger currentRunIdx = 0;
|
||||
ZAttributeRun *currentRun;
|
||||
NSUInteger nextRunStart;
|
||||
ZFont *currentFont;
|
||||
fontTable *currentTable;
|
||||
|
||||
#define READ_RUN() readRunInformation(attributes, len, fontTableMap, \
|
||||
currentRunIdx, ¤tRun, &nextRunStart, \
|
||||
¤tFont, ¤tTable)
|
||||
|
||||
READ_RUN();
|
||||
|
||||
// fetch the glyphs for the first run
|
||||
size_t glyphCount;
|
||||
NSUInteger glyphIdx;
|
||||
|
||||
#define READ_GLYPHS() do { \
|
||||
mapCharactersToGlyphsInFont(currentTable, &characters[currentRun.index], (nextRunStart - currentRun.index), glyphs, &glyphCount); \
|
||||
mapGlyphsToAdvancesInFont(currentFont, (nextRunStart - currentRun.index), glyphs, advances); \
|
||||
glyphIdx = 0; \
|
||||
} while (0)
|
||||
|
||||
READ_GLYPHS();
|
||||
|
||||
NSMutableCharacterSet *alphaCharset = [NSMutableCharacterSet alphanumericCharacterSet];
|
||||
[alphaCharset addCharactersInString:@"([{'\"\u2019\u02BC"];
|
||||
|
||||
// scan left-to-right looking for newlines or until we hit the width constraint
|
||||
// When we hit a wrapping point, calculate truncation as follows:
|
||||
// If we have room to draw at least one more character on the next line, no truncation
|
||||
// Otherwise apply the truncation algorithm to the current line.
|
||||
// After calculating any truncation, draw.
|
||||
// Each time we hit the end of an attribute run, calculate the new font and make sure
|
||||
// it fits (vertically) within the size constraint. If not, truncate this line.
|
||||
// When we draw, iterate over the attribute runs for this line and draw each run separately
|
||||
BOOL lastLine = NO; // used to indicate truncation and to stop the iterating
|
||||
NSUInteger lineCount = 1;
|
||||
while (idx < len && !lastLine) {
|
||||
if (maxLines > 0 && lineCount == maxLines) {
|
||||
lastLine = YES;
|
||||
}
|
||||
// scan left-to-right
|
||||
struct {
|
||||
NSUInteger index;
|
||||
NSUInteger glyphIndex;
|
||||
NSUInteger currentRunIdx;
|
||||
} indexCache = { idx, glyphIdx, currentRunIdx };
|
||||
CGSize lineSize = CGSizeMake(0, currentFont.leading);
|
||||
CGFloat lineAscender = currentFont.ascender;
|
||||
struct {
|
||||
NSUInteger index;
|
||||
NSUInteger glyphIndex;
|
||||
NSUInteger currentRunIdx;
|
||||
CGSize lineSize;
|
||||
} lastWrapCache = {0, 0, 0, CGSizeZero};
|
||||
BOOL inAlpha = NO; // used for calculating wrap points
|
||||
|
||||
BOOL finishLine = NO;
|
||||
for (;idx <= len && !finishLine;) {
|
||||
NSUInteger skipCount = 0;
|
||||
if (idx == len) {
|
||||
finishLine = YES;
|
||||
lastLine = YES;
|
||||
} else {
|
||||
if (idx >= nextRunStart) {
|
||||
// cycle the font and table and grab the next set of glyphs
|
||||
do {
|
||||
currentRunIdx++;
|
||||
READ_RUN();
|
||||
} while (idx >= nextRunStart);
|
||||
READ_GLYPHS();
|
||||
// re-scan the characters to synchronize the glyph index
|
||||
for (NSUInteger j = currentRun.index; j < idx; j++) {
|
||||
if (UnicharIsHighSurrogate(characters[j]) && j+1<len && UnicharIsLowSurrogate(characters[j+1])) {
|
||||
j++;
|
||||
}
|
||||
glyphIdx++;
|
||||
}
|
||||
if (currentFont.leading > lineSize.height) {
|
||||
lineSize.height = currentFont.leading;
|
||||
if (retValue.height + currentFont.ascender > constrainedSize.height) {
|
||||
lastLine = YES;
|
||||
finishLine = YES;
|
||||
}
|
||||
}
|
||||
lineAscender = MAX(lineAscender, currentFont.ascender);
|
||||
}
|
||||
unichar c = characters[idx];
|
||||
// Mark a wrap point before spaces and after any stretch of non-alpha characters
|
||||
BOOL markWrap = NO;
|
||||
if (c == (unichar)' ') {
|
||||
markWrap = YES;
|
||||
} else if ([alphaCharset characterIsMember:c]) {
|
||||
if (!inAlpha) {
|
||||
markWrap = YES;
|
||||
inAlpha = YES;
|
||||
}
|
||||
} else {
|
||||
inAlpha = NO;
|
||||
}
|
||||
if (markWrap) {
|
||||
lastWrapCache = (__typeof__(lastWrapCache)){
|
||||
.index = idx,
|
||||
.glyphIndex = glyphIdx,
|
||||
.currentRunIdx = currentRunIdx,
|
||||
.lineSize = lineSize
|
||||
};
|
||||
}
|
||||
// process the line
|
||||
if (c == (unichar)'\n' || c == 0x0085) { // U+0085 is the NEXT_LINE unicode character
|
||||
finishLine = YES;
|
||||
skipCount = 1;
|
||||
} else if (c == (unichar)'\r') {
|
||||
finishLine = YES;
|
||||
// check for CRLF
|
||||
if (idx+1 < len && characters[idx+1] == (unichar)'\n') {
|
||||
skipCount = 2;
|
||||
} else {
|
||||
skipCount = 1;
|
||||
}
|
||||
} else if (lineSize.width + advances[glyphIdx] > constrainedSize.width) {
|
||||
finishLine = YES;
|
||||
if (retValue.height + lineSize.height + currentFont.ascender > constrainedSize.height) {
|
||||
lastLine = YES;
|
||||
}
|
||||
// walk backwards if wrapping is necessary
|
||||
if (lastWrapCache.index > indexCache.index && lineBreakMode != UILineBreakModeCharacterWrap &&
|
||||
(!lastLine || lineBreakMode != UILineBreakModeClip)) {
|
||||
// we're doing some sort of word wrapping
|
||||
idx = lastWrapCache.index;
|
||||
lineSize = lastWrapCache.lineSize;
|
||||
if (!lastLine) {
|
||||
// re-check if this is the last line
|
||||
if (lastWrapCache.currentRunIdx != currentRunIdx) {
|
||||
currentRunIdx = lastWrapCache.currentRunIdx;
|
||||
READ_RUN();
|
||||
READ_GLYPHS();
|
||||
}
|
||||
if (retValue.height + lineSize.height + currentFont.ascender > constrainedSize.height) {
|
||||
lastLine = YES;
|
||||
}
|
||||
}
|
||||
glyphIdx = lastWrapCache.glyphIndex;
|
||||
// skip any spaces
|
||||
for (NSUInteger j = idx; j < len && characters[j] == (unichar)' '; j++) {
|
||||
skipCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (finishLine) {
|
||||
// TODO: support head/middle truncation
|
||||
if (lastLine && idx < len && lineBreakMode == UILineBreakModeTailTruncation) {
|
||||
// truncate
|
||||
unichar ellipsis = 0x2026; // ellipsis (…)
|
||||
CGGlyph ellipsisGlyph;
|
||||
mapCharactersToGlyphsInFont(currentTable, &ellipsis, 1, &ellipsisGlyph, NULL);
|
||||
CGFloat ellipsisWidth;
|
||||
mapGlyphsToAdvancesInFont(currentFont, 1, &ellipsisGlyph, &ellipsisWidth);
|
||||
while ((idx - indexCache.index) > 1 && lineSize.width + ellipsisWidth > constrainedSize.width) {
|
||||
// we have more than 1 character and we're too wide, so back up
|
||||
idx--;
|
||||
if (UnicharIsHighSurrogate(characters[idx]) && UnicharIsLowSurrogate(characters[idx+1])) {
|
||||
idx--;
|
||||
}
|
||||
if (idx < currentRun.index) {
|
||||
ZFont *oldFont = currentFont;
|
||||
do {
|
||||
currentRunIdx--;
|
||||
READ_RUN();
|
||||
} while (idx < currentRun.index);
|
||||
READ_GLYPHS();
|
||||
glyphIdx = glyphCount-1;
|
||||
if (oldFont != currentFont) {
|
||||
mapCharactersToGlyphsInFont(currentTable, &ellipsis, 1, &ellipsisGlyph, NULL);
|
||||
mapGlyphsToAdvancesInFont(currentFont, 1, &ellipsisGlyph, &ellipsisWidth);
|
||||
}
|
||||
} else {
|
||||
glyphIdx--;
|
||||
}
|
||||
lineSize.width -= advances[glyphIdx];
|
||||
}
|
||||
// skip any spaces before truncating
|
||||
while ((idx - indexCache.index) > 1 && characters[idx-1] == (unichar)' ') {
|
||||
idx--;
|
||||
if (idx < currentRun.index) {
|
||||
currentRunIdx--;
|
||||
READ_RUN();
|
||||
READ_GLYPHS();
|
||||
glyphIdx = glyphCount-1;
|
||||
} else {
|
||||
glyphIdx--;
|
||||
}
|
||||
lineSize.width -= advances[glyphIdx];
|
||||
}
|
||||
lineSize.width += ellipsisWidth;
|
||||
glyphs[glyphIdx] = ellipsisGlyph;
|
||||
idx++;
|
||||
glyphIdx++;
|
||||
}
|
||||
retValue.width = MAX(retValue.width, lineSize.width);
|
||||
retValue.height += lineSize.height;
|
||||
|
||||
// draw
|
||||
if (performDraw) {
|
||||
switch (alignment) {
|
||||
case UITextAlignmentLeft:
|
||||
drawPoint.x = 0;
|
||||
break;
|
||||
case UITextAlignmentCenter:
|
||||
drawPoint.x = (constrainedSize.width - lineSize.width) / 2.0f;
|
||||
break;
|
||||
case UITextAlignmentRight:
|
||||
drawPoint.x = constrainedSize.width - lineSize.width;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
NSUInteger stopGlyphIdx = glyphIdx;
|
||||
NSUInteger lastRunIdx = currentRunIdx;
|
||||
NSUInteger stopCharIdx = idx;
|
||||
idx = indexCache.index;
|
||||
if (currentRunIdx != indexCache.currentRunIdx) {
|
||||
currentRunIdx = indexCache.currentRunIdx;
|
||||
READ_RUN();
|
||||
READ_GLYPHS();
|
||||
}
|
||||
glyphIdx = indexCache.glyphIndex;
|
||||
for (NSUInteger drawIdx = currentRunIdx; drawIdx <= lastRunIdx; drawIdx++) {
|
||||
if (drawIdx != currentRunIdx) {
|
||||
currentRunIdx = drawIdx;
|
||||
READ_RUN();
|
||||
READ_GLYPHS();
|
||||
}
|
||||
NSUInteger numGlyphs;
|
||||
if (drawIdx == lastRunIdx) {
|
||||
numGlyphs = stopGlyphIdx - glyphIdx;
|
||||
idx = stopCharIdx;
|
||||
} else {
|
||||
numGlyphs = glyphCount - glyphIdx;
|
||||
idx = nextRunStart;
|
||||
}
|
||||
CGContextSetFont(ctx, currentFont.cgFont);
|
||||
CGContextSetFontSize(ctx, currentFont.pointSize);
|
||||
// calculate the fragment size
|
||||
CGFloat fragmentWidth = 0;
|
||||
for (NSUInteger g = 0; g < numGlyphs; g++) {
|
||||
fragmentWidth += advances[glyphIdx + g];
|
||||
}
|
||||
|
||||
if (!ignoreColor) {
|
||||
UIColor *foregroundColor = getValueOrDefaultForRun(currentRun, ZForegroundColorAttributeName);
|
||||
UIColor *backgroundColor = getValueOrDefaultForRun(currentRun, ZBackgroundColorAttributeName);
|
||||
if (backgroundColor != nil && ![backgroundColor isEqual:[UIColor clearColor]]) {
|
||||
[backgroundColor setFill];
|
||||
UIRectFillUsingBlendMode((CGRect){ drawPoint, { fragmentWidth, lineSize.height } }, kCGBlendModeNormal);
|
||||
}
|
||||
[foregroundColor setFill];
|
||||
}
|
||||
|
||||
CGContextShowGlyphsAtPoint(ctx, drawPoint.x, drawPoint.y + lineAscender, &glyphs[glyphIdx], numGlyphs);
|
||||
NSNumber *underlineStyle = getValueOrDefaultForRun(currentRun, ZUnderlineStyleAttributeName);
|
||||
if ([underlineStyle integerValue] & ZUnderlineStyleMask) {
|
||||
// we only support single for the time being
|
||||
UIRectFill(CGRectMake(drawPoint.x, drawPoint.y + lineAscender, fragmentWidth, 1));
|
||||
}
|
||||
drawPoint.x += fragmentWidth;
|
||||
glyphIdx += numGlyphs;
|
||||
}
|
||||
drawPoint.y += lineSize.height;
|
||||
}
|
||||
idx += skipCount;
|
||||
glyphIdx += skipCount;
|
||||
lineCount++;
|
||||
} else {
|
||||
lineSize.width += advances[glyphIdx];
|
||||
glyphIdx++;
|
||||
idx++;
|
||||
if (idx < len && UnicharIsHighSurrogate(characters[idx-1]) && UnicharIsLowSurrogate(characters[idx])) {
|
||||
// skip the second half of the surrogate pair
|
||||
idx++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
CFRelease(fontTableMap);
|
||||
free(glyphs);
|
||||
free(advances);
|
||||
free(characters);
|
||||
|
||||
#undef READ_GLYPHS
|
||||
#undef READ_RUN
|
||||
|
||||
return retValue;
|
||||
}
|
||||
|
||||
static NSArray *attributeRunForFont(ZFont *font) {
|
||||
return [NSArray arrayWithObject:[ZAttributeRun attributeRunWithIndex:0
|
||||
attributes:[NSDictionary dictionaryWithObject:font
|
||||
forKey:ZFontAttributeName]]];
|
||||
}
|
||||
|
||||
static CGSize drawTextInRect(CGRect rect, NSString *text, NSArray *attributes, UILineBreakMode lineBreakMode,
|
||||
UITextAlignment alignment, NSUInteger numberOfLines, BOOL ignoreColor) {
|
||||
CGContextRef ctx = UIGraphicsGetCurrentContext();
|
||||
|
||||
CGContextSaveGState(ctx);
|
||||
|
||||
// flip it upside-down because our 0,0 is upper-left, whereas ttfs are for screens where 0,0 is lower-left
|
||||
CGAffineTransform textTransform = CGAffineTransformMake(1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f);
|
||||
CGContextSetTextMatrix(ctx, textTransform);
|
||||
|
||||
CGContextTranslateCTM(ctx, rect.origin.x, rect.origin.y);
|
||||
|
||||
CGContextSetTextDrawingMode(ctx, kCGTextFill);
|
||||
CGSize size = drawOrSizeTextConstrainedToSize(YES, text, attributes, rect.size, numberOfLines, lineBreakMode, alignment, ignoreColor);
|
||||
|
||||
CGContextRestoreGState(ctx);
|
||||
|
||||
return size;
|
||||
}
|
||||
|
||||
@implementation NSString (FontLabelStringDrawing)
|
||||
// CGFontRef-based methods
|
||||
- (CGSize)sizeWithCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize {
|
||||
return [self sizeWithZFont:[ZFont fontWithCGFont:font size:pointSize]];
|
||||
}
|
||||
|
||||
- (CGSize)sizeWithCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize constrainedToSize:(CGSize)size {
|
||||
return [self sizeWithZFont:[ZFont fontWithCGFont:font size:pointSize] constrainedToSize:size];
|
||||
}
|
||||
|
||||
- (CGSize)sizeWithCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize constrainedToSize:(CGSize)size
|
||||
lineBreakMode:(UILineBreakMode)lineBreakMode {
|
||||
return [self sizeWithZFont:[ZFont fontWithCGFont:font size:pointSize] constrainedToSize:size lineBreakMode:lineBreakMode];
|
||||
}
|
||||
|
||||
- (CGSize)drawAtPoint:(CGPoint)point withCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize {
|
||||
return [self drawAtPoint:point withZFont:[ZFont fontWithCGFont:font size:pointSize]];
|
||||
}
|
||||
|
||||
- (CGSize)drawInRect:(CGRect)rect withCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize {
|
||||
return [self drawInRect:rect withZFont:[ZFont fontWithCGFont:font size:pointSize]];
|
||||
}
|
||||
|
||||
- (CGSize)drawInRect:(CGRect)rect withCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize lineBreakMode:(UILineBreakMode)lineBreakMode {
|
||||
return [self drawInRect:rect withZFont:[ZFont fontWithCGFont:font size:pointSize] lineBreakMode:lineBreakMode];
|
||||
}
|
||||
|
||||
- (CGSize)drawInRect:(CGRect)rect withCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize
|
||||
lineBreakMode:(UILineBreakMode)lineBreakMode alignment:(UITextAlignment)alignment {
|
||||
return [self drawInRect:rect withZFont:[ZFont fontWithCGFont:font size:pointSize] lineBreakMode:lineBreakMode alignment:alignment];
|
||||
}
|
||||
|
||||
// ZFont-based methods
|
||||
- (CGSize)sizeWithZFont:(ZFont *)font {
|
||||
CGSize size = drawOrSizeTextConstrainedToSize(NO, self, attributeRunForFont(font), CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX), 1,
|
||||
UILineBreakModeClip, UITextAlignmentLeft, YES);
|
||||
return CGSizeMake(ceilf(size.width), ceilf(size.height));
|
||||
}
|
||||
|
||||
- (CGSize)sizeWithZFont:(ZFont *)font constrainedToSize:(CGSize)size {
|
||||
return [self sizeWithZFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];
|
||||
}
|
||||
|
||||
/*
|
||||
According to experimentation with UIStringDrawing, this can actually return a CGSize whose height is greater
|
||||
than the one passed in. The two cases are as follows:
|
||||
1. If the given size parameter's height is smaller than a single line, the returned value will
|
||||
be the height of one line.
|
||||
2. If the given size parameter's height falls between multiples of a line height, and the wrapped string
|
||||
actually extends past the size.height, and the difference between size.height and the previous multiple
|
||||
of a line height is >= the font's ascender, then the returned size's height is extended to the next line.
|
||||
To put it simply, if the baseline point of a given line falls in the given size, the entire line will
|
||||
be present in the output size.
|
||||
*/
|
||||
- (CGSize)sizeWithZFont:(ZFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode {
|
||||
size = drawOrSizeTextConstrainedToSize(NO, self, attributeRunForFont(font), size, 0, lineBreakMode, UITextAlignmentLeft, YES);
|
||||
return CGSizeMake(ceilf(size.width), ceilf(size.height));
|
||||
}
|
||||
|
||||
- (CGSize)sizeWithZFont:(ZFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode
|
||||
numberOfLines:(NSUInteger)numberOfLines {
|
||||
size = drawOrSizeTextConstrainedToSize(NO, self, attributeRunForFont(font), size, numberOfLines, lineBreakMode, UITextAlignmentLeft, YES);
|
||||
return CGSizeMake(ceilf(size.width), ceilf(size.height));
|
||||
}
|
||||
|
||||
- (CGSize)drawAtPoint:(CGPoint)point withZFont:(ZFont *)font {
|
||||
return [self drawAtPoint:point forWidth:CGFLOAT_MAX withZFont:font lineBreakMode:UILineBreakModeClip];
|
||||
}
|
||||
|
||||
- (CGSize)drawAtPoint:(CGPoint)point forWidth:(CGFloat)width withZFont:(ZFont *)font lineBreakMode:(UILineBreakMode)lineBreakMode {
|
||||
return drawTextInRect((CGRect){ point, { width, CGFLOAT_MAX } }, self, attributeRunForFont(font), lineBreakMode, UITextAlignmentLeft, 1, YES);
|
||||
}
|
||||
|
||||
- (CGSize)drawInRect:(CGRect)rect withZFont:(ZFont *)font {
|
||||
return [self drawInRect:rect withZFont:font lineBreakMode:UILineBreakModeWordWrap];
|
||||
}
|
||||
|
||||
- (CGSize)drawInRect:(CGRect)rect withZFont:(ZFont *)font lineBreakMode:(UILineBreakMode)lineBreakMode {
|
||||
return [self drawInRect:rect withZFont:font lineBreakMode:lineBreakMode alignment:UITextAlignmentLeft];
|
||||
}
|
||||
|
||||
- (CGSize)drawInRect:(CGRect)rect withZFont:(ZFont *)font lineBreakMode:(UILineBreakMode)lineBreakMode
|
||||
alignment:(UITextAlignment)alignment {
|
||||
return drawTextInRect(rect, self, attributeRunForFont(font), lineBreakMode, alignment, 0, YES);
|
||||
}
|
||||
|
||||
- (CGSize)drawInRect:(CGRect)rect withZFont:(ZFont *)font lineBreakMode:(UILineBreakMode)lineBreakMode
|
||||
alignment:(UITextAlignment)alignment numberOfLines:(NSUInteger)numberOfLines {
|
||||
return drawTextInRect(rect, self, attributeRunForFont(font), lineBreakMode, alignment, numberOfLines, YES);
|
||||
}
|
||||
@end
|
||||
|
||||
@implementation ZAttributedString (ZAttributedStringDrawing)
|
||||
- (CGSize)size {
|
||||
CGSize size = drawOrSizeTextConstrainedToSize(NO, self.string, self.attributes, CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX), 1,
|
||||
UILineBreakModeClip, UITextAlignmentLeft, NO);
|
||||
return CGSizeMake(ceilf(size.width), ceilf(size.height));
|
||||
}
|
||||
|
||||
- (CGSize)sizeConstrainedToSize:(CGSize)size {
|
||||
return [self sizeConstrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];
|
||||
}
|
||||
|
||||
- (CGSize)sizeConstrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode {
|
||||
size = drawOrSizeTextConstrainedToSize(NO, self.string, self.attributes, size, 0, lineBreakMode, UITextAlignmentLeft, NO);
|
||||
return CGSizeMake(ceilf(size.width), ceilf(size.height));
|
||||
}
|
||||
|
||||
- (CGSize)sizeConstrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode
|
||||
numberOfLines:(NSUInteger)numberOfLines {
|
||||
size = drawOrSizeTextConstrainedToSize(NO, self.string, self.attributes, size, numberOfLines, lineBreakMode, UITextAlignmentLeft, NO);
|
||||
return CGSizeMake(ceilf(size.width), ceilf(size.height));
|
||||
}
|
||||
|
||||
- (CGSize)drawAtPoint:(CGPoint)point {
|
||||
return [self drawAtPoint:point forWidth:CGFLOAT_MAX lineBreakMode:UILineBreakModeClip];
|
||||
}
|
||||
|
||||
- (CGSize)drawAtPoint:(CGPoint)point forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode {
|
||||
return drawTextInRect((CGRect){ point, { width, CGFLOAT_MAX } }, self.string, self.attributes, lineBreakMode, UITextAlignmentLeft, 1, NO);
|
||||
}
|
||||
|
||||
- (CGSize)drawInRect:(CGRect)rect {
|
||||
return [self drawInRect:rect withLineBreakMode:UILineBreakModeWordWrap];
|
||||
}
|
||||
|
||||
- (CGSize)drawInRect:(CGRect)rect withLineBreakMode:(UILineBreakMode)lineBreakMode {
|
||||
return [self drawInRect:rect withLineBreakMode:lineBreakMode alignment:UITextAlignmentLeft];
|
||||
}
|
||||
|
||||
- (CGSize)drawInRect:(CGRect)rect withLineBreakMode:(UILineBreakMode)lineBreakMode alignment:(UITextAlignment)alignment {
|
||||
return drawTextInRect(rect, self.string, self.attributes, lineBreakMode, alignment, 0, NO);
|
||||
}
|
||||
|
||||
- (CGSize)drawInRect:(CGRect)rect withLineBreakMode:(UILineBreakMode)lineBreakMode alignment:(UITextAlignment)alignment
|
||||
numberOfLines:(NSUInteger)numberOfLines {
|
||||
return drawTextInRect(rect, self.string, self.attributes, lineBreakMode, alignment, numberOfLines, NO);
|
||||
}
|
||||
@end
|
||||
|
||||
@implementation FontLabelStringDrawingHelper
|
||||
+ (CGSize)sizeWithZFont:(NSString*)string zfont:(ZFont *)font {
|
||||
CGSize size = drawOrSizeTextConstrainedToSize(NO, string, attributeRunForFont(font), CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX), 1,
|
||||
UILineBreakModeClip, UITextAlignmentLeft, YES);
|
||||
return CGSizeMake(ceilf(size.width), ceilf(size.height));
|
||||
}
|
||||
|
||||
+ (CGSize)sizeWithZFont:(NSString *)string zfont:(ZFont *)font constrainedToSize:(CGSize)size {
|
||||
CGSize s = drawOrSizeTextConstrainedToSize(NO, string, attributeRunForFont(font), size, 0, UILineBreakModeWordWrap, UITextAlignmentLeft, YES);
|
||||
return CGSizeMake(ceilf(s.width), ceilf(s.height));
|
||||
}
|
||||
|
||||
|
||||
|
||||
+ (CGSize)drawInRect:(NSString*)string rect:(CGRect)rect withZFont:(ZFont *)font lineBreakMode:(UILineBreakMode)lineBreakMode
|
||||
alignment:(UITextAlignment)alignment {
|
||||
return [string drawInRect:rect withZFont:font lineBreakMode:lineBreakMode alignment:alignment];
|
||||
}
|
||||
@end
|
||||
|
|
@ -1,85 +0,0 @@
|
|||
//
|
||||
// FontManager.h
|
||||
// FontLabel
|
||||
//
|
||||
// Created by Kevin Ballard on 5/5/09.
|
||||
// Copyright © 2009 Zynga Game Networks
|
||||
//
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <CoreGraphics/CoreGraphics.h>
|
||||
|
||||
@class ZFont;
|
||||
|
||||
@interface FontManager : NSObject {
|
||||
CFMutableDictionaryRef fonts;
|
||||
NSMutableDictionary *urls;
|
||||
}
|
||||
+ (FontManager *)sharedManager;
|
||||
/*!
|
||||
@method
|
||||
@abstract Loads a TTF font from the main bundle
|
||||
@param filename The name of the font file to load (with or without extension).
|
||||
@return YES if the font was loaded, NO if an error occurred
|
||||
@discussion If the font has already been loaded, this method does nothing and returns YES.
|
||||
This method first attempts to load the font by appending .ttf to the filename.
|
||||
If that file does not exist, it tries the filename exactly as given.
|
||||
*/
|
||||
- (BOOL)loadFont:(NSString *)filename;
|
||||
/*!
|
||||
@method
|
||||
@abstract Loads a font from the given file URL
|
||||
@param url A file URL that points to a font file
|
||||
@return YES if the font was loaded, NO if an error occurred
|
||||
@discussion If the font has already been loaded, this method does nothing and returns YES.
|
||||
*/
|
||||
- (BOOL)loadFontURL:(NSURL *)url;
|
||||
/*!
|
||||
@method
|
||||
@abstract Returns the loaded font with the given filename
|
||||
@param filename The name of the font file that was given to -loadFont:
|
||||
@return A CGFontRef, or NULL if the specified font cannot be found
|
||||
@discussion If the font has not been loaded yet, -loadFont: will be
|
||||
called with the given name first.
|
||||
*/
|
||||
- (CGFontRef)fontWithName:(NSString *)filename __AVAILABILITY_INTERNAL_DEPRECATED;
|
||||
/*!
|
||||
@method
|
||||
@abstract Returns a ZFont object corresponding to the loaded font with the given filename and point size
|
||||
@param filename The name of the font file that was given to -loadFont:
|
||||
@param pointSize The point size of the font
|
||||
@return A ZFont, or NULL if the specified font cannot be found
|
||||
@discussion If the font has not been loaded yet, -loadFont: will be
|
||||
called with the given name first.
|
||||
*/
|
||||
- (ZFont *)zFontWithName:(NSString *)filename pointSize:(CGFloat)pointSize;
|
||||
/*!
|
||||
@method
|
||||
@abstract Returns a ZFont object corresponding to the loaded font with the given file URL and point size
|
||||
@param url A file URL that points to a font file
|
||||
@param pointSize The point size of the font
|
||||
@return A ZFont, or NULL if the specified font cannot be loaded
|
||||
@discussion If the font has not been loaded yet, -loadFontURL: will be called with the given URL first.
|
||||
*/
|
||||
- (ZFont *)zFontWithURL:(NSURL *)url pointSize:(CGFloat)pointSize;
|
||||
/*!
|
||||
@method
|
||||
@abstract Returns a CFArrayRef of all loaded CGFont objects
|
||||
@return A CFArrayRef of all loaded CGFont objects
|
||||
@description You are responsible for releasing the CFArrayRef
|
||||
*/
|
||||
- (CFArrayRef)copyAllFonts;
|
||||
@end
|
|
@ -1,123 +0,0 @@
|
|||
//
|
||||
// FontManager.m
|
||||
// FontLabel
|
||||
//
|
||||
// Created by Kevin Ballard on 5/5/09.
|
||||
// Copyright © 2009 Zynga Game Networks
|
||||
//
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
#import "FontManager.h"
|
||||
#import "ZFont.h"
|
||||
|
||||
static FontManager *sharedFontManager = nil;
|
||||
|
||||
@implementation FontManager
|
||||
+ (FontManager *)sharedManager {
|
||||
@synchronized(self) {
|
||||
if (sharedFontManager == nil) {
|
||||
sharedFontManager = [[self alloc] init];
|
||||
}
|
||||
}
|
||||
return sharedFontManager;
|
||||
}
|
||||
|
||||
- (id)init {
|
||||
if ((self = [super init])) {
|
||||
fonts = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
|
||||
urls = [[NSMutableDictionary alloc] init];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (BOOL)loadFont:(NSString *)filename {
|
||||
NSString *fontPath = [[NSBundle mainBundle] pathForResource:filename ofType:@"ttf"];
|
||||
if (fontPath == nil) {
|
||||
fontPath = [[NSBundle mainBundle] pathForResource:filename ofType:nil];
|
||||
}
|
||||
if (fontPath == nil) return NO;
|
||||
|
||||
NSURL *url = [NSURL fileURLWithPath:fontPath];
|
||||
if ([self loadFontURL:url]) {
|
||||
[urls setObject:url forKey:filename];
|
||||
return YES;
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
- (BOOL)loadFontURL:(NSURL *)url {
|
||||
CGDataProviderRef fontDataProvider = CGDataProviderCreateWithURL((CFURLRef)url);
|
||||
if (fontDataProvider == NULL) return NO;
|
||||
CGFontRef newFont = CGFontCreateWithDataProvider(fontDataProvider);
|
||||
CGDataProviderRelease(fontDataProvider);
|
||||
if (newFont == NULL) return NO;
|
||||
|
||||
CFDictionarySetValue(fonts, url, newFont);
|
||||
CGFontRelease(newFont);
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (CGFontRef)fontWithName:(NSString *)filename {
|
||||
CGFontRef font = NULL;
|
||||
NSURL *url = [urls objectForKey:filename];
|
||||
if (url == nil && [self loadFont:filename]) {
|
||||
url = [urls objectForKey:filename];
|
||||
}
|
||||
if (url != nil) {
|
||||
font = (CGFontRef)CFDictionaryGetValue(fonts, url);
|
||||
}
|
||||
return font;
|
||||
}
|
||||
|
||||
- (ZFont *)zFontWithName:(NSString *)filename pointSize:(CGFloat)pointSize {
|
||||
NSURL *url = [urls objectForKey:filename];
|
||||
if (url == nil && [self loadFont:filename]) {
|
||||
url = [urls objectForKey:filename];
|
||||
}
|
||||
if (url != nil) {
|
||||
CGFontRef cgFont = (CGFontRef)CFDictionaryGetValue(fonts, url);
|
||||
if (cgFont != NULL) {
|
||||
return [ZFont fontWithCGFont:cgFont size:pointSize];
|
||||
}
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
- (ZFont *)zFontWithURL:(NSURL *)url pointSize:(CGFloat)pointSize {
|
||||
CGFontRef cgFont = (CGFontRef)CFDictionaryGetValue(fonts, url);
|
||||
if (cgFont == NULL && [self loadFontURL:url]) {
|
||||
cgFont = (CGFontRef)CFDictionaryGetValue(fonts, url);
|
||||
}
|
||||
if (cgFont != NULL) {
|
||||
return [ZFont fontWithCGFont:cgFont size:pointSize];
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
- (CFArrayRef)copyAllFonts {
|
||||
CFIndex count = CFDictionaryGetCount(fonts);
|
||||
CGFontRef *values = (CGFontRef *)malloc(sizeof(CGFontRef) * count);
|
||||
CFDictionaryGetKeysAndValues(fonts, NULL, (const void **)values);
|
||||
CFArrayRef array = CFArrayCreate(NULL, (const void **)values, count, &kCFTypeArrayCallBacks);
|
||||
free(values);
|
||||
return array;
|
||||
}
|
||||
|
||||
- (void)dealloc {
|
||||
CFRelease(fonts);
|
||||
[urls release];
|
||||
[super dealloc];
|
||||
}
|
||||
@end
|
|
@ -1,77 +0,0 @@
|
|||
//
|
||||
// ZAttributedString.h
|
||||
// FontLabel
|
||||
//
|
||||
// Created by Kevin Ballard on 9/22/09.
|
||||
// Copyright 2009 Zynga Game Networks. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#if NS_BLOCKS_AVAILABLE
|
||||
#define Z_BLOCKS 1
|
||||
#else
|
||||
// set this to 1 if you are using PLBlocks
|
||||
#define Z_BLOCKS 0
|
||||
#endif
|
||||
|
||||
#if Z_BLOCKS
|
||||
enum {
|
||||
ZAttributedStringEnumerationReverse = (1UL << 1),
|
||||
ZAttributedStringEnumerationLongestEffectiveRangeNotRequired = (1UL << 20)
|
||||
};
|
||||
typedef NSUInteger ZAttributedStringEnumerationOptions;
|
||||
#endif
|
||||
|
||||
@interface ZAttributedString : NSObject <NSCoding, NSCopying, NSMutableCopying> {
|
||||
NSMutableString *_buffer;
|
||||
NSMutableArray *_attributes;
|
||||
}
|
||||
@property (nonatomic, readonly) NSUInteger length;
|
||||
@property (nonatomic, readonly) NSString *string;
|
||||
- (id)initWithAttributedString:(ZAttributedString *)attr;
|
||||
- (id)initWithString:(NSString *)str;
|
||||
- (id)initWithString:(NSString *)str attributes:(NSDictionary *)attributes;
|
||||
- (id)attribute:(NSString *)attributeName atIndex:(NSUInteger)index effectiveRange:(NSRangePointer)aRange;
|
||||
- (id)attribute:(NSString *)attributeName atIndex:(NSUInteger)index longestEffectiveRange:(NSRangePointer)aRange inRange:(NSRange)rangeLimit;
|
||||
- (ZAttributedString *)attributedSubstringFromRange:(NSRange)aRange;
|
||||
- (NSDictionary *)attributesAtIndex:(NSUInteger)index effectiveRange:(NSRangePointer)aRange;
|
||||
- (NSDictionary *)attributesAtIndex:(NSUInteger)index longestEffectiveRange:(NSRangePointer)aRange inRange:(NSRange)rangeLimit;
|
||||
#if Z_BLOCKS
|
||||
- (void)enumerateAttribute:(NSString *)attrName inRange:(NSRange)enumerationRange options:(ZAttributedStringEnumerationOptions)opts
|
||||
usingBlock:(void (^)(id value, NSRange range, BOOL *stop))block;
|
||||
- (void)enumerateAttributesInRange:(NSRange)enumerationRange options:(ZAttributedStringEnumerationOptions)opts
|
||||
usingBlock:(void (^)(NSDictionary *attrs, NSRange range, BOOL *stop))block;
|
||||
#endif
|
||||
- (BOOL)isEqualToAttributedString:(ZAttributedString *)otherString;
|
||||
@end
|
||||
|
||||
@interface ZMutableAttributedString : ZAttributedString {
|
||||
}
|
||||
- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;
|
||||
- (void)addAttributes:(NSDictionary *)attributes range:(NSRange)range;
|
||||
- (void)appendAttributedString:(ZAttributedString *)str;
|
||||
- (void)deleteCharactersInRange:(NSRange)range;
|
||||
- (void)insertAttributedString:(ZAttributedString *)str atIndex:(NSUInteger)idx;
|
||||
- (void)removeAttribute:(NSString *)name range:(NSRange)range;
|
||||
- (void)replaceCharactersInRange:(NSRange)range withAttributedString:(ZAttributedString *)str;
|
||||
- (void)replaceCharactersInRange:(NSRange)range withString:(NSString *)str;
|
||||
- (void)setAttributedString:(ZAttributedString *)str;
|
||||
- (void)setAttributes:(NSDictionary *)attributes range:(NSRange)range;
|
||||
@end
|
||||
|
||||
extern NSString * const ZFontAttributeName;
|
||||
extern NSString * const ZForegroundColorAttributeName;
|
||||
extern NSString * const ZBackgroundColorAttributeName;
|
||||
extern NSString * const ZUnderlineStyleAttributeName;
|
||||
|
||||
enum {
|
||||
ZUnderlineStyleNone = 0x00,
|
||||
ZUnderlineStyleSingle = 0x01
|
||||
};
|
||||
#define ZUnderlineStyleMask 0x00FF
|
||||
|
||||
enum {
|
||||
ZUnderlinePatternSolid = 0x0000
|
||||
};
|
||||
#define ZUnderlinePatternMask 0xFF00
|
|
@ -1,597 +0,0 @@
|
|||
//
|
||||
// ZAttributedString.m
|
||||
// FontLabel
|
||||
//
|
||||
// Created by Kevin Ballard on 9/22/09.
|
||||
// Copyright 2009 Zynga Game Networks. All rights reserved.
|
||||
//
|
||||
|
||||
#import "ZAttributedString.h"
|
||||
#import "ZAttributedStringPrivate.h"
|
||||
|
||||
@interface ZAttributedString ()
|
||||
- (NSUInteger)indexOfEffectiveAttributeRunForIndex:(NSUInteger)index;
|
||||
- (NSDictionary *)attributesAtIndex:(NSUInteger)index effectiveRange:(NSRangePointer)aRange uniquingOnName:(NSString *)attributeName;
|
||||
- (NSDictionary *)attributesAtIndex:(NSUInteger)index longestEffectiveRange:(NSRangePointer)aRange
|
||||
inRange:(NSRange)rangeLimit uniquingOnName:(NSString *)attributeName;
|
||||
@end
|
||||
|
||||
@interface ZAttributedString ()
|
||||
@property (nonatomic, readonly) NSArray *attributes;
|
||||
@end
|
||||
|
||||
@implementation ZAttributedString
|
||||
@synthesize string = _buffer;
|
||||
@synthesize attributes = _attributes;
|
||||
|
||||
- (id)initWithAttributedString:(ZAttributedString *)attr {
|
||||
NSParameterAssert(attr != nil);
|
||||
if ((self = [super init])) {
|
||||
_buffer = [attr->_buffer mutableCopy];
|
||||
_attributes = [[NSMutableArray alloc] initWithArray:attr->_attributes copyItems:YES];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (id)initWithString:(NSString *)str {
|
||||
return [self initWithString:str attributes:nil];
|
||||
}
|
||||
|
||||
- (id)initWithString:(NSString *)str attributes:(NSDictionary *)attributes {
|
||||
if ((self = [super init])) {
|
||||
_buffer = [str mutableCopy];
|
||||
_attributes = [[NSMutableArray alloc] initWithObjects:[ZAttributeRun attributeRunWithIndex:0 attributes:attributes], nil];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (id)init {
|
||||
return [self initWithString:@"" attributes:nil];
|
||||
}
|
||||
|
||||
- (id)initWithCoder:(NSCoder *)decoder {
|
||||
if ((self = [super init])) {
|
||||
_buffer = [[decoder decodeObjectForKey:@"buffer"] mutableCopy];
|
||||
_attributes = [[decoder decodeObjectForKey:@"attributes"] mutableCopy];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(NSCoder *)aCoder {
|
||||
[aCoder encodeObject:_buffer forKey:@"buffer"];
|
||||
[aCoder encodeObject:_attributes forKey:@"attributes"];
|
||||
}
|
||||
|
||||
- (id)copyWithZone:(NSZone *)zone {
|
||||
return [self retain];
|
||||
}
|
||||
|
||||
- (id)mutableCopyWithZone:(NSZone *)zone {
|
||||
return [(ZMutableAttributedString *)[ZMutableAttributedString allocWithZone:zone] initWithAttributedString:self];
|
||||
}
|
||||
|
||||
- (NSUInteger)length {
|
||||
return [_buffer length];
|
||||
}
|
||||
|
||||
- (NSString *)description {
|
||||
NSMutableArray *components = [NSMutableArray arrayWithCapacity:[_attributes count]*2];
|
||||
NSRange range = NSMakeRange(0, 0);
|
||||
for (NSUInteger i = 0; i <= [_attributes count]; i++) {
|
||||
range.location = NSMaxRange(range);
|
||||
ZAttributeRun *run;
|
||||
if (i < [_attributes count]) {
|
||||
run = [_attributes objectAtIndex:i];
|
||||
range.length = run.index - range.location;
|
||||
} else {
|
||||
run = nil;
|
||||
range.length = [_buffer length] - range.location;
|
||||
}
|
||||
if (range.length > 0) {
|
||||
[components addObject:[NSString stringWithFormat:@"\"%@\"", [_buffer substringWithRange:range]]];
|
||||
}
|
||||
if (run != nil) {
|
||||
NSMutableArray *attrDesc = [NSMutableArray arrayWithCapacity:[run.attributes count]];
|
||||
for (id key in run.attributes) {
|
||||
[attrDesc addObject:[NSString stringWithFormat:@"%@: %@", key, [run.attributes objectForKey:key]]];
|
||||
}
|
||||
[components addObject:[NSString stringWithFormat:@"{%@}", [attrDesc componentsJoinedByString:@", "]]];
|
||||
}
|
||||
}
|
||||
return [NSString stringWithFormat:@"%@", [components componentsJoinedByString:@" "]];
|
||||
}
|
||||
|
||||
- (id)attribute:(NSString *)attributeName atIndex:(NSUInteger)index effectiveRange:(NSRangePointer)aRange {
|
||||
NSParameterAssert(attributeName != nil);
|
||||
return [[self attributesAtIndex:index effectiveRange:aRange uniquingOnName:attributeName] objectForKey:attributeName];
|
||||
}
|
||||
|
||||
- (id)attribute:(NSString *)attributeName atIndex:(NSUInteger)index longestEffectiveRange:(NSRangePointer)aRange inRange:(NSRange)rangeLimit {
|
||||
NSParameterAssert(attributeName != nil);
|
||||
return [[self attributesAtIndex:index longestEffectiveRange:aRange inRange:rangeLimit uniquingOnName:attributeName] objectForKey:attributeName];
|
||||
}
|
||||
|
||||
- (ZAttributedString *)attributedSubstringFromRange:(NSRange)aRange {
|
||||
if (NSMaxRange(aRange) > [_buffer length]) {
|
||||
@throw [NSException exceptionWithName:NSRangeException reason:@"range was outside of the attributed string" userInfo:nil];
|
||||
}
|
||||
ZMutableAttributedString *newStr = [self mutableCopy];
|
||||
if (aRange.location > 0) {
|
||||
[newStr deleteCharactersInRange:NSMakeRange(0, aRange.location)];
|
||||
}
|
||||
if (NSMaxRange(aRange) < [_buffer length]) {
|
||||
[newStr deleteCharactersInRange:NSMakeRange(aRange.length, [_buffer length] - NSMaxRange(aRange))];
|
||||
}
|
||||
return [newStr autorelease];
|
||||
}
|
||||
|
||||
- (NSDictionary *)attributesAtIndex:(NSUInteger)index effectiveRange:(NSRangePointer)aRange {
|
||||
return [NSDictionary dictionaryWithDictionary:[self attributesAtIndex:index effectiveRange:aRange uniquingOnName:nil]];
|
||||
}
|
||||
|
||||
- (NSDictionary *)attributesAtIndex:(NSUInteger)index longestEffectiveRange:(NSRangePointer)aRange inRange:(NSRange)rangeLimit {
|
||||
return [NSDictionary dictionaryWithDictionary:[self attributesAtIndex:index longestEffectiveRange:aRange inRange:rangeLimit uniquingOnName:nil]];
|
||||
}
|
||||
|
||||
#if Z_BLOCKS
|
||||
// Warning: this code has not been tested. The only guarantee is that it compiles.
|
||||
- (void)enumerateAttribute:(NSString *)attrName inRange:(NSRange)enumerationRange options:(ZAttributedStringEnumerationOptions)opts
|
||||
usingBlock:(void (^)(id, NSRange, BOOL*))block {
|
||||
if (opts & ZAttributedStringEnumerationLongestEffectiveRangeNotRequired) {
|
||||
[self enumerateAttributesInRange:enumerationRange options:opts usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
|
||||
id value = [attrs objectForKey:attrName];
|
||||
if (value != nil) {
|
||||
block(value, range, stop);
|
||||
}
|
||||
}];
|
||||
} else {
|
||||
__block id oldValue = nil;
|
||||
__block NSRange effectiveRange = NSMakeRange(0, 0);
|
||||
[self enumerateAttributesInRange:enumerationRange options:opts usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
|
||||
id value = [attrs objectForKey:attrName];
|
||||
if (oldValue == nil) {
|
||||
oldValue = value;
|
||||
effectiveRange = range;
|
||||
} else if (value != nil && [oldValue isEqual:value]) {
|
||||
// combine the attributes
|
||||
effectiveRange = NSUnionRange(effectiveRange, range);
|
||||
} else {
|
||||
BOOL innerStop = NO;
|
||||
block(oldValue, effectiveRange, &innerStop);
|
||||
if (innerStop) {
|
||||
*stop = YES;
|
||||
oldValue = nil;
|
||||
} else {
|
||||
oldValue = value;
|
||||
}
|
||||
}
|
||||
}];
|
||||
if (oldValue != nil) {
|
||||
BOOL innerStop = NO; // necessary for the block, but unused
|
||||
block(oldValue, effectiveRange, &innerStop);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (void)enumerateAttributesInRange:(NSRange)enumerationRange options:(ZAttributedStringEnumerationOptions)opts
|
||||
usingBlock:(void (^)(NSDictionary*, NSRange, BOOL*))block {
|
||||
// copy the attributes so we can mutate the string if necessary during enumeration
|
||||
// also clip the array during copy to only the subarray of attributes that cover the requested range
|
||||
NSArray *attrs;
|
||||
if (NSEqualRanges(enumerationRange, NSMakeRange(0, 0))) {
|
||||
attrs = [NSArray arrayWithArray:_attributes];
|
||||
} else {
|
||||
// in this binary search, last is the first run after the range
|
||||
NSUInteger first = 0, last = [_attributes count];
|
||||
while (last > first+1) {
|
||||
NSUInteger pivot = (last + first) / 2;
|
||||
ZAttributeRun *run = [_attributes objectAtIndex:pivot];
|
||||
if (run.index < enumerationRange.location) {
|
||||
first = pivot;
|
||||
} else if (run.index >= NSMaxRange(enumerationRange)) {
|
||||
last = pivot;
|
||||
}
|
||||
}
|
||||
attrs = [_attributes subarrayWithRange:NSMakeRange(first, last-first)];
|
||||
}
|
||||
if (opts & ZAttributedStringEnumerationReverse) {
|
||||
NSUInteger end = [_buffer length];
|
||||
for (ZAttributeRun *run in [attrs reverseObjectEnumerator]) {
|
||||
BOOL stop = NO;
|
||||
NSUInteger start = run.index;
|
||||
// clip to enumerationRange
|
||||
start = MAX(start, enumerationRange.location);
|
||||
end = MIN(end, NSMaxRange(enumerationRange));
|
||||
block(run.attributes, NSMakeRange(start, end - start), &stop);
|
||||
if (stop) break;
|
||||
end = run.index;
|
||||
}
|
||||
} else {
|
||||
NSUInteger start = 0;
|
||||
ZAttributeRun *run = [attrs objectAtIndex:0];
|
||||
NSInteger offset = 0;
|
||||
NSInteger oldLength = [_buffer length];
|
||||
for (NSUInteger i = 1;;i++) {
|
||||
NSUInteger end;
|
||||
if (i >= [attrs count]) {
|
||||
end = oldLength;
|
||||
} else {
|
||||
end = [[attrs objectAtIndex:i] index];
|
||||
}
|
||||
BOOL stop = NO;
|
||||
NSUInteger clippedStart = MAX(start, enumerationRange.location);
|
||||
NSUInteger clippedEnd = MIN(end, NSMaxRange(enumerationRange));
|
||||
block(run.attributes, NSMakeRange(clippedStart + offset, clippedEnd - start), &stop);
|
||||
if (stop || i >= [attrs count]) break;
|
||||
start = end;
|
||||
NSUInteger newLength = [_buffer length];
|
||||
offset += (newLength - oldLength);
|
||||
oldLength = newLength;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
- (BOOL)isEqualToAttributedString:(ZAttributedString *)otherString {
|
||||
return ([_buffer isEqualToString:otherString->_buffer] && [_attributes isEqualToArray:otherString->_attributes]);
|
||||
}
|
||||
|
||||
- (BOOL)isEqual:(id)object {
|
||||
return [object isKindOfClass:[ZAttributedString class]] && [self isEqualToAttributedString:(ZAttributedString *)object];
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (NSUInteger)indexOfEffectiveAttributeRunForIndex:(NSUInteger)index {
|
||||
NSUInteger first = 0, last = [_attributes count];
|
||||
while (last > first + 1) {
|
||||
NSUInteger pivot = (last + first) / 2;
|
||||
ZAttributeRun *run = [_attributes objectAtIndex:pivot];
|
||||
if (run.index > index) {
|
||||
last = pivot;
|
||||
} else if (run.index < index) {
|
||||
first = pivot;
|
||||
} else {
|
||||
first = pivot;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return first;
|
||||
}
|
||||
|
||||
- (NSDictionary *)attributesAtIndex:(NSUInteger)index effectiveRange:(NSRangePointer)aRange uniquingOnName:(NSString *)attributeName {
|
||||
if (index >= [_buffer length]) {
|
||||
@throw [NSException exceptionWithName:NSRangeException reason:@"index beyond range of attributed string" userInfo:nil];
|
||||
}
|
||||
NSUInteger runIndex = [self indexOfEffectiveAttributeRunForIndex:index];
|
||||
ZAttributeRun *run = [_attributes objectAtIndex:runIndex];
|
||||
if (aRange != NULL) {
|
||||
aRange->location = run.index;
|
||||
runIndex++;
|
||||
if (runIndex < [_attributes count]) {
|
||||
aRange->length = [[_attributes objectAtIndex:runIndex] index] - aRange->location;
|
||||
} else {
|
||||
aRange->length = [_buffer length] - aRange->location;
|
||||
}
|
||||
}
|
||||
return run.attributes;
|
||||
}
|
||||
- (NSDictionary *)attributesAtIndex:(NSUInteger)index longestEffectiveRange:(NSRangePointer)aRange
|
||||
inRange:(NSRange)rangeLimit uniquingOnName:(NSString *)attributeName {
|
||||
if (index >= [_buffer length]) {
|
||||
@throw [NSException exceptionWithName:NSRangeException reason:@"index beyond range of attributed string" userInfo:nil];
|
||||
} else if (NSMaxRange(rangeLimit) > [_buffer length]) {
|
||||
@throw [NSException exceptionWithName:NSRangeException reason:@"rangeLimit beyond range of attributed string" userInfo:nil];
|
||||
}
|
||||
NSUInteger runIndex = [self indexOfEffectiveAttributeRunForIndex:index];
|
||||
ZAttributeRun *run = [_attributes objectAtIndex:runIndex];
|
||||
if (aRange != NULL) {
|
||||
if (attributeName != nil) {
|
||||
id value = [run.attributes objectForKey:attributeName];
|
||||
NSUInteger endRunIndex = runIndex+1;
|
||||
runIndex--;
|
||||
// search backwards
|
||||
while (1) {
|
||||
if (run.index <= rangeLimit.location) {
|
||||
break;
|
||||
}
|
||||
ZAttributeRun *prevRun = [_attributes objectAtIndex:runIndex];
|
||||
id prevValue = [prevRun.attributes objectForKey:attributeName];
|
||||
if (prevValue == value || (value != nil && [prevValue isEqual:value])) {
|
||||
runIndex--;
|
||||
run = prevRun;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// search forwards
|
||||
ZAttributeRun *endRun = nil;
|
||||
while (endRunIndex < [_attributes count]) {
|
||||
ZAttributeRun *nextRun = [_attributes objectAtIndex:endRunIndex];
|
||||
if (nextRun.index >= NSMaxRange(rangeLimit)) {
|
||||
endRun = nextRun;
|
||||
break;
|
||||
}
|
||||
id nextValue = [nextRun.attributes objectForKey:attributeName];
|
||||
if (nextValue == value || (value != nil && [nextValue isEqual:value])) {
|
||||
endRunIndex++;
|
||||
} else {
|
||||
endRun = nextRun;
|
||||
break;
|
||||
}
|
||||
}
|
||||
aRange->location = MAX(run.index, rangeLimit.location);
|
||||
aRange->length = MIN((endRun ? endRun.index : [_buffer length]), NSMaxRange(rangeLimit)) - aRange->location;
|
||||
} else {
|
||||
// with no attribute name, we don't need to do any real searching,
|
||||
// as we already guarantee each run has unique attributes.
|
||||
// just make sure to clip the range to the rangeLimit
|
||||
aRange->location = MAX(run.index, rangeLimit.location);
|
||||
ZAttributeRun *endRun = (runIndex+1 < [_attributes count] ? [_attributes objectAtIndex:runIndex+1] : nil);
|
||||
aRange->length = MIN((endRun ? endRun.index : [_buffer length]), NSMaxRange(rangeLimit)) - aRange->location;
|
||||
}
|
||||
}
|
||||
return run.attributes;
|
||||
}
|
||||
|
||||
- (void)dealloc {
|
||||
[_buffer release];
|
||||
[_attributes release];
|
||||
[super dealloc];
|
||||
}
|
||||
@end
|
||||
|
||||
@interface ZMutableAttributedString ()
|
||||
- (void)cleanupAttributesInRange:(NSRange)range;
|
||||
- (NSRange)rangeOfAttributeRunsForRange:(NSRange)range;
|
||||
- (void)offsetRunsInRange:(NSRange )range byOffset:(NSInteger)offset;
|
||||
@end
|
||||
|
||||
@implementation ZMutableAttributedString
|
||||
- (id)copyWithZone:(NSZone *)zone {
|
||||
return [(ZAttributedString *)[ZAttributedString allocWithZone:zone] initWithAttributedString:self];
|
||||
}
|
||||
|
||||
- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range {
|
||||
range = [self rangeOfAttributeRunsForRange:range];
|
||||
for (ZAttributeRun *run in [_attributes subarrayWithRange:range]) {
|
||||
[run.attributes setObject:value forKey:name];
|
||||
}
|
||||
[self cleanupAttributesInRange:range];
|
||||
}
|
||||
|
||||
- (void)addAttributes:(NSDictionary *)attributes range:(NSRange)range {
|
||||
range = [self rangeOfAttributeRunsForRange:range];
|
||||
for (ZAttributeRun *run in [_attributes subarrayWithRange:range]) {
|
||||
[run.attributes addEntriesFromDictionary:attributes];
|
||||
}
|
||||
[self cleanupAttributesInRange:range];
|
||||
}
|
||||
|
||||
- (void)appendAttributedString:(ZAttributedString *)str {
|
||||
[self insertAttributedString:str atIndex:[_buffer length]];
|
||||
}
|
||||
|
||||
- (void)deleteCharactersInRange:(NSRange)range {
|
||||
NSRange runRange = [self rangeOfAttributeRunsForRange:range];
|
||||
[_buffer replaceCharactersInRange:range withString:@""];
|
||||
[_attributes removeObjectsInRange:runRange];
|
||||
for (NSUInteger i = runRange.location; i < [_attributes count]; i++) {
|
||||
ZAttributeRun *run = [_attributes objectAtIndex:i];
|
||||
ZAttributeRun *newRun = [[ZAttributeRun alloc] initWithIndex:(run.index - range.length) attributes:run.attributes];
|
||||
[_attributes replaceObjectAtIndex:i withObject:newRun];
|
||||
[newRun release];
|
||||
}
|
||||
[self cleanupAttributesInRange:NSMakeRange(runRange.location, 0)];
|
||||
}
|
||||
|
||||
- (void)insertAttributedString:(ZAttributedString *)str atIndex:(NSUInteger)idx {
|
||||
[self replaceCharactersInRange:NSMakeRange(idx, 0) withAttributedString:str];
|
||||
}
|
||||
|
||||
- (void)removeAttribute:(NSString *)name range:(NSRange)range {
|
||||
range = [self rangeOfAttributeRunsForRange:range];
|
||||
for (ZAttributeRun *run in [_attributes subarrayWithRange:range]) {
|
||||
[run.attributes removeObjectForKey:name];
|
||||
}
|
||||
[self cleanupAttributesInRange:range];
|
||||
}
|
||||
|
||||
- (void)replaceCharactersInRange:(NSRange)range withAttributedString:(ZAttributedString *)str {
|
||||
NSRange replaceRange = [self rangeOfAttributeRunsForRange:range];
|
||||
NSInteger offset = [str->_buffer length] - range.length;
|
||||
[_buffer replaceCharactersInRange:range withString:str->_buffer];
|
||||
[_attributes replaceObjectsInRange:replaceRange withObjectsFromArray:str->_attributes];
|
||||
NSRange newRange = NSMakeRange(replaceRange.location, [str->_attributes count]);
|
||||
[self offsetRunsInRange:newRange byOffset:range.location];
|
||||
[self offsetRunsInRange:NSMakeRange(NSMaxRange(newRange), [_attributes count] - NSMaxRange(newRange)) byOffset:offset];
|
||||
[self cleanupAttributesInRange:NSMakeRange(newRange.location, 0)];
|
||||
[self cleanupAttributesInRange:NSMakeRange(NSMaxRange(newRange), 0)];
|
||||
}
|
||||
|
||||
- (void)replaceCharactersInRange:(NSRange)range withString:(NSString *)str {
|
||||
[self replaceCharactersInRange:range withAttributedString:[[[ZAttributedString alloc] initWithString:str] autorelease]];
|
||||
}
|
||||
|
||||
- (void)setAttributedString:(ZAttributedString *)str {
|
||||
[_buffer release], _buffer = [str->_buffer mutableCopy];
|
||||
[_attributes release], _attributes = [str->_attributes mutableCopy];
|
||||
}
|
||||
|
||||
- (void)setAttributes:(NSDictionary *)attributes range:(NSRange)range {
|
||||
range = [self rangeOfAttributeRunsForRange:range];
|
||||
for (ZAttributeRun *run in [_attributes subarrayWithRange:range]) {
|
||||
[run.attributes setDictionary:attributes];
|
||||
}
|
||||
[self cleanupAttributesInRange:range];
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
// splits the existing runs to provide one or more new runs for the given range
|
||||
- (NSRange)rangeOfAttributeRunsForRange:(NSRange)range {
|
||||
NSParameterAssert(NSMaxRange(range) <= [_buffer length]);
|
||||
|
||||
// find (or create) the first run
|
||||
NSUInteger first = 0;
|
||||
ZAttributeRun *lastRun = nil;
|
||||
for (;;first++) {
|
||||
if (first >= [_attributes count]) {
|
||||
// we didn't find a run
|
||||
first = [_attributes count];
|
||||
ZAttributeRun *newRun = [[ZAttributeRun alloc] initWithIndex:range.location attributes:lastRun.attributes];
|
||||
[_attributes addObject:newRun];
|
||||
[newRun release];
|
||||
break;
|
||||
}
|
||||
ZAttributeRun *run = [_attributes objectAtIndex:first];
|
||||
if (run.index == range.location) {
|
||||
break;
|
||||
} else if (run.index > range.location) {
|
||||
ZAttributeRun *newRun = [[ZAttributeRun alloc] initWithIndex:range.location attributes:lastRun.attributes];
|
||||
[_attributes insertObject:newRun atIndex:first];
|
||||
[newRun release];
|
||||
break;
|
||||
}
|
||||
lastRun = run;
|
||||
}
|
||||
|
||||
if (((ZAttributeRun *)[_attributes lastObject]).index < NSMaxRange(range)) {
|
||||
NSRange subrange = NSMakeRange(first, [_attributes count] - first);
|
||||
if (NSMaxRange(range) < [_buffer length]) {
|
||||
ZAttributeRun *newRun = [[ZAttributeRun alloc] initWithIndex:NSMaxRange(range)
|
||||
attributes:(NSDictionary*)[(ZAttributeRun *)[_attributes lastObject] attributes]];
|
||||
[_attributes addObject:newRun];
|
||||
[newRun release];
|
||||
}
|
||||
return subrange;
|
||||
} else {
|
||||
// find the last run within and the first run after the range
|
||||
NSUInteger lastIn = first, firstAfter = [_attributes count]-1;
|
||||
while (firstAfter > lastIn + 1) {
|
||||
NSUInteger idx = (firstAfter + lastIn) / 2;
|
||||
ZAttributeRun *run = [_attributes objectAtIndex:idx];
|
||||
if (run.index < range.location) {
|
||||
lastIn = idx;
|
||||
} else if (run.index > range.location) {
|
||||
firstAfter = idx;
|
||||
} else {
|
||||
// this is definitively the first run after the range
|
||||
firstAfter = idx;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ([[_attributes objectAtIndex:firstAfter] index] > NSMaxRange(range)) {
|
||||
// the first after is too far after, insert another run!
|
||||
ZAttributeRun *newRun = [[ZAttributeRun alloc] initWithIndex:NSMaxRange(range)
|
||||
attributes:[(ZAttributeRun *)[_attributes objectAtIndex:firstAfter-1] attributes]];
|
||||
[_attributes insertObject:newRun atIndex:firstAfter];
|
||||
[newRun release];
|
||||
}
|
||||
return NSMakeRange(lastIn, firstAfter - lastIn);
|
||||
}
|
||||
}
|
||||
|
||||
- (void)cleanupAttributesInRange:(NSRange)range {
|
||||
// expand the range to include one surrounding attribute on each side
|
||||
if (range.location > 0) {
|
||||
range.location -= 1;
|
||||
range.length += 1;
|
||||
}
|
||||
if (NSMaxRange(range) < [_attributes count]) {
|
||||
range.length += 1;
|
||||
} else {
|
||||
// make sure the range is capped to the attributes count
|
||||
range.length = [_attributes count] - range.location;
|
||||
}
|
||||
if (range.length == 0) return;
|
||||
ZAttributeRun *lastRun = [_attributes objectAtIndex:range.location];
|
||||
for (NSUInteger i = range.location+1; i < NSMaxRange(range);) {
|
||||
ZAttributeRun *run = [_attributes objectAtIndex:i];
|
||||
if ([lastRun.attributes isEqualToDictionary:run.attributes]) {
|
||||
[_attributes removeObjectAtIndex:i];
|
||||
range.length -= 1;
|
||||
} else {
|
||||
lastRun = run;
|
||||
i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (void)offsetRunsInRange:(NSRange)range byOffset:(NSInteger)offset {
|
||||
for (NSUInteger i = range.location; i < NSMaxRange(range); i++) {
|
||||
ZAttributeRun *run = [_attributes objectAtIndex:i];
|
||||
ZAttributeRun *newRun = [[ZAttributeRun alloc] initWithIndex:run.index + offset attributes:run.attributes];
|
||||
[_attributes replaceObjectAtIndex:i withObject:newRun];
|
||||
[newRun release];
|
||||
}
|
||||
}
|
||||
@end
|
||||
|
||||
@implementation ZAttributeRun
|
||||
@synthesize index = _index;
|
||||
@synthesize attributes = _attributes;
|
||||
|
||||
+ (id)attributeRunWithIndex:(NSUInteger)idx attributes:(NSDictionary *)attrs {
|
||||
return [[[self alloc] initWithIndex:idx attributes:attrs] autorelease];
|
||||
}
|
||||
|
||||
- (id)initWithIndex:(NSUInteger)idx attributes:(NSDictionary *)attrs {
|
||||
NSParameterAssert(idx >= 0);
|
||||
if ((self = [super init])) {
|
||||
_index = idx;
|
||||
if (attrs == nil) {
|
||||
_attributes = [[NSMutableDictionary alloc] init];
|
||||
} else {
|
||||
_attributes = [attrs mutableCopy];
|
||||
}
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (id)initWithCoder:(NSCoder *)decoder {
|
||||
if ((self = [super init])) {
|
||||
_index = [[decoder decodeObjectForKey:@"index"] unsignedIntegerValue];
|
||||
_attributes = [[decoder decodeObjectForKey:@"attributes"] mutableCopy];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (id)init {
|
||||
return [self initWithIndex:0 attributes:[NSDictionary dictionary]];
|
||||
}
|
||||
|
||||
- (id)copyWithZone:(NSZone *)zone {
|
||||
return [[ZAttributeRun allocWithZone:zone] initWithIndex:_index attributes:_attributes];
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(NSCoder *)aCoder {
|
||||
[aCoder encodeObject:[NSNumber numberWithUnsignedInteger:_index] forKey:@"index"];
|
||||
[aCoder encodeObject:_attributes forKey:@"attributes"];
|
||||
}
|
||||
|
||||
- (NSString *)description {
|
||||
NSMutableArray *components = [NSMutableArray arrayWithCapacity:[_attributes count]];
|
||||
for (id key in _attributes) {
|
||||
[components addObject:[NSString stringWithFormat:@"%@=%@", key, [_attributes objectForKey:key]]];
|
||||
}
|
||||
return [NSString stringWithFormat:@"<%@: %p index=%lu attributes={%@}>",
|
||||
NSStringFromClass([self class]), self, (unsigned long)_index, [components componentsJoinedByString:@" "]];
|
||||
}
|
||||
|
||||
- (BOOL)isEqual:(id)object {
|
||||
if (![object isKindOfClass:[ZAttributeRun class]]) return NO;
|
||||
ZAttributeRun *other = (ZAttributeRun *)object;
|
||||
return _index == other->_index && [_attributes isEqualToDictionary:other->_attributes];
|
||||
}
|
||||
|
||||
- (void)dealloc {
|
||||
[_attributes release];
|
||||
[super dealloc];
|
||||
}
|
||||
@end
|
||||
|
||||
NSString * const ZFontAttributeName = @"ZFontAttributeName";
|
||||
NSString * const ZForegroundColorAttributeName = @"ZForegroundColorAttributeName";
|
||||
NSString * const ZBackgroundColorAttributeName = @"ZBackgroundColorAttributeName";
|
||||
NSString * const ZUnderlineStyleAttributeName = @"ZUnderlineStyleAttributeName";
|
|
@ -1,24 +0,0 @@
|
|||
//
|
||||
// ZAttributedStringPrivate.h
|
||||
// FontLabel
|
||||
//
|
||||
// Created by Kevin Ballard on 9/23/09.
|
||||
// Copyright 2009 Zynga Game Networks. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "ZAttributedString.h"
|
||||
|
||||
@interface ZAttributeRun : NSObject <NSCopying, NSCoding> {
|
||||
NSUInteger _index;
|
||||
NSMutableDictionary *_attributes;
|
||||
}
|
||||
@property (nonatomic, readonly) NSUInteger index;
|
||||
@property (nonatomic, readonly) NSMutableDictionary *attributes;
|
||||
+ (id)attributeRunWithIndex:(NSUInteger)idx attributes:(NSDictionary *)attrs;
|
||||
- (id)initWithIndex:(NSUInteger)idx attributes:(NSDictionary *)attrs;
|
||||
@end
|
||||
|
||||
@interface ZAttributedString (ZAttributedStringPrivate)
|
||||
@property (nonatomic, readonly) NSArray *attributes;
|
||||
@end
|
|
@ -1,47 +0,0 @@
|
|||
//
|
||||
// ZFont.h
|
||||
// FontLabel
|
||||
//
|
||||
// Created by Kevin Ballard on 7/2/09.
|
||||
// Copyright © 2009 Zynga Game Networks
|
||||
//
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
@interface ZFont : NSObject {
|
||||
CGFontRef _cgFont;
|
||||
CGFloat _pointSize;
|
||||
CGFloat _ratio;
|
||||
NSString *_familyName;
|
||||
NSString *_fontName;
|
||||
NSString *_postScriptName;
|
||||
}
|
||||
@property (nonatomic, readonly) CGFontRef cgFont;
|
||||
@property (nonatomic, readonly) CGFloat pointSize;
|
||||
@property (nonatomic, readonly) CGFloat ascender;
|
||||
@property (nonatomic, readonly) CGFloat descender;
|
||||
@property (nonatomic, readonly) CGFloat leading;
|
||||
@property (nonatomic, readonly) CGFloat xHeight;
|
||||
@property (nonatomic, readonly) CGFloat capHeight;
|
||||
@property (nonatomic, readonly) NSString *familyName;
|
||||
@property (nonatomic, readonly) NSString *fontName;
|
||||
@property (nonatomic, readonly) NSString *postScriptName;
|
||||
+ (ZFont *)fontWithCGFont:(CGFontRef)cgFont size:(CGFloat)fontSize;
|
||||
+ (ZFont *)fontWithUIFont:(UIFont *)uiFont;
|
||||
- (id)initWithCGFont:(CGFontRef)cgFont size:(CGFloat)fontSize;
|
||||
- (ZFont *)fontWithSize:(CGFloat)fontSize;
|
||||
@end
|
|
@ -1,170 +0,0 @@
|
|||
//
|
||||
// ZFont.m
|
||||
// FontLabel
|
||||
//
|
||||
// Created by Kevin Ballard on 7/2/09.
|
||||
// Copyright © 2009 Zynga Game Networks
|
||||
//
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
#import "ZFont.h"
|
||||
|
||||
@interface ZFont ()
|
||||
@property (nonatomic, readonly) CGFloat ratio;
|
||||
- (NSString *)copyNameTableEntryForID:(UInt16)nameID;
|
||||
@end
|
||||
|
||||
@implementation ZFont
|
||||
@synthesize cgFont=_cgFont, pointSize=_pointSize, ratio=_ratio;
|
||||
|
||||
+ (ZFont *)fontWithCGFont:(CGFontRef)cgFont size:(CGFloat)fontSize {
|
||||
return [[[self alloc] initWithCGFont:cgFont size:fontSize] autorelease];
|
||||
}
|
||||
|
||||
+ (ZFont *)fontWithUIFont:(UIFont *)uiFont {
|
||||
NSParameterAssert(uiFont != nil);
|
||||
CGFontRef cgFont = CGFontCreateWithFontName((CFStringRef)uiFont.fontName);
|
||||
ZFont *zFont = [[self alloc] initWithCGFont:cgFont size:uiFont.pointSize];
|
||||
CGFontRelease(cgFont);
|
||||
return [zFont autorelease];
|
||||
}
|
||||
|
||||
- (id)initWithCGFont:(CGFontRef)cgFont size:(CGFloat)fontSize {
|
||||
if ((self = [super init])) {
|
||||
_cgFont = CGFontRetain(cgFont);
|
||||
_pointSize = fontSize;
|
||||
_ratio = fontSize/CGFontGetUnitsPerEm(cgFont);
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (id)init {
|
||||
NSAssert(NO, @"-init is not valid for ZFont");
|
||||
return nil;
|
||||
}
|
||||
|
||||
- (CGFloat)ascender {
|
||||
return ceilf(self.ratio * CGFontGetAscent(self.cgFont));
|
||||
}
|
||||
|
||||
- (CGFloat)descender {
|
||||
return floorf(self.ratio * CGFontGetDescent(self.cgFont));
|
||||
}
|
||||
|
||||
- (CGFloat)leading {
|
||||
return (self.ascender - self.descender);
|
||||
}
|
||||
|
||||
- (CGFloat)capHeight {
|
||||
return ceilf(self.ratio * CGFontGetCapHeight(self.cgFont));
|
||||
}
|
||||
|
||||
- (CGFloat)xHeight {
|
||||
return ceilf(self.ratio * CGFontGetXHeight(self.cgFont));
|
||||
}
|
||||
|
||||
- (NSString *)familyName {
|
||||
if (_familyName == nil) {
|
||||
_familyName = [self copyNameTableEntryForID:1];
|
||||
}
|
||||
return _familyName;
|
||||
}
|
||||
|
||||
- (NSString *)fontName {
|
||||
if (_fontName == nil) {
|
||||
_fontName = [self copyNameTableEntryForID:4];
|
||||
}
|
||||
return _fontName;
|
||||
}
|
||||
|
||||
- (NSString *)postScriptName {
|
||||
if (_postScriptName == nil) {
|
||||
_postScriptName = [self copyNameTableEntryForID:6];
|
||||
}
|
||||
return _postScriptName;
|
||||
}
|
||||
|
||||
- (ZFont *)fontWithSize:(CGFloat)fontSize {
|
||||
if (fontSize == self.pointSize) return self;
|
||||
NSParameterAssert(fontSize > 0.0);
|
||||
return [[[ZFont alloc] initWithCGFont:self.cgFont size:fontSize] autorelease];
|
||||
}
|
||||
|
||||
- (BOOL)isEqual:(id)object {
|
||||
if (![object isKindOfClass:[ZFont class]]) return NO;
|
||||
ZFont *font = (ZFont *)object;
|
||||
return (font.cgFont == self.cgFont && font.pointSize == self.pointSize);
|
||||
}
|
||||
|
||||
- (NSString *)copyNameTableEntryForID:(UInt16)aNameID {
|
||||
CFDataRef nameTable = CGFontCopyTableForTag(self.cgFont, 'name');
|
||||
NSAssert1(nameTable != NULL, @"CGFontCopyTableForTag returned NULL for 'name' tag in font %@",
|
||||
[(id)CFCopyDescription(self.cgFont) autorelease]);
|
||||
const UInt8 * const bytes = CFDataGetBytePtr(nameTable);
|
||||
NSAssert1(OSReadBigInt16(bytes, 0) == 0, @"name table for font %@ has bad version number",
|
||||
[(id)CFCopyDescription(self.cgFont) autorelease]);
|
||||
const UInt16 count = OSReadBigInt16(bytes, 2);
|
||||
const UInt16 stringOffset = OSReadBigInt16(bytes, 4);
|
||||
const UInt8 * const nameRecords = &bytes[6];
|
||||
UInt16 nameLength = 0;
|
||||
UInt16 nameOffset = 0;
|
||||
NSStringEncoding encoding = 0;
|
||||
for (UInt16 idx = 0; idx < count; idx++) {
|
||||
const uintptr_t recordOffset = 12 * idx;
|
||||
const UInt16 nameID = OSReadBigInt16(nameRecords, recordOffset + 6);
|
||||
if (nameID != aNameID) continue;
|
||||
const UInt16 platformID = OSReadBigInt16(nameRecords, recordOffset + 0);
|
||||
const UInt16 platformSpecificID = OSReadBigInt16(nameRecords, recordOffset + 2);
|
||||
encoding = 0;
|
||||
// for now, we only support a subset of encodings
|
||||
switch (platformID) {
|
||||
case 0: // Unicode
|
||||
encoding = NSUTF16StringEncoding;
|
||||
break;
|
||||
case 1: // Macintosh
|
||||
switch (platformSpecificID) {
|
||||
case 0:
|
||||
encoding = NSMacOSRomanStringEncoding;
|
||||
break;
|
||||
}
|
||||
case 3: // Microsoft
|
||||
switch (platformSpecificID) {
|
||||
case 1:
|
||||
encoding = NSUTF16StringEncoding;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (encoding == 0) continue;
|
||||
nameLength = OSReadBigInt16(nameRecords, recordOffset + 8);
|
||||
nameOffset = OSReadBigInt16(nameRecords, recordOffset + 10);
|
||||
break;
|
||||
}
|
||||
NSString *result = nil;
|
||||
if (nameOffset > 0) {
|
||||
const UInt8 *nameBytes = &bytes[stringOffset + nameOffset];
|
||||
result = [[NSString alloc] initWithBytes:nameBytes length:nameLength encoding:encoding];
|
||||
}
|
||||
CFRelease(nameTable);
|
||||
return result;
|
||||
}
|
||||
|
||||
- (void)dealloc {
|
||||
CGFontRelease(_cgFont);
|
||||
[_familyName release];
|
||||
[_fontName release];
|
||||
[_postScriptName release];
|
||||
[super dealloc];
|
||||
}
|
||||
@end
|
|
@ -35,16 +35,16 @@ THE SOFTWARE.
|
|||
|
||||
NS_CC_BEGIN
|
||||
|
||||
// Windows Touch define
|
||||
#define MOUSEEVENTF_FROMTOUCH 0xFF515700
|
||||
// Windows Touch define
|
||||
#define MOUSEEVENTF_FROMTOUCH 0xFF515700
|
||||
|
||||
// Windows Touch functions
|
||||
// Workaround to be able tu run app on Windows XP
|
||||
typedef WINUSERAPI BOOL (WINAPI *RegisterTouchWindowFn)(_In_ HWND hwnd, _In_ ULONG ulFlags);
|
||||
typedef WINUSERAPI BOOL (WINAPI *UnregisterTouchWindowFn)(_In_ HWND hwnd);
|
||||
typedef WINUSERAPI LPARAM (WINAPI *GetMessageExtraInfoFn)(VOID);
|
||||
typedef WINUSERAPI BOOL (WINAPI *GetTouchInputInfoFn)(_In_ HTOUCHINPUT hTouchInput, _In_ UINT cInputs, __out_ecount(cInputs) PTOUCHINPUT pInputs, _In_ int cbSize);
|
||||
typedef WINUSERAPI BOOL (WINAPI *CloseTouchInputHandleFn)(_In_ HTOUCHINPUT hTouchInput);
|
||||
// Windows Touch functions
|
||||
// Workaround to be able tu run app on Windows XP
|
||||
typedef WINUSERAPI BOOL (WINAPI *RegisterTouchWindowFn)(_In_ HWND hwnd, _In_ ULONG ulFlags);
|
||||
typedef WINUSERAPI BOOL (WINAPI *UnregisterTouchWindowFn)(_In_ HWND hwnd);
|
||||
typedef WINUSERAPI LPARAM (WINAPI *GetMessageExtraInfoFn)(VOID);
|
||||
typedef WINUSERAPI BOOL (WINAPI *GetTouchInputInfoFn)(_In_ HTOUCHINPUT hTouchInput, _In_ UINT cInputs, __out_ecount(cInputs) PTOUCHINPUT pInputs, _In_ int cbSize);
|
||||
typedef WINUSERAPI BOOL (WINAPI *CloseTouchInputHandleFn)(_In_ HTOUCHINPUT hTouchInput);
|
||||
|
||||
RegisterTouchWindowFn RegisterTouchWindowFunction = NULL;
|
||||
UnregisterTouchWindowFn UnregisterTouchWindowFunction = NULL;
|
||||
|
@ -52,16 +52,16 @@ GetMessageExtraInfoFn GetMessageExtraInfoFunction = NULL;
|
|||
GetTouchInputInfoFn GetTouchInputInfoFunction = NULL;
|
||||
CloseTouchInputHandleFn CloseTouchInputHandleFunction = NULL;
|
||||
|
||||
bool CheckTouchSupport()
|
||||
{
|
||||
RegisterTouchWindowFunction = (RegisterTouchWindowFn)GetProcAddress(GetModuleHandle(TEXT("user32.dll")), "RegisterTouchWindow");
|
||||
UnregisterTouchWindowFunction = (UnregisterTouchWindowFn)GetProcAddress(GetModuleHandle(TEXT("user32.dll")), "UnregisterTouchWindow");
|
||||
GetMessageExtraInfoFunction = (GetMessageExtraInfoFn)GetProcAddress(GetModuleHandle(TEXT("user32.dll")), "GetMessageExtraInfo");
|
||||
GetTouchInputInfoFunction = (GetTouchInputInfoFn)GetProcAddress(GetModuleHandle(TEXT("user32.dll")), "GetTouchInputInfo");
|
||||
CloseTouchInputHandleFunction = (CloseTouchInputHandleFn)GetProcAddress(GetModuleHandle(TEXT("user32.dll")), "CloseTouchInputHandle");
|
||||
|
||||
return (RegisterTouchWindowFunction && UnregisterTouchWindowFunction && GetMessageExtraInfoFunction && GetTouchInputInfoFunction && CloseTouchInputHandleFunction);
|
||||
}
|
||||
bool CheckTouchSupport()
|
||||
{
|
||||
RegisterTouchWindowFunction = (RegisterTouchWindowFn)GetProcAddress(GetModuleHandle(TEXT("user32.dll")), "RegisterTouchWindow");
|
||||
UnregisterTouchWindowFunction = (UnregisterTouchWindowFn)GetProcAddress(GetModuleHandle(TEXT("user32.dll")), "UnregisterTouchWindow");
|
||||
GetMessageExtraInfoFunction = (GetMessageExtraInfoFn)GetProcAddress(GetModuleHandle(TEXT("user32.dll")), "GetMessageExtraInfo");
|
||||
GetTouchInputInfoFunction = (GetTouchInputInfoFn)GetProcAddress(GetModuleHandle(TEXT("user32.dll")), "GetTouchInputInfo");
|
||||
CloseTouchInputHandleFunction = (CloseTouchInputHandleFn)GetProcAddress(GetModuleHandle(TEXT("user32.dll")), "CloseTouchInputHandle");
|
||||
|
||||
return (RegisterTouchWindowFunction && UnregisterTouchWindowFunction && GetMessageExtraInfoFunction && GetTouchInputInfoFunction && CloseTouchInputHandleFunction);
|
||||
}
|
||||
|
||||
static void SetupPixelFormat(HDC hDC)
|
||||
{
|
||||
|
@ -335,7 +335,7 @@ LRESULT CCEGLView::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
|
|||
if (m_pDelegate && MK_LBUTTON == wParam)
|
||||
{
|
||||
POINT point = {(short)LOWORD(lParam), (short)HIWORD(lParam)};
|
||||
CCPoint pt(point.x/CC_CONTENT_SCALE_FACTOR(), point.y/CC_CONTENT_SCALE_FACTOR());
|
||||
CCPoint pt(point.x, point.y);
|
||||
CCPoint tmp = ccp(pt.x, m_obScreenSize.height - pt.y);
|
||||
if (m_obViewPortRect.equals(CCRectZero) || m_obViewPortRect.containsPoint(tmp))
|
||||
{
|
||||
|
@ -356,7 +356,7 @@ LRESULT CCEGLView::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
|
|||
if (MK_LBUTTON == wParam && m_bCaptured)
|
||||
{
|
||||
POINT point = {(short)LOWORD(lParam), (short)HIWORD(lParam)};
|
||||
CCPoint pt(point.x/CC_CONTENT_SCALE_FACTOR(), point.y/CC_CONTENT_SCALE_FACTOR());
|
||||
CCPoint pt(point.x, point.y);
|
||||
int id = 0;
|
||||
pt.x *= m_windowTouchScaleX;
|
||||
pt.y *= m_windowTouchScaleY;
|
||||
|
@ -371,7 +371,7 @@ LRESULT CCEGLView::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
|
|||
if (m_bCaptured)
|
||||
{
|
||||
POINT point = {(short)LOWORD(lParam), (short)HIWORD(lParam)};
|
||||
CCPoint pt(point.x/CC_CONTENT_SCALE_FACTOR(), point.y/CC_CONTENT_SCALE_FACTOR());
|
||||
CCPoint pt(point.x, point.y);
|
||||
int id = 0;
|
||||
pt.x *= m_windowTouchScaleX;
|
||||
pt.y *= m_windowTouchScaleY;
|
||||
|
@ -560,12 +560,6 @@ void CCEGLView::setIMEKeyboardState(bool /*bOpen*/)
|
|||
|
||||
}
|
||||
|
||||
bool CCEGLView::enableRetina()
|
||||
{
|
||||
m_bIsRetinaEnabled = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
void CCEGLView::setMenuResource(LPCWSTR menu)
|
||||
{
|
||||
m_menu = menu;
|
||||
|
@ -666,15 +660,6 @@ void CCEGLView::centerWindow()
|
|||
SetWindowPos(m_hWnd, 0, offsetX, offsetY, 0, 0, SWP_NOCOPYBITS | SWP_NOSIZE | SWP_NOOWNERZORDER | SWP_NOZORDER);
|
||||
}
|
||||
|
||||
bool CCEGLView::setContentScaleFactor(float contentScaleFactor)
|
||||
{
|
||||
CCEGLViewProtocol::setContentScaleFactor(contentScaleFactor);
|
||||
resize((int)(m_obScreenSize.width * contentScaleFactor), (int)(m_obScreenSize.height * contentScaleFactor));
|
||||
centerWindow();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
CCEGLView* CCEGLView::sharedOpenGLView(const char* pTitle)
|
||||
{
|
||||
static CCEGLView* s_pEglView = NULL;
|
||||
|
|
|
@ -46,10 +46,8 @@ public:
|
|||
virtual bool isOpenGLReady();
|
||||
virtual void end();
|
||||
virtual void swapBuffers();
|
||||
virtual bool setContentScaleFactor(float contentScaleFactor);
|
||||
virtual void setFrameSize(float width, float height);
|
||||
virtual void setIMEKeyboardState(bool bOpen);
|
||||
virtual bool enableRetina();
|
||||
|
||||
void setMenuResource(LPCWSTR menu);
|
||||
void setWndProc(CUSTOM_WND_PROC proc);
|
||||
|
|
|
@ -1 +1 @@
|
|||
c6b576d638eb4ac03aebd8111bba28397aa96625
|
||||
d9f2b205ba4de8125ca7740a1740767028020681
|
|
@ -131,8 +131,10 @@ void CCNotificationCenter::unregisterScriptObserver(void)
|
|||
|
||||
void CCNotificationCenter::postNotification(const char *name, CCObject *object)
|
||||
{
|
||||
CCArray* ObserversCopy = CCArray::createWithCapacity(m_observers->count());
|
||||
ObserversCopy->addObjectsFromArray(m_observers);
|
||||
CCObject* obj = NULL;
|
||||
CCARRAY_FOREACH(m_observers, obj)
|
||||
CCARRAY_FOREACH(ObserversCopy, obj)
|
||||
{
|
||||
CCNotificationObserver* observer = (CCNotificationObserver*) obj;
|
||||
if (!observer)
|
||||
|
|
|
@ -46,7 +46,7 @@ public:
|
|||
CCPoint getLocation() const;
|
||||
/** returns the previous touch location in OpenGL coordinates */
|
||||
CCPoint getPreviousLocation() const;
|
||||
/** returns the current touch location in screen coordinates */
|
||||
/** returns the delta of 2 current touches locations in screen coordinates */
|
||||
CCPoint getDelta() const;
|
||||
/** returns the current touch location in screen coordinates */
|
||||
CCPoint getLocationInView() const;
|
||||
|
|
|
@ -80,7 +80,10 @@ bool CCControlColourPicker::init()
|
|||
|
||||
// MIPMAP
|
||||
// ccTexParams params = {GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR, GL_REPEAT, GL_REPEAT};
|
||||
spriteSheet->getTexture()->setAliasTexParameters();
|
||||
/* Comment next line to avoid something like mosaic in 'CCControlExtensionTest',
|
||||
especially the display of 'huePickerBackground.png' when in 800*480 window size with 480*320 design resolution and hd(960*640) resources.
|
||||
*/
|
||||
// spriteSheet->getTexture()->setAliasTexParameters();
|
||||
// spriteSheet->getTexture()->setTexParameters(¶ms);
|
||||
// spriteSheet->getTexture()->generateMipmap();
|
||||
|
||||
|
|
|
@ -64,6 +64,7 @@ private:
|
|||
CCSize m_tContentSize;
|
||||
void* m_pSysEdit;
|
||||
int m_nMaxTextLength;
|
||||
bool m_bInRetinaMode;
|
||||
};
|
||||
|
||||
|
||||
|
|
|
@ -42,7 +42,7 @@ CCEditBoxImplIOS::CCEditBoxImplIOS(CCEditBox* pEditText)
|
|||
, m_pSysEdit(NULL)
|
||||
, m_nMaxTextLength(-1)
|
||||
{
|
||||
|
||||
m_bInRetinaMode = [[EAGLView sharedEGLView] contentScaleFactor] == 2.0f ? true : false;
|
||||
}
|
||||
|
||||
CCEditBoxImplIOS::~CCEditBoxImplIOS()
|
||||
|
@ -64,15 +64,14 @@ bool CCEditBoxImplIOS::initWithSize(const CCSize& size)
|
|||
{
|
||||
CCEGLViewProtocol* eglView = CCEGLView::sharedOpenGLView();
|
||||
|
||||
CGRect rect;
|
||||
if (eglView->isRetinaEnabled())
|
||||
CGRect rect = CGRectMake(0, 0, size.width * eglView->getScaleX(),size.height * eglView->getScaleY());
|
||||
|
||||
if (m_bInRetinaMode)
|
||||
{
|
||||
rect = CGRectMake(0, 0, size.width,size.height);
|
||||
}
|
||||
else
|
||||
{
|
||||
rect = CGRectMake(0, 0, size.width * eglView->getScaleX(),size.height * eglView->getScaleY());
|
||||
rect.size.width /= 2.0f;
|
||||
rect.size.height /= 2.0f;
|
||||
}
|
||||
|
||||
m_pSysEdit = [[EditBoxImplIOS alloc] initWithFrame:rect editBox:this];
|
||||
if (!m_pSysEdit) break;
|
||||
|
||||
|
@ -195,29 +194,29 @@ void CCEditBoxImplIOS::setPlaceHolder(const char* pText)
|
|||
GET_IMPL.textField.placeholder = [NSString stringWithUTF8String:pText];
|
||||
}
|
||||
|
||||
static CGPoint convertDesignCoordToScreenCoord(const CCPoint& designCoord)
|
||||
static CGPoint convertDesignCoordToScreenCoord(const CCPoint& designCoord, bool bInRetinaMode)
|
||||
{
|
||||
float viewH = (float)[[EAGLView sharedEGLView] getHeight];
|
||||
CCEGLViewProtocol* eglView = CCEGLView::sharedOpenGLView();
|
||||
CCPoint visiblePos;
|
||||
if (eglView->isRetinaEnabled())
|
||||
{
|
||||
visiblePos = ccp(designCoord.x, designCoord.y);
|
||||
}
|
||||
else
|
||||
{
|
||||
visiblePos = ccp(designCoord.x * eglView->getScaleX(), designCoord.y * eglView->getScaleY());
|
||||
}
|
||||
|
||||
float viewH = (float)[[EAGLView sharedEGLView] getHeight];
|
||||
|
||||
CCPoint visiblePos = ccp(designCoord.x * eglView->getScaleX(), designCoord.y * eglView->getScaleY());
|
||||
CCPoint screenGLPos = ccpAdd(visiblePos, eglView->getViewPortRect().origin);
|
||||
|
||||
CGPoint screenPos = CGPointMake(screenGLPos.x, viewH - screenGLPos.y);
|
||||
|
||||
if (bInRetinaMode)
|
||||
{
|
||||
screenPos.x = screenPos.x / 2.0f;
|
||||
screenPos.y = screenPos.y / 2.0f;
|
||||
}
|
||||
CCLOG("[EditBox] pos x = %f, y = %f", screenGLPos.x, screenGLPos.y);
|
||||
return screenPos;
|
||||
}
|
||||
|
||||
void CCEditBoxImplIOS::setPosition(const CCPoint& pos)
|
||||
{
|
||||
//TODO should consider anchor point, the default value is (0.5, 0,5)
|
||||
[GET_IMPL setPosition:convertDesignCoordToScreenCoord(ccp(pos.x-m_tContentSize.width/2, pos.y+m_tContentSize.height/2))];
|
||||
[GET_IMPL setPosition:convertDesignCoordToScreenCoord(ccp(pos.x-m_tContentSize.width/2, pos.y+m_tContentSize.height/2), m_bInRetinaMode)];
|
||||
}
|
||||
|
||||
void CCEditBoxImplIOS::setContentSize(const CCSize& size)
|
||||
|
|
|
@ -131,15 +131,19 @@ CCTableViewCell *CCTableView::cellAtIndex(unsigned int idx)
|
|||
|
||||
void CCTableView::updateCellAtIndex(unsigned int idx)
|
||||
{
|
||||
if (idx == CC_INVALID_INDEX || idx > m_pDataSource->numberOfCellsInTableView(this)-1)
|
||||
if (idx == CC_INVALID_INDEX)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
CCTableViewCell *cell;
|
||||
|
||||
cell = this->_cellWithIndex(idx);
|
||||
if (cell) {
|
||||
unsigned int uCountOfItems = m_pDataSource->numberOfCellsInTableView(this);
|
||||
if (0 == uCountOfItems || idx > uCountOfItems-1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
CCTableViewCell* cell = this->_cellWithIndex(idx);
|
||||
if (cell)
|
||||
{
|
||||
this->_moveCellOutOfSight(cell);
|
||||
}
|
||||
cell = m_pDataSource->tableCellAtIndex(this, idx);
|
||||
|
@ -149,11 +153,19 @@ void CCTableView::updateCellAtIndex(unsigned int idx)
|
|||
|
||||
void CCTableView::insertCellAtIndex(unsigned int idx)
|
||||
{
|
||||
if (idx == CC_INVALID_INDEX || idx > m_pDataSource->numberOfCellsInTableView(this)-1) {
|
||||
if (idx == CC_INVALID_INDEX)
|
||||
{
|
||||
return;
|
||||
}
|
||||
CCTableViewCell *cell;
|
||||
int newIdx;
|
||||
|
||||
unsigned int uCountOfItems = m_pDataSource->numberOfCellsInTableView(this);
|
||||
if (0 == uCountOfItems || idx > uCountOfItems-1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
CCTableViewCell* cell = NULL;
|
||||
int newIdx = 0;
|
||||
|
||||
cell = (CCTableViewCell*)m_pCellsUsed->objectWithObjectID(idx);
|
||||
if (cell)
|
||||
|
@ -178,12 +190,19 @@ void CCTableView::insertCellAtIndex(unsigned int idx)
|
|||
|
||||
void CCTableView::removeCellAtIndex(unsigned int idx)
|
||||
{
|
||||
if (idx == CC_INVALID_INDEX || idx > m_pDataSource->numberOfCellsInTableView(this)-1) {
|
||||
if (idx == CC_INVALID_INDEX)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
CCTableViewCell *cell;
|
||||
unsigned int newIdx;
|
||||
unsigned int uCountOfItems = m_pDataSource->numberOfCellsInTableView(this);
|
||||
if (0 == uCountOfItems || idx > uCountOfItems-1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
CCTableViewCell* cell = NULL;
|
||||
unsigned int newIdx = 0;
|
||||
|
||||
cell = this->_cellWithIndex(idx);
|
||||
if (!cell) {
|
||||
|
@ -362,15 +381,19 @@ void CCTableView::_setIndexForCell(unsigned int index, CCTableViewCell *cell)
|
|||
|
||||
void CCTableView::scrollViewDidScroll(CCScrollView* view)
|
||||
{
|
||||
unsigned int startIdx = 0, endIdx = 0, idx = 0, maxIdx = 0;
|
||||
CCPoint offset;
|
||||
unsigned int uCountOfItems = m_pDataSource->numberOfCellsInTableView(this);
|
||||
if (0 == uCountOfItems)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
offset = ccpMult(this->getContentOffset(), -1);
|
||||
maxIdx = MAX(m_pDataSource->numberOfCellsInTableView(this)-1, 0);
|
||||
|
||||
unsigned int startIdx = 0, endIdx = 0, idx = 0, maxIdx = 0;
|
||||
CCPoint offset = ccpMult(this->getContentOffset(), -1);
|
||||
maxIdx = MAX(uCountOfItems-1, 0);
|
||||
const CCSize cellSize = m_pDataSource->cellSizeForTable(this);
|
||||
|
||||
if (m_eVordering == kCCTableViewFillTopDown) {
|
||||
if (m_eVordering == kCCTableViewFillTopDown)
|
||||
{
|
||||
offset.y = offset.y + m_tViewSize.height/this->getContainer()->getScaleY() - cellSize.height;
|
||||
}
|
||||
startIdx = this->_indexFromOffset(offset);
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
#include "AppDelegate.h"
|
||||
#include "HelloWorldScene.h"
|
||||
#include "AppMacros.h"
|
||||
|
||||
USING_NS_CC;
|
||||
|
||||
|
@ -16,41 +17,27 @@ bool AppDelegate::applicationDidFinishLaunching() {
|
|||
CCDirector *pDirector = CCDirector::sharedDirector();
|
||||
|
||||
pDirector->setOpenGLView(CCEGLView::sharedOpenGLView());
|
||||
//pDirector->setProjection(kCCDirectorProjection2D);
|
||||
CCSize screenSize = CCEGLView::sharedOpenGLView()->getFrameSize();
|
||||
|
||||
TargetPlatform target = getTargetPlatform();
|
||||
if (screenSize.height > 768)
|
||||
{
|
||||
CCFileUtils::sharedFileUtils()->setResourceDirectory("ipadhd");
|
||||
pDirector->setContentScaleFactor(1536.0f/kDesignResolutionSize_height);
|
||||
}
|
||||
else if (screenSize.height > 320)
|
||||
{
|
||||
CCFileUtils::sharedFileUtils()->setResourceDirectory("ipad");
|
||||
pDirector->setContentScaleFactor(768.0f/kDesignResolutionSize_height);
|
||||
}
|
||||
else
|
||||
{
|
||||
CCFileUtils::sharedFileUtils()->setResourceDirectory("iphone");
|
||||
pDirector->setContentScaleFactor(320.0f/kDesignResolutionSize_height);
|
||||
}
|
||||
|
||||
CCEGLView::sharedOpenGLView()->setDesignResolutionSize(kDesignResolutionSize_width, kDesignResolutionSize_height, kResolutionNoBorder);
|
||||
|
||||
if (target == kTargetIpad)
|
||||
{
|
||||
// ipad
|
||||
|
||||
CCFileUtils::sharedFileUtils()->setResourceDirectory("iphonehd");
|
||||
|
||||
// don't enable retina because we don't have ipad hd resource
|
||||
CCEGLView::sharedOpenGLView()->setDesignResolutionSize(960, 640, kResolutionNoBorder);
|
||||
}
|
||||
else if (target == kTargetIphone)
|
||||
{
|
||||
// iphone
|
||||
|
||||
// try to enable retina on device
|
||||
if (true == CCDirector::sharedDirector()->enableRetinaDisplay(true))
|
||||
{
|
||||
// iphone hd
|
||||
CCFileUtils::sharedFileUtils()->setResourceDirectory("iphonehd");
|
||||
}
|
||||
else
|
||||
{
|
||||
CCFileUtils::sharedFileUtils()->setResourceDirectory("iphone");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// android, windows, blackberry, linux or mac
|
||||
// use 960*640 resources as design resolution size
|
||||
CCFileUtils::sharedFileUtils()->setResourceDirectory("iphonehd");
|
||||
CCEGLView::sharedOpenGLView()->setDesignResolutionSize(960, 640, kResolutionNoBorder);
|
||||
}
|
||||
|
||||
// turn on display FPS
|
||||
pDirector->setDisplayStats(true);
|
||||
|
||||
|
|
|
@ -0,0 +1,30 @@
|
|||
#ifndef __APPMACROS_H__
|
||||
#define __APPMACROS_H__
|
||||
|
||||
|
||||
#define kDesignResolution_480x320 0
|
||||
#define kDesignResolution_1024x768 1
|
||||
#define kDesignResolution_2048x1536 2
|
||||
|
||||
#define kTargetDesignResolutionSize kDesignResolution_2048x1536
|
||||
|
||||
#if (kTargetDesignResolutionSize == kDesignResolution_480x320)
|
||||
#define kDesignResolutionSize_width 480.0f
|
||||
#define kDesignResolutionSize_height 320.0f
|
||||
|
||||
|
||||
#elif (kTargetDesignResolutionSize == kDesignResolution_1024x768)
|
||||
#define kDesignResolutionSize_width 1024.0f
|
||||
#define kDesignResolutionSize_height 768.0f
|
||||
|
||||
#elif (kTargetDesignResolutionSize == kDesignResolution_2048x1536)
|
||||
#define kDesignResolutionSize_width 2048.0f
|
||||
#define kDesignResolutionSize_height 1536.0f
|
||||
|
||||
#else
|
||||
#error unknown target design resolution!
|
||||
#endif
|
||||
|
||||
#define kTitleFontSize (kDesignResolutionSize_width / 480.0f * 24)
|
||||
|
||||
#endif /* __APPMACROS_H__ */
|
|
@ -1,7 +1,8 @@
|
|||
#include "HelloWorldScene.h"
|
||||
|
||||
#include "AppMacros.h"
|
||||
USING_NS_CC;
|
||||
|
||||
|
||||
CCScene* HelloWorld::scene()
|
||||
{
|
||||
// 'scene' is an autorelease object
|
||||
|
@ -40,8 +41,8 @@ bool HelloWorld::init()
|
|||
"CloseSelected.png",
|
||||
this,
|
||||
menu_selector(HelloWorld::menuCloseCallback));
|
||||
|
||||
pCloseItem->setPosition(ccp(origin.x + visibleSize.width - pCloseItem->getContentSize().width/2 ,
|
||||
|
||||
pCloseItem->setPosition(ccp(origin.x + visibleSize.width - pCloseItem->getContentSize().width/2 ,
|
||||
origin.y + pCloseItem->getContentSize().height/2));
|
||||
|
||||
// create menu, it's an autorelease object
|
||||
|
@ -54,8 +55,9 @@ bool HelloWorld::init()
|
|||
|
||||
// add a label shows "Hello World"
|
||||
// create and initialize a label
|
||||
CCLabelTTF* pLabel = CCLabelTTF::create("Hello World", "Arial", 24);
|
||||
|
||||
|
||||
CCLabelTTF* pLabel = CCLabelTTF::create("Hello World", "Arial", kTitleFontSize);
|
||||
|
||||
// position the label on the center of the screen
|
||||
pLabel->setPosition(ccp(origin.x + visibleSize.width/2,
|
||||
origin.y + visibleSize.height - pLabel->getContentSize().height));
|
||||
|
@ -72,12 +74,10 @@ bool HelloWorld::init()
|
|||
// add the sprite as a child to this layer
|
||||
this->addChild(pSprite, 0);
|
||||
|
||||
// enable standard touch
|
||||
this->setTouchEnabled(true);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
void HelloWorld::menuCloseCallback(CCObject* pSender)
|
||||
{
|
||||
CCDirector::sharedDirector()->end();
|
||||
|
@ -86,11 +86,3 @@ void HelloWorld::menuCloseCallback(CCObject* pSender)
|
|||
exit(0);
|
||||
#endif
|
||||
}
|
||||
|
||||
void HelloWorld::ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent)
|
||||
{
|
||||
CCTouch* touch = (CCTouch*)(* pTouches->begin());
|
||||
CCPoint pos = touch->getLocation();
|
||||
|
||||
CCLog("touch, x = %f, y = %f", pos.x, pos.y);
|
||||
}
|
||||
|
|
|
@ -14,9 +14,6 @@ public:
|
|||
|
||||
// a selector callback
|
||||
void menuCloseCallback(CCObject* pSender);
|
||||
|
||||
// touch callback
|
||||
void ccTouchesBegan(cocos2d::CCSet *pTouches, cocos2d::CCEvent *pEvent);
|
||||
|
||||
// implement the "static node()" method manually
|
||||
CREATE_FUNC(HelloWorld);
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
709d78b7f3eab27056a98d63e9153b35d57b84bc
|
|
@ -0,0 +1 @@
|
|||
7aa1e9dc799acf384a1c4603054242cc09c1b63e
|
|
@ -1 +1 @@
|
|||
5fe89fb5bd58cedf13b0363f97b20e3ea7ff255d
|
||||
9d6facb31897d010352e7b57f4a82715c260408a
|
|
@ -1 +0,0 @@
|
|||
6b7a2544be32ce26e75737865743649598d83bdf
|
|
@ -8,8 +8,9 @@
|
|||
|
||||
/* Begin PBXBuildFile section */
|
||||
15003FA315D2601D00B6775A /* iphone in Resources */ = {isa = PBXBuildFile; fileRef = 15003FA215D2601D00B6775A /* iphone */; };
|
||||
15003FA515D2602400B6775A /* iphonehd in Resources */ = {isa = PBXBuildFile; fileRef = 15003FA415D2602400B6775A /* iphonehd */; };
|
||||
154269EB15B5669E00712A7F /* libcocos2dx.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 154269D015B5644500712A7F /* libcocos2dx.a */; };
|
||||
1A1CF3691626CEFF00AFC938 /* ipad in Resources */ = {isa = PBXBuildFile; fileRef = 1A1CF3671626CEFF00AFC938 /* ipad */; };
|
||||
1A1CF36A1626CEFF00AFC938 /* ipadhd in Resources */ = {isa = PBXBuildFile; fileRef = 1A1CF3681626CEFF00AFC938 /* ipadhd */; };
|
||||
1D60589F0D05DD5A006BFB54 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1D30AB110D05D00D00671497 /* Foundation.framework */; };
|
||||
1DF5F4E00D08C38300B7A737 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1DF5F4DF0D08C38300B7A737 /* UIKit.framework */; };
|
||||
288765A50DF7441C002DB57D /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 288765A40DF7441C002DB57D /* CoreGraphics.framework */; };
|
||||
|
@ -50,8 +51,10 @@
|
|||
|
||||
/* Begin PBXFileReference section */
|
||||
15003FA215D2601D00B6775A /* iphone */ = {isa = PBXFileReference; lastKnownFileType = folder; path = iphone; sourceTree = "<group>"; };
|
||||
15003FA415D2602400B6775A /* iphonehd */ = {isa = PBXFileReference; lastKnownFileType = folder; path = iphonehd; sourceTree = "<group>"; };
|
||||
154269C815B5644500712A7F /* cocos2dx.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = cocos2dx.xcodeproj; path = ../../../cocos2dx/proj.ios/cocos2dx.xcodeproj; sourceTree = "<group>"; };
|
||||
1A1CF3661626CB6000AFC938 /* AppMacros.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppMacros.h; sourceTree = "<group>"; };
|
||||
1A1CF3671626CEFF00AFC938 /* ipad */ = {isa = PBXFileReference; lastKnownFileType = folder; path = ipad; sourceTree = "<group>"; };
|
||||
1A1CF3681626CEFF00AFC938 /* ipadhd */ = {isa = PBXFileReference; lastKnownFileType = folder; path = ipadhd; sourceTree = "<group>"; };
|
||||
1D30AB110D05D00D00671497 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; };
|
||||
1D6058910D05DD3D006BFB54 /* HelloCpp.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = HelloCpp.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
1DF5F4DF0D08C38300B7A737 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; };
|
||||
|
@ -149,7 +152,8 @@
|
|||
784521C214EBA449009D533B /* Resources */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
15003FA415D2602400B6775A /* iphonehd */,
|
||||
1A1CF3671626CEFF00AFC938 /* ipad */,
|
||||
1A1CF3681626CEFF00AFC938 /* ipadhd */,
|
||||
15003FA215D2601D00B6775A /* iphone */,
|
||||
D4EF94ED15BD319D00D803EB /* Icon-144.png */,
|
||||
D4EF94EB15BD319B00D803EB /* Icon-72.png */,
|
||||
|
@ -166,6 +170,7 @@
|
|||
BF23D4E2143315EB00657E08 /* Classes */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
1A1CF3661626CB6000AFC938 /* AppMacros.h */,
|
||||
BF23D4E3143315EB00657E08 /* AppDelegate.cpp */,
|
||||
BF23D4E4143315EB00657E08 /* AppDelegate.h */,
|
||||
BF23D4E5143315EB00657E08 /* HelloWorldScene.cpp */,
|
||||
|
@ -261,10 +266,11 @@
|
|||
D4EF94EC15BD319B00D803EB /* Icon-72.png in Resources */,
|
||||
D4EF94EE15BD319D00D803EB /* Icon-144.png in Resources */,
|
||||
15003FA315D2601D00B6775A /* iphone in Resources */,
|
||||
15003FA515D2602400B6775A /* iphonehd in Resources */,
|
||||
D446FD79161028E9000ADA7B /* Default.png in Resources */,
|
||||
D446FD7B161028ED000ADA7B /* Default@2x.png in Resources */,
|
||||
D446FD7D161028F4000ADA7B /* Default-568h@2x.png in Resources */,
|
||||
1A1CF3691626CEFF00AFC938 /* ipad in Resources */,
|
||||
1A1CF36A1626CEFF00AFC938 /* ipadhd in Resources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
|
|
|
@ -15,6 +15,6 @@ int APIENTRY _tWinMain(HINSTANCE hInstance,
|
|||
// create the application instance
|
||||
AppDelegate app;
|
||||
CCEGLView* eglView = CCEGLView::sharedOpenGLView();
|
||||
eglView->setFrameSize(960, 640 );
|
||||
eglView->setFrameSize(1136, 640 );
|
||||
return CCApplication::sharedApplication()->run();
|
||||
}
|
||||
|
|
|
@ -26,7 +26,7 @@ bool AppDelegate::applicationDidFinishLaunching()
|
|||
CCDirector *pDirector = CCDirector::sharedDirector();
|
||||
pDirector->setOpenGLView(CCEGLView::sharedOpenGLView());
|
||||
|
||||
CCEGLView::sharedOpenGLView()->setDesignResolutionSize(480, 320, kResolutionShowAll);
|
||||
CCEGLView::sharedOpenGLView()->setDesignResolutionSize(480, 320, kResolutionNoBorder);
|
||||
|
||||
// enable High Resource Mode(2x, such as iphone4) and maintains low resource on other devices.
|
||||
// pDirector->enableRetinaDisplay(true);
|
||||
|
|
|
@ -21,7 +21,8 @@ local function main()
|
|||
|
||||
---------------
|
||||
|
||||
local winSize = CCDirector:sharedDirector():getWinSize()
|
||||
local visibleSize = CCDirector:sharedDirector():getVisibleSize()
|
||||
local origin = CCDirector:sharedDirector():getVisibleOrigin()
|
||||
|
||||
-- add the moving dog
|
||||
local function creatDog()
|
||||
|
@ -37,7 +38,7 @@ local function main()
|
|||
|
||||
local spriteDog = CCSprite:createWithSpriteFrame(frame0)
|
||||
spriteDog.isPaused = false
|
||||
spriteDog:setPosition(0, winSize.height / 4 * 3)
|
||||
spriteDog:setPosition(origin.x, origin.y + visibleSize.height / 4 * 3)
|
||||
|
||||
local animFrames = CCArray:create()
|
||||
|
||||
|
@ -52,8 +53,8 @@ local function main()
|
|||
local function tick()
|
||||
if spriteDog.isPaused then return end
|
||||
local x, y = spriteDog:getPosition()
|
||||
if x > winSize.width then
|
||||
x = 0
|
||||
if x > origin.x + visibleSize.width then
|
||||
x = origin.x
|
||||
else
|
||||
x = x + 1
|
||||
end
|
||||
|
@ -72,7 +73,7 @@ local function main()
|
|||
|
||||
-- add in farm background
|
||||
local bg = CCSprite:create("farm.jpg")
|
||||
bg:setPosition(winSize.width / 2 + 80, winSize.height / 2)
|
||||
bg:setPosition(origin.x + visibleSize.width / 2 + 80, origin.y + visibleSize.height / 2)
|
||||
layerFarm:addChild(bg)
|
||||
|
||||
-- add land sprite
|
||||
|
@ -166,7 +167,7 @@ local function main()
|
|||
menuPopupItem:setPosition(0, 0)
|
||||
menuPopupItem:registerScriptTapHandler(menuCallbackClosePopup)
|
||||
menuPopup = CCMenu:createWithItem(menuPopupItem)
|
||||
menuPopup:setPosition(winSize.width / 2, winSize.height / 2)
|
||||
menuPopup:setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2)
|
||||
menuPopup:setVisible(false)
|
||||
layerMenu:addChild(menuPopup)
|
||||
|
||||
|
@ -175,7 +176,9 @@ local function main()
|
|||
menuToolsItem:setPosition(0, 0)
|
||||
menuToolsItem:registerScriptTapHandler(menuCallbackOpenPopup)
|
||||
menuTools = CCMenu:createWithItem(menuToolsItem)
|
||||
menuTools:setPosition(30, 40)
|
||||
local itemWidth = menuToolsItem:getContentSize().width
|
||||
local itemHeight = menuToolsItem:getContentSize().height
|
||||
menuTools:setPosition(origin.x + itemWidth/2, origin.y + itemHeight/2)
|
||||
layerMenu:addChild(menuTools)
|
||||
|
||||
return layerMenu
|
||||
|
|
|
@ -0,0 +1,82 @@
|
|||
#include "AppDelegate.h"
|
||||
|
||||
#include "cocos2d.h"
|
||||
#include "SimpleAudioEngine.h"
|
||||
#include "ScriptingCore.h"
|
||||
#include "generated/cocos2dx.hpp"
|
||||
#include "cocos2d_specifics.hpp"
|
||||
|
||||
USING_NS_CC;
|
||||
using namespace CocosDenshion;
|
||||
|
||||
AppDelegate::AppDelegate()
|
||||
{
|
||||
}
|
||||
|
||||
AppDelegate::~AppDelegate()
|
||||
{
|
||||
CCScriptEngineManager::sharedManager()->purgeSharedManager();
|
||||
}
|
||||
|
||||
bool AppDelegate::applicationDidFinishLaunching()
|
||||
{
|
||||
// initialize director
|
||||
CCDirector *pDirector = CCDirector::sharedDirector();
|
||||
pDirector->setOpenGLView(CCEGLView::sharedOpenGLView());
|
||||
CCEGLView::sharedOpenGLView()->setDesignResolutionSize(320, 480, kResolutionShowAll);
|
||||
// enable High Resource Mode(2x, such as iphone4) and maintains low resource on other devices.
|
||||
// pDirector->enableRetinaDisplay(true);
|
||||
|
||||
// turn on display FPS
|
||||
pDirector->setDisplayStats(true);
|
||||
|
||||
// set FPS. the default value is 1.0/60 if you don't call this
|
||||
pDirector->setAnimationInterval(1.0 / 60);
|
||||
|
||||
ScriptingCore* sc = ScriptingCore::getInstance();
|
||||
sc->addRegisterCallback(register_all_cocos2dx);
|
||||
sc->addRegisterCallback(register_cocos2dx_js_extensions);
|
||||
|
||||
sc->start();
|
||||
|
||||
CCScriptEngineProtocol *pEngine = ScriptingCore::getInstance();
|
||||
CCScriptEngineManager::sharedManager()->setScriptEngine(pEngine);
|
||||
ScriptingCore::getInstance()->runScript("js/MoonWarriors-native.js");
|
||||
return true;
|
||||
}
|
||||
|
||||
void handle_signal(int signal) {
|
||||
static int internal_state = 0;
|
||||
ScriptingCore* sc = ScriptingCore::getInstance();
|
||||
// should start everything back
|
||||
CCDirector* director = CCDirector::sharedDirector();
|
||||
if (director->getRunningScene()) {
|
||||
director->popToRootScene();
|
||||
} else {
|
||||
CCPoolManager::sharedPoolManager()->finalize();
|
||||
if (internal_state == 0) {
|
||||
//sc->dumpRoot(NULL, 0, NULL);
|
||||
sc->start();
|
||||
internal_state = 1;
|
||||
} else {
|
||||
sc->runScript("hello.js");
|
||||
internal_state = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// This function will be called when the app is inactive. When comes a phone call,it's be invoked too
|
||||
void AppDelegate::applicationDidEnterBackground()
|
||||
{
|
||||
CCDirector::sharedDirector()->stopAnimation();
|
||||
SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
|
||||
SimpleAudioEngine::sharedEngine()->pauseAllEffects();
|
||||
}
|
||||
|
||||
// this function will be called when the app is active again
|
||||
void AppDelegate::applicationWillEnterForeground()
|
||||
{
|
||||
CCDirector::sharedDirector()->startAnimation();
|
||||
SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();
|
||||
SimpleAudioEngine::sharedEngine()->resumeAllEffects();
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
//
|
||||
// GCTestAppDelegate.h
|
||||
// GCTest
|
||||
//
|
||||
// Created by Rohan Kuruvilla on 06/08/2012.
|
||||
// Copyright __MyCompanyName__ 2012. All rights reserved.
|
||||
//
|
||||
|
||||
#ifndef _APP_DELEGATE_H_
|
||||
#define _APP_DELEGATE_H_
|
||||
|
||||
#include "CCApplication.h"
|
||||
/**
|
||||
@brief The cocos2d Application.
|
||||
|
||||
The reason for implement as private inheritance is to hide some interface call by CCDirector.
|
||||
*/
|
||||
class AppDelegate : private cocos2d::CCApplication
|
||||
{
|
||||
public:
|
||||
AppDelegate();
|
||||
virtual ~AppDelegate();
|
||||
|
||||
/**
|
||||
@brief Implement CCDirector and CCScene init code here.
|
||||
@return true Initialize success, app continue.
|
||||
@return false Initialize failed, app terminate.
|
||||
*/
|
||||
virtual bool applicationDidFinishLaunching();
|
||||
|
||||
/**
|
||||
@brief The function be called when the application enter background
|
||||
@param the pointer of the application
|
||||
*/
|
||||
virtual void applicationDidEnterBackground();
|
||||
|
||||
/**
|
||||
@brief The function be called when the application enter foreground
|
||||
@param the pointer of the application
|
||||
*/
|
||||
virtual void applicationWillEnterForeground();
|
||||
};
|
||||
|
||||
#endif // _APP_DELEGATE_H_
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
var AboutLayer = cc.Layer.extend({
|
||||
ctor:function () {
|
||||
cc.associateWithNative( this, cc.Layer );
|
||||
},
|
||||
init:function () {
|
||||
var bRet = false;
|
||||
if (this._super()) {
|
||||
var sp = cc.Sprite.create(s_loading);
|
||||
sp.setAnchorPoint(cc.p(0,0));
|
||||
this.addChild(sp, 0, 1);
|
||||
|
||||
var cacheImage = cc.TextureCache.getInstance().addImage(s_menuTitle);
|
||||
var title = cc.Sprite.createWithTexture(cacheImage, cc.rect(0, 36, 100, 34));
|
||||
title.setPosition(cc.p(winSize.width / 2, winSize.height - 60));
|
||||
this.addChild(title);
|
||||
|
||||
// There is a bug in LabelTTF native. Apparently it fails with some unicode chars.
|
||||
// var about = cc.LabelTTF.create(" This showcase utilizes many features from Cocos2d-html5 engine, including: Parallax background, tilemap, actions, ease, frame animation, schedule, Labels, keyboard Dispatcher, Scene Transition. \n Art and audio is copyrighted by Enigmata Genus Revenge, you may not use any copyrigted material without permission. This showcase is licensed under GPL. \n \n Programmer: \n Shengxiang Chen (陈升想) \n Dingping Lv (吕定平) \n Effects animation: Hao Wu(吴昊)\n Quality Assurance: Sean Lin(林顺)", "Arial", 14, cc.size(winSize.width * 0.85, 100), cc.TEXT_ALIGNMENT_LEFT );
|
||||
var about = cc.LabelTTF.create(" This showcase utilizes many features from Cocos2d-html5 engine, including: Parallax background, tilemap, actions, ease, frame animation, schedule, Labels, keyboard Dispatcher, Scene Transition. \n Art and audio is copyrighted by Enigmata Genus Revenge, you may not use any copyrigted material without permission. This showcase is licensed under GPL. \n\nProgrammer: \n Shengxiang Chen\n Dingping Lv \n Effects animation: Hao Wu\n Quality Assurance: Sean Lin", "Arial", 14, cc.size(winSize.width * 0.85, 320), cc.TEXT_ALIGNMENT_LEFT );
|
||||
about.setPosition(cc.p(winSize.width / 2, winSize.height/2 -20) );
|
||||
about.setAnchorPoint( cc.p(0.5, 0.5));
|
||||
this.addChild(about);
|
||||
|
||||
var label = cc.LabelTTF.create("Go back", "Arial", 14);
|
||||
var back = cc.MenuItemLabel.create(label, this, this.backCallback);
|
||||
var menu = cc.Menu.create(back);
|
||||
menu.setPosition(cc.p(winSize.width / 2, 40));
|
||||
this.addChild(menu);
|
||||
bRet = true;
|
||||
}
|
||||
|
||||
return bRet;
|
||||
},
|
||||
backCallback:function (pSender) {
|
||||
var scene = cc.Scene.create();
|
||||
scene.addChild(SysMenu.create());
|
||||
cc.Director.getInstance().replaceScene(cc.TransitionFade.create(1.2, scene));
|
||||
}
|
||||
});
|
||||
|
||||
AboutLayer.create = function () {
|
||||
var sg = new AboutLayer();
|
||||
if (sg && sg.init()) {
|
||||
return sg;
|
||||
}
|
||||
return null;
|
||||
};
|
|
@ -0,0 +1,62 @@
|
|||
//bullet
|
||||
var Bullet = cc.Sprite.extend({
|
||||
active:true,
|
||||
xVelocity:0,
|
||||
yVelocity:200,
|
||||
power:1,
|
||||
HP:1,
|
||||
moveType:null,
|
||||
zOrder:3000,
|
||||
attackMode:MW.ENEMY_MOVE_TYPE.NORMAL,
|
||||
parentType:MW.BULLET_TYPE.PLAYER,
|
||||
ctor:function (bulletSpeed, weaponType, attackMode) {
|
||||
// needed for JS-Bindings compatibility
|
||||
cc.associateWithNative( this, cc.Sprite );
|
||||
|
||||
this.yVelocity = -bulletSpeed;
|
||||
this.attackMode = attackMode;
|
||||
cc.SpriteFrameCache.getInstance().addSpriteFrames(s_bullet_plist);
|
||||
this.initWithSpriteFrameName(weaponType);
|
||||
this.setBlendFunc(gl.SRC_ALPHA, gl.ONE);
|
||||
/*var tmpAction;
|
||||
switch (this.attackMode) {
|
||||
case MW.ENEMY_MOVE_TYPE.NORMAL:
|
||||
tmpAction = cc.MoveBy.create(2, cc.p(this.getPosition().x, 400));
|
||||
break;
|
||||
case MW.ENEMY_ATTACK_MODE.TSUIHIKIDAN:
|
||||
tmpAction = cc.MoveTo.create(2, GameLayer.create()._ship.getPosition());
|
||||
break;
|
||||
}
|
||||
this.runAction(tmpAction);*/
|
||||
},
|
||||
update:function (dt) {
|
||||
var p = this.getPosition();
|
||||
p.x -= this.xVelocity * dt;
|
||||
p.y -= this.yVelocity * dt;
|
||||
this.setPosition( p );
|
||||
if (this.HP <= 0) {
|
||||
this.active = false;
|
||||
}
|
||||
},
|
||||
destroy:function () {
|
||||
var explode = cc.Sprite.create(s_hit);
|
||||
explode.setBlendFunc(gl.SRC_ALPHA, gl.ONE);
|
||||
explode.setPosition(this.getPosition());
|
||||
explode.setRotation(Math.random()*360);
|
||||
explode.setScale(0.75);
|
||||
this.getParent().addChild(explode,9999);
|
||||
cc.ArrayRemoveObject(MW.CONTAINER.ENEMY_BULLETS,this);
|
||||
cc.ArrayRemoveObject(MW.CONTAINER.PLAYER_BULLETS,this);
|
||||
this.removeFromParentAndCleanup(true);
|
||||
var removeExplode = cc.CallFunc.create(explode,explode.removeFromParentAndCleanup);
|
||||
explode.runAction(cc.ScaleBy.create(0.3, 2,2));
|
||||
explode.runAction(cc.Sequence.create(cc.FadeOut.create(0.3), removeExplode));
|
||||
},
|
||||
hurt:function () {
|
||||
this.HP--;
|
||||
},
|
||||
collideRect:function(){
|
||||
var p = this.getPosition();
|
||||
return cc.rect(p.x - 3, p.y - 3, 6, 6);
|
||||
}
|
||||
});
|
|
@ -0,0 +1,78 @@
|
|||
var flareEffect = function (parent, target, callback) {
|
||||
var flare = cc.Sprite.create(s_flare);
|
||||
flare.setBlendFunc(gl.SRC_ALPHA, gl.ONE);
|
||||
parent.addChild(flare, 10);
|
||||
flare.setOpacity(0);
|
||||
flare.setPosition(cc.p(-30, 297));
|
||||
flare.setRotation(-120);
|
||||
flare.setScale(0.2);
|
||||
|
||||
var opacityAnim = cc.FadeTo.create(0.5, 255);
|
||||
var opacDim = cc.FadeTo.create(1, 0);
|
||||
var biggeAnim = cc.ScaleBy.create(0.7, 1.2, 1.2);
|
||||
var biggerEase = cc.EaseSineOut.create(biggeAnim);
|
||||
var moveAnim = cc.MoveBy.create(0.5, cc.p(328, 0));
|
||||
var easeMove = cc.EaseSineOut.create(moveAnim);
|
||||
var rotateAnim = cc.RotateBy.create(2.5, 90);
|
||||
var rotateEase = cc.EaseExponentialOut.create(rotateAnim);
|
||||
var bigger = cc.ScaleTo.create(0.5, 1);
|
||||
|
||||
var onComplete = cc.CallFunc.create(target, callback);
|
||||
var killflare = cc.CallFunc.create(flare, function () {
|
||||
this.getParent().removeChild(this,true);
|
||||
});
|
||||
flare.runAction(cc.Sequence.create(opacityAnim, biggerEase, opacDim, killflare, onComplete));
|
||||
flare.runAction(easeMove);
|
||||
flare.runAction(rotateEase);
|
||||
flare.runAction(bigger);
|
||||
};
|
||||
|
||||
var removeFromParent = function( sprite )
|
||||
{
|
||||
sprite.removeFromParentAndCleanup( true );
|
||||
};
|
||||
|
||||
var spark = function (ccpoint, parent, scale, duration) {
|
||||
scale = scale || 0.3;
|
||||
duration = duration || 0.5;
|
||||
|
||||
var one = cc.Sprite.create(s_explode1);
|
||||
var two = cc.Sprite.create(s_explode2);
|
||||
var three = cc.Sprite.create(s_explode3);
|
||||
|
||||
one.setBlendFunc(gl.SRC_ALPHA, gl.ONE);
|
||||
two.setBlendFunc(gl.SRC_ALPHA, gl.ONE);
|
||||
three.setBlendFunc(gl.SRC_ALPHA, gl.ONE);
|
||||
|
||||
one.setPosition(ccpoint);
|
||||
two.setPosition(ccpoint);
|
||||
three.setPosition(ccpoint);
|
||||
|
||||
//parent.addChild(one);
|
||||
parent.addChild(two);
|
||||
parent.addChild(three);
|
||||
one.setScale(scale);
|
||||
two.setScale(scale);
|
||||
three.setScale(scale);
|
||||
|
||||
three.setRotation(Math.random() * 360);
|
||||
|
||||
var left = cc.RotateBy.create(duration, -45);
|
||||
var right = cc.RotateBy.create(duration, 45);
|
||||
var scaleBy = cc.ScaleBy.create(duration, 3, 3);
|
||||
var fadeOut = cc.FadeOut.create(duration);
|
||||
var remove = cc.CallFunc.create(this, removeFromParent );
|
||||
var seq = cc.Sequence.create( fadeOut, remove );
|
||||
|
||||
one.runAction(left);
|
||||
two.runAction(right);
|
||||
|
||||
one.runAction(scaleBy);
|
||||
two.runAction(scaleBy.copy());
|
||||
three.runAction(scaleBy.copy());
|
||||
|
||||
one.runAction(seq);
|
||||
two.runAction(seq.copy() );
|
||||
three.runAction(seq.copy());
|
||||
};
|
||||
|
|
@ -0,0 +1,75 @@
|
|||
var Enemy = cc.Sprite.extend({
|
||||
eID:0,
|
||||
active:true,
|
||||
speed:200,
|
||||
bulletSpeed:-200,
|
||||
HP:15,
|
||||
bulletPowerValue:1,
|
||||
moveType:null,
|
||||
scoreValue:200,
|
||||
zOrder:1000,
|
||||
delayTime:1 + 1.2 * Math.random(),
|
||||
attackMode:MW.ENEMY_MOVE_TYPE.NORMAL,
|
||||
_hurtColorLife:0,
|
||||
ctor:function (arg) {
|
||||
// needed for JS-Bindings compatibility
|
||||
cc.associateWithNative( this, cc.Sprite );
|
||||
|
||||
this.HP = arg.HP;
|
||||
this.moveType = arg.moveType;
|
||||
this.scoreValue = arg.scoreValue;
|
||||
this.attackMode = arg.attackMode;
|
||||
|
||||
this.initWithSpriteFrameName(arg.textureName);
|
||||
this.schedule(this.shoot, this.delayTime);
|
||||
},
|
||||
_timeTick:0,
|
||||
update:function (dt) {
|
||||
if (this.HP <= 0) {
|
||||
this.active = false;
|
||||
}
|
||||
this._timeTick += dt;
|
||||
if (this._timeTick > 0.1) {
|
||||
this._timeTick = 0;
|
||||
if (this._hurtColorLife > 0) {
|
||||
this._hurtColorLife--;
|
||||
}
|
||||
if (this._hurtColorLife == 1) {
|
||||
this.setColor( cc.WHITE );
|
||||
}
|
||||
}
|
||||
},
|
||||
destroy:function () {
|
||||
MW.SCORE += this.scoreValue;
|
||||
var a = new Explosion();
|
||||
a.setPosition(this.getPosition());
|
||||
this.getParent().addChild(a);
|
||||
spark(this.getPosition(),this.getParent(), 1.2, 0.7);
|
||||
cc.ArrayRemoveObject(MW.CONTAINER.ENEMIES,this);
|
||||
this.removeFromParentAndCleanup(true);
|
||||
if(MW.SOUND){
|
||||
cc.AudioEngine.getInstance().playEffect(s_explodeEffect);
|
||||
}
|
||||
},
|
||||
shoot:function () {
|
||||
var p = this.getPosition();
|
||||
var b = new Bullet(this.bulletSpeed, "W2.png", this.attackMode);
|
||||
MW.CONTAINER.ENEMY_BULLETS.push(b);
|
||||
this.getParent().addChild(b, b.zOrder, MW.UNIT_TAG.ENMEY_BULLET);
|
||||
b.setPosition(cc.p(p.x, p.y - this.getContentSize().height * 0.2));
|
||||
},
|
||||
hurt:function () {
|
||||
this._hurtColorLife = 2;
|
||||
this.HP--;
|
||||
this.setColor( cc.RED );
|
||||
},
|
||||
collideRect:function(){
|
||||
var a = this.getContentSize();
|
||||
var p = this.getPosition();
|
||||
return cc.rect(p.x - a.width/2, p.y - a.height/4,a.width,a.height/2);
|
||||
}
|
||||
});
|
||||
|
||||
Enemy.sharedEnemy = function(){
|
||||
cc.SpriteFrameCache.getInstance().addSpriteFrames(s_Enemy_plist, s_Enemy);
|
||||
};
|
|
@ -0,0 +1,38 @@
|
|||
var Explosion = cc.Sprite.extend({
|
||||
tmpWidth:0,
|
||||
tmpHeight:0,
|
||||
ctor:function () {
|
||||
// needed for JS-Bindings compatibility
|
||||
cc.associateWithNative( this, cc.Sprite );
|
||||
|
||||
var pFrame = cc.SpriteFrameCache.getInstance().getSpriteFrame("explosion_01.png");
|
||||
this.initWithSpriteFrame(pFrame);
|
||||
|
||||
var cs = this.getContentSize();
|
||||
this.tmpWidth = cs.width;
|
||||
this.tmpHeight = cs.height;
|
||||
|
||||
var animation = cc.AnimationCache.getInstance().getAnimation("Explosion");
|
||||
this.runAction(cc.Sequence.create(
|
||||
cc.Animate.create(animation),
|
||||
cc.CallFunc.create(this, this.destroy)
|
||||
));
|
||||
this.setBlendFunc(gl.SRC_ALPHA, gl.ONE);
|
||||
},
|
||||
destroy:function () {
|
||||
this.getParent().removeChild(this,true);
|
||||
}
|
||||
});
|
||||
|
||||
Explosion.sharedExplosion = function () {
|
||||
cc.SpriteFrameCache.getInstance().addSpriteFrames(s_explosion_plist);
|
||||
var animFrames = [];
|
||||
var str = "";
|
||||
for (var i = 1; i < 35; i++) {
|
||||
str = "explosion_" + (i < 10 ? ("0" + i) : i) + ".png";
|
||||
var frame = cc.SpriteFrameCache.getInstance().getSpriteFrame(str);
|
||||
animFrames.push(frame);
|
||||
}
|
||||
var animation = cc.Animation.create(animFrames, 0.04);
|
||||
cc.AnimationCache.getInstance().addAnimation(animation, "Explosion");
|
||||
};
|
|
@ -0,0 +1,35 @@
|
|||
var GameControlMenu = cc.Layer.extend({
|
||||
ctor:function() {
|
||||
// needed for JS-Bindings compatibility
|
||||
cc.associateWithNative( this, cc.Layer);
|
||||
},
|
||||
init:function () {
|
||||
var bRet = false;
|
||||
if (this._super()) {
|
||||
cc.MenuItemFont.setFontSize(18);
|
||||
cc.MenuItemFont.setFontName("Arial");
|
||||
var systemMenu = cc.MenuItemFont.create("Main Menu", this, this.sysMenu);
|
||||
var menu = cc.Menu.create(systemMenu);
|
||||
menu.setPosition(cc.p(0, 0));
|
||||
systemMenu.setAnchorPoint(cc.p(0, 0));
|
||||
systemMenu.setPosition(cc.p(winSize.width-95, 5));
|
||||
this.addChild(menu, 1, 2);
|
||||
bRet = true;
|
||||
}
|
||||
|
||||
return bRet;
|
||||
},
|
||||
sysMenu:function (pSender) {
|
||||
var scene = cc.Scene.create();
|
||||
scene.addChild(SysMenu.create());
|
||||
cc.Director.getInstance().replaceScene(cc.TransitionFade.create(1.2,scene));
|
||||
}
|
||||
});
|
||||
|
||||
GameControlMenu.create = function () {
|
||||
var sg = new GameControlMenu();
|
||||
if (sg && sg.init()) {
|
||||
return sg;
|
||||
}
|
||||
return null;
|
||||
};
|
|
@ -0,0 +1,70 @@
|
|||
/**
|
||||
* Cocos2d-html5 show case : Moon Warriors
|
||||
*
|
||||
* @Licensed:
|
||||
* This showcase is licensed under GPL.
|
||||
*
|
||||
* @Authors:
|
||||
* Programmer: Shengxiang Chen (陈升想), Dingping Lv (吕定平), Ricardo Quesada
|
||||
* Effects animation: Hao Wu (吴昊)
|
||||
* Quality Assurance: Sean Lin (林顺)
|
||||
*
|
||||
* @Links:
|
||||
* http://www.cocos2d-x.org
|
||||
* http://bbs.html5china.com
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
MW.GameController = cc.Class.extend({
|
||||
_curScene:null,
|
||||
_gameState:MW.GAME_STATE.HOME,
|
||||
_isNewGame:true,
|
||||
_curLevel:MW.LEVEL.STAGE1,
|
||||
_selectLevel:MW.LEVEL.STAGE1,
|
||||
init:function () {
|
||||
return true;
|
||||
},
|
||||
setCurScene:function (s) {
|
||||
if (this._curScene != s) {
|
||||
if (this._curScene !== null) {
|
||||
this._curScene.onExit();
|
||||
}
|
||||
this._curScene = s;
|
||||
if (this._curScene) {
|
||||
this._curScene.onEnter();
|
||||
cc.Director.getInstance().replaceScene(s);
|
||||
}
|
||||
}
|
||||
},
|
||||
getCurScene:function () {
|
||||
return this._curScene;
|
||||
},
|
||||
runGame:function () {
|
||||
|
||||
},
|
||||
newGame:function () {
|
||||
|
||||
},
|
||||
option:function () {
|
||||
|
||||
},
|
||||
about:function () {
|
||||
|
||||
}
|
||||
});
|
||||
|
||||
MW.GameController.getInstance = function () {
|
||||
cc.Assert(this._sharedGame, "Havn't call setSharedGame");
|
||||
if (!this._sharedGame) {
|
||||
this._sharedGame = new MW.GameController();
|
||||
if (this._sharedGame.init()) {
|
||||
return this._sharedGame;
|
||||
}
|
||||
} else {
|
||||
return this._sharedGame;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
MW.GameController._sharedGame = null;
|
|
@ -0,0 +1,315 @@
|
|||
//
|
||||
// MoonWarriors
|
||||
//
|
||||
// Handles the Game Logic
|
||||
//
|
||||
|
||||
STATE_PLAYING = 0;
|
||||
STATE_GAMEOVER = 1;
|
||||
|
||||
var GameLayer = cc.Layer.extend({
|
||||
_time:null,
|
||||
_ship:null,
|
||||
_backSky:null,
|
||||
_backSkyHeight:0,
|
||||
_backSkyRe:null,
|
||||
_backTileMap:null,
|
||||
_backTileMapHeight:0,
|
||||
_backTileMapRe:null,
|
||||
_levelManager:null,
|
||||
_tmpScore:0,
|
||||
_isBackSkyReload:false,
|
||||
_isBackTileReload:false,
|
||||
lbScore:null,
|
||||
screenRect:null,
|
||||
explosionAnimation:[],
|
||||
_beginPos:cc.p(0, 0),
|
||||
_state:STATE_PLAYING,
|
||||
ctor:function () {
|
||||
cc.associateWithNative( this, cc.Layer );
|
||||
},
|
||||
init:function () {
|
||||
var bRet = false;
|
||||
if (this._super()) {
|
||||
|
||||
// reset global values
|
||||
MW.CONTAINER.ENEMIES = [];
|
||||
MW.CONTAINER.ENEMY_BULLETS = [];
|
||||
MW.CONTAINER.PLAYER_BULLETS = [];
|
||||
MW.SCORE = 0;
|
||||
MW.LIFE = 4;
|
||||
this._state = STATE_PLAYING;
|
||||
|
||||
Explosion.sharedExplosion();
|
||||
Enemy.sharedEnemy();
|
||||
winSize = cc.Director.getInstance().getWinSize();
|
||||
this._levelManager = new LevelManager(this);
|
||||
this.initBackground();
|
||||
this.screenRect = cc.rect(0, 0, winSize.width, winSize.height + 10);
|
||||
|
||||
// score
|
||||
this.lbScore = cc.LabelBMFont.create("Score: 0", s_arial14_fnt);
|
||||
this.lbScore.setAnchorPoint( cc.p(1,0) );
|
||||
this.lbScore.setAlignment( cc.TEXT_ALIGNMENT_RIGHT );
|
||||
this.addChild(this.lbScore, 1000);
|
||||
this.lbScore.setPosition(cc.p(winSize.width - 5 , winSize.height - 30));
|
||||
|
||||
// ship life
|
||||
var shipTexture = cc.TextureCache.getInstance().addImage(s_ship01);
|
||||
var life = cc.Sprite.createWithTexture(shipTexture, cc.rect(0, 0, 60, 38));
|
||||
life.setScale(0.6);
|
||||
life.setPosition(cc.p(30, 460));
|
||||
this.addChild(life, 1, 5);
|
||||
|
||||
// ship Life count
|
||||
this._lbLife = cc.LabelTTF.create("0", "Arial", 20);
|
||||
this._lbLife.setPosition(cc.p(60, 463));
|
||||
this._lbLife.setColor(cc.RED);
|
||||
this.addChild(this._lbLife, 1000);
|
||||
|
||||
// ship
|
||||
this._ship = new Ship();
|
||||
this.addChild(this._ship, this._ship.zOrder, MW.UNIT_TAG.PLAYER);
|
||||
|
||||
// accept touch now!
|
||||
|
||||
var t = cc.config.deviceType;
|
||||
if( t == 'browser' ) {
|
||||
this.setTouchEnabled(true);
|
||||
this.setKeyboardEnabled(true);
|
||||
} else if( t == 'desktop' ) {
|
||||
this.setMouseEnabled(true);
|
||||
} else if( t == 'mobile' ) {
|
||||
this.setTouchEnabled(true);
|
||||
}
|
||||
|
||||
// schedule
|
||||
this.scheduleUpdate();
|
||||
this.schedule(this.scoreCounter, 1);
|
||||
|
||||
if (MW.SOUND) {
|
||||
cc.AudioEngine.getInstance().playBackgroundMusic(s_bgMusic, true);
|
||||
}
|
||||
|
||||
bRet = true;
|
||||
}
|
||||
return bRet;
|
||||
},
|
||||
scoreCounter:function () {
|
||||
if( this._state == STATE_PLAYING ) {
|
||||
this._time++;
|
||||
|
||||
var minute = 0 | (this._time / 60);
|
||||
var second = this._time % 60;
|
||||
minute = minute > 9 ? minute : "0" + minute;
|
||||
second = second > 9 ? second : "0" + second;
|
||||
var curTime = minute + ":" + second;
|
||||
this._levelManager.loadLevelResource(this._time);
|
||||
}
|
||||
},
|
||||
|
||||
onTouchesMoved:function (touches, event) {
|
||||
this.processEvent( touches[0] );
|
||||
},
|
||||
|
||||
onMouseDragged:function( event ) {
|
||||
this.processEvent( event );
|
||||
},
|
||||
|
||||
processEvent:function( event ) {
|
||||
if( this._state == STATE_PLAYING ) {
|
||||
var delta = event.getDelta();
|
||||
var curPos = this._ship.getPosition();
|
||||
curPos= cc.pAdd( curPos, delta );
|
||||
curPos = cc.pClamp(curPos, cc.POINT_ZERO, cc.p(winSize.width, winSize.height) );
|
||||
this._ship.setPosition( curPos );
|
||||
}
|
||||
},
|
||||
|
||||
onKeyDown:function (e) {
|
||||
MW.KEYS[e] = true;
|
||||
},
|
||||
|
||||
onKeyUp:function (e) {
|
||||
MW.KEYS[e] = false;
|
||||
},
|
||||
|
||||
update:function (dt) {
|
||||
if( this._state == STATE_PLAYING ) {
|
||||
this.checkIsCollide();
|
||||
this.removeInactiveUnit(dt);
|
||||
this.checkIsReborn();
|
||||
this.updateUI();
|
||||
}
|
||||
|
||||
if( cc.config.deviceType == 'browser' )
|
||||
cc.$("#cou").innerHTML = "Ship:" + 1 + ", Enemy: " + MW.CONTAINER.ENEMIES.length + ", Bullet:" + MW.CONTAINER.ENEMY_BULLETS.length + "," + MW.CONTAINER.PLAYER_BULLETS.length + " all:" + this.getChildren().length;
|
||||
},
|
||||
checkIsCollide:function () {
|
||||
var selChild, bulletChild;
|
||||
//check collide
|
||||
var i =0;
|
||||
for (i = 0; i < MW.CONTAINER.ENEMIES.length; i++) {
|
||||
selChild = MW.CONTAINER.ENEMIES[i];
|
||||
for (var j = 0; j < MW.CONTAINER.PLAYER_BULLETS.length; j++) {
|
||||
bulletChild = MW.CONTAINER.PLAYER_BULLETS[j];
|
||||
if (this.collide(selChild, bulletChild)) {
|
||||
bulletChild.hurt();
|
||||
selChild.hurt();
|
||||
}
|
||||
if (!cc.rectIntersectsRect(this.screenRect, bulletChild.getBoundingBox() )) {
|
||||
bulletChild.destroy();
|
||||
}
|
||||
}
|
||||
if (this.collide(selChild, this._ship)) {
|
||||
if (this._ship.active) {
|
||||
selChild.hurt();
|
||||
this._ship.hurt();
|
||||
}
|
||||
}
|
||||
if (!cc.rectIntersectsRect(this.screenRect, selChild.getBoundingBox() )) {
|
||||
selChild.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
for (i = 0; i < MW.CONTAINER.ENEMY_BULLETS.length; i++) {
|
||||
selChild = MW.CONTAINER.ENEMY_BULLETS[i];
|
||||
if (this.collide(selChild, this._ship)) {
|
||||
if (this._ship.active) {
|
||||
selChild.hurt();
|
||||
this._ship.hurt();
|
||||
}
|
||||
}
|
||||
if (!cc.rectIntersectsRect(this.screenRect, selChild.getBoundingBox() )) {
|
||||
selChild.destroy();
|
||||
}
|
||||
}
|
||||
},
|
||||
removeInactiveUnit:function (dt) {
|
||||
var selChild, layerChildren = this.getChildren();
|
||||
for (var i in layerChildren) {
|
||||
selChild = layerChildren[i];
|
||||
if (selChild) {
|
||||
if( typeof selChild.update == 'function' ) {
|
||||
selChild.update(dt);
|
||||
var tag = selChild.getTag();
|
||||
if ((tag == MW.UNIT_TAG.PLAYER) || (tag == MW.UNIT_TAG.PLAYER_BULLET) ||
|
||||
(tag == MW.UNIT_TAG.ENEMY) || (tag == MW.UNIT_TAG.ENMEY_BULLET)) {
|
||||
if (selChild && !selChild.active) {
|
||||
selChild.destroy();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
checkIsReborn:function () {
|
||||
if (MW.LIFE > 0 && !this._ship.active) {
|
||||
// ship
|
||||
this._ship = new Ship();
|
||||
this.addChild(this._ship, this._ship.zOrder, MW.UNIT_TAG.PLAYER);
|
||||
}
|
||||
else if (MW.LIFE <= 0 && !this._ship.active) {
|
||||
this._state = STATE_GAMEOVER;
|
||||
// XXX: needed for JS bindings.
|
||||
this._ship = null;
|
||||
this.runAction(cc.Sequence.create(
|
||||
cc.DelayTime.create(0.2),
|
||||
cc.CallFunc.create(this, this.onGameOver)));
|
||||
}
|
||||
},
|
||||
updateUI:function () {
|
||||
if (this._tmpScore < MW.SCORE) {
|
||||
this._tmpScore += 5;
|
||||
}
|
||||
this._lbLife.setString(MW.LIFE);
|
||||
this.lbScore.setString("Score: " + this._tmpScore);
|
||||
},
|
||||
collide:function (a, b) {
|
||||
var aRect = a.collideRect();
|
||||
var bRect = b.collideRect();
|
||||
if (cc.rectIntersectsRect(aRect, bRect)) {
|
||||
return true;
|
||||
}
|
||||
},
|
||||
initBackground:function () {
|
||||
// bg
|
||||
this._backSky = cc.Sprite.create(s_bg01);
|
||||
this._backSky.setAnchorPoint(cc.p(0, 0));
|
||||
this._backSkyHeight = this._backSky.getContentSize().height;
|
||||
this.addChild(this._backSky, -10);
|
||||
|
||||
//tilemap
|
||||
this._backTileMap = cc.TMXTiledMap.create(s_level01);
|
||||
this.addChild(this._backTileMap, -9);
|
||||
this._backTileMapHeight = this._backTileMap.getMapSize().height * this._backTileMap.getTileSize().height;
|
||||
|
||||
this._backSkyHeight -= 48;
|
||||
this._backTileMapHeight -= 200;
|
||||
this._backSky.runAction(cc.MoveBy.create(3, cc.p(0, -48)));
|
||||
this._backTileMap.runAction(cc.MoveBy.create(3, cc.p(0, -200)));
|
||||
|
||||
this.schedule(this.movingBackground, 3);
|
||||
},
|
||||
movingBackground:function () {
|
||||
this._backSky.runAction(cc.MoveBy.create(3, cc.p(0, -48)));
|
||||
this._backTileMap.runAction(cc.MoveBy.create(3, cc.p(0, -200)));
|
||||
this._backSkyHeight -= 48;
|
||||
this._backTileMapHeight -= 200;
|
||||
|
||||
if (this._backSkyHeight <= winSize.height) {
|
||||
if (!this._isBackSkyReload) {
|
||||
this._backSkyRe = cc.Sprite.create(s_bg01);
|
||||
this._backSkyRe.setAnchorPoint(cc.p(0, 0));
|
||||
this.addChild(this._backSkyRe, -10);
|
||||
this._backSkyRe.setPosition(cc.p(0, winSize.height));
|
||||
this._isBackSkyReload = true;
|
||||
}
|
||||
this._backSkyRe.runAction(cc.MoveBy.create(3, cc.p(0, -48)));
|
||||
}
|
||||
if (this._backSkyHeight <= 0) {
|
||||
this._backSkyHeight = this._backSky.getContentSize().height;
|
||||
this.removeChild(this._backSky, true);
|
||||
this._backSky = this._backSkyRe;
|
||||
this._backSkyRe = null;
|
||||
this._isBackSkyReload = false;
|
||||
}
|
||||
|
||||
if (this._backTileMapHeight <= winSize.height) {
|
||||
if (!this._isBackTileReload) {
|
||||
this._backTileMapRe = cc.TMXTiledMap.create(s_level01);
|
||||
this.addChild(this._backTileMapRe, -9);
|
||||
this._backTileMapRe.setPosition(cc.p(0, winSize.height));
|
||||
this._isBackTileReload = true;
|
||||
}
|
||||
this._backTileMapRe.runAction(cc.MoveBy.create(3, cc.p(0, -200)));
|
||||
}
|
||||
if (this._backTileMapHeight <= 0) {
|
||||
this._backTileMapHeight = this._backTileMapRe.getMapSize().height * this._backTileMapRe.getTileSize().height;
|
||||
this.removeChild(this._backTileMap, true);
|
||||
this._backTileMap = this._backTileMapRe;
|
||||
this._backTileMapRe = null;
|
||||
this._isBackTileReload = false;
|
||||
}
|
||||
},
|
||||
onGameOver:function () {
|
||||
var scene = cc.Scene.create();
|
||||
scene.addChild(GameOver.create());
|
||||
cc.Director.getInstance().replaceScene(cc.TransitionFade.create(1.2, scene));
|
||||
}
|
||||
});
|
||||
|
||||
GameLayer.create = function () {
|
||||
var sg = new GameLayer();
|
||||
if (sg && sg.init()) {
|
||||
return sg;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
GameLayer.scene = function () {
|
||||
var scene = cc.Scene.create();
|
||||
var layer = GameLayer.create();
|
||||
scene.addChild(layer, 1);
|
||||
return scene;
|
||||
};
|
|
@ -0,0 +1,83 @@
|
|||
var GameOver = cc.Layer.extend({
|
||||
_ship:null,
|
||||
_lbScore:0,
|
||||
ctor:function() {
|
||||
// needed for JS-Bindings compatibility
|
||||
cc.associateWithNative( this, cc.Layer);
|
||||
},
|
||||
init:function () {
|
||||
var bRet = false;
|
||||
if (this._super()) {
|
||||
var sp = cc.Sprite.create(s_loading);
|
||||
sp.setAnchorPoint( cc.p(0,0) );
|
||||
this.addChild(sp, 0, 1);
|
||||
|
||||
var logo = cc.Sprite.create(s_gameOver);
|
||||
logo.setAnchorPoint(cc.p(0,0));
|
||||
logo.setPosition(cc.p(0,300));
|
||||
this.addChild(logo,10,1);
|
||||
|
||||
var playAgainNormal = cc.Sprite.create(s_menu, cc.rect(378, 0, 126, 33));
|
||||
var playAgainSelected = cc.Sprite.create(s_menu, cc.rect(378, 33, 126, 33));
|
||||
var playAgainDisabled = cc.Sprite.create(s_menu, cc.rect(378, 33 * 2, 126, 33));
|
||||
|
||||
var cocos2dhtml5 = cc.Sprite.create(s_cocos2dhtml5);
|
||||
cocos2dhtml5.setPosition(cc.p(160,150));
|
||||
this.addChild(cocos2dhtml5,10);
|
||||
var playAgain = cc.MenuItemSprite.create(playAgainNormal, playAgainSelected, playAgainDisabled, this, function(){
|
||||
flareEffect(this,this,this.onPlayAgain);
|
||||
});
|
||||
|
||||
var menu = cc.Menu.create(playAgain);
|
||||
this.addChild(menu, 1, 2);
|
||||
menu.setPosition(cc.p(winSize.width / 2, 220));
|
||||
|
||||
var lbScore = cc.LabelTTF.create("Your Score:"+MW.SCORE,"Arial Bold",16);
|
||||
lbScore.setPosition(cc.p(160,280));
|
||||
lbScore.setColor(cc.c3b(250,179,0));
|
||||
this.addChild(lbScore,10);
|
||||
|
||||
var b1 = cc.LabelTTF.create("Download Cocos2d-html5","Arial",14);
|
||||
var b2 = cc.LabelTTF.create("Download This Sample","Arial",14);
|
||||
var menu1 = cc.MenuItemLabel.create(b1,this,function(){
|
||||
window.location.href = "http://www.cocos2d-x.org/projects/cocos2d-x/wiki/Cocos2d-html5";
|
||||
});
|
||||
var menu2 = cc.MenuItemLabel.create(b2,this,function(){
|
||||
window.location.href = "https://github.com/ShengxiangChen/MoonWarriors";
|
||||
});
|
||||
var cocos2dMenu = cc.Menu.create(menu1,menu2);
|
||||
cocos2dMenu.alignItemsVerticallyWithPadding(10);
|
||||
cocos2dMenu.setPosition(cc.p(160,80));
|
||||
this.addChild(cocos2dMenu);
|
||||
|
||||
|
||||
if(MW.SOUND){
|
||||
cc.AudioEngine.getInstance().playBackgroundMusic(s_mainMainMusic);
|
||||
}
|
||||
|
||||
bRet = true;
|
||||
}
|
||||
return bRet;
|
||||
},
|
||||
onPlayAgain:function (pSender) {
|
||||
var scene = cc.Scene.create();
|
||||
scene.addChild(GameLayer.create());
|
||||
scene.addChild(GameControlMenu.create());
|
||||
cc.Director.getInstance().replaceScene(cc.TransitionFade.create(1.2,scene));
|
||||
}
|
||||
});
|
||||
|
||||
GameOver.create = function () {
|
||||
var sg = new GameOver();
|
||||
if (sg && sg.init()) {
|
||||
return sg;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
GameOver.scene = function () {
|
||||
var scene = cc.Scene.create();
|
||||
var layer = GameOver.create();
|
||||
scene.addChild(layer);
|
||||
return scene;
|
||||
};
|
|
@ -0,0 +1,99 @@
|
|||
var LevelManager = cc.Class.extend({
|
||||
_currentLevel:null,
|
||||
_gameLayer:null,
|
||||
ctor:function(gameLayer){
|
||||
if(!gameLayer){
|
||||
throw "gameLayer must be non-nil";
|
||||
}
|
||||
this._currentLevel = Level1;
|
||||
this._gameLayer = gameLayer;
|
||||
this.setLevel(this._currentLevel);
|
||||
},
|
||||
|
||||
setLevel:function(level){
|
||||
for(var i = 0; i< level.enemies.length; i++){
|
||||
this._currentLevel.enemies[i].ShowTime = this._minuteToSecond(this._currentLevel.enemies[i].ShowTime);
|
||||
}
|
||||
},
|
||||
_minuteToSecond:function(minuteStr){
|
||||
if(!minuteStr)
|
||||
return 0;
|
||||
if(typeof(minuteStr) != "number"){
|
||||
var mins = minuteStr.split(':');
|
||||
if(mins.length == 1){
|
||||
return parseInt(mins[0],10);
|
||||
}else {
|
||||
return parseInt(mins[0],10 )* 60 + parseInt(mins[1],10);
|
||||
}
|
||||
}
|
||||
return minuteStr;
|
||||
},
|
||||
|
||||
loadLevelResource:function(deltaTime){
|
||||
//load enemy
|
||||
for(var i = 0; i< this._currentLevel.enemies.length; i++){
|
||||
var selEnemy = this._currentLevel.enemies[i];
|
||||
if(selEnemy){
|
||||
if(selEnemy.ShowType == "Once"){
|
||||
if(selEnemy.ShowTime == deltaTime){
|
||||
for(var tIndex = 0; tIndex < selEnemy.Types.length;tIndex++ ){
|
||||
this.addEnemyToGameLayer(selEnemy.Types[tIndex]);
|
||||
}
|
||||
}
|
||||
}else if(selEnemy.ShowType == "Repeate"){
|
||||
if(deltaTime % selEnemy.ShowTime === 0){
|
||||
for(var rIndex = 0; rIndex < selEnemy.Types.length;rIndex++ ){
|
||||
this.addEnemyToGameLayer(selEnemy.Types[rIndex]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
addEnemyToGameLayer:function(enemyType){
|
||||
var addEnemy = new Enemy(EnemyType[enemyType]);
|
||||
|
||||
var enemypos = cc.p( 80 + (winSize.width - 160) * Math.random(), winSize.height);
|
||||
var enemycs = addEnemy.getContentSize();
|
||||
addEnemy.setPosition( enemypos );
|
||||
|
||||
|
||||
var offset, tmpAction;
|
||||
var a0=0;
|
||||
var a1=0;
|
||||
switch (addEnemy.moveType) {
|
||||
case MW.ENEMY_MOVE_TYPE.ATTACK:
|
||||
offset = this._gameLayer._ship.getPosition();
|
||||
tmpAction = cc.MoveTo.create(1, offset);
|
||||
break;
|
||||
case MW.ENEMY_MOVE_TYPE.VERTICAL:
|
||||
offset = cc.p(0, -winSize.height - enemycs.height);
|
||||
tmpAction = cc.MoveBy.create(4, offset);
|
||||
break;
|
||||
case MW.ENEMY_MOVE_TYPE.HORIZONTAL:
|
||||
offset = cc.p(0, -100 - 200 * Math.random());
|
||||
a0 = cc.MoveBy.create(0.5, offset);
|
||||
a1 = cc.MoveBy.create(1, cc.p(-50 - 100 * Math.random(), 0));
|
||||
var onComplete = cc.CallFunc.create(addEnemy, function (pSender) {
|
||||
var a2 = cc.DelayTime.create(1);
|
||||
var a3 = cc.MoveBy.create(1, cc.p(100 + 100 * Math.random(), 0));
|
||||
pSender.runAction(cc.RepeatForever.create(
|
||||
cc.Sequence.create(a2, a3, a2.copy(), a3.reverse())
|
||||
));
|
||||
});
|
||||
tmpAction = cc.Sequence.create(a0, a1, onComplete);
|
||||
break;
|
||||
case MW.ENEMY_MOVE_TYPE.OVERLAP:
|
||||
var newX = (enemypos.x <= winSize.width / 2) ? 320 : -320;
|
||||
a0 = cc.MoveBy.create(4, cc.p(newX, -240));
|
||||
a1 = cc.MoveBy.create(4,cc.p(-newX,-320));
|
||||
tmpAction = cc.Sequence.create(a0,a1);
|
||||
break;
|
||||
}
|
||||
|
||||
this._gameLayer.addChild(addEnemy, addEnemy.zOrder, MW.UNIT_TAG.ENEMY);
|
||||
MW.CONTAINER.ENEMIES.push(addEnemy);
|
||||
addEnemy.runAction(tmpAction);
|
||||
}
|
||||
});
|
|
@ -0,0 +1,69 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2010-2012 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.
|
||||
****************************************************************************/
|
||||
|
||||
// boot code needed for cocos2d-html5
|
||||
// Not needed by cocos2d + JS bindings
|
||||
|
||||
var MW = MW || {};
|
||||
|
||||
(function () {
|
||||
var d = document;
|
||||
var c = {
|
||||
menuType:'canvas', //whether to use canvas mode menu or dom menu
|
||||
COCOS2D_DEBUG:2, //0 to turn debug off, 1 for basic debug, and 2 for full debug
|
||||
showFPS:true,
|
||||
frameRate:60,
|
||||
tag:'gameCanvas', //the dom element to run cocos2d on
|
||||
engineDir:'libs/cocos2d/',
|
||||
appFiles:[
|
||||
'MoonWarriors/src/Resource.js',
|
||||
'MoonWarriors/src/config/GameConfig.js',
|
||||
'MoonWarriors/src/config/EnemyType.js',
|
||||
'MoonWarriors/src/config/Level.js',
|
||||
'MoonWarriors/src/Effect.js',
|
||||
'MoonWarriors/src/Bullet.js',
|
||||
'MoonWarriors/src/Enemy.js',
|
||||
'MoonWarriors/src/Explosion.js',
|
||||
'MoonWarriors/src/Ship.js',
|
||||
'MoonWarriors/src/LevelManager.js',
|
||||
'MoonWarriors/src/GameController.js',
|
||||
'MoonWarriors/src/GameControlMenu.js',
|
||||
'MoonWarriors/src/GameLayer.js',
|
||||
'MoonWarriors/src/GameOver.js',
|
||||
'MoonWarriors/src/AboutLayer.js',
|
||||
'MoonWarriors/src/SettingsLayer.js',
|
||||
'MoonWarriors/src/SysMenu.js'
|
||||
]
|
||||
};
|
||||
window.addEventListener('DOMContentLoaded', function () {
|
||||
//first load engine file if specified
|
||||
var s = d.createElement('script');
|
||||
s.src = c.engineDir + 'platform/jsloader.js';
|
||||
d.body.appendChild(s);
|
||||
s.c = c;
|
||||
s.id = 'cocos2d-html5';
|
||||
//else if single file specified, load singlefile
|
||||
});
|
||||
})();
|
|
@ -0,0 +1,69 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2010-2012 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.
|
||||
****************************************************************************/
|
||||
|
||||
// boot code needed for cocos2d + JS bindings.
|
||||
// Not needed by cocos2d-html5
|
||||
|
||||
require("js/helper/jsb_constants.js");
|
||||
|
||||
var MW = MW || {};
|
||||
|
||||
var appFiles = [
|
||||
'js/Resource.js',
|
||||
'js/config/GameConfig.js',
|
||||
'js/config/EnemyType.js',
|
||||
'js/config/Level.js',
|
||||
'js/Effect.js',
|
||||
'js/Bullet.js',
|
||||
'js/Enemy.js',
|
||||
'js/Explosion.js',
|
||||
'js/Ship.js',
|
||||
'js/LevelManager.js',
|
||||
'js/GameControlMenu.js',
|
||||
'js/GameLayer.js',
|
||||
'js/GameOver.js',
|
||||
'js/AboutLayer.js',
|
||||
'js/SettingsLayer.js',
|
||||
'js/SysMenu.js'
|
||||
];
|
||||
|
||||
cc.dumpConfig();
|
||||
|
||||
for( var i=0; i < appFiles.length; i++) {
|
||||
require( appFiles[i] );
|
||||
}
|
||||
|
||||
var director = cc.Director.getInstance();
|
||||
director.setDisplayStats(true);
|
||||
|
||||
// set FPS. the default value is 1.0/60 if you don't call this
|
||||
director.setAnimationInterval(1.0 / 60);
|
||||
|
||||
// create a scene. it's an autorelease object
|
||||
var mainScene = SysMenu.scene();
|
||||
|
||||
// run
|
||||
director.runWithScene(mainScene);
|
||||
|
|
@ -0,0 +1,94 @@
|
|||
var dirImg = "";
|
||||
var dirMusic = "";
|
||||
var musicSuffix = ".mp3";
|
||||
if( cc.config.deviceType == 'browser') {
|
||||
dirImg = "res/";
|
||||
dirMusic = "res/Music/";
|
||||
musicSuffix = "";
|
||||
}
|
||||
else if( cc.config.engine == 'cocos2d-x') {
|
||||
dirImg = "res/";
|
||||
dirMusic = "res/Music/";
|
||||
musicSuffix = ".mp3";
|
||||
}
|
||||
|
||||
//image
|
||||
var s_bg01 = dirImg + "bg01.jpg";
|
||||
var s_loading = dirImg + "loading.png";
|
||||
var s_ship01 = dirImg + "ship01.png";
|
||||
var s_menu = dirImg + "menu.png";
|
||||
var s_logo = dirImg + "logo.png";
|
||||
var s_cocos2dhtml5 = dirImg + "cocos2d-html5.png";
|
||||
var s_gameOver = dirImg + "gameOver.png";
|
||||
var s_menuTitle = dirImg + "menuTitle.png";
|
||||
var s_Enemy = dirImg + "Enemy.png";
|
||||
var s_flare = dirImg + "flare.jpg";
|
||||
var s_bullet = dirImg + "bullet.png";
|
||||
var s_explosion = dirImg + "explosion.png";
|
||||
var s_explode1 = dirImg + "explode1.jpg";
|
||||
var s_explode2= dirImg + "explode2.jpg";
|
||||
var s_explode3 = dirImg + "explode3.jpg";
|
||||
var s_hit = dirImg + "hit.jpg";
|
||||
var s_arial14 = dirImg + "arial-14.png";
|
||||
var s_arial14_fnt = dirImg + "arial-14.fnt";
|
||||
|
||||
//music
|
||||
var s_bgMusic = dirMusic + "bgMusic" + musicSuffix;
|
||||
var s_mainMainMusic = dirMusic + "mainMainMusic" + musicSuffix;
|
||||
|
||||
//effect
|
||||
var s_buttonEffect = dirMusic + "buttonEffet" + musicSuffix;
|
||||
var s_explodeEffect = dirMusic + "explodeEffect" + musicSuffix;
|
||||
var s_fireEffect = dirMusic + "fireEffect" + musicSuffix;
|
||||
var s_shipDestroyEffect = dirMusic + "shipDestroyEffect" + musicSuffix;
|
||||
|
||||
//tmx
|
||||
var s_level01 = dirImg + "level01.tmx";
|
||||
|
||||
//plist
|
||||
var s_Enemy_plist = dirImg + "Enemy.plist";
|
||||
var s_explosion_plist = dirImg + "explosion.plist";
|
||||
var s_bullet_plist = dirImg + "bullet.plist";
|
||||
|
||||
var g_ressources = [
|
||||
//image
|
||||
{type:"image", src:s_bg01},
|
||||
{type:"image", src:s_loading},
|
||||
{type:"image", src:s_ship01},
|
||||
{type:"image", src:s_menu},
|
||||
{type:"image", src:s_logo},
|
||||
{type:"image", src:s_cocos2dhtml5},
|
||||
{type:"image", src:s_gameOver},
|
||||
{type:"image", src:s_menuTitle},
|
||||
{type:"image", src:s_Enemy},
|
||||
{type:"image", src:s_flare},
|
||||
{type:"image", src:s_bullet},
|
||||
{type:"image", src:s_explosion},
|
||||
{type:"image", src:s_explode1},
|
||||
{type:"image", src:s_explode2},
|
||||
{type:"image", src:s_explode3},
|
||||
{type:"image", src:s_hit},
|
||||
{type:"image", src:s_arial14},
|
||||
|
||||
//tmx
|
||||
{type:"tmx", src:s_level01},
|
||||
|
||||
//plist
|
||||
{type:"plist", src:s_Enemy_plist},
|
||||
{type:"plist", src:s_explosion_plist},
|
||||
{type:"plist", src:s_bullet_plist},
|
||||
|
||||
//music
|
||||
{type:"bgm", src:s_bgMusic},
|
||||
{type:"bgm", src:s_mainMainMusic},
|
||||
|
||||
//effect
|
||||
{type:"effect", src:s_buttonEffect},
|
||||
{type:"effect", src:s_explodeEffect},
|
||||
{type:"effect", src:s_fireEffect},
|
||||
{type:"effect", src:s_shipDestroyEffect},
|
||||
|
||||
// FNT
|
||||
{type:"fnt", src:s_arial14_fnt}
|
||||
|
||||
];
|
|
@ -0,0 +1,85 @@
|
|||
var SettingsLayer = cc.Layer.extend({
|
||||
ctor:function () {
|
||||
cc.associateWithNative( this, cc.Layer );
|
||||
},
|
||||
init:function () {
|
||||
var bRet = false;
|
||||
if (this._super()) {
|
||||
var sp = cc.Sprite.create(s_loading);
|
||||
sp.setAnchorPoint(cc.p(0,0));
|
||||
this.addChild(sp, 0, 1);
|
||||
|
||||
var cacheImage = cc.TextureCache.getInstance().addImage(s_menuTitle);
|
||||
var title = cc.Sprite.createWithTexture(cacheImage, cc.rect(0, 0, 134, 34));
|
||||
title.setPosition(cc.p(winSize.width / 2, winSize.height - 120));
|
||||
this.addChild(title);
|
||||
|
||||
|
||||
cc.MenuItemFont.setFontName("Arial");
|
||||
cc.MenuItemFont.setFontSize(18);
|
||||
var title1 = cc.MenuItemFont.create("Sound");
|
||||
title1.setEnabled(false);
|
||||
|
||||
cc.MenuItemFont.setFontName("Arial");
|
||||
cc.MenuItemFont.setFontSize(26);
|
||||
var item1 = cc.MenuItemToggle.create(
|
||||
cc.MenuItemFont.create("On"),
|
||||
cc.MenuItemFont.create("Off") );
|
||||
item1.setCallback(this, this.soundControl );
|
||||
|
||||
cc.MenuItemFont.setFontName("Arial");
|
||||
cc.MenuItemFont.setFontSize(18);
|
||||
var title2 = cc.MenuItemFont.create("Mode");
|
||||
title2.setEnabled(false);
|
||||
|
||||
cc.MenuItemFont.setFontName("Arial");
|
||||
cc.MenuItemFont.setFontSize(26);
|
||||
var item2 = cc.MenuItemToggle.create(
|
||||
cc.MenuItemFont.create("Easy"),
|
||||
cc.MenuItemFont.create("Normal"),
|
||||
cc.MenuItemFont.create("Hard"));
|
||||
item2.setCallback( this, this.modeControl );
|
||||
|
||||
|
||||
cc.MenuItemFont.setFontName("Arial");
|
||||
cc.MenuItemFont.setFontSize(26);
|
||||
var label = cc.LabelTTF.create("Go back", "Arial", 20);
|
||||
var back = cc.MenuItemLabel.create(label, this, this.backCallback);
|
||||
back.setScale(0.8);
|
||||
|
||||
var menu = cc.Menu.create(title1, title2, item1, item2, back);
|
||||
menu.alignItemsInColumns(2, 2, 1);
|
||||
this.addChild(menu);
|
||||
|
||||
var cp_back = back.getPosition();
|
||||
cp_back.y -= 50.0;
|
||||
back.setPosition(cp_back);
|
||||
|
||||
|
||||
bRet = true;
|
||||
}
|
||||
|
||||
return bRet;
|
||||
},
|
||||
backCallback:function (pSender) {
|
||||
var scene = cc.Scene.create();
|
||||
scene.addChild(SysMenu.create());
|
||||
cc.Director.getInstance().replaceScene(cc.TransitionFade.create(1.2, scene));
|
||||
},
|
||||
soundControl:function(){
|
||||
MW.SOUND = MW.SOUND ? false : true;
|
||||
if(!MW.SOUND){
|
||||
cc.AudioEngine.getInstance().stopBackgroundMusic();
|
||||
}
|
||||
},
|
||||
modeControl:function(){
|
||||
}
|
||||
});
|
||||
|
||||
SettingsLayer.create = function () {
|
||||
var sg = new SettingsLayer();
|
||||
if (sg && sg.init()) {
|
||||
return sg;
|
||||
}
|
||||
return null;
|
||||
};
|
|
@ -0,0 +1,128 @@
|
|||
var Ship = cc.Sprite.extend({
|
||||
speed:220,
|
||||
bulletSpeed:900,
|
||||
HP:5,
|
||||
bulletTypeValue:1,
|
||||
bulletPowerValue:1,
|
||||
throwBombing:false,
|
||||
canBeAttack:true,
|
||||
isThrowingBomb:false,
|
||||
zOrder:3000,
|
||||
maxBulletPowerValue:4,
|
||||
appearPosition:cc.p(160, 60),
|
||||
_hurtColorLife:0,
|
||||
active:true,
|
||||
ctor:function () {
|
||||
|
||||
// needed for JS-Bindings compatibility
|
||||
cc.associateWithNative( this, cc.Sprite );
|
||||
|
||||
//init life
|
||||
var shipTexture = cc.TextureCache.getInstance().addImage(s_ship01);
|
||||
this.initWithTexture(shipTexture, cc.rect(0, 0, 60, 38));
|
||||
this.setTag(this.zOrder);
|
||||
this.setPosition(this.appearPosition);
|
||||
|
||||
// set frame
|
||||
var frame0 = cc.SpriteFrame.createWithTexture(shipTexture, cc.rect(0, 0, 60, 38));
|
||||
var frame1 = cc.SpriteFrame.createWithTexture(shipTexture, cc.rect(60, 0, 60, 38));
|
||||
|
||||
var animFrames = [];
|
||||
animFrames.push(frame0);
|
||||
animFrames.push(frame1);
|
||||
|
||||
// ship animate
|
||||
var animation = cc.Animation.create(animFrames, 0.1);
|
||||
var animate = cc.Animate.create(animation);
|
||||
this.runAction(cc.RepeatForever.create(animate));
|
||||
this.schedule(this.shoot, 1 / 6);
|
||||
|
||||
//revive effect
|
||||
this.canBeAttack = false;
|
||||
var ghostSprite = cc.Sprite.createWithTexture(shipTexture, cc.rect(0, 45, 60, 38));
|
||||
ghostSprite.setBlendFunc(gl.SRC_ALPHA, gl.ONE);
|
||||
ghostSprite.setScale(8);
|
||||
ghostSprite.setPosition(cc.p(this.getContentSize().width / 2, 12));
|
||||
this.addChild(ghostSprite, 3000, 99999);
|
||||
ghostSprite.runAction(cc.ScaleTo.create(0.5, 1, 1));
|
||||
var blinks = cc.Blink.create(3, 9);
|
||||
var makeBeAttack = cc.CallFunc.create(this, function (t) {
|
||||
t.canBeAttack = true;
|
||||
t.setVisible(true);
|
||||
t.removeChild(ghostSprite,true);
|
||||
});
|
||||
this.runAction(cc.Sequence.create(cc.DelayTime.create(0.5), blinks, makeBeAttack));
|
||||
},
|
||||
update:function (dt) {
|
||||
|
||||
// Keys are only enabled on the browser
|
||||
if( cc.config.deviceType == 'browser' ) {
|
||||
var pos = this.getPosition();
|
||||
if ((MW.KEYS[cc.KEY.w] || MW.KEYS[cc.KEY.up]) && pos.y <= winSize.height) {
|
||||
pos.y += dt * this.speed;
|
||||
}
|
||||
if ((MW.KEYS[cc.KEY.s] || MW.KEYS[cc.KEY.down]) && pos.y >= 0) {
|
||||
pos.y -= dt * this.speed;
|
||||
}
|
||||
if ((MW.KEYS[cc.KEY.a] || MW.KEYS[cc.KEY.left]) && pos.x >= 0) {
|
||||
pos.x -= dt * this.speed;
|
||||
}
|
||||
if ((MW.KEYS[cc.KEY.d] || MW.KEYS[cc.KEY.right]) && pos.x <= winSize.width) {
|
||||
pos.x += dt * this.speed;
|
||||
}
|
||||
this.setPosition( pos );
|
||||
}
|
||||
|
||||
if (this.HP <= 0) {
|
||||
this.active = false;
|
||||
}
|
||||
this._timeTick += dt;
|
||||
if (this._timeTick > 0.1) {
|
||||
this._timeTick = 0;
|
||||
if (this._hurtColorLife > 0) {
|
||||
this._hurtColorLife--;
|
||||
}
|
||||
if (this._hurtColorLife == 1) {
|
||||
this.setColor(cc.WHITE);
|
||||
}
|
||||
}
|
||||
},
|
||||
shoot:function (dt) {
|
||||
//this.shootEffect();
|
||||
var offset = 13;
|
||||
var p = this.getPosition();
|
||||
var cs = this.getContentSize();
|
||||
var a = new Bullet(this.bulletSpeed, "W1.png", MW.ENEMY_MOVE_TYPE.NORMAL);
|
||||
MW.CONTAINER.PLAYER_BULLETS.push(a);
|
||||
this.getParent().addChild(a, a.zOrder, MW.UNIT_TAG.PLAYER_BULLET);
|
||||
a.setPosition(cc.p(p.x + offset, p.y + 3 + cs.height * 0.3));
|
||||
|
||||
var b = new Bullet(this.bulletSpeed, "W1.png", MW.ENEMY_MOVE_TYPE.NORMAL);
|
||||
MW.CONTAINER.PLAYER_BULLETS.push(b);
|
||||
this.getParent().addChild(b, b.zOrder, MW.UNIT_TAG.PLAYER_BULLET);
|
||||
b.setPosition(cc.p(p.x - offset, p.y + 3 + cs.height * 0.3));
|
||||
},
|
||||
destroy:function () {
|
||||
MW.LIFE--;
|
||||
var p = this.getPosition();
|
||||
var myParent = this.getParent();
|
||||
myParent.addChild( new Explosion(p) );
|
||||
myParent.removeChild(this,true);
|
||||
if (MW.SOUND) {
|
||||
cc.AudioEngine.getInstance().playEffect(s_shipDestroyEffect);
|
||||
}
|
||||
},
|
||||
hurt:function () {
|
||||
if (this.canBeAttack) {
|
||||
this._hurtColorLife = 2;
|
||||
this.HP--;
|
||||
this.setColor(cc.RED);
|
||||
}
|
||||
},
|
||||
collideRect:function(){
|
||||
var p = this.getPosition();
|
||||
var a = this.getContentSize();
|
||||
var r = new cc.rect(p.x - a.width/2, p.y - a.height/2, a.width, a.height/2);
|
||||
return r;
|
||||
}
|
||||
});
|
|
@ -0,0 +1,110 @@
|
|||
cc.dumpConfig();
|
||||
|
||||
var SysMenu = cc.Layer.extend({
|
||||
_ship:null,
|
||||
|
||||
ctor:function () {
|
||||
cc.associateWithNative( this, cc.Layer );
|
||||
},
|
||||
init:function () {
|
||||
var bRet = false;
|
||||
if (this._super()) {
|
||||
winSize = cc.Director.getInstance().getWinSize();
|
||||
var sp = cc.Sprite.create(s_loading);
|
||||
sp.setAnchorPoint(cc.p(0,0));
|
||||
this.addChild(sp, 0, 1);
|
||||
|
||||
var logo = cc.Sprite.create(s_logo);
|
||||
logo.setAnchorPoint(cc.p(0, 0));
|
||||
logo.setPosition(cc.p(0, 250));
|
||||
this.addChild(logo, 10, 1);
|
||||
|
||||
var newGameNormal = cc.Sprite.create(s_menu, cc.rect(0, 0, 126, 33));
|
||||
var newGameSelected = cc.Sprite.create(s_menu, cc.rect(0, 33, 126, 33));
|
||||
var newGameDisabled = cc.Sprite.create(s_menu, cc.rect(0, 33 * 2, 126, 33));
|
||||
|
||||
var gameSettingsNormal = cc.Sprite.create(s_menu, cc.rect(126, 0, 126, 33));
|
||||
var gameSettingsSelected = cc.Sprite.create(s_menu, cc.rect(126, 33, 126, 33));
|
||||
var gameSettingsDisabled = cc.Sprite.create(s_menu, cc.rect(126, 33 * 2, 126, 33));
|
||||
|
||||
var aboutNormal = cc.Sprite.create(s_menu, cc.rect(252, 0, 126, 33));
|
||||
var aboutSelected = cc.Sprite.create(s_menu, cc.rect(252, 33, 126, 33));
|
||||
var aboutDisabled = cc.Sprite.create(s_menu, cc.rect(252, 33 * 2, 126, 33));
|
||||
|
||||
var newGame = cc.MenuItemSprite.create(newGameNormal, newGameSelected, newGameDisabled, this, function () {
|
||||
this.onButtonEffect();
|
||||
flareEffect(this, this, this.onNewGame);
|
||||
});
|
||||
var gameSettings = cc.MenuItemSprite.create(gameSettingsNormal, gameSettingsSelected, gameSettingsDisabled, this, this.onSettings);
|
||||
var about = cc.MenuItemSprite.create(aboutNormal, aboutSelected, aboutDisabled, this, this.onAbout);
|
||||
|
||||
var menu = cc.Menu.create(newGame, gameSettings, about);
|
||||
menu.alignItemsVerticallyWithPadding(10);
|
||||
this.addChild(menu, 1, 2);
|
||||
menu.setPosition(cc.p(winSize.width / 2, winSize.height / 2 - 80));
|
||||
this.schedule(this.update, 0.1);
|
||||
|
||||
var tmp = cc.TextureCache.getInstance().addImage(s_ship01);
|
||||
this._ship = cc.Sprite.createWithTexture(tmp,cc.rect(0, 45, 60, 38));
|
||||
this.addChild(this._ship, 0, 4);
|
||||
var pos = cc.p(Math.random() * winSize.width, 0);
|
||||
this._ship.setPosition( pos );
|
||||
this._ship.runAction(cc.MoveBy.create(2, cc.p(Math.random() * winSize.width, pos.y + winSize.height + 100)));
|
||||
|
||||
if (MW.SOUND) {
|
||||
cc.AudioEngine.getInstance().setBackgroundMusicVolume(0.7);
|
||||
cc.AudioEngine.getInstance().playBackgroundMusic(s_mainMainMusic, true);
|
||||
}
|
||||
|
||||
bRet = true;
|
||||
}
|
||||
return bRet;
|
||||
},
|
||||
onNewGame:function (pSender) {
|
||||
var scene = cc.Scene.create();
|
||||
scene.addChild(GameLayer.create());
|
||||
scene.addChild(GameControlMenu.create());
|
||||
cc.Director.getInstance().replaceScene(cc.TransitionFade.create(1.2, scene));
|
||||
},
|
||||
onSettings:function (pSender) {
|
||||
this.onButtonEffect();
|
||||
var scene = cc.Scene.create();
|
||||
scene.addChild(SettingsLayer.create());
|
||||
cc.Director.getInstance().replaceScene(cc.TransitionFade.create(1.2, scene));
|
||||
},
|
||||
onAbout:function (pSender) {
|
||||
this.onButtonEffect();
|
||||
var scene = cc.Scene.create();
|
||||
scene.addChild(AboutLayer.create());
|
||||
cc.Director.getInstance().replaceScene(cc.TransitionFade.create(1.2, scene));
|
||||
},
|
||||
update:function () {
|
||||
if (this._ship.getPosition().y > 480) {
|
||||
var pos = cc.p(Math.random() * winSize.width, 10);
|
||||
this._ship.setPosition( pos );
|
||||
this._ship.runAction( cc.MoveBy.create(
|
||||
parseInt(5 * Math.random(), 10),
|
||||
cc.p(Math.random() * winSize.width, pos.y + 480)));
|
||||
}
|
||||
},
|
||||
onButtonEffect:function(){
|
||||
if (MW.SOUND) {
|
||||
var s = cc.AudioEngine.getInstance().playEffect(s_buttonEffect);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
SysMenu.create = function () {
|
||||
var sg = new SysMenu();
|
||||
if (sg && sg.init()) {
|
||||
return sg;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
SysMenu.scene = function () {
|
||||
var scene = cc.Scene.create();
|
||||
var layer = SysMenu.create();
|
||||
scene.addChild(layer);
|
||||
return scene;
|
||||
};
|
|
@ -0,0 +1,56 @@
|
|||
var EnemyType = [
|
||||
{
|
||||
type:0,
|
||||
textureName:"E0.png",
|
||||
bulletType:"W2.png",
|
||||
HP:1,
|
||||
moveType:MW.ENEMY_MOVE_TYPE.ATTACK,
|
||||
attackMode:MW.ENEMY_MOVE_TYPE.NORMAL,
|
||||
scoreValue:15
|
||||
},
|
||||
{
|
||||
type:1,
|
||||
textureName:"E1.png",
|
||||
bulletType:"W2.png",
|
||||
HP:2,
|
||||
moveType:MW.ENEMY_MOVE_TYPE.ATTACK,
|
||||
attackMode:MW.ENEMY_MOVE_TYPE.NORMAL,
|
||||
scoreValue:40
|
||||
},
|
||||
{
|
||||
type:2,
|
||||
textureName:"E2.png",
|
||||
bulletType:"W2.png",
|
||||
HP:4,
|
||||
moveType:MW.ENEMY_MOVE_TYPE.HORIZONTAL,
|
||||
attackMode:MW.ENEMY_ATTACK_MODE.TSUIHIKIDAN,
|
||||
scoreValue:60
|
||||
},
|
||||
{
|
||||
type:3,
|
||||
textureName:"E3.png",
|
||||
bulletType:"W2.png",
|
||||
HP:6,
|
||||
moveType:MW.ENEMY_MOVE_TYPE.OVERLAP,
|
||||
attackMode:MW.ENEMY_MOVE_TYPE.NORMAL,
|
||||
scoreValue:80
|
||||
},
|
||||
{
|
||||
type:4,
|
||||
textureName:"E4.png",
|
||||
bulletType:"W2.png",
|
||||
HP:10,
|
||||
moveType:MW.ENEMY_MOVE_TYPE.HORIZONTAL,
|
||||
attackMode:MW.ENEMY_ATTACK_MODE.TSUIHIKIDAN,
|
||||
scoreValue:150
|
||||
},
|
||||
{
|
||||
type:5,
|
||||
textureName:"E5.png",
|
||||
bulletType:"W2.png",
|
||||
HP:15,
|
||||
moveType:MW.ENEMY_MOVE_TYPE.HORIZONTAL,
|
||||
attackMode:MW.ENEMY_MOVE_TYPE.NORMAL,
|
||||
scoreValue:200
|
||||
}
|
||||
];
|
|
@ -0,0 +1,94 @@
|
|||
/**
|
||||
* Cocos2d-html5 show case : Moon Warriors
|
||||
*
|
||||
* @Licensed:
|
||||
* This showcase is licensed under GPL.
|
||||
*
|
||||
* @Authors:
|
||||
* Programmer: Shengxiang Chen (陈升想), Dingping Lv (吕定平), Ricardo Quesada
|
||||
* Effects animation: Hao Wu (吴昊)
|
||||
* Quality Assurance: Sean Lin (林顺)
|
||||
*
|
||||
* @Links:
|
||||
* http://www.cocos2d-x.org
|
||||
* http://bbs.html5china.com
|
||||
*
|
||||
*/
|
||||
|
||||
//game state
|
||||
MW.GAME_STATE = {
|
||||
HOME:0,
|
||||
PLAY:1,
|
||||
OVER:2
|
||||
};
|
||||
|
||||
//keys
|
||||
MW.KEYS = [];
|
||||
|
||||
//level
|
||||
MW.LEVEL = {
|
||||
STAGE1:1,
|
||||
STAGE2:2,
|
||||
STAGE3:3
|
||||
};
|
||||
|
||||
//life
|
||||
MW.LIFE = 4;
|
||||
|
||||
//score
|
||||
MW.SCORE = 0;
|
||||
|
||||
//sound
|
||||
MW.SOUND = true;
|
||||
|
||||
//enemy move type
|
||||
MW.ENEMY_MOVE_TYPE = {
|
||||
ATTACK:0,
|
||||
VERTICAL:1,
|
||||
HORIZONTAL:2,
|
||||
OVERLAP:3
|
||||
};
|
||||
|
||||
//delta x
|
||||
MW.DELTA_X = -100;
|
||||
|
||||
//offset x
|
||||
MW.OFFSET_X = -24;
|
||||
|
||||
//rot
|
||||
MW.ROT = -5.625;
|
||||
|
||||
//bullet type
|
||||
MW.BULLET_TYPE = {
|
||||
PLAYER:1,
|
||||
ENEMY:2
|
||||
};
|
||||
|
||||
//weapon type
|
||||
MW.WEAPON_TYPE = {
|
||||
ONE:1
|
||||
};
|
||||
|
||||
//unit tag
|
||||
MW.UNIT_TAG = {
|
||||
ENMEY_BULLET:900,
|
||||
PLAYER_BULLET:901,
|
||||
ENEMY:1000,
|
||||
PLAYER:1000
|
||||
};
|
||||
|
||||
//attack mode
|
||||
MW.ENEMY_ATTACK_MODE = {
|
||||
NORMAL:1,
|
||||
TSUIHIKIDAN:2
|
||||
};
|
||||
|
||||
//life up sorce
|
||||
MW.LIFEUP_SORCE = [50000, 100000, 150000, 200000, 250000, 300000];
|
||||
|
||||
//container
|
||||
MW.CONTAINER = {
|
||||
ENEMIES:[],
|
||||
ENEMY_BULLETS:[],
|
||||
PLAYER_BULLETS:[]
|
||||
};
|
|
@ -0,0 +1,49 @@
|
|||
var Level1 = {
|
||||
enemies:[
|
||||
{
|
||||
ShowType:"Repeate",
|
||||
ShowTime:"00:02",
|
||||
Types:[0,1,2]
|
||||
},
|
||||
{
|
||||
ShowType:"Repeate",
|
||||
ShowTime:"00:05",
|
||||
Types:[3,4,5]
|
||||
}
|
||||
/*{
|
||||
ShowType:"Repeate",
|
||||
ShowTime:"00:08",
|
||||
Types:[0,4,3,5]
|
||||
},
|
||||
{
|
||||
ShowType:"Once",
|
||||
ShowTime:"00:6",
|
||||
Types:[0,2,4,3]
|
||||
},
|
||||
{
|
||||
ShowType:"Once",
|
||||
ShowTime:"00:16",
|
||||
Types:[0,2,5,4,3]
|
||||
},
|
||||
{
|
||||
ShowType:"Once",
|
||||
ShowTime:"00:25",
|
||||
Types:[0,3,5,4,3]
|
||||
},
|
||||
{
|
||||
ShowType:"Once",
|
||||
ShowTime:"00:35",
|
||||
Types:[4,5,3,1,3]
|
||||
},
|
||||
{
|
||||
ShowType:"Once",
|
||||
ShowTime:"00:50",
|
||||
Types:[0,3,2,1,0,3]
|
||||
},
|
||||
{
|
||||
ShowType:"Once",
|
||||
ShowTime:"01:15",
|
||||
Types:[4,5,2,1,0]
|
||||
}*/
|
||||
]
|
||||
};
|
|
@ -1,3 +1,4 @@
|
|||
require('js/helper/jsb_constants_gl.js');
|
||||
// cocos2d Helper
|
||||
|
||||
cc.c3 = cc.c3 || function (r, g, b) {
|
||||
|
@ -263,6 +264,33 @@ cc.pDistance = function (v1, v2) {
|
|||
return cc.pLength(cc.pSub(v1, v2));
|
||||
};
|
||||
|
||||
/**
|
||||
* Clamp a value between from and to.
|
||||
* @param {Number} value
|
||||
* @param {Number} min_inclusive
|
||||
* @param {Number} max_inclusive
|
||||
* @return {Number}
|
||||
*/
|
||||
cc.clampf = function (value, min_inclusive, max_inclusive) {
|
||||
if (min_inclusive > max_inclusive) {
|
||||
var temp = min_inclusive;
|
||||
min_inclusive = max_inclusive;
|
||||
max_inclusive = temp;
|
||||
}
|
||||
return value < min_inclusive ? min_inclusive : value < max_inclusive ? value : max_inclusive;
|
||||
};
|
||||
|
||||
/**
|
||||
* Clamp a point between from and to.
|
||||
* @param {Number} p
|
||||
* @param {Number} min_inclusive
|
||||
* @param {Number} max_inclusive
|
||||
* @return {cc.Point}
|
||||
*/
|
||||
cc.pClamp = function (p, min_inclusive, max_inclusive) {
|
||||
return cc.p(cc.clampf(p.x, min_inclusive.x, max_inclusive.x), cc.clampf(p.y, min_inclusive.y, max_inclusive.y));
|
||||
};
|
||||
|
||||
/**
|
||||
* returns a random float between 0 and 1
|
||||
* @return {Number}
|
||||
|
@ -272,6 +300,16 @@ cc.RANDOM_0_1 = function () {
|
|||
return Math.random();
|
||||
};
|
||||
|
||||
/**
|
||||
* Associates a base class with a native superclass
|
||||
* @function
|
||||
* @param {object} jsobj subclass
|
||||
* @param {object} klass superclass
|
||||
*/
|
||||
cc.associateWithNative = function( jsobj, superclass ) {
|
||||
var native = new superclass();
|
||||
__associateObjWithNative( jsobj, native );
|
||||
};
|
||||
|
||||
//
|
||||
// Array: for cocos2d-hmtl5 compatibility
|
|
@ -0,0 +1,23 @@
|
|||
//
|
||||
// OpenGL defines
|
||||
//
|
||||
|
||||
var gl = gl || {};
|
||||
gl.NEAREST = 0x2600;
|
||||
gl.LINEAR = 0x2601;
|
||||
gl.REPEAT = 0x2901;
|
||||
gl.CLAMP_TO_EDGE = 0x812F;
|
||||
gl.CLAMP_TO_BORDER = 0x812D;
|
||||
gl.LINEAR_MIPMAP_NEAREST = 0x2701;
|
||||
gl.NEAREST_MIPMAP_NEAREST = 0x2700;
|
||||
gl.ZERO = 0;
|
||||
gl.ONE = 1;
|
||||
gl.SRC_COLOR = 0x0300;
|
||||
gl.ONE_MINUS_SRC_COLOR = 0x0301;
|
||||
gl.SRC_ALPHA = 0x0302;
|
||||
gl.ONE_MINUS_SRC_ALPHA = 0x0303;
|
||||
gl.DST_ALPHA = 0x0304;
|
||||
gl.ONE_MINUS_DST_ALPHA = 0x0305;
|
||||
gl.DST_COLOR = 0x0306;
|
||||
gl.ONE_MINUS_DST_COLOR = 0x0307;
|
||||
gl.SRC_ALPHA_SATURATE = 0x0308;
|
|
@ -0,0 +1 @@
|
|||
59362b16ba4da187e064648be4d0bcb1c09b504d
|
|
@ -0,0 +1 @@
|
|||
c0488f23a6a785893f4845b7fadc59ed892ceedc
|
Binary file not shown.
|
@ -0,0 +1 @@
|
|||
46f10a6bf5c63f03ddf8566f392aa7a8f258d7e8
|
|
@ -0,0 +1 @@
|
|||
97bca7d49fb6ec5c330f6ab6f5f49d335601a669
|
|
@ -0,0 +1 @@
|
|||
ca7905a1a07e2be3e02fbf329772c2c361400af7
|
|
@ -0,0 +1,8 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<classpath>
|
||||
<classpathentry kind="src" path="src"/>
|
||||
<classpathentry kind="src" path="gen"/>
|
||||
<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
|
||||
<classpathentry kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
|
||||
<classpathentry kind="output" path="bin/classes"/>
|
||||
</classpath>
|
|
@ -0,0 +1,33 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<projectDescription>
|
||||
<name>MoonWarriors</name>
|
||||
<comment></comment>
|
||||
<projects>
|
||||
</projects>
|
||||
<buildSpec>
|
||||
<buildCommand>
|
||||
<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
<buildCommand>
|
||||
<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
<buildCommand>
|
||||
<name>org.eclipse.jdt.core.javabuilder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
<buildCommand>
|
||||
<name>com.android.ide.eclipse.adt.ApkBuilder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
</buildSpec>
|
||||
<natures>
|
||||
<nature>com.android.ide.eclipse.adt.AndroidNature</nature>
|
||||
<nature>org.eclipse.jdt.core.javanature</nature>
|
||||
</natures>
|
||||
</projectDescription>
|
|
@ -0,0 +1,28 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="org.cocos2dx.moonwarriors"
|
||||
android:versionCode="1"
|
||||
android:versionName="1.0">
|
||||
|
||||
<uses-sdk android:minSdkVersion="8"/>
|
||||
|
||||
<application android:label="@string/app_name"
|
||||
android:debuggable="true"
|
||||
android:icon="@drawable/icon">
|
||||
|
||||
<activity android:name=".MoonWarriors"
|
||||
android:label="@string/app_name"
|
||||
android:screenOrientation="portrait"
|
||||
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
|
||||
android:configChanges="orientation">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
</application>
|
||||
<supports-screens android:largeScreens="true"
|
||||
android:smallScreens="true"
|
||||
android:anyDensity="true"
|
||||
android:normalScreens="true"/>
|
||||
</manifest>
|
|
@ -0,0 +1 @@
|
|||
aapt.ignore.assets="!*.pvr.gz:!*.gz:!.svn:!.git:.*:<dir>_*:!CVS:!thumbs.db:!picasa.ini:!*.scc:*~"
|
|
@ -0,0 +1,92 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project name="MoonWarriors" default="help">
|
||||
|
||||
<!-- The local.properties file is created and updated by the 'android' tool.
|
||||
It contains the path to the SDK. It should *NOT* be checked into
|
||||
Version Control Systems. -->
|
||||
<property file="local.properties" />
|
||||
|
||||
<!-- The ant.properties file can be created by you. It is only edited by the
|
||||
'android' tool to add properties to it.
|
||||
This is the place to change some Ant specific build properties.
|
||||
Here are some properties you may want to change/update:
|
||||
|
||||
source.dir
|
||||
The name of the source directory. Default is 'src'.
|
||||
out.dir
|
||||
The name of the output directory. Default is 'bin'.
|
||||
|
||||
For other overridable properties, look at the beginning of the rules
|
||||
files in the SDK, at tools/ant/build.xml
|
||||
|
||||
Properties related to the SDK location or the project target should
|
||||
be updated using the 'android' tool with the 'update' action.
|
||||
|
||||
This file is an integral part of the build system for your
|
||||
application and should be checked into Version Control Systems.
|
||||
|
||||
-->
|
||||
<property file="ant.properties" />
|
||||
|
||||
<!-- if sdk.dir was not set from one of the property file, then
|
||||
get it from the ANDROID_HOME env var.
|
||||
This must be done before we load project.properties since
|
||||
the proguard config can use sdk.dir -->
|
||||
<property environment="env" />
|
||||
<condition property="sdk.dir" value="${env.ANDROID_HOME}">
|
||||
<isset property="env.ANDROID_HOME" />
|
||||
</condition>
|
||||
|
||||
<!-- The project.properties file is created and updated by the 'android'
|
||||
tool, as well as ADT.
|
||||
|
||||
This contains project specific properties such as project target, and library
|
||||
dependencies. Lower level build properties are stored in ant.properties
|
||||
(or in .classpath for Eclipse projects).
|
||||
|
||||
This file is an integral part of the build system for your
|
||||
application and should be checked into Version Control Systems. -->
|
||||
<loadproperties srcFile="project.properties" />
|
||||
|
||||
<!-- quick check on sdk.dir -->
|
||||
<fail
|
||||
message="sdk.dir is missing. Make sure to generate local.properties using 'android update project' or to inject it through the ANDROID_HOME environment variable."
|
||||
unless="sdk.dir"
|
||||
/>
|
||||
|
||||
<!--
|
||||
Import per project custom build rules if present at the root of the project.
|
||||
This is the place to put custom intermediary targets such as:
|
||||
-pre-build
|
||||
-pre-compile
|
||||
-post-compile (This is typically used for code obfuscation.
|
||||
Compiled code location: ${out.classes.absolute.dir}
|
||||
If this is not done in place, override ${out.dex.input.absolute.dir})
|
||||
-post-package
|
||||
-post-build
|
||||
-pre-clean
|
||||
-->
|
||||
<import file="custom_rules.xml" optional="true" />
|
||||
|
||||
<!-- Import the actual build file.
|
||||
|
||||
To customize existing targets, there are two options:
|
||||
- Customize only one target:
|
||||
- copy/paste the target into this file, *before* the
|
||||
<import> task.
|
||||
- customize it to your needs.
|
||||
- Customize the whole content of build.xml
|
||||
- copy/paste the content of the rules files (minus the top node)
|
||||
into this file, replacing the <import> task.
|
||||
- customize to your needs.
|
||||
|
||||
***********************
|
||||
****** IMPORTANT ******
|
||||
***********************
|
||||
In all cases you must update the value of version-tag below to read 'custom' instead of an integer,
|
||||
in order to avoid having your file be overridden by tools such as "android update project"
|
||||
-->
|
||||
<!-- version-tag: 1 -->
|
||||
<import file="${sdk.dir}/tools/ant/build.xml" />
|
||||
|
||||
</project>
|
|
@ -0,0 +1,100 @@
|
|||
APPNAME="MoonWarriors"
|
||||
|
||||
# options
|
||||
|
||||
buildexternalsfromsource=
|
||||
PARALLEL_BUILD_FLAG=
|
||||
|
||||
usage(){
|
||||
cat << EOF
|
||||
usage: $0 [options]
|
||||
|
||||
Build C/C++ code for $APPNAME using Android NDK
|
||||
|
||||
OPTIONS:
|
||||
-s Build externals from source
|
||||
-p Run make with -j8 option to take advantage of multiple processors
|
||||
-h this help
|
||||
EOF
|
||||
}
|
||||
|
||||
while getopts "sph" OPTION; do
|
||||
case "$OPTION" in
|
||||
s)
|
||||
buildexternalsfromsource=1
|
||||
;;
|
||||
p)
|
||||
PARALLEL_BUILD_FLAG=\-j8
|
||||
;;
|
||||
h)
|
||||
usage
|
||||
exit 0
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
# exit this script if any commmand fails
|
||||
set -e
|
||||
|
||||
# paths
|
||||
|
||||
if [ -z "${NDK_ROOT+aaa}" ];then
|
||||
echo "please define NDK_ROOT"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
||||
# ... use paths relative to current directory
|
||||
COCOS2DX_ROOT="$DIR/../../.."
|
||||
APP_ROOT="$DIR/.."
|
||||
APP_ANDROID_ROOT="$DIR"
|
||||
|
||||
echo
|
||||
echo "Paths"
|
||||
echo " NDK_ROOT = $NDK_ROOT"
|
||||
echo " COCOS2DX_ROOT = $COCOS2DX_ROOT"
|
||||
echo " APP_ROOT = $APP_ROOT"
|
||||
echo " APP_ANDROID_ROOT = $APP_ANDROID_ROOT"
|
||||
echo
|
||||
|
||||
# make sure assets is exist
|
||||
if [ -d "$APP_ANDROID_ROOT"/assets ]; then
|
||||
rm -rf "$APP_ANDROID_ROOT"/assets
|
||||
fi
|
||||
|
||||
mkdir "$APP_ANDROID_ROOT"/assets
|
||||
|
||||
|
||||
# copy resources
|
||||
for file in "$APP_ROOT"/Resources/*
|
||||
do
|
||||
if [ -d "$file" ]; then
|
||||
cp -rf "$file" "$APP_ANDROID_ROOT"/assets
|
||||
fi
|
||||
|
||||
|
||||
if [ -f "$file" ]; then
|
||||
cp "$file" "$APP_ANDROID_ROOT"/assets
|
||||
fi
|
||||
done
|
||||
|
||||
|
||||
rm -f "$APP_ANDROID_ROOT"/assets/Images/landscape-1024x1024-rgba8888.pvr.gz
|
||||
rm -f "$APP_ANDROID_ROOT"/assets/Images/test_image_rgba4444.pvr.gz
|
||||
rm -f "$APP_ANDROID_ROOT"/assets/Images/test_1021x1024_a8.pvr.gz
|
||||
rm -f "$APP_ANDROID_ROOT"/assets/Images/test_1021x1024_rgb888.pvr.gz
|
||||
rm -f "$APP_ANDROID_ROOT"/assets/Images/test_1021x1024_rgba4444.pvr.gz
|
||||
rm -f "$APP_ANDROID_ROOT"/assets/Images/test_1021x1024_rgba8888.pvr.gz
|
||||
rm -f "$APP_ANDROID_ROOT"/assets/Images/test_image_rgba4444.pvr.gz
|
||||
rm -f "$APP_ANDROID_ROOT"/assets/Images/texture1024x1024_rgba4444.pvr.gz
|
||||
rm -f "$APP_ANDROID_ROOT"/assets/Images/PlanetCute-1024x1024-rgba4444.pvr.gz
|
||||
|
||||
|
||||
echo "Using prebuilt externals"
|
||||
echo
|
||||
|
||||
set -x
|
||||
|
||||
"$NDK_ROOT"/ndk-build $PARALLEL_BUILD_FLAG -C "$APP_ANDROID_ROOT" $* \
|
||||
"NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos2dx/platform/third_party/android/prebuilt" \
|
||||
NDK_LOG=1 V=1
|
|
@ -0,0 +1,28 @@
|
|||
LOCAL_PATH := $(call my-dir)
|
||||
|
||||
include $(CLEAR_VARS)
|
||||
|
||||
LOCAL_MODULE := moonwarriors_shared
|
||||
|
||||
LOCAL_MODULE_FILENAME := libmoonwarriors
|
||||
|
||||
LOCAL_SRC_FILES := moonwarriors/main.cpp \
|
||||
../../Classes/AppDelegate.cpp
|
||||
|
||||
LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes
|
||||
|
||||
LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static
|
||||
LOCAL_WHOLE_STATIC_LIBRARIES += cocosdenshion_static
|
||||
LOCAL_WHOLE_STATIC_LIBRARIES += chipmunk_static
|
||||
LOCAL_WHOLE_STATIC_LIBRARIES += spidermonkey_static
|
||||
LOCAL_WHOLE_STATIC_LIBRARIES += scriptingcore-spidermonkey
|
||||
|
||||
LOCAL_EXPORT_CFLAGS := -DCOCOS2D_DEBUG=2 -DCOCOS2D_JAVASCRIPT
|
||||
|
||||
include $(BUILD_SHARED_LIBRARY)
|
||||
|
||||
$(call import-module,cocos2dx)
|
||||
$(call import-module,CocosDenshion/android)
|
||||
$(call import-module,external/chipmunk)
|
||||
$(call import-module,scripting/javascript/spidermonkey-android)
|
||||
$(call import-module,scripting/javascript/bindings)
|
|
@ -0,0 +1,3 @@
|
|||
APP_STL := gnustl_static
|
||||
APP_CPPFLAGS := -frtti -DCOCOS2D_JAVASCRIPT=1
|
||||
APP_CPPFLAGS += -DCOCOS2D_DEBUG=2
|
|
@ -0,0 +1,45 @@
|
|||
#include "AppDelegate.h"
|
||||
#include "cocos2d.h"
|
||||
#include "platform/android/jni/JniHelper.h"
|
||||
#include "CCEventType.h"
|
||||
#include <jni.h>
|
||||
#include <android/log.h>
|
||||
|
||||
#define LOG_TAG "main"
|
||||
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
|
||||
|
||||
using namespace cocos2d;
|
||||
|
||||
extern "C"
|
||||
{
|
||||
|
||||
jint JNI_OnLoad(JavaVM *vm, void *reserved)
|
||||
{
|
||||
JniHelper::setJavaVM(vm);
|
||||
|
||||
return JNI_VERSION_1_4;
|
||||
}
|
||||
|
||||
void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeInit(JNIEnv* env, jobject thiz, jint w, jint h)
|
||||
{
|
||||
if (!CCDirector::sharedDirector()->getOpenGLView())
|
||||
{
|
||||
CCEGLView *view = CCEGLView::sharedOpenGLView();
|
||||
view->setFrameSize(w, h);
|
||||
|
||||
AppDelegate *pAppDelegate = new AppDelegate();
|
||||
CCApplication::sharedApplication()->run();
|
||||
}
|
||||
else
|
||||
{
|
||||
ccDrawInit();
|
||||
ccGLInvalidateStateCache();
|
||||
|
||||
CCShaderCache::sharedShaderCache()->reloadDefaultShaders();
|
||||
CCTextureCache::reloadAllTextures();
|
||||
CCNotificationCenter::sharedNotificationCenter()->postNotification(EVNET_COME_TO_FOREGROUND, NULL);
|
||||
CCDirector::sharedDirector()->setGLDefaultValues();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
# To enable ProGuard in your project, edit project.properties
|
||||
# to define the proguard.config property as described in that file.
|
||||
#
|
||||
# Add project specific ProGuard rules here.
|
||||
# By default, the flags in this file are appended to flags specified
|
||||
# in ${sdk.dir}/tools/proguard/proguard-android.txt
|
||||
# You can edit the include path and order by changing the ProGuard
|
||||
# include property in project.properties.
|
||||
#
|
||||
# For more details, see
|
||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
||||
|
||||
# Add any project specific keep options here:
|
||||
|
||||
# If your project uses WebView with JS, uncomment the following
|
||||
# and specify the fully qualified class name to the JavaScript interface
|
||||
# class:
|
||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
||||
# public *;
|
||||
#}
|
|
@ -0,0 +1,13 @@
|
|||
# This file is automatically generated by Android Tools.
|
||||
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
|
||||
#
|
||||
# This file must be checked in Version Control Systems.
|
||||
#
|
||||
# To customize properties used by the Ant build system use,
|
||||
# "ant.properties", and override values to adapt the script to your
|
||||
# project structure.
|
||||
|
||||
# Project target.
|
||||
target=android-8
|
||||
|
||||
android.library.reference.1=../../../cocos2dx/platform/android/java
|
|
@ -0,0 +1,4 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="app_name">MoonWarriors</string>
|
||||
</resources>
|
|
@ -0,0 +1,39 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2010-2012 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.
|
||||
****************************************************************************/
|
||||
package org.cocos2dx.moonwarriors;
|
||||
|
||||
import org.cocos2dx.lib.Cocos2dxActivity;
|
||||
|
||||
import android.os.Bundle;
|
||||
|
||||
public class MoonWarriors extends Cocos2dxActivity{
|
||||
|
||||
protected void onCreate(Bundle savedInstanceState){
|
||||
super.onCreate(savedInstanceState);
|
||||
}
|
||||
|
||||
static {
|
||||
System.loadLibrary("moonwarriors");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
//
|
||||
// testjsAppController.h
|
||||
// testjs
|
||||
//
|
||||
// Created by Rolando Abarca on 3/19/12.
|
||||
// Copyright __MyCompanyName__ 2012. All rights reserved.
|
||||
//
|
||||
|
||||
@class RootViewController;
|
||||
|
||||
@interface AppController : NSObject <UIAccelerometerDelegate, UIAlertViewDelegate, UITextFieldDelegate,UIApplicationDelegate> {
|
||||
UIWindow *window;
|
||||
RootViewController *viewController;
|
||||
}
|
||||
|
||||
@end
|
||||
|
|
@ -0,0 +1,119 @@
|
|||
//
|
||||
// testjsAppController.mm
|
||||
// testjs
|
||||
//
|
||||
// Created by Rolando Abarca on 3/19/12.
|
||||
// Copyright __MyCompanyName__ 2012. All rights reserved.
|
||||
//
|
||||
#import <UIKit/UIKit.h>
|
||||
#import "AppController.h"
|
||||
#import "cocos2d.h"
|
||||
#import "EAGLView.h"
|
||||
#import "AppDelegate.h"
|
||||
|
||||
#import "RootViewController.h"
|
||||
|
||||
@implementation AppController
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Application lifecycle
|
||||
|
||||
// cocos2d application instance
|
||||
static AppDelegate s_sharedApplication;
|
||||
|
||||
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
|
||||
|
||||
// Override point for customization after application launch.
|
||||
|
||||
// Add the view controller's view to the window and display.
|
||||
window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
|
||||
EAGLView *__glView = [EAGLView viewWithFrame: [window bounds]
|
||||
pixelFormat: kEAGLColorFormatRGBA8
|
||||
depthFormat: GL_DEPTH_COMPONENT16 //_OES
|
||||
preserveBackbuffer: NO
|
||||
sharegroup: nil
|
||||
multiSampling: NO
|
||||
numberOfSamples: 0 ];
|
||||
|
||||
// Use RootViewController manage EAGLView
|
||||
viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil];
|
||||
viewController.wantsFullScreenLayout = YES;
|
||||
viewController.view = __glView;
|
||||
|
||||
// Set RootViewController to window
|
||||
if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0)
|
||||
{
|
||||
// warning: addSubView doesn't work on iOS6
|
||||
[window addSubview: viewController.view];
|
||||
}
|
||||
else
|
||||
{
|
||||
// use this method on ios6
|
||||
[window setRootViewController:viewController];
|
||||
}
|
||||
|
||||
[window makeKeyAndVisible];
|
||||
|
||||
[[UIApplication sharedApplication] setStatusBarHidden: YES];
|
||||
|
||||
cocos2d::CCApplication::sharedApplication()->run();
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
||||
- (void)applicationWillResignActive:(UIApplication *)application {
|
||||
/*
|
||||
Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
|
||||
Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
|
||||
*/
|
||||
cocos2d::CCDirector::sharedDirector()->pause();
|
||||
}
|
||||
|
||||
- (void)applicationDidBecomeActive:(UIApplication *)application {
|
||||
/*
|
||||
Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
|
||||
*/
|
||||
cocos2d::CCDirector::sharedDirector()->resume();
|
||||
}
|
||||
|
||||
- (void)applicationDidEnterBackground:(UIApplication *)application {
|
||||
/*
|
||||
Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
|
||||
If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
|
||||
*/
|
||||
cocos2d::CCApplication::sharedApplication()->applicationDidEnterBackground();
|
||||
}
|
||||
|
||||
- (void)applicationWillEnterForeground:(UIApplication *)application {
|
||||
/*
|
||||
Called as part of transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
|
||||
*/
|
||||
cocos2d::CCApplication::sharedApplication()->applicationWillEnterForeground();
|
||||
}
|
||||
|
||||
- (void)applicationWillTerminate:(UIApplication *)application {
|
||||
/*
|
||||
Called when the application is about to terminate.
|
||||
See also applicationDidEnterBackground:.
|
||||
*/
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Memory management
|
||||
|
||||
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
|
||||
/*
|
||||
Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
|
||||
*/
|
||||
cocos2d::CCDirector::sharedDirector()->purgeCachedData();
|
||||
}
|
||||
|
||||
|
||||
- (void)dealloc {
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
|
||||
@end
|
||||
|
|
@ -0,0 +1 @@
|
|||
66c6d1cead373b45218424f6a82f370897e443e4
|
|
@ -0,0 +1 @@
|
|||
84689888a14a2123d2b39f7f2f61be8c15207479
|
|
@ -0,0 +1,562 @@
|
|||
// !$*UTF8*$!
|
||||
{
|
||||
archiveVersion = 1;
|
||||
classes = {
|
||||
};
|
||||
objectVersion = 46;
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
1A1D97421625AFB400D5E31D /* js in Resources */ = {isa = PBXBuildFile; fileRef = 1A1D97401625AFB400D5E31D /* js */; };
|
||||
1A1D97431625AFB400D5E31D /* res in Resources */ = {isa = PBXBuildFile; fileRef = 1A1D97411625AFB400D5E31D /* res */; };
|
||||
1A7CC34016257DF6006B3D18 /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A7CC33F16257DF6006B3D18 /* QuartzCore.framework */; };
|
||||
1A7CC34216257DF6006B3D18 /* OpenGLES.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A7CC34116257DF6006B3D18 /* OpenGLES.framework */; };
|
||||
1A7CC34416257DF6006B3D18 /* OpenAL.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A7CC34316257DF6006B3D18 /* OpenAL.framework */; };
|
||||
1A7CC34616257DF6006B3D18 /* AudioToolbox.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A7CC34516257DF6006B3D18 /* AudioToolbox.framework */; };
|
||||
1A7CC34816257DF6006B3D18 /* AVFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A7CC34716257DF6006B3D18 /* AVFoundation.framework */; };
|
||||
1A7CC34A16257DF6006B3D18 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A7CC34916257DF6006B3D18 /* UIKit.framework */; };
|
||||
1A7CC34C16257DF6006B3D18 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A7CC34B16257DF6006B3D18 /* Foundation.framework */; };
|
||||
1A7CC34E16257DF6006B3D18 /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A7CC34D16257DF6006B3D18 /* CoreGraphics.framework */; };
|
||||
1A7CC72116258056006B3D18 /* AppDelegate.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A7CC71F16258056006B3D18 /* AppDelegate.cpp */; };
|
||||
1A7CC72816258081006B3D18 /* AppController.mm in Sources */ = {isa = PBXBuildFile; fileRef = 1A7CC72416258081006B3D18 /* AppController.mm */; };
|
||||
1A7CC72916258081006B3D18 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 1A7CC72516258081006B3D18 /* main.m */; };
|
||||
1A7CC72A16258081006B3D18 /* RootViewController.mm in Sources */ = {isa = PBXBuildFile; fileRef = 1A7CC72716258081006B3D18 /* RootViewController.mm */; };
|
||||
1A7CC75F16258252006B3D18 /* Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = 1A7CC75D16258252006B3D18 /* Info.plist */; };
|
||||
1A7CC76716258283006B3D18 /* Default-568h@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = 1A7CC76016258283006B3D18 /* Default-568h@2x.png */; };
|
||||
1A7CC76816258283006B3D18 /* Default.png in Resources */ = {isa = PBXBuildFile; fileRef = 1A7CC76116258283006B3D18 /* Default.png */; };
|
||||
1A7CC76916258283006B3D18 /* Default@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = 1A7CC76216258283006B3D18 /* Default@2x.png */; };
|
||||
1A7CC76A16258283006B3D18 /* Icon-57.png in Resources */ = {isa = PBXBuildFile; fileRef = 1A7CC76316258283006B3D18 /* Icon-57.png */; };
|
||||
1A7CC76B16258283006B3D18 /* Icon-72.png in Resources */ = {isa = PBXBuildFile; fileRef = 1A7CC76416258283006B3D18 /* Icon-72.png */; };
|
||||
1A7CC76C16258283006B3D18 /* Icon-114.png in Resources */ = {isa = PBXBuildFile; fileRef = 1A7CC76516258283006B3D18 /* Icon-114.png */; };
|
||||
1A7CC76D16258283006B3D18 /* Icon-144.png in Resources */ = {isa = PBXBuildFile; fileRef = 1A7CC76616258283006B3D18 /* Icon-144.png */; };
|
||||
1A7CC77C16258754006B3D18 /* cocos2d_specifics.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A7CC76E16258754006B3D18 /* cocos2d_specifics.cpp */; };
|
||||
1A7CC77D16258754006B3D18 /* cocos2dx.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A7CC77116258754006B3D18 /* cocos2dx.cpp */; };
|
||||
1A7CC77E16258754006B3D18 /* cocos2dxapi.js in Sources */ = {isa = PBXBuildFile; fileRef = 1A7CC77316258754006B3D18 /* cocos2dxapi.js */; };
|
||||
1A7CC77F16258754006B3D18 /* README in Resources */ = {isa = PBXBuildFile; fileRef = 1A7CC77416258754006B3D18 /* README */; };
|
||||
1A7CC78016258754006B3D18 /* js_manual_conversions.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A7CC77616258754006B3D18 /* js_manual_conversions.cpp */; };
|
||||
1A7CC78116258754006B3D18 /* ScriptingCore.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A7CC77816258754006B3D18 /* ScriptingCore.cpp */; };
|
||||
1A7CC782162587E0006B3D18 /* libcocos2dx.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A7CC71D16257E75006B3D18 /* libcocos2dx.a */; };
|
||||
1A7CC79216258828006B3D18 /* CDAudioManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 1A7CC78916258828006B3D18 /* CDAudioManager.m */; };
|
||||
1A7CC79316258828006B3D18 /* CDOpenALSupport.m in Sources */ = {isa = PBXBuildFile; fileRef = 1A7CC78C16258828006B3D18 /* CDOpenALSupport.m */; };
|
||||
1A7CC79416258828006B3D18 /* CocosDenshion.m in Sources */ = {isa = PBXBuildFile; fileRef = 1A7CC78E16258828006B3D18 /* CocosDenshion.m */; };
|
||||
1A7CC79516258828006B3D18 /* SimpleAudioEngine.mm in Sources */ = {isa = PBXBuildFile; fileRef = 1A7CC78F16258828006B3D18 /* SimpleAudioEngine.mm */; };
|
||||
1A7CC79616258828006B3D18 /* SimpleAudioEngine_objc.m in Sources */ = {isa = PBXBuildFile; fileRef = 1A7CC79116258828006B3D18 /* SimpleAudioEngine_objc.m */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXContainerItemProxy section */
|
||||
1A7CC71C16257E75006B3D18 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 1A7CC71516257E74006B3D18 /* cocos2dx.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 1551A33F158F2AB200E66CFE;
|
||||
remoteInfo = cocos2dx;
|
||||
};
|
||||
1A7CC730162580CE006B3D18 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 1A7CC71516257E74006B3D18 /* cocos2dx.xcodeproj */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = 1551A33E158F2AB200E66CFE;
|
||||
remoteInfo = cocos2dx;
|
||||
};
|
||||
/* End PBXContainerItemProxy section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
1A1D97401625AFB400D5E31D /* js */ = {isa = PBXFileReference; lastKnownFileType = folder; name = js; path = ../Resources/js; sourceTree = "<group>"; };
|
||||
1A1D97411625AFB400D5E31D /* res */ = {isa = PBXFileReference; lastKnownFileType = folder; name = res; path = ../Resources/res; sourceTree = "<group>"; };
|
||||
1A7CC33B16257DF5006B3D18 /* MoonWarriors.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = MoonWarriors.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
1A7CC33F16257DF6006B3D18 /* QuartzCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QuartzCore.framework; path = System/Library/Frameworks/QuartzCore.framework; sourceTree = SDKROOT; };
|
||||
1A7CC34116257DF6006B3D18 /* OpenGLES.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenGLES.framework; path = System/Library/Frameworks/OpenGLES.framework; sourceTree = SDKROOT; };
|
||||
1A7CC34316257DF6006B3D18 /* OpenAL.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenAL.framework; path = System/Library/Frameworks/OpenAL.framework; sourceTree = SDKROOT; };
|
||||
1A7CC34516257DF6006B3D18 /* AudioToolbox.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AudioToolbox.framework; path = System/Library/Frameworks/AudioToolbox.framework; sourceTree = SDKROOT; };
|
||||
1A7CC34716257DF6006B3D18 /* AVFoundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AVFoundation.framework; path = System/Library/Frameworks/AVFoundation.framework; sourceTree = SDKROOT; };
|
||||
1A7CC34916257DF6006B3D18 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; };
|
||||
1A7CC34B16257DF6006B3D18 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; };
|
||||
1A7CC34D16257DF6006B3D18 /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; };
|
||||
1A7CC71516257E74006B3D18 /* cocos2dx.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = cocos2dx.xcodeproj; path = ../../../cocos2dx/proj.ios/cocos2dx.xcodeproj; sourceTree = "<group>"; };
|
||||
1A7CC71F16258056006B3D18 /* AppDelegate.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = AppDelegate.cpp; sourceTree = "<group>"; };
|
||||
1A7CC72016258056006B3D18 /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = "<group>"; };
|
||||
1A7CC72316258081006B3D18 /* AppController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppController.h; sourceTree = "<group>"; };
|
||||
1A7CC72416258081006B3D18 /* AppController.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = AppController.mm; sourceTree = "<group>"; };
|
||||
1A7CC72516258081006B3D18 /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; };
|
||||
1A7CC72616258081006B3D18 /* RootViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RootViewController.h; sourceTree = "<group>"; };
|
||||
1A7CC72716258081006B3D18 /* RootViewController.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = RootViewController.mm; sourceTree = "<group>"; };
|
||||
1A7CC75D16258252006B3D18 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
1A7CC75E16258252006B3D18 /* Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Prefix.pch; sourceTree = "<group>"; };
|
||||
1A7CC76016258283006B3D18 /* Default-568h@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default-568h@2x.png"; sourceTree = "<group>"; };
|
||||
1A7CC76116258283006B3D18 /* Default.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = Default.png; sourceTree = "<group>"; };
|
||||
1A7CC76216258283006B3D18 /* Default@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default@2x.png"; sourceTree = "<group>"; };
|
||||
1A7CC76316258283006B3D18 /* Icon-57.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Icon-57.png"; sourceTree = "<group>"; };
|
||||
1A7CC76416258283006B3D18 /* Icon-72.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Icon-72.png"; sourceTree = "<group>"; };
|
||||
1A7CC76516258283006B3D18 /* Icon-114.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Icon-114.png"; sourceTree = "<group>"; };
|
||||
1A7CC76616258283006B3D18 /* Icon-144.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Icon-144.png"; sourceTree = "<group>"; };
|
||||
1A7CC76E16258754006B3D18 /* cocos2d_specifics.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = cocos2d_specifics.cpp; sourceTree = "<group>"; };
|
||||
1A7CC76F16258754006B3D18 /* cocos2d_specifics.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = cocos2d_specifics.hpp; sourceTree = "<group>"; };
|
||||
1A7CC77116258754006B3D18 /* cocos2dx.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = cocos2dx.cpp; sourceTree = "<group>"; };
|
||||
1A7CC77216258754006B3D18 /* cocos2dx.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = cocos2dx.hpp; sourceTree = "<group>"; };
|
||||
1A7CC77316258754006B3D18 /* cocos2dxapi.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; path = cocos2dxapi.js; sourceTree = "<group>"; };
|
||||
1A7CC77416258754006B3D18 /* README */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = README; sourceTree = "<group>"; };
|
||||
1A7CC77516258754006B3D18 /* js_bindings_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = js_bindings_config.h; sourceTree = "<group>"; };
|
||||
1A7CC77616258754006B3D18 /* js_manual_conversions.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = js_manual_conversions.cpp; sourceTree = "<group>"; };
|
||||
1A7CC77716258754006B3D18 /* js_manual_conversions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = js_manual_conversions.h; sourceTree = "<group>"; };
|
||||
1A7CC77816258754006B3D18 /* ScriptingCore.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ScriptingCore.cpp; sourceTree = "<group>"; };
|
||||
1A7CC77916258754006B3D18 /* ScriptingCore.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ScriptingCore.h; sourceTree = "<group>"; };
|
||||
1A7CC77A16258754006B3D18 /* spidermonkey_specifics.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = spidermonkey_specifics.h; sourceTree = "<group>"; };
|
||||
1A7CC77B16258754006B3D18 /* uthash.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = uthash.h; sourceTree = "<group>"; };
|
||||
1A7CC78516258828006B3D18 /* Export.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Export.h; sourceTree = "<group>"; };
|
||||
1A7CC78616258828006B3D18 /* SimpleAudioEngine.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SimpleAudioEngine.h; sourceTree = "<group>"; };
|
||||
1A7CC78816258828006B3D18 /* CDAudioManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDAudioManager.h; sourceTree = "<group>"; };
|
||||
1A7CC78916258828006B3D18 /* CDAudioManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDAudioManager.m; sourceTree = "<group>"; };
|
||||
1A7CC78A16258828006B3D18 /* CDConfig.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDConfig.h; sourceTree = "<group>"; };
|
||||
1A7CC78B16258828006B3D18 /* CDOpenALSupport.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDOpenALSupport.h; sourceTree = "<group>"; };
|
||||
1A7CC78C16258828006B3D18 /* CDOpenALSupport.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDOpenALSupport.m; sourceTree = "<group>"; };
|
||||
1A7CC78D16258828006B3D18 /* CocosDenshion.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CocosDenshion.h; sourceTree = "<group>"; };
|
||||
1A7CC78E16258828006B3D18 /* CocosDenshion.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CocosDenshion.m; sourceTree = "<group>"; };
|
||||
1A7CC78F16258828006B3D18 /* SimpleAudioEngine.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = SimpleAudioEngine.mm; sourceTree = "<group>"; };
|
||||
1A7CC79016258828006B3D18 /* SimpleAudioEngine_objc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SimpleAudioEngine_objc.h; sourceTree = "<group>"; };
|
||||
1A7CC79116258828006B3D18 /* SimpleAudioEngine_objc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SimpleAudioEngine_objc.m; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
1A7CC33816257DF5006B3D18 /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
1A7CC782162587E0006B3D18 /* libcocos2dx.a in Frameworks */,
|
||||
1A7CC34016257DF6006B3D18 /* QuartzCore.framework in Frameworks */,
|
||||
1A7CC34216257DF6006B3D18 /* OpenGLES.framework in Frameworks */,
|
||||
1A7CC34416257DF6006B3D18 /* OpenAL.framework in Frameworks */,
|
||||
1A7CC34616257DF6006B3D18 /* AudioToolbox.framework in Frameworks */,
|
||||
1A7CC34816257DF6006B3D18 /* AVFoundation.framework in Frameworks */,
|
||||
1A7CC34A16257DF6006B3D18 /* UIKit.framework in Frameworks */,
|
||||
1A7CC34C16257DF6006B3D18 /* Foundation.framework in Frameworks */,
|
||||
1A7CC34E16257DF6006B3D18 /* CoreGraphics.framework in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
1A7CC33016257DF5006B3D18 = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
1A7CC71516257E74006B3D18 /* cocos2dx.xcodeproj */,
|
||||
1A7CC732162580F9006B3D18 /* bindings */,
|
||||
1A7CC71E16258056006B3D18 /* Classes */,
|
||||
1A7CC78316258819006B3D18 /* CocosDenshion */,
|
||||
1A7CC33E16257DF5006B3D18 /* Frameworks */,
|
||||
1A7CC7221625806F006B3D18 /* ios */,
|
||||
1A7CC33C16257DF5006B3D18 /* Products */,
|
||||
1A7CC72B162580AD006B3D18 /* Resources */,
|
||||
);
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
1A7CC33C16257DF5006B3D18 /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
1A7CC33B16257DF5006B3D18 /* MoonWarriors.app */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
1A7CC33E16257DF5006B3D18 /* Frameworks */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
1A7CC33F16257DF6006B3D18 /* QuartzCore.framework */,
|
||||
1A7CC34116257DF6006B3D18 /* OpenGLES.framework */,
|
||||
1A7CC34316257DF6006B3D18 /* OpenAL.framework */,
|
||||
1A7CC34516257DF6006B3D18 /* AudioToolbox.framework */,
|
||||
1A7CC34716257DF6006B3D18 /* AVFoundation.framework */,
|
||||
1A7CC34916257DF6006B3D18 /* UIKit.framework */,
|
||||
1A7CC34B16257DF6006B3D18 /* Foundation.framework */,
|
||||
1A7CC34D16257DF6006B3D18 /* CoreGraphics.framework */,
|
||||
);
|
||||
name = Frameworks;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
1A7CC71616257E74006B3D18 /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
1A7CC71D16257E75006B3D18 /* libcocos2dx.a */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
1A7CC71E16258056006B3D18 /* Classes */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
1A7CC71F16258056006B3D18 /* AppDelegate.cpp */,
|
||||
1A7CC72016258056006B3D18 /* AppDelegate.h */,
|
||||
);
|
||||
name = Classes;
|
||||
path = ../Classes;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
1A7CC7221625806F006B3D18 /* ios */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
1A7CC75D16258252006B3D18 /* Info.plist */,
|
||||
1A7CC75E16258252006B3D18 /* Prefix.pch */,
|
||||
1A7CC72316258081006B3D18 /* AppController.h */,
|
||||
1A7CC72416258081006B3D18 /* AppController.mm */,
|
||||
1A7CC72516258081006B3D18 /* main.m */,
|
||||
1A7CC72616258081006B3D18 /* RootViewController.h */,
|
||||
1A7CC72716258081006B3D18 /* RootViewController.mm */,
|
||||
);
|
||||
name = ios;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
1A7CC72B162580AD006B3D18 /* Resources */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
1A1D97401625AFB400D5E31D /* js */,
|
||||
1A1D97411625AFB400D5E31D /* res */,
|
||||
1A7CC76016258283006B3D18 /* Default-568h@2x.png */,
|
||||
1A7CC76116258283006B3D18 /* Default.png */,
|
||||
1A7CC76216258283006B3D18 /* Default@2x.png */,
|
||||
1A7CC76316258283006B3D18 /* Icon-57.png */,
|
||||
1A7CC76416258283006B3D18 /* Icon-72.png */,
|
||||
1A7CC76516258283006B3D18 /* Icon-114.png */,
|
||||
1A7CC76616258283006B3D18 /* Icon-144.png */,
|
||||
);
|
||||
name = Resources;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
1A7CC732162580F9006B3D18 /* bindings */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
1A7CC76E16258754006B3D18 /* cocos2d_specifics.cpp */,
|
||||
1A7CC76F16258754006B3D18 /* cocos2d_specifics.hpp */,
|
||||
1A7CC77016258754006B3D18 /* generated */,
|
||||
1A7CC77516258754006B3D18 /* js_bindings_config.h */,
|
||||
1A7CC77616258754006B3D18 /* js_manual_conversions.cpp */,
|
||||
1A7CC77716258754006B3D18 /* js_manual_conversions.h */,
|
||||
1A7CC77816258754006B3D18 /* ScriptingCore.cpp */,
|
||||
1A7CC77916258754006B3D18 /* ScriptingCore.h */,
|
||||
1A7CC77A16258754006B3D18 /* spidermonkey_specifics.h */,
|
||||
1A7CC77B16258754006B3D18 /* uthash.h */,
|
||||
);
|
||||
name = bindings;
|
||||
path = ../../../scripting/javascript/bindings;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
1A7CC77016258754006B3D18 /* generated */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
1A7CC77116258754006B3D18 /* cocos2dx.cpp */,
|
||||
1A7CC77216258754006B3D18 /* cocos2dx.hpp */,
|
||||
1A7CC77316258754006B3D18 /* cocos2dxapi.js */,
|
||||
1A7CC77416258754006B3D18 /* README */,
|
||||
);
|
||||
path = generated;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
1A7CC78316258819006B3D18 /* CocosDenshion */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
1A7CC78416258828006B3D18 /* include */,
|
||||
1A7CC78716258828006B3D18 /* ios */,
|
||||
);
|
||||
name = CocosDenshion;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
1A7CC78416258828006B3D18 /* include */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
1A7CC78516258828006B3D18 /* Export.h */,
|
||||
1A7CC78616258828006B3D18 /* SimpleAudioEngine.h */,
|
||||
);
|
||||
name = include;
|
||||
path = ../../../CocosDenshion/include;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
1A7CC78716258828006B3D18 /* ios */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
1A7CC78816258828006B3D18 /* CDAudioManager.h */,
|
||||
1A7CC78916258828006B3D18 /* CDAudioManager.m */,
|
||||
1A7CC78A16258828006B3D18 /* CDConfig.h */,
|
||||
1A7CC78B16258828006B3D18 /* CDOpenALSupport.h */,
|
||||
1A7CC78C16258828006B3D18 /* CDOpenALSupport.m */,
|
||||
1A7CC78D16258828006B3D18 /* CocosDenshion.h */,
|
||||
1A7CC78E16258828006B3D18 /* CocosDenshion.m */,
|
||||
1A7CC78F16258828006B3D18 /* SimpleAudioEngine.mm */,
|
||||
1A7CC79016258828006B3D18 /* SimpleAudioEngine_objc.h */,
|
||||
1A7CC79116258828006B3D18 /* SimpleAudioEngine_objc.m */,
|
||||
);
|
||||
name = ios;
|
||||
path = ../../../CocosDenshion/ios;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
1A7CC33A16257DF5006B3D18 /* MoonWarriors */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 1A7CC70D16257E02006B3D18 /* Build configuration list for PBXNativeTarget "MoonWarriors" */;
|
||||
buildPhases = (
|
||||
1A7CC33716257DF5006B3D18 /* Sources */,
|
||||
1A7CC33816257DF5006B3D18 /* Frameworks */,
|
||||
1A7CC33916257DF5006B3D18 /* Resources */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
1A7CC731162580CE006B3D18 /* PBXTargetDependency */,
|
||||
);
|
||||
name = MoonWarriors;
|
||||
productName = MoonWarriors;
|
||||
productReference = 1A7CC33B16257DF5006B3D18 /* MoonWarriors.app */;
|
||||
productType = "com.apple.product-type.application";
|
||||
};
|
||||
/* End PBXNativeTarget section */
|
||||
|
||||
/* Begin PBXProject section */
|
||||
1A7CC33216257DF5006B3D18 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
LastUpgradeCheck = 0450;
|
||||
};
|
||||
buildConfigurationList = 1A7CC33516257DF5006B3D18 /* Build configuration list for PBXProject "MoonWarriors" */;
|
||||
compatibilityVersion = "Xcode 3.2";
|
||||
developmentRegion = English;
|
||||
hasScannedForEncodings = 0;
|
||||
knownRegions = (
|
||||
en,
|
||||
);
|
||||
mainGroup = 1A7CC33016257DF5006B3D18;
|
||||
productRefGroup = 1A7CC33C16257DF5006B3D18 /* Products */;
|
||||
projectDirPath = "";
|
||||
projectReferences = (
|
||||
{
|
||||
ProductGroup = 1A7CC71616257E74006B3D18 /* Products */;
|
||||
ProjectRef = 1A7CC71516257E74006B3D18 /* cocos2dx.xcodeproj */;
|
||||
},
|
||||
);
|
||||
projectRoot = "";
|
||||
targets = (
|
||||
1A7CC33A16257DF5006B3D18 /* MoonWarriors */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
|
||||
/* Begin PBXReferenceProxy section */
|
||||
1A7CC71D16257E75006B3D18 /* libcocos2dx.a */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = archive.ar;
|
||||
path = libcocos2dx.a;
|
||||
remoteRef = 1A7CC71C16257E75006B3D18 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
/* End PBXReferenceProxy section */
|
||||
|
||||
/* Begin PBXResourcesBuildPhase section */
|
||||
1A7CC33916257DF5006B3D18 /* Resources */ = {
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
1A7CC75F16258252006B3D18 /* Info.plist in Resources */,
|
||||
1A7CC76716258283006B3D18 /* Default-568h@2x.png in Resources */,
|
||||
1A7CC76816258283006B3D18 /* Default.png in Resources */,
|
||||
1A7CC76916258283006B3D18 /* Default@2x.png in Resources */,
|
||||
1A7CC76A16258283006B3D18 /* Icon-57.png in Resources */,
|
||||
1A7CC76B16258283006B3D18 /* Icon-72.png in Resources */,
|
||||
1A7CC76C16258283006B3D18 /* Icon-114.png in Resources */,
|
||||
1A7CC76D16258283006B3D18 /* Icon-144.png in Resources */,
|
||||
1A7CC77F16258754006B3D18 /* README in Resources */,
|
||||
1A1D97421625AFB400D5E31D /* js in Resources */,
|
||||
1A1D97431625AFB400D5E31D /* res in Resources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXResourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
1A7CC33716257DF5006B3D18 /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
1A7CC72116258056006B3D18 /* AppDelegate.cpp in Sources */,
|
||||
1A7CC72816258081006B3D18 /* AppController.mm in Sources */,
|
||||
1A7CC72916258081006B3D18 /* main.m in Sources */,
|
||||
1A7CC72A16258081006B3D18 /* RootViewController.mm in Sources */,
|
||||
1A7CC77C16258754006B3D18 /* cocos2d_specifics.cpp in Sources */,
|
||||
1A7CC77D16258754006B3D18 /* cocos2dx.cpp in Sources */,
|
||||
1A7CC77E16258754006B3D18 /* cocos2dxapi.js in Sources */,
|
||||
1A7CC78016258754006B3D18 /* js_manual_conversions.cpp in Sources */,
|
||||
1A7CC78116258754006B3D18 /* ScriptingCore.cpp in Sources */,
|
||||
1A7CC79216258828006B3D18 /* CDAudioManager.m in Sources */,
|
||||
1A7CC79316258828006B3D18 /* CDOpenALSupport.m in Sources */,
|
||||
1A7CC79416258828006B3D18 /* CocosDenshion.m in Sources */,
|
||||
1A7CC79516258828006B3D18 /* SimpleAudioEngine.mm in Sources */,
|
||||
1A7CC79616258828006B3D18 /* SimpleAudioEngine_objc.m in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXTargetDependency section */
|
||||
1A7CC731162580CE006B3D18 /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
name = cocos2dx;
|
||||
targetProxy = 1A7CC730162580CE006B3D18 /* PBXContainerItemProxy */;
|
||||
};
|
||||
/* End PBXTargetDependency section */
|
||||
|
||||
/* Begin XCBuildConfiguration section */
|
||||
1A7CC70B16257E02006B3D18 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ARCHS = "$(ARCHS_STANDARD_32_BIT)";
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
|
||||
GCC_C_LANGUAGE_STANDARD = gnu99;
|
||||
GCC_OPTIMIZATION_LEVEL = 0;
|
||||
GCC_PREPROCESSOR_DEFINITIONS = (
|
||||
DEBUG,
|
||||
"COCOS2D_DEBUG=1",
|
||||
USE_FILE32API,
|
||||
TARGET_OS_IPHONE,
|
||||
COCOS2D_JAVASCRIPT,
|
||||
);
|
||||
GCC_SYMBOLS_PRIVATE_EXTERN = NO;
|
||||
GCC_WARN_ABOUT_RETURN_TYPE = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
HEADER_SEARCH_PATHS = (
|
||||
"\"$(PROJECT_NAME)/libs/cocos2dx/kazmath/include\"",
|
||||
"\"$(PROJECT_NAME)/libs/cocos2dx\"",
|
||||
"\"$(PROJECT_NAME)/libs/CocosDenshion/include\"",
|
||||
"\"$(SDKROOT)/usr/include/libxml2\"",
|
||||
"\"$(PROJECT_NAME)/libs/cocos2dx/include\"",
|
||||
"\"$(PROJECT_NAME)/libs/cocos2dx/platform/third_party/ios\"",
|
||||
"\"$(PROJECT_NAME)/libs/cocos2dx/platform/ios\"",
|
||||
);
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 6.0;
|
||||
SDKROOT = iphoneos;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
1A7CC70C16257E02006B3D18 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ARCHS = "$(ARCHS_STANDARD_32_BIT)";
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
|
||||
GCC_C_LANGUAGE_STANDARD = gnu99;
|
||||
GCC_PREPROCESSOR_DEFINITIONS = (
|
||||
NDEBUG,
|
||||
USE_FILE32API,
|
||||
TARGET_OS_IPHONE,
|
||||
COCOS2D_JAVASCRIPT,
|
||||
);
|
||||
GCC_WARN_ABOUT_RETURN_TYPE = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
HEADER_SEARCH_PATHS = (
|
||||
"\"$(PROJECT_NAME)/libs/cocos2dx/kazmath/include\"",
|
||||
"\"$(PROJECT_NAME)/libs/cocos2dx\"",
|
||||
"\"$(PROJECT_NAME)/libs/CocosDenshion/include\"",
|
||||
"\"$(SDKROOT)/usr/include/libxml2\"",
|
||||
"\"$(PROJECT_NAME)/libs/cocos2dx/include\"",
|
||||
"\"$(PROJECT_NAME)/libs/cocos2dx/platform/third_party/ios\"",
|
||||
"\"$(PROJECT_NAME)/libs/cocos2dx/platform/ios\"",
|
||||
);
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 6.0;
|
||||
OTHER_CFLAGS = "-DNS_BLOCK_ASSERTIONS=1";
|
||||
SDKROOT = iphoneos;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
1A7CC70E16257E02006B3D18 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
GCC_DYNAMIC_NO_PIC = NO;
|
||||
GCC_PRECOMPILE_PREFIX_HEADER = YES;
|
||||
GCC_PREFIX_HEADER = Prefix.pch;
|
||||
"GCC_THUMB_SUPPORT[arch=armv6]" = "";
|
||||
HEADER_SEARCH_PATHS = (
|
||||
"\"$(SRCROOT)/../../../cocos2dx/kazmath/include\"",
|
||||
"\"$(SRCROOT)/../../../cocos2dx\"",
|
||||
"\"$(SRCROOT)/../../../CocosDenshion/include\"",
|
||||
"\"$(SDKROOT)/usr/include/libxml2\"",
|
||||
"\"$(SRCROOT)/../../../cocos2dx/include\"",
|
||||
"\"$(SRCROOT)/../../../cocos2dx/platform/third_party/ios\"",
|
||||
"\"$(SRCROOT)/../../../cocos2dx/platform/ios\"",
|
||||
"$(SRCROOT)/../../../scripting/javascript/spidermonkey-ios/include",
|
||||
"$(SRCROOT)/../../../scripting/javascript/bindings",
|
||||
);
|
||||
INFOPLIST_FILE = Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 5.1;
|
||||
LIBRARY_SEARCH_PATHS = "\"$(SRCROOT)/../../../scripting/javascript/spidermonkey-ios/lib\"";
|
||||
OTHER_LDFLAGS = (
|
||||
"-lxml2",
|
||||
"-lz",
|
||||
"-ljs_static",
|
||||
);
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
USER_HEADER_SEARCH_PATHS = "";
|
||||
WRAPPER_EXTENSION = app;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
1A7CC70F16257E02006B3D18 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
COPY_PHASE_STRIP = YES;
|
||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
GCC_PRECOMPILE_PREFIX_HEADER = YES;
|
||||
GCC_PREFIX_HEADER = Prefix.pch;
|
||||
"GCC_THUMB_SUPPORT[arch=armv6]" = "";
|
||||
HEADER_SEARCH_PATHS = (
|
||||
"\"$(SRCROOT)/../../../cocos2dx/kazmath/include\"",
|
||||
"\"$(SRCROOT)/../../../cocos2dx\"",
|
||||
"\"$(SRCROOT)/../../../CocosDenshion/include\"",
|
||||
"\"$(SDKROOT)/usr/include/libxml2\"",
|
||||
"\"$(SRCROOT)/../../../cocos2dx/include\"",
|
||||
"\"$(SRCROOT)/../../../cocos2dx/platform/third_party/ios\"",
|
||||
"\"$(SRCROOT)/../../../cocos2dx/platform/ios\"",
|
||||
"$(SRCROOT)/../../../scripting/javascript/spidermonkey-ios/include",
|
||||
"$(SRCROOT)/../../../scripting/javascript/bindings",
|
||||
);
|
||||
INFOPLIST_FILE = Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 5.1;
|
||||
LIBRARY_SEARCH_PATHS = "\"$(SRCROOT)/../../../scripting/javascript/spidermonkey-ios/lib\"";
|
||||
OTHER_LDFLAGS = (
|
||||
"-lxml2",
|
||||
"-lz",
|
||||
"-ljs_static",
|
||||
);
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
USER_HEADER_SEARCH_PATHS = "";
|
||||
VALIDATE_PRODUCT = YES;
|
||||
WRAPPER_EXTENSION = app;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
1A7CC33516257DF5006B3D18 /* Build configuration list for PBXProject "MoonWarriors" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
1A7CC70B16257E02006B3D18 /* Debug */,
|
||||
1A7CC70C16257E02006B3D18 /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
1A7CC70D16257E02006B3D18 /* Build configuration list for PBXNativeTarget "MoonWarriors" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
1A7CC70E16257E02006B3D18 /* Debug */,
|
||||
1A7CC70F16257E02006B3D18 /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
/* End XCConfigurationList section */
|
||||
};
|
||||
rootObject = 1A7CC33216257DF5006B3D18 /* Project object */;
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
//
|
||||
// Prefix header for all source files of the 'testjs' target in the 'testjs' project
|
||||
//
|
||||
|
||||
#ifdef __OBJC__
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <UIKit/UIKit.h>
|
||||
#endif
|
|
@ -0,0 +1,33 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2010-2011 cocos2d-x.org
|
||||
Copyright (c) 2010 Ricardo Quesada
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
|
||||
@interface RootViewController : UIViewController {
|
||||
|
||||
}
|
||||
|
||||
@end
|
|
@ -0,0 +1,73 @@
|
|||
//
|
||||
// testjsAppController.h
|
||||
// testjs
|
||||
//
|
||||
// Created by Rolando Abarca on 3/19/12.
|
||||
// Copyright __MyCompanyName__ 2012. All rights reserved.
|
||||
//
|
||||
|
||||
#import "RootViewController.h"
|
||||
|
||||
|
||||
@implementation RootViewController
|
||||
|
||||
/*
|
||||
// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
|
||||
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
|
||||
if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
|
||||
// Custom initialization
|
||||
}
|
||||
return self;
|
||||
}
|
||||
*/
|
||||
|
||||
/*
|
||||
// Implement loadView to create a view hierarchy programmatically, without using a nib.
|
||||
- (void)loadView {
|
||||
}
|
||||
*/
|
||||
|
||||
/*
|
||||
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
|
||||
- (void)viewDidLoad {
|
||||
[super viewDidLoad];
|
||||
}
|
||||
|
||||
*/
|
||||
// Override to allow orientations other than the default portrait orientation.
|
||||
// This method is deprecated on ios6
|
||||
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
|
||||
return UIInterfaceOrientationIsLandscape( interfaceOrientation );
|
||||
}
|
||||
|
||||
// For ios6, use supportedInterfaceOrientations & shouldAutorotate instead
|
||||
- (NSUInteger) supportedInterfaceOrientations{
|
||||
#ifdef __IPHONE_6_0
|
||||
return UIInterfaceOrientationMaskAllButUpsideDown;
|
||||
#endif
|
||||
}
|
||||
|
||||
- (BOOL) shouldAutorotate {
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (void)didReceiveMemoryWarning {
|
||||
// Releases the view if it doesn't have a superview.
|
||||
[super didReceiveMemoryWarning];
|
||||
|
||||
// Release any cached data, images, etc that aren't in use.
|
||||
}
|
||||
|
||||
- (void)viewDidUnload {
|
||||
[super viewDidUnload];
|
||||
// Release any retained subviews of the main view.
|
||||
// e.g. self.myOutlet = nil;
|
||||
}
|
||||
|
||||
|
||||
- (void)dealloc {
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
|
||||
@end
|
|
@ -0,0 +1,17 @@
|
|||
//
|
||||
// main.m
|
||||
// testjs
|
||||
//
|
||||
// Created by Rolando Abarca on 3/19/12.
|
||||
// Copyright __MyCompanyName__ 2012. All rights reserved.
|
||||
//
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
|
||||
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
|
||||
int retVal = UIApplicationMain(argc, argv, nil, @"AppController");
|
||||
[pool release];
|
||||
return retVal;
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue