From b0d7ecec420e6cf6aea544f3740d08ec0e0ffbc9 Mon Sep 17 00:00:00 2001 From: yodesoft Date: Mon, 3 Sep 2012 12:38:29 +0800 Subject: [PATCH 01/15] Supported display Unicode chars. --- cocos2dx/platform/linux/CCImage.cpp | 174 +++++++++++++++++----------- 1 file changed, 107 insertions(+), 67 deletions(-) diff --git a/cocos2dx/platform/linux/CCImage.cpp b/cocos2dx/platform/linux/CCImage.cpp index 0925eb7cc0..3e65ef7919 100644 --- a/cocos2dx/platform/linux/CCImage.cpp +++ b/cocos2dx/platform/linux/CCImage.cpp @@ -22,8 +22,8 @@ using namespace std; struct TextLine { - string sLineStr; int iLineWidth; + wchar_t* text; }; NS_CC_BEGIN @@ -43,89 +43,134 @@ public: // if (m_pData) { // delete m_pData; // } - + reset(); } void reset() { iMaxLineWidth = 0; iMaxLineHeight = 0; - vLines.clear(); + //Free all text lines + size_t size = vLines.size(); + for (int i=0; iglyph->metrics.horiAdvance + face->glyph->metrics.horiBearingX - face->glyph->metrics.width))/*-iInterval*/;//TODO interval + return a; + } + if ((**p & 0xE0) == 0xC0) + { + int a = *((*p)++) & 0x1F; + int b = *((*p)++) & 0x3F; + + return (a << 6) | b; + } + if ((**p & 0xF0) == 0xE0) + { + int a = *((*p)++) & 0x0F; + int b = *((*p)++) & 0x3F; + int c = *((*p)++) & 0x3F; + + return (a << 12) | (b << 6) | c; + } + if ((**p & 0xF8) == 0xF0) + { + int a = *((*p)++) & 0x07; + int b = *((*p)++) & 0x3F; + int c = *((*p)++) & 0x3F; + int d = *((*p)++) & 0x3F; + + return (a << 18) | (b << 12) | (c << 8) | d; + } + return 0; + } + + void buildLine(wchar_t* buf, size_t buf_len, FT_Face face, int iCurXCursor, FT_UInt cLastChar) { + TextLine oTempLine; + wchar_t* text = (wchar_t*)malloc(sizeof(wchar_t) * (buf_len+1)); + memcpy(text, buf, sizeof(wchar_t) * buf_len); + text[buf_len] = '\0'; + oTempLine.text = text; + + //get last glyph + int iError = FT_Load_Char(face, cLastChar, FT_LOAD_DEFAULT); + + oTempLine.iLineWidth = iCurXCursor;// - SHIFT6((face->glyph->metrics.horiAdvance + face->glyph->metrics.horiBearingX - face->glyph->metrics.width))/*-iInterval*/;//TODO interval iMaxLineWidth = MAX(iMaxLineWidth, oTempLine.iLineWidth); - ss.clear(); - ss.str(""); - vLines.push_back(oTempLine); + vLines.push_back(oTempLine); } bool divideString(FT_Face face, const char* sText, int iMaxWidth, int iMaxHeight) { - const char* pText = sText; int iError = 0; int iCurXCursor, iCurYCursor; - iError = FT_Load_Glyph(face, FT_Get_Char_Index(face, *pText), - FT_LOAD_DEFAULT); + const char* pText = sText; + + FT_UInt unicode = utf8((char**)&pText); + iError = FT_Load_Char(face, unicode, FT_LOAD_DEFAULT); if (iError) { return false; } iCurXCursor = -SHIFT6(face->glyph->metrics.horiBearingX); - //init stringstream - stringstream ss; + FT_UInt cLastCh = 0; - int cLastCh = 0; + pText = sText; + size_t text_len = 0; + wchar_t* text_buf = (wchar_t*) malloc(sizeof(wchar_t) * strlen(sText)); + while (unicode=utf8((char**)&pText)) { + if (unicode == '\n') { + buildLine(text_buf, text_len, face, iCurXCursor, cLastCh); + text_len = 0; - while (*pText != '\0') { - if (*pText == '\n') { - buildLine(ss, face, iCurXCursor, cLastCh); - - pText++; - iError = FT_Load_Glyph(face, FT_Get_Char_Index(face, *pText), - FT_LOAD_DEFAULT); + iError = FT_Load_Char(face, unicode, FT_LOAD_DEFAULT); if (iError) { + free(text_buf); return false; } iCurXCursor = -SHIFT6(face->glyph->metrics.horiBearingX); continue; } - iError = FT_Load_Glyph(face, FT_Get_Char_Index(face, *pText), - FT_LOAD_DEFAULT); + iError = FT_Load_Char(face, unicode, FT_LOAD_DEFAULT); if (iError) { + free(text_buf); return false; - //break; } + //check its width //divide it when exceeding if ((iMaxWidth > 0 && iCurXCursor + SHIFT6(face->glyph->metrics.width) > iMaxWidth)) { - buildLine(ss, face , iCurXCursor, cLastCh); + buildLine(text_buf, text_len, face , iCurXCursor, cLastCh); + text_len = 0; iCurXCursor = -SHIFT6(face->glyph->metrics.horiBearingX); } - cLastCh = *pText; - ss << *pText; + cLastCh = unicode; + text_buf[text_len] = unicode; + ++text_len; iCurXCursor += SHIFT6(face->glyph->metrics.horiAdvance) + iInterval; - pText++; - } + if (iError) { + free(text_buf); return false; } - buildLine(ss,face, iCurXCursor, cLastCh); + buildLine(text_buf, text_len, face, iCurXCursor, cLastCh); + free(text_buf); return true; } @@ -137,11 +182,10 @@ public: * while -1 means fail * */ - int computeLineStart(FT_Face face, CCImage::ETextAlign eAlignMask, char cText, + int computeLineStart(FT_Face face, CCImage::ETextAlign eAlignMask, FT_UInt unicode, int iLineIndex) { int iRet; - int iError = FT_Load_Glyph(face, FT_Get_Char_Index(face, cText), - FT_LOAD_DEFAULT); + int iError = FT_Load_Char(face, unicode, FT_LOAD_DEFAULT); if (iError) { return -1; } @@ -183,7 +227,6 @@ public: FT_Face face; FT_Error iError; - const char* pText = text; //data will be deleted by CCImage // if (m_pData) { // delete m_pData; @@ -195,7 +238,9 @@ public: return false; } do { - iError = FT_New_Face( library, pFontName, 0, &face ); + //iError = FT_New_Face( library, pFontName, 0, &face ); + //TODO: Create font name array??? + iError = FT_New_Face( library, "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc", 0, &face ); if (iError) { //no valid font found use default @@ -216,8 +261,7 @@ public: //compute the final line width iMaxLineWidth = MAX(iMaxLineWidth, nWidth); - iMaxLineHeight = (face->size->metrics.ascender >> 6) - - (face->size->metrics.descender >> 6); + iMaxLineHeight = (face->size->metrics.ascender >> 6) - (face->size->metrics.descender >> 6); iMaxLineHeight *= vLines.size(); int txtHeight = iMaxLineHeight; @@ -230,31 +274,34 @@ public: memset(m_pData,0, iMaxLineWidth * iMaxLineHeight*4); - for (size_t i = 0; i < vLines.size(); i++) { - pText = vLines[i].sLineStr.c_str(); - //initialize the origin cursor - iCurXCursor = computeLineStart(face, eAlignMask, *pText, i); + size_t lines = vLines.size(); + for (size_t i = 0; i < lines; i++) { + const wchar_t* text_ptr = vLines[i].text; - while (*pText != 0) { - int iError = FT_Load_Glyph(face, FT_Get_Char_Index(face, *pText), - FT_LOAD_RENDER); + //initialize the origin cursor + iCurXCursor = computeLineStart(face, eAlignMask, text_ptr[0], i); + + size_t text_len = wcslen(text_ptr); + for (size_t i=0; iglyph->bitmap; + FT_Bitmap& bitmap = face->glyph->bitmap; + int yoffset = iCurYCursor - (face->glyph->metrics.horiBearingY >> 6); + int xoffset = iCurXCursor + (face->glyph->metrics.horiBearingX >> 6); for (int i = 0; i < bitmap.rows; ++i) { for (int j = 0; j < bitmap.width; ++j) { + unsigned char cTemp = bitmap.buffer[i * bitmap.width + j]; + if (cTemp == 0) continue; + // if it has gray>0 we set show it as 1, o otherwise - int iY = iCurYCursor + i - - (face->glyph->metrics.horiBearingY - >> 6); - int iX = iCurXCursor - + (face->glyph->metrics.horiBearingX - >> 6) + j; + int iY = yoffset + i; + int iX = xoffset + j; if (iY>=iMaxLineHeight) { //exceed the height truncate @@ -270,20 +317,16 @@ public: // bitmap.buffer[i * bitmap.width + j];//G // m_pData[(iY * iMaxLineWidth + iX) * 4 + 0] = // bitmap.buffer[i * bitmap.width + j];//B + int iTemp = 0; - unsigned char cTemp = bitmap.buffer[i - * bitmap.width + j]; iTemp |= (cTemp ? 0xff : 0)<<24; iTemp |= cTemp << 16 | cTemp << 8 | cTemp; - *(int*) &m_pData[(iY * iMaxLineWidth + iX) - * 4 + 0] = iTemp; + *(int*) &m_pData[(iY * iMaxLineWidth + iX) * 4 + 0] = iTemp; } } //step to next glyph - iCurXCursor += (face->glyph->metrics.horiAdvance >> 6) - + iInterval; + iCurXCursor += (face->glyph->metrics.horiAdvance >> 6) + iInterval; - pText++; } iCurYCursor += (face->size->metrics.ascender >> 6) - (face->size->metrics.descender >> 6); @@ -301,9 +344,6 @@ public: FT_Done_Face(face); face = NULL; - //clear all lines - vLines.clear(); - //success; if (iError) { bRet = false; From 95f204cd17e0ed31484aeb25eafb25588f5b2a33 Mon Sep 17 00:00:00 2001 From: yodesoft Date: Tue, 4 Sep 2012 10:48:02 +0800 Subject: [PATCH 02/15] Add font table to handler font info, eg. family_name, style_name, filename --- cocos2dx/platform/linux/CCImage.cpp | 48 ++++++++++++++++++++++++++--- 1 file changed, 43 insertions(+), 5 deletions(-) diff --git a/cocos2dx/platform/linux/CCImage.cpp b/cocos2dx/platform/linux/CCImage.cpp index 3e65ef7919..e9ea9daa2e 100644 --- a/cocos2dx/platform/linux/CCImage.cpp +++ b/cocos2dx/platform/linux/CCImage.cpp @@ -26,6 +26,21 @@ struct TextLine { wchar_t* text; }; +struct FontTableItem { + char* family_name; + char* style_name; + char* filename; +}; + +const int fontTableItems = 4; +const char* fontPath = "/usr/share/fonts/truetype/"; +FontTableItem fontsTable[fontTableItems] = { + { "Serif", "Medium", "freefont/FreeSerif.ttf" }, + { "Sans", "Medium", "freefont/FreeSans.ttf" }, + { "WenQuanYi Micro Hei", "Regular", "wqy/wqy-microhei.ttc" }, + { "WenQuanYi Zen Hei", "Regular", "wqy/wqy-zenhei.ttc" }, +}; + NS_CC_BEGIN class BitmapDC { @@ -223,6 +238,29 @@ public: return iRet; } + char* getFontFile(const char* family_name) { + char* ret = NULL; + for (int i=0; ifamily_name, family_name) == 0) { + size_t len = strlen(fontPath) + strlen(item->filename) + 1; + ret = (char*) malloc(len); + snprintf(ret, len, "%s%s", fontPath, item->filename); + break; + } + } + + // Return a default font , if font is not found + if (ret == NULL) { + FontTableItem* item = &fontsTable[0]; + size_t len = strlen(fontPath) + strlen(item->filename) + 1; + ret = (char*) malloc(len); + snprintf(ret, len, "%s%s", fontPath, item->filename); + } + + return ret; + } + bool getBitmap(const char *text, int nWidth, int nHeight, CCImage::ETextAlign eAlignMask, const char * pFontName, float fontSize) { FT_Face face; FT_Error iError; @@ -238,9 +276,9 @@ public: return false; } do { - //iError = FT_New_Face( library, pFontName, 0, &face ); - //TODO: Create font name array??? - iError = FT_New_Face( library, "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc", 0, &face ); + char* fontfile = getFontFile(pFontName); + iError = FT_New_Face( library, fontfile, 0, &face ); + free(fontfile); if (iError) { //no valid font found use default @@ -384,9 +422,9 @@ bool CCImage::initWithString( BitmapDC &dc = sharedBitmapDC(); - const char* pFullFontName = CCFileUtils::sharedFileUtils()->fullPathFromRelativePath(pFontName); + //const char* pFullFontName = CCFileUtils::sharedFileUtils()->fullPathFromRelativePath(pFontName); - CC_BREAK_IF(! dc.getBitmap(pText, nWidth, nHeight, eAlignMask, pFullFontName, nSize)); + CC_BREAK_IF(! dc.getBitmap(pText, nWidth, nHeight, eAlignMask, pFontName, nSize)); // assign the dc.m_pData to m_pData in order to save time m_pData = dc.m_pData; From 856763e1d6a144bb82db0c14a7b144e42b522ef1 Mon Sep 17 00:00:00 2001 From: trentm Date: Tue, 4 Sep 2012 10:55:00 -0600 Subject: [PATCH 03/15] Change 2012 solution version number. --- cocos2d-win32.vc2012.sln | 190 +++++++++++++++++++-------------------- 1 file changed, 95 insertions(+), 95 deletions(-) diff --git a/cocos2d-win32.vc2012.sln b/cocos2d-win32.vc2012.sln index 8245115887..455a21bf06 100644 --- a/cocos2d-win32.vc2012.sln +++ b/cocos2d-win32.vc2012.sln @@ -1,5 +1,99 @@  -Microsoft Visual Studio Solution File, Format Version 11.00 +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2012 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libBox2D", "external\Box2D\proj.win32\Box2D.vcxproj", "{929480E7-23C0-4DF6-8456-096D71547116}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libchipmunk", "external\chipmunk\proj.win32\chipmunk.vcxproj", "{207BC7A9-CCF1-4F2F-A04D-45F72242AE25}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libCocosDenshion", "CocosDenshion\proj.win32\CocosDenshion.vcxproj", "{F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libcocos2d", "cocos2dx\proj.win32\cocos2d.vcxproj", "{98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "liblua", "scripting\lua\proj.win32\liblua.vcxproj", "{DDC3E27F-004D-4DD4-9DD3-931A013D2159}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloLua", "samples\HelloLua\proj.win32\HelloLua.vcxproj", "{13E55395-94A2-4CD9-BFC2-1A051F80C17D}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloCpp", "samples\HelloCpp\proj.win32\HelloCpp.vcxproj", "{B8BF9E81-35FD-4582-BA1C-B85FA365BABB}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestCpp", "samples\TestCpp\proj.win32\TestCpp.vcxproj", "{76A39BB2-9B84-4C65-98A5-654D86B86F2A}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestJavascript", "samples\TestJavascript\proj.win32\TestJavascript.vcxproj", "{D0F06A44-A245-4D13-A498-0120C203B539}" + ProjectSection(ProjectDependencies) = postProject + {207BC7A9-CCF1-4F2F-A04D-45F72242AE25} = {207BC7A9-CCF1-4F2F-A04D-45F72242AE25} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libExtensions", "extensions\proj.win32\libExtensions.vcxproj", "{21B2C324-891F-48EA-AD1A-5AE13DE12E28}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestLua", "samples\TestLua\proj.win32\TestLua.win32.vcxproj", "{4E6A7A0E-DDD8-4BAA-8B22-C964069364ED}" + ProjectSection(ProjectDependencies) = postProject + {21B2C324-891F-48EA-AD1A-5AE13DE12E28} = {21B2C324-891F-48EA-AD1A-5AE13DE12E28} + {DDC3E27F-004D-4DD4-9DD3-931A013D2159} = {DDC3E27F-004D-4DD4-9DD3-931A013D2159} + {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} = {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} + {207BC7A9-CCF1-4F2F-A04D-45F72242AE25} = {207BC7A9-CCF1-4F2F-A04D-45F72242AE25} + {929480E7-23C0-4DF6-8456-096D71547116} = {929480E7-23C0-4DF6-8456-096D71547116} + {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} = {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} + EndProjectSection +EndProject +Global + GlobalSection(DPCodeReviewSolutionGUID) = preSolution + DPCodeReviewSolutionGUID = {00000000-0000-0000-0000-000000000000} + EndGlobalSection + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {929480E7-23C0-4DF6-8456-096D71547116}.Debug|Win32.ActiveCfg = Debug|Win32 + {929480E7-23C0-4DF6-8456-096D71547116}.Debug|Win32.Build.0 = Debug|Win32 + {929480E7-23C0-4DF6-8456-096D71547116}.Release|Win32.ActiveCfg = Release|Win32 + {929480E7-23C0-4DF6-8456-096D71547116}.Release|Win32.Build.0 = Release|Win32 + {207BC7A9-CCF1-4F2F-A04D-45F72242AE25}.Debug|Win32.ActiveCfg = Debug|Win32 + {207BC7A9-CCF1-4F2F-A04D-45F72242AE25}.Debug|Win32.Build.0 = Debug|Win32 + {207BC7A9-CCF1-4F2F-A04D-45F72242AE25}.Release|Win32.ActiveCfg = Release|Win32 + {207BC7A9-CCF1-4F2F-A04D-45F72242AE25}.Release|Win32.Build.0 = Release|Win32 + {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Debug|Win32.ActiveCfg = Debug|Win32 + {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Debug|Win32.Build.0 = Debug|Win32 + {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Release|Win32.ActiveCfg = Release|Win32 + {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Release|Win32.Build.0 = Release|Win32 + {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}.Debug|Win32.ActiveCfg = Debug|Win32 + {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}.Debug|Win32.Build.0 = Debug|Win32 + {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}.Release|Win32.ActiveCfg = Release|Win32 + {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}.Release|Win32.Build.0 = Release|Win32 + {DDC3E27F-004D-4DD4-9DD3-931A013D2159}.Debug|Win32.ActiveCfg = Debug|Win32 + {DDC3E27F-004D-4DD4-9DD3-931A013D2159}.Debug|Win32.Build.0 = Debug|Win32 + {DDC3E27F-004D-4DD4-9DD3-931A013D2159}.Release|Win32.ActiveCfg = Release|Win32 + {DDC3E27F-004D-4DD4-9DD3-931A013D2159}.Release|Win32.Build.0 = Release|Win32 + {13E55395-94A2-4CD9-BFC2-1A051F80C17D}.Debug|Win32.ActiveCfg = Debug|Win32 + {13E55395-94A2-4CD9-BFC2-1A051F80C17D}.Debug|Win32.Build.0 = Debug|Win32 + {13E55395-94A2-4CD9-BFC2-1A051F80C17D}.Release|Win32.ActiveCfg = Release|Win32 + {13E55395-94A2-4CD9-BFC2-1A051F80C17D}.Release|Win32.Build.0 = Release|Win32 + {B8BF9E81-35FD-4582-BA1C-B85FA365BABB}.Debug|Win32.ActiveCfg = Debug|Win32 + {B8BF9E81-35FD-4582-BA1C-B85FA365BABB}.Debug|Win32.Build.0 = Debug|Win32 + {B8BF9E81-35FD-4582-BA1C-B85FA365BABB}.Release|Win32.ActiveCfg = Release|Win32 + {B8BF9E81-35FD-4582-BA1C-B85FA365BABB}.Release|Win32.Build.0 = Release|Win32 + {76A39BB2-9B84-4C65-98A5-654D86B86F2A}.Debug|Win32.ActiveCfg = Debug|Win32 + {76A39BB2-9B84-4C65-98A5-654D86B86F2A}.Debug|Win32.Build.0 = Debug|Win32 + {76A39BB2-9B84-4C65-98A5-654D86B86F2A}.Release|Win32.ActiveCfg = Release|Win32 + {76A39BB2-9B84-4C65-98A5-654D86B86F2A}.Release|Win32.Build.0 = Release|Win32 + {D0F06A44-A245-4D13-A498-0120C203B539}.Debug|Win32.ActiveCfg = Debug|Win32 + {D0F06A44-A245-4D13-A498-0120C203B539}.Debug|Win32.Build.0 = Debug|Win32 + {D0F06A44-A245-4D13-A498-0120C203B539}.Release|Win32.ActiveCfg = Release|Win32 + {D0F06A44-A245-4D13-A498-0120C203B539}.Release|Win32.Build.0 = Release|Win32 + {21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Debug|Win32.ActiveCfg = Debug|Win32 + {21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Debug|Win32.Build.0 = Debug|Win32 + {21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Release|Win32.ActiveCfg = Release|Win32 + {21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Release|Win32.Build.0 = Release|Win32 + {4E6A7A0E-DDD8-4BAA-8B22-C964069364ED}.Debug|Win32.ActiveCfg = Debug|Win32 + {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 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal + +Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libBox2D", "external\Box2D\proj.win32\Box2D.vcxproj", "{929480E7-23C0-4DF6-8456-096D71547116}" EndProject @@ -92,97 +186,3 @@ Global HideSolutionNode = FALSE EndGlobalSection EndGlobal - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2012 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libBox2D", "external\Box2D\proj.win32\Box2D.vcxproj", "{929480E7-23C0-4DF6-8456-096D71547116}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libchipmunk", "external\chipmunk\proj.win32\chipmunk.vcxproj", "{207BC7A9-CCF1-4F2F-A04D-45F72242AE25}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libCocosDenshion", "CocosDenshion\proj.win32\CocosDenshion.vcxproj", "{F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libcocos2d", "cocos2dx\proj.win32\cocos2d.vcxproj", "{98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "liblua", "scripting\lua\proj.win32\liblua.vcxproj", "{DDC3E27F-004D-4DD4-9DD3-931A013D2159}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloLua", "samples\HelloLua\proj.win32\HelloLua.vcxproj", "{13E55395-94A2-4CD9-BFC2-1A051F80C17D}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloCpp", "samples\HelloCpp\proj.win32\HelloCpp.vcxproj", "{B8BF9E81-35FD-4582-BA1C-B85FA365BABB}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestCpp", "samples\TestCpp\proj.win32\TestCpp.vcxproj", "{76A39BB2-9B84-4C65-98A5-654D86B86F2A}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestJavascript", "samples\TestJavascript\proj.win32\TestJavascript.vcxproj", "{D0F06A44-A245-4D13-A498-0120C203B539}" - ProjectSection(ProjectDependencies) = postProject - {207BC7A9-CCF1-4F2F-A04D-45F72242AE25} = {207BC7A9-CCF1-4F2F-A04D-45F72242AE25} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libExtensions", "extensions\proj.win32\libExtensions.vcxproj", "{21B2C324-891F-48EA-AD1A-5AE13DE12E28}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestLua", "samples\TestLua\proj.win32\TestLua.win32.vcxproj", "{4E6A7A0E-DDD8-4BAA-8B22-C964069364ED}" - ProjectSection(ProjectDependencies) = postProject - {21B2C324-891F-48EA-AD1A-5AE13DE12E28} = {21B2C324-891F-48EA-AD1A-5AE13DE12E28} - {DDC3E27F-004D-4DD4-9DD3-931A013D2159} = {DDC3E27F-004D-4DD4-9DD3-931A013D2159} - {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} = {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} - {207BC7A9-CCF1-4F2F-A04D-45F72242AE25} = {207BC7A9-CCF1-4F2F-A04D-45F72242AE25} - {929480E7-23C0-4DF6-8456-096D71547116} = {929480E7-23C0-4DF6-8456-096D71547116} - {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} = {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} - EndProjectSection -EndProject -Global - GlobalSection(DPCodeReviewSolutionGUID) = preSolution - DPCodeReviewSolutionGUID = {00000000-0000-0000-0000-000000000000} - EndGlobalSection - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Release|Win32 = Release|Win32 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {929480E7-23C0-4DF6-8456-096D71547116}.Debug|Win32.ActiveCfg = Debug|Win32 - {929480E7-23C0-4DF6-8456-096D71547116}.Debug|Win32.Build.0 = Debug|Win32 - {929480E7-23C0-4DF6-8456-096D71547116}.Release|Win32.ActiveCfg = Release|Win32 - {929480E7-23C0-4DF6-8456-096D71547116}.Release|Win32.Build.0 = Release|Win32 - {207BC7A9-CCF1-4F2F-A04D-45F72242AE25}.Debug|Win32.ActiveCfg = Debug|Win32 - {207BC7A9-CCF1-4F2F-A04D-45F72242AE25}.Debug|Win32.Build.0 = Debug|Win32 - {207BC7A9-CCF1-4F2F-A04D-45F72242AE25}.Release|Win32.ActiveCfg = Release|Win32 - {207BC7A9-CCF1-4F2F-A04D-45F72242AE25}.Release|Win32.Build.0 = Release|Win32 - {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Debug|Win32.ActiveCfg = Debug|Win32 - {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Debug|Win32.Build.0 = Debug|Win32 - {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Release|Win32.ActiveCfg = Release|Win32 - {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Release|Win32.Build.0 = Release|Win32 - {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}.Debug|Win32.ActiveCfg = Debug|Win32 - {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}.Debug|Win32.Build.0 = Debug|Win32 - {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}.Release|Win32.ActiveCfg = Release|Win32 - {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}.Release|Win32.Build.0 = Release|Win32 - {DDC3E27F-004D-4DD4-9DD3-931A013D2159}.Debug|Win32.ActiveCfg = Debug|Win32 - {DDC3E27F-004D-4DD4-9DD3-931A013D2159}.Debug|Win32.Build.0 = Debug|Win32 - {DDC3E27F-004D-4DD4-9DD3-931A013D2159}.Release|Win32.ActiveCfg = Release|Win32 - {DDC3E27F-004D-4DD4-9DD3-931A013D2159}.Release|Win32.Build.0 = Release|Win32 - {13E55395-94A2-4CD9-BFC2-1A051F80C17D}.Debug|Win32.ActiveCfg = Debug|Win32 - {13E55395-94A2-4CD9-BFC2-1A051F80C17D}.Debug|Win32.Build.0 = Debug|Win32 - {13E55395-94A2-4CD9-BFC2-1A051F80C17D}.Release|Win32.ActiveCfg = Release|Win32 - {13E55395-94A2-4CD9-BFC2-1A051F80C17D}.Release|Win32.Build.0 = Release|Win32 - {B8BF9E81-35FD-4582-BA1C-B85FA365BABB}.Debug|Win32.ActiveCfg = Debug|Win32 - {B8BF9E81-35FD-4582-BA1C-B85FA365BABB}.Debug|Win32.Build.0 = Debug|Win32 - {B8BF9E81-35FD-4582-BA1C-B85FA365BABB}.Release|Win32.ActiveCfg = Release|Win32 - {B8BF9E81-35FD-4582-BA1C-B85FA365BABB}.Release|Win32.Build.0 = Release|Win32 - {76A39BB2-9B84-4C65-98A5-654D86B86F2A}.Debug|Win32.ActiveCfg = Debug|Win32 - {76A39BB2-9B84-4C65-98A5-654D86B86F2A}.Debug|Win32.Build.0 = Debug|Win32 - {76A39BB2-9B84-4C65-98A5-654D86B86F2A}.Release|Win32.ActiveCfg = Release|Win32 - {76A39BB2-9B84-4C65-98A5-654D86B86F2A}.Release|Win32.Build.0 = Release|Win32 - {D0F06A44-A245-4D13-A498-0120C203B539}.Debug|Win32.ActiveCfg = Debug|Win32 - {D0F06A44-A245-4D13-A498-0120C203B539}.Debug|Win32.Build.0 = Debug|Win32 - {D0F06A44-A245-4D13-A498-0120C203B539}.Release|Win32.ActiveCfg = Release|Win32 - {D0F06A44-A245-4D13-A498-0120C203B539}.Release|Win32.Build.0 = Release|Win32 - {21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Debug|Win32.ActiveCfg = Debug|Win32 - {21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Debug|Win32.Build.0 = Debug|Win32 - {21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Release|Win32.ActiveCfg = Release|Win32 - {21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Release|Win32.Build.0 = Release|Win32 - {4E6A7A0E-DDD8-4BAA-8B22-C964069364ED}.Debug|Win32.ActiveCfg = Debug|Win32 - {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 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal From 7c4ad685e5365022129b36833a5cdaeafaef4a63 Mon Sep 17 00:00:00 2001 From: Walzer Date: Sun, 9 Sep 2012 18:25:02 +0800 Subject: [PATCH 04/15] add comment for a potential bug in HttpClient.cpp --- extensions/network/HttpClient.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/extensions/network/HttpClient.cpp b/extensions/network/HttpClient.cpp index 9227771575..bde526ed21 100644 --- a/extensions/network/HttpClient.cpp +++ b/extensions/network/HttpClient.cpp @@ -76,6 +76,9 @@ size_t writeData(void *ptr, size_t size, size_t nmemb, void *stream) size_t sizes = size * nmemb; recvBuffer->clear(); + // someone reported a bug of losting data potentially here + // use recvBuffer->insert(recvBuffer->end(), (char*)ptr, (char*)ptr+sizes); can resolve. + recvBuffer->assign((char*)ptr, (char*)ptr + sizes); return sizes; From 7e4615cd7bdd7ac7ae64b8a30d2e07370fe36cc9 Mon Sep 17 00:00:00 2001 From: Walzer Date: Sun, 9 Sep 2012 20:20:29 +0800 Subject: [PATCH 05/15] upgrade Cocos2dSimpleGame to v2.0.2 framework, add it into samples folder --- samples/SimpleGame/Classes/AppDelegate.cpp | 81 +++ samples/SimpleGame/Classes/AppDelegate.h | 38 ++ samples/SimpleGame/Classes/GameOverScene.cpp | 94 ++++ samples/SimpleGame/Classes/GameOverScene.h | 55 ++ .../SimpleGame/Classes/HelloWorldScene.cpp | 310 ++++++++++++ samples/SimpleGame/Classes/HelloWorldScene.h | 47 ++ .../background-music-aac.wav.REMOVED.git-id | 1 + samples/SimpleGame/proj.ios/AppController.h | 33 ++ samples/SimpleGame/proj.ios/AppController.mm | 124 +++++ .../SimpleGame/proj.ios/RootViewController.h | 33 ++ .../SimpleGame/proj.ios/RootViewController.mm | 78 +++ .../SimpleGame.xcodeproj/project.pbxproj | 477 ++++++++++++++++++ .../SimpleGame/proj.ios/SimpleGame_Prefix.pch | 8 + samples/SimpleGame/proj.ios/main.m | 17 + 14 files changed, 1396 insertions(+) create mode 100644 samples/SimpleGame/Classes/AppDelegate.cpp create mode 100644 samples/SimpleGame/Classes/AppDelegate.h create mode 100755 samples/SimpleGame/Classes/GameOverScene.cpp create mode 100755 samples/SimpleGame/Classes/GameOverScene.h create mode 100755 samples/SimpleGame/Classes/HelloWorldScene.cpp create mode 100755 samples/SimpleGame/Classes/HelloWorldScene.h create mode 100644 samples/SimpleGame/Resources/background-music-aac.wav.REMOVED.git-id create mode 100644 samples/SimpleGame/proj.ios/AppController.h create mode 100644 samples/SimpleGame/proj.ios/AppController.mm create mode 100644 samples/SimpleGame/proj.ios/RootViewController.h create mode 100644 samples/SimpleGame/proj.ios/RootViewController.mm create mode 100644 samples/SimpleGame/proj.ios/SimpleGame.xcodeproj/project.pbxproj create mode 100644 samples/SimpleGame/proj.ios/SimpleGame_Prefix.pch create mode 100644 samples/SimpleGame/proj.ios/main.m diff --git a/samples/SimpleGame/Classes/AppDelegate.cpp b/samples/SimpleGame/Classes/AppDelegate.cpp new file mode 100644 index 0000000000..72e3dca794 --- /dev/null +++ b/samples/SimpleGame/Classes/AppDelegate.cpp @@ -0,0 +1,81 @@ +#include "AppDelegate.h" +#include "HelloWorldScene.h" + +USING_NS_CC; + +AppDelegate::AppDelegate() { + +} + +AppDelegate::~AppDelegate() +{ +} + +bool AppDelegate::applicationDidFinishLaunching() { + // initialize director + CCDirector *pDirector = CCDirector::sharedDirector(); + + pDirector->setOpenGLView(CCEGLView::sharedOpenGLView()); + + TargetPlatform target = getTargetPlatform(); + + if (target == kTargetIpad) + { + // ipad + + CCFileUtils::sharedFileUtils()->setResourceDirectory("hd"); + + // don't enable retina because we don't have ipad hd resource + CCEGLView::sharedOpenGLView()->setDesignResolutionSize(960, 640, kResolutionNoBorder); + } + else if (target == kTargetIphone) + { + if (pDirector->enableRetinaDisplay(true)) + { + // well, it's a iPhone 4 and above, with 960x480 Retina resolution + CCFileUtils::sharedFileUtils()->setResourceDirectory("hd"); + } + else + { + // iPhone 3GS and before, with 480x320 resolution + CCFileUtils::sharedFileUtils()->setResourceDirectory("sd"); + } + } + else + { + // android, windows, blackberry, linux or mac + // use 960*640 resources as design resolution size + CCFileUtils::sharedFileUtils()->setResourceDirectory("hd"); + CCEGLView::sharedOpenGLView()->setDesignResolutionSize(960, 640, kResolutionNoBorder); + } + + // 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); + + // create a scene. it's an autorelease object + CCScene *pScene = HelloWorld::scene(); + + // run + pDirector->runWithScene(pScene); + + return true; +} + +// 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(); + + // if you use SimpleAudioEngine, it must be pause + // SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic(); +} + +// this function will be called when the app is active again +void AppDelegate::applicationWillEnterForeground() { + CCDirector::sharedDirector()->startAnimation(); + + // if you use SimpleAudioEngine, it must resume here + // SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic(); +} diff --git a/samples/SimpleGame/Classes/AppDelegate.h b/samples/SimpleGame/Classes/AppDelegate.h new file mode 100644 index 0000000000..268c6c6504 --- /dev/null +++ b/samples/SimpleGame/Classes/AppDelegate.h @@ -0,0 +1,38 @@ +#ifndef _APP_DELEGATE_H_ +#define _APP_DELEGATE_H_ + +#include "cocos2d.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_ + diff --git a/samples/SimpleGame/Classes/GameOverScene.cpp b/samples/SimpleGame/Classes/GameOverScene.cpp new file mode 100755 index 0000000000..1fe64e1a14 --- /dev/null +++ b/samples/SimpleGame/Classes/GameOverScene.cpp @@ -0,0 +1,94 @@ +/**************************************************************************** + Copyright (c) 2010-2011 cocos2d-x.org + Copyright (c) 2010 Ray Wenderlich + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "GameOverScene.h" +#include "HelloWorldScene.h" + +using namespace cocos2d; + +bool GameOverScene::init() +{ + if( CCScene::init() ) + { + this->_layer = GameOverLayer::create(); + this->_layer->retain(); + this->addChild(_layer); + + return true; + } + else + { + return false; + } +} + +GameOverScene::~GameOverScene() +{ + if (_layer) + { + _layer->release(); + _layer = NULL; + } +} + + +bool GameOverLayer::init() +{ + if ( CCLayerColor::initWithColor( ccc4(255,255,255,255) ) ) + { + CCSize winSize = CCDirector::sharedDirector()->getWinSize(); + this->_label = CCLabelTTF::create("","Artial", 32); + _label->retain(); + _label->setColor( ccc3(0, 0, 0) ); + _label->setPosition( ccp(winSize.width/2, winSize.height/2) ); + this->addChild(_label); + + this->runAction( CCSequence::create( + CCDelayTime::create(3), + CCCallFunc::create(this, + callfunc_selector(GameOverLayer::gameOverDone)), + NULL)); + + return true; + } + else + { + return false; + } +} + +void GameOverLayer::gameOverDone() +{ + CCDirector::sharedDirector()->replaceScene( HelloWorld::scene() ); +} + +GameOverLayer::~GameOverLayer() +{ + if (_label) + { + _label->release(); + _label = NULL; + } +} diff --git a/samples/SimpleGame/Classes/GameOverScene.h b/samples/SimpleGame/Classes/GameOverScene.h new file mode 100755 index 0000000000..a9ef166ef2 --- /dev/null +++ b/samples/SimpleGame/Classes/GameOverScene.h @@ -0,0 +1,55 @@ +/**************************************************************************** + Copyright (c) 2010-2011 cocos2d-x.org + Copyright (c) 2010 Ray Wenderlich + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef _GAME_OVER_SCENE_H_ +#define _GAME_OVER_SCENE_H_ + +#include "cocos2d.h" + +class GameOverLayer : public cocos2d::CCLayerColor +{ +public: + GameOverLayer():_label(NULL) {}; + virtual ~GameOverLayer(); + bool init(); + CREATE_FUNC(GameOverLayer); + + void gameOverDone(); + + CC_SYNTHESIZE_READONLY(cocos2d::CCLabelTTF*, _label, Label); +}; + +class GameOverScene : public cocos2d::CCScene +{ +public: + GameOverScene():_layer(NULL) {}; + ~GameOverScene(); + bool init(); + CREATE_FUNC(GameOverScene); + + CC_SYNTHESIZE_READONLY(GameOverLayer*, _layer, Layer); +}; + +#endif // _GAME_OVER_SCENE_H_ diff --git a/samples/SimpleGame/Classes/HelloWorldScene.cpp b/samples/SimpleGame/Classes/HelloWorldScene.cpp new file mode 100755 index 0000000000..e8f2e5f7d4 --- /dev/null +++ b/samples/SimpleGame/Classes/HelloWorldScene.cpp @@ -0,0 +1,310 @@ +#include "HelloWorldScene.h" +#include "GameOverScene.h" +#include "SimpleAudioEngine.h" + +using namespace cocos2d; + +HelloWorld::~HelloWorld() +{ + if (_targets) + { + _targets->release(); + _targets = NULL; + } + + if (_projectiles) + { + _projectiles->release(); + _projectiles = NULL; + } + + // cpp don't need to call super dealloc + // virtual destructor will do this +} + +HelloWorld::HelloWorld() +:_targets(NULL) +,_projectiles(NULL) +,_projectilesDestroyed(0) +{ +} + +CCScene* HelloWorld::scene() +{ + CCScene * scene = NULL; + do + { + // 'scene' is an autorelease object + scene = CCScene::create(); + CC_BREAK_IF(! scene); + + // 'layer' is an autorelease object + HelloWorld *layer = HelloWorld::create(); + CC_BREAK_IF(! layer); + + // add layer as a child to scene + scene->addChild(layer); + } while (0); + + // return the scene + return scene; +} + +// on "init" you need to initialize your instance +bool HelloWorld::init() +{ + bool bRet = false; + do + { + ////////////////////////////////////////////////////////////////////////// + // super init first + ////////////////////////////////////////////////////////////////////////// + + CC_BREAK_IF(! CCLayerColor::initWithColor( ccc4(255,255,255,255) ) ); + + ////////////////////////////////////////////////////////////////////////// + // add your codes below... + ////////////////////////////////////////////////////////////////////////// + + // 1. Add a menu item with "X" image, which is clicked to quit the program. + + // Create a "close" menu item with close icon, it's an auto release object. + CCMenuItemImage *pCloseItem = CCMenuItemImage::create( + "CloseNormal.png", + "CloseSelected.png", + this, + menu_selector(HelloWorld::menuCloseCallback)); + CC_BREAK_IF(! pCloseItem); + + // Place the menu item bottom-right conner. + pCloseItem->setPosition(ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20)); + + // Create a menu with the "close" menu item, it's an auto release object. + CCMenu* pMenu = CCMenu::create(pCloseItem, NULL); + pMenu->setPosition(CCPointZero); + CC_BREAK_IF(! pMenu); + + // Add the menu to HelloWorld layer as a child layer. + this->addChild(pMenu, 1); + + ///////////////////////////// + // 2. add your codes below... + + CCSize winSize = CCDirector::sharedDirector()->getWinSize(); + CCSprite *player = CCSprite::create("Player.png", CCRectMake(0, 0, 27, 40) ); + player->setPosition( ccp(player->getContentSize().width/2, winSize.height/2) ); + this->addChild(player); + + this->schedule( schedule_selector(HelloWorld::gameLogic), 1.0 ); + + this->setTouchEnabled(true); + + _targets = new CCArray; + _projectiles = new CCArray; + + // use updateGame instead of update, otherwise it will conflit with SelectorProtocol::update + // see http://www.cocos2d-x.org/boards/6/topics/1478 + this->schedule( schedule_selector(HelloWorld::updateGame) ); + + CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic("background-music-aac.wav", true); + + bRet = true; + } while (0); + + return bRet; +} + +void HelloWorld::menuCloseCallback(CCObject* pSender) +{ + // "close" menu item clicked + CCDirector::sharedDirector()->end(); +} + +// cpp with cocos2d-x +void HelloWorld::addTarget() +{ + CCSprite *target = CCSprite::create("Target.png", CCRectMake(0,0,27,40) ); + + // Determine where to spawn the target along the Y axis + CCSize winSize = CCDirector::sharedDirector()->getWinSize(); + float minY = target->getContentSize().height/2; + float maxY = winSize.height - target->getContentSize().height/2; + int rangeY = (int)(maxY - minY); + // srand( TimGetTicks() ); + int actualY = ( rand() % rangeY ) + (int)minY; + + // Create the target slightly off-screen along the right edge, + // and along a random position along the Y axis as calculated + target->setPosition( + ccp(winSize.width + (target->getContentSize().width/2), + actualY) ); + this->addChild(target); + + // Determine speed of the target + int minDuration = (int)2.0; + int maxDuration = (int)4.0; + int rangeDuration = maxDuration - minDuration; + // srand( TimGetTicks() ); + int actualDuration = ( rand() % rangeDuration ) + minDuration; + + // Create the actions + CCFiniteTimeAction* actionMove = CCMoveTo::create( (float)actualDuration, + ccp(0 - target->getContentSize().width/2, actualY) ); + CCFiniteTimeAction* actionMoveDone = CCCallFuncN::create( this, + callfuncN_selector(HelloWorld::spriteMoveFinished)); + target->runAction( CCSequence::create(actionMove, actionMoveDone, NULL) ); + + // Add to targets array + target->setTag(1); + _targets->addObject(target); +} + +void HelloWorld::spriteMoveFinished(CCNode* sender) +{ + CCSprite *sprite = (CCSprite *)sender; + this->removeChild(sprite, true); + + if (sprite->getTag() == 1) // target + { + _targets->removeObject(sprite); + + GameOverScene *gameOverScene = GameOverScene::create(); + gameOverScene->getLayer()->getLabel()->setString("You Lose :["); + CCDirector::sharedDirector()->replaceScene(gameOverScene); + + } + else if (sprite->getTag() == 2) // projectile + { + _projectiles->removeObject(sprite); + } +} + +void HelloWorld::gameLogic(float dt) +{ + this->addTarget(); +} + +// cpp with cocos2d-x +void HelloWorld::ccTouchesEnded(CCSet* touches, CCEvent* event) +{ + // Choose one of the touches to work with + CCTouch* touch = (CCTouch*)( touches->anyObject() ); + CCPoint location = touch->getLocation(); + + CCLog("++++++++after x:%f, y:%f", location.x, location.y); + + // Set up initial location of projectile + CCSize winSize = CCDirector::sharedDirector()->getWinSize(); + CCSprite *projectile = CCSprite::create("Projectile.png", CCRectMake(0, 0, 20, 20)); + projectile->setPosition( ccp(20, winSize.height/2) ); + + // Determinie offset of location to projectile + float offX = location.x - projectile->getPosition().x; + float offY = location.y - projectile->getPosition().y; + + // Bail out if we are shooting down or backwards + if (offX <= 0) return; + + // Ok to add now - we've double checked position + this->addChild(projectile); + + // Determine where we wish to shoot the projectile to + float realX = winSize.width + (projectile->getContentSize().width/2); + float ratio = offY / offX; + float realY = (realX * ratio) + projectile->getPosition().y; + CCPoint realDest = ccp(realX, realY); + + // Determine the length of how far we're shooting + float offRealX = realX - projectile->getPosition().x; + float offRealY = realY - projectile->getPosition().y; + float length = sqrtf((offRealX * offRealX) + (offRealY*offRealY)); + float velocity = 480/1; // 480pixels/1sec + float realMoveDuration = length/velocity; + + // Move projectile to actual endpoint + projectile->runAction( CCSequence::create( + CCMoveTo::create(realMoveDuration, realDest), + CCCallFuncN::create(this, + callfuncN_selector(HelloWorld::spriteMoveFinished)), + NULL) ); + + // Add to projectiles array + projectile->setTag(2); + _projectiles->addObject(projectile); + + CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect("pew-pew-lei.wav"); +} + +void HelloWorld::updateGame(float dt) +{ + CCArray *projectilesToDelete = new CCArray; + CCObject* it = NULL; + CCObject* jt = NULL; + + // for (it = _projectiles->begin(); it != _projectiles->end(); it++) + CCARRAY_FOREACH(_projectiles, it) + { + CCSprite *projectile = dynamic_cast(it); + CCRect projectileRect = CCRectMake( + projectile->getPosition().x - (projectile->getContentSize().width/2), + projectile->getPosition().y - (projectile->getContentSize().height/2), + projectile->getContentSize().width, + projectile->getContentSize().height); + + CCArray* targetsToDelete =new CCArray; + + // for (jt = _targets->begin(); jt != _targets->end(); jt++) + CCARRAY_FOREACH(_targets, jt) + { + CCSprite *target = dynamic_cast(jt); + CCRect targetRect = CCRectMake( + target->getPosition().x - (target->getContentSize().width/2), + target->getPosition().y - (target->getContentSize().height/2), + target->getContentSize().width, + target->getContentSize().height); + + // if (CCRect::CCRectIntersectsRect(projectileRect, targetRect)) + if (projectileRect.intersectsRect(targetRect)) + { + targetsToDelete->addObject(target); + } + } + + // for (jt = targetsToDelete->begin(); jt != targetsToDelete->end(); jt++) + CCARRAY_FOREACH(targetsToDelete, jt) + { + CCSprite *target = dynamic_cast(jt); + _targets->removeObject(target); + this->removeChild(target, true); + + _projectilesDestroyed++; + if (_projectilesDestroyed >= 5) + { + GameOverScene *gameOverScene = GameOverScene::create(); + gameOverScene->getLayer()->getLabel()->setString("You Win!"); + CCDirector::sharedDirector()->replaceScene(gameOverScene); + } + } + + if (targetsToDelete->count() > 0) + { + projectilesToDelete->addObject(projectile); + } + targetsToDelete->release(); + } + + // for (it = projectilesToDelete->begin(); it != projectilesToDelete->end(); it++) + CCARRAY_FOREACH(projectilesToDelete, it) + { + CCSprite* projectile = dynamic_cast(it); + _projectiles->removeObject(projectile); + this->removeChild(projectile, true); + } + projectilesToDelete->release(); +} + +void HelloWorld::registerWithTouchDispatcher() +{ + // CCTouchDispatcher::sharedDispatcher()->addTargetedDelegate(this,0,true); + CCDirector::sharedDirector()->getTouchDispatcher()->addStandardDelegate(this,0); +} diff --git a/samples/SimpleGame/Classes/HelloWorldScene.h b/samples/SimpleGame/Classes/HelloWorldScene.h new file mode 100755 index 0000000000..c1fcbd2f1c --- /dev/null +++ b/samples/SimpleGame/Classes/HelloWorldScene.h @@ -0,0 +1,47 @@ +#ifndef __HELLOWORLD_SCENE_H__ +#define __HELLOWORLD_SCENE_H__ + +#include "cocos2d.h" + +#include "SimpleAudioEngine.h" + +class HelloWorld : public cocos2d::CCLayerColor +{ +public: + HelloWorld(); + ~HelloWorld(); + + // Here's a difference. Method 'init' in cocos2d-x returns bool, + // instead of returning 'id' in cocos2d-iphone + virtual bool init(); + + // there's no 'id' in cpp, so we recommand to return the exactly class pointer + static cocos2d::CCScene* scene(); + + // a selector callback + virtual void menuCloseCallback(cocos2d::CCObject* pSender); + + // implement the "static node()" method manually + CREATE_FUNC(HelloWorld); + + void spriteMoveFinished(cocos2d::CCNode* sender); + + void gameLogic(float dt); + + void updateGame(float dt); + + void registerWithTouchDispatcher(); + void ccTouchesEnded(cocos2d::CCSet* touches, cocos2d::CCEvent* event); + + +protected: + cocos2d::CCArray *_targets; + cocos2d::CCArray *_projectiles; + int _projectilesDestroyed; + + void addTarget(); + + +}; + +#endif // __HELLOWORLD_SCENE_H__ \ No newline at end of file diff --git a/samples/SimpleGame/Resources/background-music-aac.wav.REMOVED.git-id b/samples/SimpleGame/Resources/background-music-aac.wav.REMOVED.git-id new file mode 100644 index 0000000000..584ed4de8a --- /dev/null +++ b/samples/SimpleGame/Resources/background-music-aac.wav.REMOVED.git-id @@ -0,0 +1 @@ +db5624cd760ef3e8dfad2f751d94fac652d6667f \ No newline at end of file diff --git a/samples/SimpleGame/proj.ios/AppController.h b/samples/SimpleGame/proj.ios/AppController.h new file mode 100644 index 0000000000..3d51064ca0 --- /dev/null +++ b/samples/SimpleGame/proj.ios/AppController.h @@ -0,0 +1,33 @@ +/**************************************************************************** + Copyright (c) 2010 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +@class RootViewController; + +@interface AppController : NSObject { + UIWindow *window; + RootViewController *viewController; +} + +@end + diff --git a/samples/SimpleGame/proj.ios/AppController.mm b/samples/SimpleGame/proj.ios/AppController.mm new file mode 100644 index 0000000000..db16a9024e --- /dev/null +++ b/samples/SimpleGame/proj.ios/AppController.mm @@ -0,0 +1,124 @@ +/**************************************************************************** + Copyright (c) 2010 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ +#import +#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 + 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 + [window addSubview: viewController.view]; + [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. + */ +} + + +- (void)dealloc { + [super dealloc]; +} + + +@end + diff --git a/samples/SimpleGame/proj.ios/RootViewController.h b/samples/SimpleGame/proj.ios/RootViewController.h new file mode 100644 index 0000000000..a40c2edd28 --- /dev/null +++ b/samples/SimpleGame/proj.ios/RootViewController.h @@ -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 + + +@interface RootViewController : UIViewController { + +} + +@end diff --git a/samples/SimpleGame/proj.ios/RootViewController.mm b/samples/SimpleGame/proj.ios/RootViewController.mm new file mode 100644 index 0000000000..c1c841078d --- /dev/null +++ b/samples/SimpleGame/proj.ios/RootViewController.mm @@ -0,0 +1,78 @@ +/**************************************************************************** + 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 "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. +- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { + return UIInterfaceOrientationIsLandscape( interfaceOrientation ); +} + +- (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 diff --git a/samples/SimpleGame/proj.ios/SimpleGame.xcodeproj/project.pbxproj b/samples/SimpleGame/proj.ios/SimpleGame.xcodeproj/project.pbxproj new file mode 100644 index 0000000000..d894afef52 --- /dev/null +++ b/samples/SimpleGame/proj.ios/SimpleGame.xcodeproj/project.pbxproj @@ -0,0 +1,477 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 45; + objects = { + +/* Begin PBXBuildFile section */ + 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 */; }; + 782F4619153FEDF0009FC2E5 /* Default.png in Resources */ = {isa = PBXBuildFile; fileRef = 782F4617153FEDF0009FC2E5 /* Default.png */; }; + BF1373EF128A898400D9F789 /* OpenGLES.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BF492D4B1289302400A09262 /* OpenGLES.framework */; }; + BF1373F0128A899500D9F789 /* libxml2.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = BF492C21128924A800A09262 /* libxml2.dylib */; }; + BF1373F1128A899E00D9F789 /* libz.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = BF492B6912891AC600A09262 /* libz.dylib */; }; + BF13742F128A8E6A00D9F789 /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BF137426128A8E4600D9F789 /* QuartzCore.framework */; }; + BF23D4E7143315EB00657E08 /* AppDelegate.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BF23D4E3143315EB00657E08 /* AppDelegate.cpp */; }; + BF23D4E8143315EB00657E08 /* HelloWorldScene.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BF23D4E5143315EB00657E08 /* HelloWorldScene.cpp */; }; + BF365AA812A103F70050DCF4 /* AppController.mm in Sources */ = {isa = PBXBuildFile; fileRef = BF365AA712A103F70050DCF4 /* AppController.mm */; }; + BF4DE6AD138BB89600CF907D /* RootViewController.mm in Sources */ = {isa = PBXBuildFile; fileRef = BF4DE6AC138BB89600CF907D /* RootViewController.mm */; }; + D4ABB4B313B4395300552E6E /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = D4ABB4B213B4395300552E6E /* main.m */; }; + D4E6BC8515FCB4A4008BF525 /* libcocos2dx.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D4E6BC8315FCB477008BF525 /* libcocos2dx.a */; }; + D4E6BC9215FCB5BA008BF525 /* GameOverScene.cpp in Sources */ = {isa = PBXBuildFile; fileRef = D4E6BC9015FCB5BA008BF525 /* GameOverScene.cpp */; }; + D4E6BCA715FCB670008BF525 /* CDAudioManager.m in Sources */ = {isa = PBXBuildFile; fileRef = D4E6BC9E15FCB670008BF525 /* CDAudioManager.m */; }; + D4E6BCA815FCB670008BF525 /* CDOpenALSupport.m in Sources */ = {isa = PBXBuildFile; fileRef = D4E6BCA115FCB670008BF525 /* CDOpenALSupport.m */; }; + D4E6BCA915FCB670008BF525 /* CocosDenshion.m in Sources */ = {isa = PBXBuildFile; fileRef = D4E6BCA315FCB670008BF525 /* CocosDenshion.m */; }; + D4E6BCAA15FCB670008BF525 /* SimpleAudioEngine.mm in Sources */ = {isa = PBXBuildFile; fileRef = D4E6BCA415FCB670008BF525 /* SimpleAudioEngine.mm */; }; + D4E6BCAB15FCB670008BF525 /* SimpleAudioEngine_objc.m in Sources */ = {isa = PBXBuildFile; fileRef = D4E6BCA615FCB670008BF525 /* SimpleAudioEngine_objc.m */; }; + D4E6BCC815FCB6AA008BF525 /* background-music-aac.wav in Resources */ = {isa = PBXBuildFile; fileRef = D4E6BCC415FCB6AA008BF525 /* background-music-aac.wav */; }; + D4E6BCC915FCB6AA008BF525 /* hd in Resources */ = {isa = PBXBuildFile; fileRef = D4E6BCC515FCB6AA008BF525 /* hd */; }; + D4E6BCCA15FCB6AA008BF525 /* pew-pew-lei.wav in Resources */ = {isa = PBXBuildFile; fileRef = D4E6BCC615FCB6AA008BF525 /* pew-pew-lei.wav */; }; + D4E6BCCB15FCB6AA008BF525 /* sd in Resources */ = {isa = PBXBuildFile; fileRef = D4E6BCC715FCB6AA008BF525 /* sd */; }; + D4E6BCCC15FCBABC008BF525 /* OpenAL.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 781C33B11547F06B00633F88 /* OpenAL.framework */; }; + D4E6BCCD15FCBAC8008BF525 /* AVFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 781C33B51547F06B00633F88 /* AVFoundation.framework */; }; + D4E6BCCE15FCBAD7008BF525 /* AudioToolbox.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 781C33B31547F06B00633F88 /* AudioToolbox.framework */; }; + D4EF94E815BD319200D803EB /* Icon-57.png in Resources */ = {isa = PBXBuildFile; fileRef = D4EF94E715BD319200D803EB /* Icon-57.png */; }; + D4EF94EA15BD319500D803EB /* Icon-114.png in Resources */ = {isa = PBXBuildFile; fileRef = D4EF94E915BD319500D803EB /* Icon-114.png */; }; + D4EF94EC15BD319B00D803EB /* Icon-72.png in Resources */ = {isa = PBXBuildFile; fileRef = D4EF94EB15BD319B00D803EB /* Icon-72.png */; }; + D4EF94EE15BD319D00D803EB /* Icon-144.png in Resources */ = {isa = PBXBuildFile; fileRef = D4EF94ED15BD319D00D803EB /* Icon-144.png */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + D4E6BC8215FCB477008BF525 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D4E6BC7B15FCB477008BF525 /* cocos2dx.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 1551A33F158F2AB200E66CFE; + remoteInfo = cocos2dx; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 1D30AB110D05D00D00671497 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; + 1D6058910D05DD3D006BFB54 /* SimpleGame.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SimpleGame.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 1DF5F4DF0D08C38300B7A737 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; }; + 288765A40DF7441C002DB57D /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; }; + 781C33B11547F06B00633F88 /* OpenAL.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenAL.framework; path = System/Library/Frameworks/OpenAL.framework; sourceTree = SDKROOT; }; + 781C33B31547F06B00633F88 /* AudioToolbox.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AudioToolbox.framework; path = System/Library/Frameworks/AudioToolbox.framework; sourceTree = SDKROOT; }; + 781C33B51547F06B00633F88 /* AVFoundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AVFoundation.framework; path = System/Library/Frameworks/AVFoundation.framework; sourceTree = SDKROOT; }; + 782F4617153FEDF0009FC2E5 /* Default.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = Default.png; sourceTree = SOURCE_ROOT; }; + BF137426128A8E4600D9F789 /* QuartzCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QuartzCore.framework; path = System/Library/Frameworks/QuartzCore.framework; sourceTree = SDKROOT; }; + BF23D4E3143315EB00657E08 /* AppDelegate.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = AppDelegate.cpp; sourceTree = ""; }; + BF23D4E4143315EB00657E08 /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; + BF23D4E5143315EB00657E08 /* HelloWorldScene.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = HelloWorldScene.cpp; sourceTree = ""; }; + BF23D4E6143315EB00657E08 /* HelloWorldScene.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HelloWorldScene.h; sourceTree = ""; }; + BF365AA612A103F70050DCF4 /* AppController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppController.h; sourceTree = ""; }; + BF365AA712A103F70050DCF4 /* AppController.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = AppController.mm; sourceTree = ""; }; + BF492B6912891AC600A09262 /* libz.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libz.dylib; path = usr/lib/libz.dylib; sourceTree = SDKROOT; }; + BF492C21128924A800A09262 /* libxml2.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libxml2.dylib; path = usr/lib/libxml2.dylib; sourceTree = SDKROOT; }; + BF492D4B1289302400A09262 /* OpenGLES.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenGLES.framework; path = System/Library/Frameworks/OpenGLES.framework; sourceTree = SDKROOT; }; + BF4DE6AB138BB89600CF907D /* RootViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RootViewController.h; sourceTree = ""; }; + BF4DE6AC138BB89600CF907D /* RootViewController.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = RootViewController.mm; sourceTree = ""; }; + D4ABB4B213B4395300552E6E /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; + D4E6BC7B15FCB477008BF525 /* cocos2dx.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = cocos2dx.xcodeproj; path = ../../../cocos2dx/proj.ios/cocos2dx.xcodeproj; sourceTree = ""; }; + D4E6BC9015FCB5BA008BF525 /* GameOverScene.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = GameOverScene.cpp; sourceTree = ""; }; + D4E6BC9115FCB5BA008BF525 /* GameOverScene.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GameOverScene.h; sourceTree = ""; }; + D4E6BC9A15FCB670008BF525 /* Export.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Export.h; sourceTree = ""; }; + D4E6BC9B15FCB670008BF525 /* SimpleAudioEngine.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SimpleAudioEngine.h; sourceTree = ""; }; + D4E6BC9D15FCB670008BF525 /* CDAudioManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDAudioManager.h; sourceTree = ""; }; + D4E6BC9E15FCB670008BF525 /* CDAudioManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDAudioManager.m; sourceTree = ""; }; + D4E6BC9F15FCB670008BF525 /* CDConfig.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDConfig.h; sourceTree = ""; }; + D4E6BCA015FCB670008BF525 /* CDOpenALSupport.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDOpenALSupport.h; sourceTree = ""; }; + D4E6BCA115FCB670008BF525 /* CDOpenALSupport.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDOpenALSupport.m; sourceTree = ""; }; + D4E6BCA215FCB670008BF525 /* CocosDenshion.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CocosDenshion.h; sourceTree = ""; }; + D4E6BCA315FCB670008BF525 /* CocosDenshion.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CocosDenshion.m; sourceTree = ""; }; + D4E6BCA415FCB670008BF525 /* SimpleAudioEngine.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = SimpleAudioEngine.mm; sourceTree = ""; }; + D4E6BCA515FCB670008BF525 /* SimpleAudioEngine_objc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SimpleAudioEngine_objc.h; sourceTree = ""; }; + D4E6BCA615FCB670008BF525 /* SimpleAudioEngine_objc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SimpleAudioEngine_objc.m; sourceTree = ""; }; + D4E6BCC415FCB6AA008BF525 /* background-music-aac.wav */ = {isa = PBXFileReference; lastKnownFileType = audio.wav; path = "background-music-aac.wav"; sourceTree = ""; }; + D4E6BCC515FCB6AA008BF525 /* hd */ = {isa = PBXFileReference; lastKnownFileType = folder; path = hd; sourceTree = ""; }; + D4E6BCC615FCB6AA008BF525 /* pew-pew-lei.wav */ = {isa = PBXFileReference; lastKnownFileType = audio.wav; path = "pew-pew-lei.wav"; sourceTree = ""; }; + D4E6BCC715FCB6AA008BF525 /* sd */ = {isa = PBXFileReference; lastKnownFileType = folder; path = sd; sourceTree = ""; }; + D4EF94E715BD319200D803EB /* Icon-57.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "Icon-57.png"; path = "../proj.ios/Icon-57.png"; sourceTree = ""; }; + D4EF94E915BD319500D803EB /* Icon-114.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "Icon-114.png"; path = "../proj.ios/Icon-114.png"; sourceTree = ""; }; + D4EF94EB15BD319B00D803EB /* Icon-72.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "Icon-72.png"; path = "../proj.ios/Icon-72.png"; sourceTree = ""; }; + D4EF94ED15BD319D00D803EB /* Icon-144.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "Icon-144.png"; path = "../proj.ios/Icon-144.png"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 1D60588F0D05DD3D006BFB54 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + D4E6BCCE15FCBAD7008BF525 /* AudioToolbox.framework in Frameworks */, + D4E6BCCD15FCBAC8008BF525 /* AVFoundation.framework in Frameworks */, + D4E6BCCC15FCBABC008BF525 /* OpenAL.framework in Frameworks */, + D4E6BC8515FCB4A4008BF525 /* libcocos2dx.a in Frameworks */, + 1D60589F0D05DD5A006BFB54 /* Foundation.framework in Frameworks */, + 1DF5F4E00D08C38300B7A737 /* UIKit.framework in Frameworks */, + 288765A50DF7441C002DB57D /* CoreGraphics.framework in Frameworks */, + BF1373EF128A898400D9F789 /* OpenGLES.framework in Frameworks */, + BF1373F0128A899500D9F789 /* libxml2.dylib in Frameworks */, + BF1373F1128A899E00D9F789 /* libz.dylib in Frameworks */, + BF13742F128A8E6A00D9F789 /* QuartzCore.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 19C28FACFE9D520D11CA2CBB /* Products */ = { + isa = PBXGroup; + children = ( + 1D6058910D05DD3D006BFB54 /* SimpleGame.app */, + ); + name = Products; + sourceTree = ""; + }; + 29B97314FDCFA39411CA2CEA /* CustomTemplate */ = { + isa = PBXGroup; + children = ( + D4E6BC7B15FCB477008BF525 /* cocos2dx.xcodeproj */, + BF23D4E2143315EB00657E08 /* Classes */, + 29B97323FDCFA39411CA2CEA /* Frameworks */, + BF5681CC1313A84D0055EEAC /* ios */, + D4E6BC9815FCB650008BF525 /* CocosDenshion */, + 784521C214EBA449009D533B /* Resources */, + 19C28FACFE9D520D11CA2CBB /* Products */, + ); + name = CustomTemplate; + sourceTree = ""; + }; + 29B97323FDCFA39411CA2CEA /* Frameworks */ = { + isa = PBXGroup; + children = ( + BF492B6912891AC600A09262 /* libz.dylib */, + BF137426128A8E4600D9F789 /* QuartzCore.framework */, + BF492D4B1289302400A09262 /* OpenGLES.framework */, + BF492C21128924A800A09262 /* libxml2.dylib */, + 1DF5F4DF0D08C38300B7A737 /* UIKit.framework */, + 1D30AB110D05D00D00671497 /* Foundation.framework */, + 288765A40DF7441C002DB57D /* CoreGraphics.framework */, + 781C33B11547F06B00633F88 /* OpenAL.framework */, + 781C33B31547F06B00633F88 /* AudioToolbox.framework */, + 781C33B51547F06B00633F88 /* AVFoundation.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + 784521C214EBA449009D533B /* Resources */ = { + isa = PBXGroup; + children = ( + D4E6BCC415FCB6AA008BF525 /* background-music-aac.wav */, + D4E6BCC515FCB6AA008BF525 /* hd */, + D4E6BCC615FCB6AA008BF525 /* pew-pew-lei.wav */, + D4E6BCC715FCB6AA008BF525 /* sd */, + D4EF94ED15BD319D00D803EB /* Icon-144.png */, + D4EF94EB15BD319B00D803EB /* Icon-72.png */, + D4EF94E915BD319500D803EB /* Icon-114.png */, + D4EF94E715BD319200D803EB /* Icon-57.png */, + 782F4617153FEDF0009FC2E5 /* Default.png */, + ); + name = Resources; + path = ../Resources; + sourceTree = ""; + }; + BF23D4E2143315EB00657E08 /* Classes */ = { + isa = PBXGroup; + children = ( + BF23D4E3143315EB00657E08 /* AppDelegate.cpp */, + BF23D4E4143315EB00657E08 /* AppDelegate.h */, + BF23D4E5143315EB00657E08 /* HelloWorldScene.cpp */, + BF23D4E6143315EB00657E08 /* HelloWorldScene.h */, + D4E6BC9015FCB5BA008BF525 /* GameOverScene.cpp */, + D4E6BC9115FCB5BA008BF525 /* GameOverScene.h */, + ); + name = Classes; + path = ../Classes; + sourceTree = SOURCE_ROOT; + }; + BF5681CC1313A84D0055EEAC /* ios */ = { + isa = PBXGroup; + children = ( + D4ABB4B213B4395300552E6E /* main.m */, + BF365AA612A103F70050DCF4 /* AppController.h */, + BF365AA712A103F70050DCF4 /* AppController.mm */, + BF4DE6AB138BB89600CF907D /* RootViewController.h */, + BF4DE6AC138BB89600CF907D /* RootViewController.mm */, + ); + name = ios; + sourceTree = ""; + }; + D4E6BC7C15FCB477008BF525 /* Products */ = { + isa = PBXGroup; + children = ( + D4E6BC8315FCB477008BF525 /* libcocos2dx.a */, + ); + name = Products; + sourceTree = ""; + }; + D4E6BC9815FCB650008BF525 /* CocosDenshion */ = { + isa = PBXGroup; + children = ( + D4E6BC9915FCB670008BF525 /* include */, + D4E6BC9C15FCB670008BF525 /* ios */, + ); + name = CocosDenshion; + sourceTree = ""; + }; + D4E6BC9915FCB670008BF525 /* include */ = { + isa = PBXGroup; + children = ( + D4E6BC9A15FCB670008BF525 /* Export.h */, + D4E6BC9B15FCB670008BF525 /* SimpleAudioEngine.h */, + ); + name = include; + path = ../../../CocosDenshion/include; + sourceTree = ""; + }; + D4E6BC9C15FCB670008BF525 /* ios */ = { + isa = PBXGroup; + children = ( + D4E6BC9D15FCB670008BF525 /* CDAudioManager.h */, + D4E6BC9E15FCB670008BF525 /* CDAudioManager.m */, + D4E6BC9F15FCB670008BF525 /* CDConfig.h */, + D4E6BCA015FCB670008BF525 /* CDOpenALSupport.h */, + D4E6BCA115FCB670008BF525 /* CDOpenALSupport.m */, + D4E6BCA215FCB670008BF525 /* CocosDenshion.h */, + D4E6BCA315FCB670008BF525 /* CocosDenshion.m */, + D4E6BCA415FCB670008BF525 /* SimpleAudioEngine.mm */, + D4E6BCA515FCB670008BF525 /* SimpleAudioEngine_objc.h */, + D4E6BCA615FCB670008BF525 /* SimpleAudioEngine_objc.m */, + ); + name = ios; + path = ../../../CocosDenshion/ios; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 1D6058900D05DD3D006BFB54 /* SimpleGame */ = { + isa = PBXNativeTarget; + buildConfigurationList = 1D6058960D05DD3E006BFB54 /* Build configuration list for PBXNativeTarget "SimpleGame" */; + buildPhases = ( + 1D60588D0D05DD3D006BFB54 /* Resources */, + 1D60588E0D05DD3D006BFB54 /* Sources */, + 1D60588F0D05DD3D006BFB54 /* Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = SimpleGame; + productName = HelloWorld; + productReference = 1D6058910D05DD3D006BFB54 /* SimpleGame.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 29B97313FDCFA39411CA2CEA /* Project object */ = { + isa = PBXProject; + buildConfigurationList = C01FCF4E08A954540054247B /* Build configuration list for PBXProject "SimpleGame" */; + compatibilityVersion = "Xcode 3.1"; + developmentRegion = English; + hasScannedForEncodings = 1; + knownRegions = ( + English, + Japanese, + French, + German, + ); + mainGroup = 29B97314FDCFA39411CA2CEA /* CustomTemplate */; + projectDirPath = ""; + projectReferences = ( + { + ProductGroup = D4E6BC7C15FCB477008BF525 /* Products */; + ProjectRef = D4E6BC7B15FCB477008BF525 /* cocos2dx.xcodeproj */; + }, + ); + projectRoot = ""; + targets = ( + 1D6058900D05DD3D006BFB54 /* SimpleGame */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXReferenceProxy section */ + D4E6BC8315FCB477008BF525 /* libcocos2dx.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libcocos2dx.a; + remoteRef = D4E6BC8215FCB477008BF525 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; +/* End PBXReferenceProxy section */ + +/* Begin PBXResourcesBuildPhase section */ + 1D60588D0D05DD3D006BFB54 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 782F4619153FEDF0009FC2E5 /* Default.png in Resources */, + D4EF94E815BD319200D803EB /* Icon-57.png in Resources */, + D4EF94EA15BD319500D803EB /* Icon-114.png in Resources */, + D4EF94EC15BD319B00D803EB /* Icon-72.png in Resources */, + D4EF94EE15BD319D00D803EB /* Icon-144.png in Resources */, + D4E6BCC815FCB6AA008BF525 /* background-music-aac.wav in Resources */, + D4E6BCC915FCB6AA008BF525 /* hd in Resources */, + D4E6BCCA15FCB6AA008BF525 /* pew-pew-lei.wav in Resources */, + D4E6BCCB15FCB6AA008BF525 /* sd in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 1D60588E0D05DD3D006BFB54 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + BF365AA812A103F70050DCF4 /* AppController.mm in Sources */, + BF4DE6AD138BB89600CF907D /* RootViewController.mm in Sources */, + D4ABB4B313B4395300552E6E /* main.m in Sources */, + BF23D4E7143315EB00657E08 /* AppDelegate.cpp in Sources */, + BF23D4E8143315EB00657E08 /* HelloWorldScene.cpp in Sources */, + D4E6BC9215FCB5BA008BF525 /* GameOverScene.cpp in Sources */, + D4E6BCA715FCB670008BF525 /* CDAudioManager.m in Sources */, + D4E6BCA815FCB670008BF525 /* CDOpenALSupport.m in Sources */, + D4E6BCA915FCB670008BF525 /* CocosDenshion.m in Sources */, + D4E6BCAA15FCB670008BF525 /* SimpleAudioEngine.mm in Sources */, + D4E6BCAB15FCB670008BF525 /* SimpleAudioEngine_objc.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + 1D6058940D05DD3E006BFB54 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ARCHS = "$(ARCHS_STANDARD_32_BIT)"; + CODE_SIGN_IDENTITY = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + GCC_DYNAMIC_NO_PIC = NO; + GCC_INLINES_ARE_PRIVATE_EXTERN = NO; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_PREFIX_HEADER = SimpleGame_Prefix.pch; + GCC_PREPROCESSOR_DEFINITIONS = ( + USE_FILE32API, + TARGET_OS_IPHONE, + "COCOS2D_DEBUG=1", + ); + GCC_PREPROCESSOR_DEFINITIONS_NOT_USED_IN_PRECOMPS = ""; + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + GCC_VERSION = ""; + HEADER_SEARCH_PATHS = ( + "\"$(SDKROOT)/usr/include/libxml2/\"", + "\"$(SRCROOT)/../../../cocos2dx/include\"", + "\"$(SRCROOT)/../../../cocos2dx\"", + "\"$(SRCROOT)/../../../cocos2dx/platform/ios\"", + "\"$(SRCROOT)/../../../cocos2dx/kazmath/include\"", + ); + INFOPLIST_FILE = "SimpleGame-Info.plist"; + IPHONEOS_DEPLOYMENT_TARGET = 4.0; + PRODUCT_NAME = SimpleGame; + PROVISIONING_PROFILE = ""; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALID_ARCHS = "armv6 armv7 i386"; + }; + name = Debug; + }; + 1D6058950D05DD3E006BFB54 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ARCHS = "$(ARCHS_STANDARD_32_BIT)"; + CODE_SIGN_IDENTITY = "iPhone Developer"; + COPY_PHASE_STRIP = YES; + GCC_INLINES_ARE_PRIVATE_EXTERN = NO; + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_PREFIX_HEADER = SimpleGame_Prefix.pch; + GCC_PREPROCESSOR_DEFINITIONS = ( + USE_FILE32API, + TARGET_OS_IPHONE, + ); + GCC_PREPROCESSOR_DEFINITIONS_NOT_USED_IN_PRECOMPS = ""; + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + GCC_VERSION = ""; + HEADER_SEARCH_PATHS = ( + "\"$(SDKROOT)/usr/include/libxml2/\"", + "\"$(SRCROOT)/../../../cocos2dx/include\"", + "\"$(SRCROOT)/../../../cocos2dx\"", + "\"$(SRCROOT)/../../../cocos2dx/platform/ios\"", + "\"$(SRCROOT)/../../../cocos2dx/kazmath/include\"", + ); + INFOPLIST_FILE = "SimpleGame-Info.plist"; + IPHONEOS_DEPLOYMENT_TARGET = 4.0; + PRODUCT_NAME = SimpleGame; + PROVISIONING_PROFILE = ""; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VALID_ARCHS = "armv6 armv7 i386"; + }; + name = Release; + }; + C01FCF4F08A954540054247B /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ARCHS = "$(ARCHS_STANDARD_32_BIT)"; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + GCC_C_LANGUAGE_STANDARD = c99; + GCC_VERSION = ""; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + PREBINDING = NO; + SDKROOT = iphoneos; + VALID_ARCHS = "armv6 armv7 i386"; + }; + name = Debug; + }; + C01FCF5008A954540054247B /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ARCHS = "$(ARCHS_STANDARD_32_BIT)"; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + GCC_C_LANGUAGE_STANDARD = c99; + GCC_VERSION = ""; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + OTHER_CFLAGS = "-DNS_BLOCK_ASSERTIONS=1"; + PREBINDING = NO; + SDKROOT = iphoneos; + VALID_ARCHS = "armv6 armv7 i386"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 1D6058960D05DD3E006BFB54 /* Build configuration list for PBXNativeTarget "SimpleGame" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 1D6058940D05DD3E006BFB54 /* Debug */, + 1D6058950D05DD3E006BFB54 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + C01FCF4E08A954540054247B /* Build configuration list for PBXProject "SimpleGame" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + C01FCF4F08A954540054247B /* Debug */, + C01FCF5008A954540054247B /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 29B97313FDCFA39411CA2CEA /* Project object */; +} diff --git a/samples/SimpleGame/proj.ios/SimpleGame_Prefix.pch b/samples/SimpleGame/proj.ios/SimpleGame_Prefix.pch new file mode 100644 index 0000000000..b8914281d2 --- /dev/null +++ b/samples/SimpleGame/proj.ios/SimpleGame_Prefix.pch @@ -0,0 +1,8 @@ +// +// Prefix header for all source files of the 'HelloWorld' target in the 'HelloWorld' project +// + +#ifdef __OBJC__ + #import + #import +#endif diff --git a/samples/SimpleGame/proj.ios/main.m b/samples/SimpleGame/proj.ios/main.m new file mode 100644 index 0000000000..bd577a036e --- /dev/null +++ b/samples/SimpleGame/proj.ios/main.m @@ -0,0 +1,17 @@ +// +// main.m +// iphone +// +// Created by Walzer on 10-11-16. +// Copyright 2010 __MyCompanyName__. All rights reserved. +// + +#import + +int main(int argc, char *argv[]) { + + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + int retVal = UIApplicationMain(argc, argv, nil, @"AppController"); + [pool release]; + return retVal; +} From 11b5ae5cef199f73bb52fece8e377ad13e39522c Mon Sep 17 00:00:00 2001 From: Walzer Date: Sun, 9 Sep 2012 21:41:48 +0800 Subject: [PATCH 06/15] add proj.android to samples/SimpleGame, use getVisibleSize & getVisibleOrigin instead of getWinSize --- SimpleGame/Classes/AppDelegate.cpp | 57 +++ SimpleGame/Classes/AppDelegate.h | 38 ++ SimpleGame/Classes/HelloWorldScene.cpp | 84 ++++ SimpleGame/Classes/HelloWorldScene.h | 22 + .../Resources/HelloWorld.png.REMOVED.git-id | 1 + SimpleGame/proj.android/.classpath | 8 + SimpleGame/proj.android/.project | 33 ++ SimpleGame/proj.android/AndroidManifest.xml | 28 ++ SimpleGame/proj.android/ant.properties | 17 + SimpleGame/proj.android/build.xml | 92 ++++ SimpleGame/proj.android/build_native.sh | 91 ++++ SimpleGame/proj.android/jni/Android.mk | 21 + SimpleGame/proj.android/jni/Application.mk | 2 + SimpleGame/proj.android/jni/hellocpp/main.cpp | 45 ++ SimpleGame/proj.android/jni/list.sh | 23 + SimpleGame/proj.android/proguard-project.txt | 20 + SimpleGame/proj.android/project.properties | 14 + .../proj.android/res/values/strings.xml | 4 + .../cocos2dx/lib/Cocos2dxAccelerometer.java | 107 ++++ .../org/cocos2dx/lib/Cocos2dxActivity.java | 346 +++++++++++++ .../src/org/cocos2dx/lib/Cocos2dxBitmap.java | 455 ++++++++++++++++++ .../cocos2dx/lib/Cocos2dxEditBoxDialog.java | 338 +++++++++++++ .../org/cocos2dx/lib/Cocos2dxEditText.java | 65 +++ .../cocos2dx/lib/Cocos2dxGLSurfaceView.java | 417 ++++++++++++++++ .../src/org/cocos2dx/lib/Cocos2dxMusic.java | 228 +++++++++ .../org/cocos2dx/lib/Cocos2dxRenderer.java | 137 ++++++ .../src/org/cocos2dx/lib/Cocos2dxSound.java | 245 ++++++++++ .../org/cocos2dx/lib/Cocos2dxTypefaces.java | 44 ++ .../org/cocos2dx/simplegame/SimpleGame.java | 108 +++++ samples/SimpleGame/Classes/AppDelegate.cpp | 4 +- .../SimpleGame/Classes/HelloWorldScene.cpp | 11 +- samples/SimpleGame/proj.android/.classpath | 8 + samples/SimpleGame/proj.android/.project | 33 ++ .../proj.android/AndroidManifest.xml | 28 ++ .../SimpleGame/proj.android/ant.properties | 17 + samples/SimpleGame/proj.android/build.xml | 92 ++++ .../SimpleGame/proj.android/build_native.sh | 91 ++++ .../SimpleGame/proj.android/jni/Android.mk | 22 + .../proj.android/jni/Application.mk | 2 + .../proj.android/jni/hellocpp/main.cpp | 45 ++ samples/SimpleGame/proj.android/jni/list.sh | 23 + .../proj.android/proguard-project.txt | 20 + .../proj.android/project.properties | 14 + .../proj.android/res/values/strings.xml | 4 + .../cocos2dx/lib/Cocos2dxAccelerometer.java | 107 ++++ .../org/cocos2dx/lib/Cocos2dxActivity.java | 346 +++++++++++++ .../src/org/cocos2dx/lib/Cocos2dxBitmap.java | 455 ++++++++++++++++++ .../cocos2dx/lib/Cocos2dxEditBoxDialog.java | 338 +++++++++++++ .../org/cocos2dx/lib/Cocos2dxEditText.java | 65 +++ .../cocos2dx/lib/Cocos2dxGLSurfaceView.java | 417 ++++++++++++++++ .../src/org/cocos2dx/lib/Cocos2dxMusic.java | 228 +++++++++ .../org/cocos2dx/lib/Cocos2dxRenderer.java | 137 ++++++ .../src/org/cocos2dx/lib/Cocos2dxSound.java | 245 ++++++++++ .../org/cocos2dx/lib/Cocos2dxTypefaces.java | 44 ++ .../org/cocos2dx/simplegame/SimpleGame.java | 108 +++++ 55 files changed, 5987 insertions(+), 7 deletions(-) create mode 100644 SimpleGame/Classes/AppDelegate.cpp create mode 100644 SimpleGame/Classes/AppDelegate.h create mode 100644 SimpleGame/Classes/HelloWorldScene.cpp create mode 100644 SimpleGame/Classes/HelloWorldScene.h create mode 100644 SimpleGame/Resources/HelloWorld.png.REMOVED.git-id create mode 100644 SimpleGame/proj.android/.classpath create mode 100644 SimpleGame/proj.android/.project create mode 100644 SimpleGame/proj.android/AndroidManifest.xml create mode 100644 SimpleGame/proj.android/ant.properties create mode 100644 SimpleGame/proj.android/build.xml create mode 100755 SimpleGame/proj.android/build_native.sh create mode 100644 SimpleGame/proj.android/jni/Android.mk create mode 100644 SimpleGame/proj.android/jni/Application.mk create mode 100644 SimpleGame/proj.android/jni/hellocpp/main.cpp create mode 100644 SimpleGame/proj.android/jni/list.sh create mode 100644 SimpleGame/proj.android/proguard-project.txt create mode 100644 SimpleGame/proj.android/project.properties create mode 100644 SimpleGame/proj.android/res/values/strings.xml create mode 100644 SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxAccelerometer.java create mode 100644 SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxActivity.java create mode 100644 SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxBitmap.java create mode 100755 SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxEditBoxDialog.java create mode 100644 SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxEditText.java create mode 100644 SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java create mode 100644 SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxMusic.java create mode 100644 SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxRenderer.java create mode 100644 SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxSound.java create mode 100644 SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxTypefaces.java create mode 100644 SimpleGame/proj.android/src/org/cocos2dx/simplegame/SimpleGame.java create mode 100644 samples/SimpleGame/proj.android/.classpath create mode 100644 samples/SimpleGame/proj.android/.project create mode 100644 samples/SimpleGame/proj.android/AndroidManifest.xml create mode 100644 samples/SimpleGame/proj.android/ant.properties create mode 100644 samples/SimpleGame/proj.android/build.xml create mode 100755 samples/SimpleGame/proj.android/build_native.sh create mode 100644 samples/SimpleGame/proj.android/jni/Android.mk create mode 100644 samples/SimpleGame/proj.android/jni/Application.mk create mode 100644 samples/SimpleGame/proj.android/jni/hellocpp/main.cpp create mode 100644 samples/SimpleGame/proj.android/jni/list.sh create mode 100644 samples/SimpleGame/proj.android/proguard-project.txt create mode 100644 samples/SimpleGame/proj.android/project.properties create mode 100644 samples/SimpleGame/proj.android/res/values/strings.xml create mode 100644 samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxAccelerometer.java create mode 100644 samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxActivity.java create mode 100644 samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxBitmap.java create mode 100755 samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxEditBoxDialog.java create mode 100644 samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxEditText.java create mode 100644 samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java create mode 100644 samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxMusic.java create mode 100644 samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxRenderer.java create mode 100644 samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxSound.java create mode 100644 samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxTypefaces.java create mode 100644 samples/SimpleGame/proj.android/src/org/cocos2dx/simplegame/SimpleGame.java diff --git a/SimpleGame/Classes/AppDelegate.cpp b/SimpleGame/Classes/AppDelegate.cpp new file mode 100644 index 0000000000..447d84142f --- /dev/null +++ b/SimpleGame/Classes/AppDelegate.cpp @@ -0,0 +1,57 @@ +#include "AppDelegate.h" + +#include "cocos2d.h" +#include "HelloWorldScene.h" + +USING_NS_CC; + +AppDelegate::AppDelegate() +{ + +} + +AppDelegate::~AppDelegate() +{ +} + +bool AppDelegate::applicationDidFinishLaunching() +{ + // initialize director + CCDirector *pDirector = CCDirector::sharedDirector(); + pDirector->setOpenGLView(CCEGLView::sharedOpenGLView()); + + // 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); + + // create a scene. it's an autorelease object + CCScene *pScene = HelloWorld::scene(); + + // run + pDirector->runWithScene(pScene); + + return true; +} + +// 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()->pause(); + + // if you use SimpleAudioEngine, it must be pause + // SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic(); +} + +// this function will be called when the app is active again +void AppDelegate::applicationWillEnterForeground() +{ + CCDirector::sharedDirector()->resume(); + + // if you use SimpleAudioEngine, it must resume here + // SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic(); +} diff --git a/SimpleGame/Classes/AppDelegate.h b/SimpleGame/Classes/AppDelegate.h new file mode 100644 index 0000000000..76c1c6089f --- /dev/null +++ b/SimpleGame/Classes/AppDelegate.h @@ -0,0 +1,38 @@ +#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_ + diff --git a/SimpleGame/Classes/HelloWorldScene.cpp b/SimpleGame/Classes/HelloWorldScene.cpp new file mode 100644 index 0000000000..a936549028 --- /dev/null +++ b/SimpleGame/Classes/HelloWorldScene.cpp @@ -0,0 +1,84 @@ +#include "HelloWorldScene.h" +#include "SimpleAudioEngine.h" + +using namespace cocos2d; +using namespace CocosDenshion; + +CCScene* HelloWorld::scene() +{ + // 'scene' is an autorelease object + CCScene *scene = CCScene::create(); + + // 'layer' is an autorelease object + HelloWorld *layer = HelloWorld::create(); + + // add layer as a child to scene + scene->addChild(layer); + + // return the scene + return scene; +} + +// on "init" you need to initialize your instance +bool HelloWorld::init() +{ + ////////////////////////////// + // 1. super init first + if ( !CCLayer::init() ) + { + return false; + } + + ///////////////////////////// + // 2. add a menu item with "X" image, which is clicked to quit the program + // you may modify it. + + // add a "close" icon to exit the progress. it's an autorelease object + CCMenuItemImage *pCloseItem = CCMenuItemImage::create( + "CloseNormal.png", + "CloseSelected.png", + this, + menu_selector(HelloWorld::menuCloseCallback) ); + pCloseItem->setPosition( ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20) ); + + // create menu, it's an autorelease object + CCMenu* pMenu = CCMenu::create(pCloseItem, NULL); + pMenu->setPosition( CCPointZero ); + this->addChild(pMenu, 1); + + ///////////////////////////// + // 3. add your codes below... + + // add a label shows "Hello World" + // create and initialize a label + CCLabelTTF* pLabel = CCLabelTTF::create("Hello World", "Thonburi", 34); + + // ask director the window size + CCSize size = CCDirector::sharedDirector()->getWinSize(); + + // position the label on the center of the screen + pLabel->setPosition( ccp(size.width / 2, size.height - 20) ); + + // add the label as a child to this layer + this->addChild(pLabel, 1); + + // add "HelloWorld" splash screen" + CCSprite* pSprite = CCSprite::create("HelloWorld.png"); + + // position the sprite on the center of the screen + pSprite->setPosition( ccp(size.width/2, size.height/2) ); + + // add the sprite as a child to this layer + this->addChild(pSprite, 0); + + return true; +} + +void HelloWorld::menuCloseCallback(CCObject* pSender) +{ + CCDirector::sharedDirector()->end(); + +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) + exit(0); +#endif +} diff --git a/SimpleGame/Classes/HelloWorldScene.h b/SimpleGame/Classes/HelloWorldScene.h new file mode 100644 index 0000000000..e202b8c2c3 --- /dev/null +++ b/SimpleGame/Classes/HelloWorldScene.h @@ -0,0 +1,22 @@ +#ifndef __HELLOWORLD_SCENE_H__ +#define __HELLOWORLD_SCENE_H__ + +#include "cocos2d.h" + +class HelloWorld : public cocos2d::CCLayer +{ +public: + // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone + virtual bool init(); + + // there's no 'id' in cpp, so we recommand to return the exactly class pointer + static cocos2d::CCScene* scene(); + + // a selector callback + void menuCloseCallback(CCObject* pSender); + + // implement the "static node()" method manually + CREATE_FUNC(HelloWorld); +}; + +#endif // __HELLOWORLD_SCENE_H__ diff --git a/SimpleGame/Resources/HelloWorld.png.REMOVED.git-id b/SimpleGame/Resources/HelloWorld.png.REMOVED.git-id new file mode 100644 index 0000000000..f02d84fd8f --- /dev/null +++ b/SimpleGame/Resources/HelloWorld.png.REMOVED.git-id @@ -0,0 +1 @@ +5fe89fb5bd58cedf13b0363f97b20e3ea7ff255d \ No newline at end of file diff --git a/SimpleGame/proj.android/.classpath b/SimpleGame/proj.android/.classpath new file mode 100644 index 0000000000..a4763d1eec --- /dev/null +++ b/SimpleGame/proj.android/.classpath @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/SimpleGame/proj.android/.project b/SimpleGame/proj.android/.project new file mode 100644 index 0000000000..afc29d09d0 --- /dev/null +++ b/SimpleGame/proj.android/.project @@ -0,0 +1,33 @@ + + + SimpleGame + + + + + + com.android.ide.eclipse.adt.ResourceManagerBuilder + + + + + com.android.ide.eclipse.adt.PreCompilerBuilder + + + + + org.eclipse.jdt.core.javabuilder + + + + + com.android.ide.eclipse.adt.ApkBuilder + + + + + + com.android.ide.eclipse.adt.AndroidNature + org.eclipse.jdt.core.javanature + + diff --git a/SimpleGame/proj.android/AndroidManifest.xml b/SimpleGame/proj.android/AndroidManifest.xml new file mode 100644 index 0000000000..8574ea3ceb --- /dev/null +++ b/SimpleGame/proj.android/AndroidManifest.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + diff --git a/SimpleGame/proj.android/ant.properties b/SimpleGame/proj.android/ant.properties new file mode 100644 index 0000000000..b0971e891e --- /dev/null +++ b/SimpleGame/proj.android/ant.properties @@ -0,0 +1,17 @@ +# This file is used to override default values used by the Ant build system. +# +# This file must be checked into Version Control Systems, as it is +# integral to the build system of your project. + +# This file is only used by the Ant script. + +# You can use this to override default values such as +# 'source.dir' for the location of your java source folder and +# 'out.dir' for the location of your output folder. + +# You can also use it define how the release builds are signed by declaring +# the following properties: +# 'key.store' for the location of your keystore and +# 'key.alias' for the name of the key to use. +# The password will be asked during the build when you use the 'release' target. + diff --git a/SimpleGame/proj.android/build.xml b/SimpleGame/proj.android/build.xml new file mode 100644 index 0000000000..e9678a9b14 --- /dev/null +++ b/SimpleGame/proj.android/build.xml @@ -0,0 +1,92 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/SimpleGame/proj.android/build_native.sh b/SimpleGame/proj.android/build_native.sh new file mode 100755 index 0000000000..0078049efd --- /dev/null +++ b/SimpleGame/proj.android/build_native.sh @@ -0,0 +1,91 @@ +APPNAME="SimpleGame" + +# options + +buildexternalsfromsource= + +usage(){ +cat << EOF +usage: $0 [options] + +Build C/C++ code for $APPNAME using Android NDK + +OPTIONS: +-s Build externals from source +-h this help +EOF +} + +while getopts "sh" OPTION; do +case "$OPTION" in +s) +buildexternalsfromsource=1 +;; +h) +usage +exit 0 +;; +esac +done + +# 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 "NDK_ROOT = $NDK_ROOT" +echo "COCOS2DX_ROOT = $COCOS2DX_ROOT" +echo "APP_ROOT = $APP_ROOT" +echo "APP_ANDROID_ROOT = $APP_ANDROID_ROOT" + +# 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 + +# copy icons (if they exist) +file="$APP_ANDROID_ROOT"/assets/Icon-72.png +if [ -f "$file" ]; then + cp "$file" "$APP_ANDROID_ROOT"/res/drawable-hdpi/icon.png +fi +file="$APP_ANDROID_ROOT"/assets/Icon-48.png +if [ -f "$file" ]; then + cp "$file" "$APP_ANDROID_ROOT"/res/drawable-mdpi/icon.png +fi +file="$APP_ANDROID_ROOT"/assets/Icon-32.png +if [ -f "$file" ]; then + cp "$file" "$APP_ANDROID_ROOT"/res/drawable-ldpi/icon.png +fi + + +if [[ "$buildexternalsfromsource" ]]; then + echo "Building external dependencies from source" + "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ + "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos2dx/platform/third_party/android/source" +else + echo "Using prebuilt externals" + "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ + "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos2dx/platform/third_party/android/prebuilt" +fi diff --git a/SimpleGame/proj.android/jni/Android.mk b/SimpleGame/proj.android/jni/Android.mk new file mode 100644 index 0000000000..61af0085d6 --- /dev/null +++ b/SimpleGame/proj.android/jni/Android.mk @@ -0,0 +1,21 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE := game_shared + +LOCAL_MODULE_FILENAME := libgame + +LOCAL_SRC_FILES := hellocpp/main.cpp \ + ../../Classes/AppDelegate.cpp \ + ../../Classes/HelloWorldScene.cpp + +LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes + +LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static cocosdenshion_static cocos_extension_static + +include $(BUILD_SHARED_LIBRARY) + +$(call import-module,CocosDenshion/android) \ +$(call import-module,cocos2dx) \ +$(call import-module,extensions) diff --git a/SimpleGame/proj.android/jni/Application.mk b/SimpleGame/proj.android/jni/Application.mk new file mode 100644 index 0000000000..22d424dab7 --- /dev/null +++ b/SimpleGame/proj.android/jni/Application.mk @@ -0,0 +1,2 @@ +APP_STL := gnustl_static +APP_CPPFLAGS := -frtti \ No newline at end of file diff --git a/SimpleGame/proj.android/jni/hellocpp/main.cpp b/SimpleGame/proj.android/jni/hellocpp/main.cpp new file mode 100644 index 0000000000..035fb201c4 --- /dev/null +++ b/SimpleGame/proj.android/jni/hellocpp/main.cpp @@ -0,0 +1,45 @@ +#include "AppDelegate.h" +#include "platform/android/jni/JniHelper.h" +#include +#include + +#include "HelloWorldScene.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(); + } +} + +} diff --git a/SimpleGame/proj.android/jni/list.sh b/SimpleGame/proj.android/jni/list.sh new file mode 100644 index 0000000000..b95448ebbb --- /dev/null +++ b/SimpleGame/proj.android/jni/list.sh @@ -0,0 +1,23 @@ +#!/bin/bash + +append_str=' \' + +list_alldir() +{ + for file in $1/* + do + if [ -f $file ]; then + echo $file$append_str | grep .cpp + fi + + if [ -d $file ]; then + list_alldir $file + fi + done +} + +if [ $# -gt 0 ]; then + list_alldir "$1" +else + list_alldir "." +fi \ No newline at end of file diff --git a/SimpleGame/proj.android/proguard-project.txt b/SimpleGame/proj.android/proguard-project.txt new file mode 100644 index 0000000000..f2fe1559a2 --- /dev/null +++ b/SimpleGame/proj.android/proguard-project.txt @@ -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 *; +#} diff --git a/SimpleGame/proj.android/project.properties b/SimpleGame/proj.android/project.properties new file mode 100644 index 0000000000..85aac54016 --- /dev/null +++ b/SimpleGame/proj.android/project.properties @@ -0,0 +1,14 @@ +# 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 edit +# "ant.properties", and override values to adapt the script to your +# project structure. +# +# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): +#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt + +# Project target. +target=android-8 diff --git a/SimpleGame/proj.android/res/values/strings.xml b/SimpleGame/proj.android/res/values/strings.xml new file mode 100644 index 0000000000..f197c895b7 --- /dev/null +++ b/SimpleGame/proj.android/res/values/strings.xml @@ -0,0 +1,4 @@ + + + SimpleGame + diff --git a/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxAccelerometer.java b/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxAccelerometer.java new file mode 100644 index 0000000000..c515349cab --- /dev/null +++ b/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxAccelerometer.java @@ -0,0 +1,107 @@ +/**************************************************************************** +Copyright (c) 2010-2011 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.lib; + +import android.content.Context; +import android.content.res.Configuration; +import android.hardware.Sensor; +import android.hardware.SensorEvent; +import android.hardware.SensorEventListener; +import android.hardware.SensorManager; +import android.view.Display; +import android.view.Surface; +import android.view.WindowManager; + +/** + * + * This class is used for controlling the Accelerometer + * + */ +public class Cocos2dxAccelerometer implements SensorEventListener { + + private static final String TAG = "Cocos2dxAccelerometer"; + private Context mContext; + private SensorManager mSensorManager; + private Sensor mAccelerometer; + private int mNaturalOrientation; + + public Cocos2dxAccelerometer(Context context){ + mContext = context; + + //Get an instance of the SensorManager + mSensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE); + mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); + + Display display = ((WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); + mNaturalOrientation = display.getOrientation(); + } + + public void enable() { + mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_GAME); + } + + public void disable () { + mSensorManager.unregisterListener(this); + } + + @Override + public void onSensorChanged(SensorEvent event) { + + if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER){ + return; + } + + float x = event.values[0]; + float y = event.values[1]; + float z = event.values[2]; + + /* + * Because the axes are not swapped when the device's screen orientation changes. + * So we should swap it here. + * In tablets such as Motorola Xoom, the default orientation is landscape, so should + * consider this. + */ + int orientation = mContext.getResources().getConfiguration().orientation; + if ((orientation == Configuration.ORIENTATION_LANDSCAPE) && (mNaturalOrientation != Surface.ROTATION_0)){ + float tmp = x; + x = -y; + y = tmp; + } + else if ((orientation == Configuration.ORIENTATION_PORTRAIT) && (mNaturalOrientation != Surface.ROTATION_0)) + { + float tmp = x; + x = y; + y = -tmp; + } + + onSensorChanged(x, y, z, event.timestamp); + // Log.d(TAG, "x = " + event.values[0] + " y = " + event.values[1] + " z = " + event.values[2]); + } + + @Override + public void onAccuracyChanged(Sensor sensor, int accuracy) { + } + + private static native void onSensorChanged(float x, float y, float z, long timeStamp); +} diff --git a/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxActivity.java b/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxActivity.java new file mode 100644 index 0000000000..952d5148fb --- /dev/null +++ b/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxActivity.java @@ -0,0 +1,346 @@ +/**************************************************************************** +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.lib; + +import java.lang.ref.WeakReference; + +import android.app.Activity; +import android.app.AlertDialog; +import android.app.Dialog; +import android.content.DialogInterface; +import android.content.pm.ApplicationInfo; +import android.content.pm.PackageManager; +import android.content.pm.PackageManager.NameNotFoundException; +import android.content.res.AssetManager; +import android.os.Build; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.util.DisplayMetrics; +import android.util.Log; + +public class Cocos2dxActivity extends Activity{ + + protected Cocos2dxGLSurfaceView mGLView; + private static Cocos2dxMusic backgroundMusicPlayer; + private static Cocos2dxSound soundPlayer; + private static Cocos2dxAccelerometer accelerometer; + private static AssetManager assetManager; + private static boolean accelerometerEnabled = false; + private static Handler handler; + private final static int HANDLER_SHOW_DIALOG = 1; + private final static int HANDLER_SHOW_EDITBOX_DIALOG = 2; + + private static String packageName; + + private static native void nativeSetPaths(String apkPath); + private static native void nativeSetEditboxText(byte[] text); + + + static class ShowDialogHandler extends Handler { + WeakReference mActivity; + + ShowDialogHandler(Cocos2dxActivity activity) { + mActivity = new WeakReference(activity); + } + + @Override + public void handleMessage(Message msg) { + Cocos2dxActivity theActivity = mActivity.get(); + switch(msg.what) { + case HANDLER_SHOW_DIALOG: + theActivity.showDialog(((DialogMessage)msg.obj).title, ((DialogMessage)msg.obj).message); + break; + case HANDLER_SHOW_EDITBOX_DIALOG: + theActivity.onShowEditBoxDialog((EditBoxMessage)msg.obj); + break; + } + } + }; + + public Cocos2dxGLSurfaceView getGLView() { + return mGLView; + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + // get frame size + DisplayMetrics dm = new DisplayMetrics(); + getWindowManager().getDefaultDisplay().getMetrics(dm); + accelerometer = new Cocos2dxAccelerometer(this); + + // init media player and sound player + backgroundMusicPlayer = new Cocos2dxMusic(this); + soundPlayer = new Cocos2dxSound(this); + + // init asset manager for jni call + assetManager = getAssets(); + + // init bitmap context + Cocos2dxBitmap.setContext(this); + + handler = new ShowDialogHandler(this); + } + + public static String getDeviceModel(){ + return Build.MODEL; + } + + public static AssetManager getAssetManager() { + return assetManager; + } + + public static String getCurrentLanguage() { + String languageName = java.util.Locale.getDefault().getLanguage(); + return languageName; + } + + public static void showMessageBox(String title, String message){ + Message msg = new Message(); + msg.what = HANDLER_SHOW_DIALOG; + msg.obj = new DialogMessage(title, message); + + handler.sendMessage(msg); + } + + public static void enableAccelerometer() { + accelerometerEnabled = true; + accelerometer.enable(); + } + + public static void disableAccelerometer() { + accelerometerEnabled = false; + accelerometer.disable(); + } + + public static void preloadBackgroundMusic(String path){ + backgroundMusicPlayer.preloadBackgroundMusic(path); + } + + public static void playBackgroundMusic(String path, boolean isLoop){ + backgroundMusicPlayer.playBackgroundMusic(path, isLoop); + } + + public static void stopBackgroundMusic(){ + backgroundMusicPlayer.stopBackgroundMusic(); + } + + public static void pauseBackgroundMusic(){ + backgroundMusicPlayer.pauseBackgroundMusic(); + } + + public static void resumeBackgroundMusic(){ + backgroundMusicPlayer.resumeBackgroundMusic(); + } + + public static void rewindBackgroundMusic(){ + backgroundMusicPlayer.rewindBackgroundMusic(); + } + + public static boolean isBackgroundMusicPlaying(){ + return backgroundMusicPlayer.isBackgroundMusicPlaying(); + } + + public static float getBackgroundMusicVolume(){ + return backgroundMusicPlayer.getBackgroundVolume(); + } + + public static void setBackgroundMusicVolume(float volume){ + backgroundMusicPlayer.setBackgroundVolume(volume); + } + + public static int playEffect(String path, boolean isLoop){ + return soundPlayer.playEffect(path, isLoop); + } + + public static void stopEffect(int soundId){ + soundPlayer.stopEffect(soundId); + } + + public static void pauseEffect(int soundId){ + soundPlayer.pauseEffect(soundId); + } + + public static void resumeEffect(int soundId){ + soundPlayer.resumeEffect(soundId); + } + + public static float getEffectsVolume(){ + return soundPlayer.getEffectsVolume(); + } + + public static void setEffectsVolume(float volume){ + soundPlayer.setEffectsVolume(volume); + } + + public static void preloadEffect(String path){ + soundPlayer.preloadEffect(path); + } + + public static void unloadEffect(String path){ + soundPlayer.unloadEffect(path); + } + + public static void stopAllEffects(){ + soundPlayer.stopAllEffects(); + } + + public static void pauseAllEffects(){ + soundPlayer.pauseAllEffects(); + } + + public static void resumeAllEffects(){ + soundPlayer.resumeAllEffects(); + } + + public static void end(){ + backgroundMusicPlayer.end(); + soundPlayer.end(); + } + + public static String getCocos2dxPackageName(){ + return packageName; + } + + public static void terminateProcess(){ + android.os.Process.killProcess(android.os.Process.myPid()); + } + + @Override + protected void onResume() { + super.onResume(); + if (accelerometerEnabled) { + accelerometer.enable(); + } + } + + @Override + protected void onPause() { + super.onPause(); + if (accelerometerEnabled) { + accelerometer.disable(); + } + } + + protected void setPackageName(String packageName) { + Cocos2dxActivity.packageName = packageName; + + String apkFilePath = ""; + ApplicationInfo appInfo = null; + PackageManager packMgmr = getApplication().getPackageManager(); + try { + appInfo = packMgmr.getApplicationInfo(packageName, 0); + } catch (NameNotFoundException e) { + e.printStackTrace(); + throw new RuntimeException("Unable to locate assets, aborting..."); + } + apkFilePath = appInfo.sourceDir; + Log.w("apk path", apkFilePath); + + // add this link at the renderer class + nativeSetPaths(apkFilePath); + } + + private void showDialog(String title, String message){ + Dialog dialog = new AlertDialog.Builder(this) + .setTitle(title) + .setMessage(message) + .setPositiveButton("Ok", + new DialogInterface.OnClickListener() + { + public void onClick(DialogInterface dialog, int whichButton){ + + } + }).create(); + + dialog.show(); + } + + private static void showEditBoxDialog(String title, String content, int inputMode, int inputFlag, int returnType, int maxLength) + { + Message msg = new Message(); + msg.what = HANDLER_SHOW_EDITBOX_DIALOG; + msg.obj = new EditBoxMessage(title, content, inputMode, inputFlag, returnType, maxLength); + handler.sendMessage(msg); + } + + private void onShowEditBoxDialog(EditBoxMessage msg) + { + Dialog dialog = new Cocos2dxEditBoxDialog(this, msg); + dialog.show(); + } + + public void setEditBoxResult(String editResult) + { + Log.i("editbox_content", editResult); + + try + { + final byte[] bytesUTF8 = editResult.getBytes("UTF8"); + // pass utf8 string from editbox activity to native. + // Should invoke native method in GL thread. + mGLView.queueEvent(new Runnable() { + @Override + public void run() { + nativeSetEditboxText(bytesUTF8); + } + }); + } + catch (java.io.UnsupportedEncodingException e) + { + e.printStackTrace(); + } + } +} + +class DialogMessage { + public String title; + public String message; + + public DialogMessage(String title, String message){ + this.message = message; + this.title = title; + } +} + +class EditBoxMessage { + public String title; + public String content; + public int inputMode; + public int inputFlag; + public int returnType; + public int maxLength; + + public EditBoxMessage(String title, String content, int inputMode, int inputFlag, int returnType, int maxLength){ + this.content = content; + this.title = title; + this.inputMode = inputMode; + this.inputFlag = inputFlag; + this.returnType = returnType; + this.maxLength = maxLength; + } +} diff --git a/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxBitmap.java b/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxBitmap.java new file mode 100644 index 0000000000..395400b779 --- /dev/null +++ b/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxBitmap.java @@ -0,0 +1,455 @@ +/**************************************************************************** +Copyright (c) 2010-2011 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.lib; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.LinkedList; + +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.graphics.Rect; +import android.graphics.Typeface; +import android.graphics.Paint.Align; +import android.graphics.Paint.FontMetricsInt; +import android.text.TextPaint; +import android.text.TextUtils; +import android.util.Log; + +public class Cocos2dxBitmap{ + /* + * The values are the same as cocos2dx/platform/CCImage.h. + */ + private static final int HALIGNCENTER = 3; + private static final int HALIGNLEFT = 1; + private static final int HALIGNRIGHT = 2; + // vertical alignment + private static final int VALIGNTOP = 1; + private static final int VALIGNBOTTOM = 2; + private static final int VALIGNCENTER = 3; + + private static Context context; + + public static void setContext(Context context){ + Cocos2dxBitmap.context = context; + } + + /* + * @width: the width to draw, it can be 0 + * @height: the height to draw, it can be 0 + */ + public static void createTextBitmap(String content, String fontName, + int fontSize, int alignment, int width, int height){ + + content = refactorString(content); + Paint paint = newPaint(fontName, fontSize, alignment); + + TextProperty textProperty = computeTextProperty(content, paint, width, height); + + int bitmapTotalHeight = (height == 0 ? textProperty.totalHeight:height); + + // Draw text to bitmap + Bitmap bitmap = Bitmap.createBitmap(textProperty.maxWidth, + bitmapTotalHeight, Bitmap.Config.ARGB_8888); + Canvas canvas = new Canvas(bitmap); + + // Draw string + FontMetricsInt fm = paint.getFontMetricsInt(); + int x = 0; + int y = computeY(fm, height, textProperty.totalHeight, alignment); + String[] lines = textProperty.lines; + for (String line : lines){ + x = computeX(paint, line, textProperty.maxWidth, alignment); + canvas.drawText(line, x, y, paint); + y += textProperty.heightPerLine; + } + + initNativeObject(bitmap); + } + + private static int computeX(Paint paint, String content, int w, int alignment){ + int ret = 0; + int hAlignment = alignment & 0x0F; + + switch (hAlignment){ + case HALIGNCENTER: + ret = w / 2; + break; + + // ret = 0 + case HALIGNLEFT: + break; + + case HALIGNRIGHT: + ret = w; + break; + + /* + * Default is align left. + * Should be same as newPaint(). + */ + default: + break; + } + + return ret; + } + + private static int computeY(FontMetricsInt fm, int constrainHeight, int totalHeight, int alignment) { + int y = -fm.top; + + if (constrainHeight > totalHeight) { + int vAlignment = (alignment >> 4) & 0x0F; + + switch (vAlignment) { + case VALIGNTOP: + y = -fm.top; + break; + case VALIGNCENTER: + y = -fm.top + (constrainHeight - totalHeight)/2; + break; + case VALIGNBOTTOM: + y = -fm.top + (constrainHeight - totalHeight); + break; + default: + break; + } + } + + return y; + } + + private static class TextProperty{ + // The max width of lines + int maxWidth; + // The height of all lines + int totalHeight; + int heightPerLine; + String[] lines; + + TextProperty(int w, int h, String[] lines){ + this.maxWidth = w; + this.heightPerLine = h; + this.totalHeight = h * lines.length; + this.lines = lines; + } + } + + private static TextProperty computeTextProperty(String content, Paint paint, + int maxWidth, int maxHeight){ + FontMetricsInt fm = paint.getFontMetricsInt(); + int h = (int)Math.ceil(fm.bottom - fm.top); + int maxContentWidth = 0; + + String[] lines = splitString(content, maxHeight, maxWidth, paint); + + if (maxWidth != 0){ + maxContentWidth = maxWidth; + } + else { + /* + * Compute the max width + */ + int temp = 0; + for (String line : lines){ + temp = (int)Math.ceil(paint.measureText(line, 0, line.length())); + if (temp > maxContentWidth){ + maxContentWidth = temp; + } + } + } + + return new TextProperty(maxContentWidth, h, lines); + } + + /* + * If maxWidth or maxHeight is not 0, + * split the string to fix the maxWidth and maxHeight. + */ + private static String[] splitString(String content, int maxHeight, int maxWidth, + Paint paint){ + String[] lines = content.split("\\n"); + String[] ret = null; + FontMetricsInt fm = paint.getFontMetricsInt(); + int heightPerLine = (int)Math.ceil(fm.bottom - fm.top); + int maxLines = maxHeight / heightPerLine; + + if (maxWidth != 0){ + LinkedList strList = new LinkedList(); + for (String line : lines){ + /* + * The width of line is exceed maxWidth, should divide it into + * two or more lines. + */ + int lineWidth = (int)Math.ceil(paint.measureText(line)); + if (lineWidth > maxWidth){ + strList.addAll(divideStringWithMaxWidth(paint, line, maxWidth)); + } + else{ + strList.add(line); + } + + /* + * Should not exceed the max height; + */ + if (maxLines > 0 && strList.size() >= maxLines){ + break; + } + } + + /* + * Remove exceeding lines + */ + if (maxLines > 0 && strList.size() > maxLines){ + while (strList.size() > maxLines){ + strList.removeLast(); + } + } + + ret = new String[strList.size()]; + strList.toArray(ret); + } else + if (maxHeight != 0 && lines.length > maxLines) { + /* + * Remove exceeding lines + */ + LinkedList strList = new LinkedList(); + for (int i = 0; i < maxLines; i++){ + strList.add(lines[i]); + } + ret = new String[strList.size()]; + strList.toArray(ret); + } + else { + ret = lines; + } + + return ret; + } + + private static LinkedList divideStringWithMaxWidth(Paint paint, String content, + int width){ + int charLength = content.length(); + int start = 0; + int tempWidth = 0; + LinkedList strList = new LinkedList(); + + /* + * Break a String into String[] by the width & should wrap the word + */ + for (int i = 1; i <= charLength; ++i){ + tempWidth = (int)Math.ceil(paint.measureText(content, start, i)); + if (tempWidth >= width){ + int lastIndexOfSpace = content.substring(0, i).lastIndexOf(" "); + + if (lastIndexOfSpace != -1 && lastIndexOfSpace > start){ + /** + * Should wrap the word + */ + strList.add(content.substring(start, lastIndexOfSpace)); + i = lastIndexOfSpace; + } + else { + /* + * Should not exceed the width + */ + if (tempWidth > width){ + strList.add(content.substring(start, i - 1)); + /* + * compute from previous char + */ + --i; + } + else { + strList.add(content.substring(start, i)); + } + } + + // remove spaces at the beginning of a new line + while(content.indexOf(i++) == ' ') { + } + + start = i; + } + } + + /* + * Add the last chars + */ + if (start < charLength){ + strList.add(content.substring(start)); + } + + return strList; + } + + private static Paint newPaint(String fontName, int fontSize, int alignment){ + Paint paint = new Paint(); + paint.setColor(Color.WHITE); + paint.setTextSize(fontSize); + paint.setAntiAlias(true); + + /* + * Set type face for paint, now it support .ttf file. + */ + if (fontName.endsWith(".ttf")){ + try { + //Typeface typeFace = Typeface.createFromAsset(context.getAssets(), fontName); + Typeface typeFace = Cocos2dxTypefaces.get(context, fontName); + paint.setTypeface(typeFace); + } catch (Exception e){ + Log.e("Cocos2dxBitmap", + "error to create ttf type face: " + fontName); + + /* + * The file may not find, use system font + */ + paint.setTypeface(Typeface.create(fontName, Typeface.NORMAL)); + } + } + else { + paint.setTypeface(Typeface.create(fontName, Typeface.NORMAL)); + } + + int hAlignment = alignment & 0x0F; + switch (hAlignment){ + case HALIGNCENTER: + paint.setTextAlign(Align.CENTER); + break; + + case HALIGNLEFT: + paint.setTextAlign(Align.LEFT); + break; + + case HALIGNRIGHT: + paint.setTextAlign(Align.RIGHT); + break; + + default: + paint.setTextAlign(Align.LEFT); + break; + } + + return paint; + } + + private static String refactorString(String str){ + // Avoid error when content is "" + if (str.compareTo("") == 0){ + return " "; + } + + /* + * If the font of "\n" is "" or "\n", insert " " in front of it. + * + * For example: + * "\nabc" -> " \nabc" + * "\nabc\n\n" -> " \nabc\n \n" + */ + StringBuilder strBuilder = new StringBuilder(str); + int start = 0; + int index = strBuilder.indexOf("\n"); + while (index != -1){ + if (index == 0 || strBuilder.charAt(index -1) == '\n'){ + strBuilder.insert(start, " "); + start = index + 2; + } else { + start = index + 1; + } + + if (start > strBuilder.length() || index == strBuilder.length()){ + break; + } + + index = strBuilder.indexOf("\n", start); + } + + return strBuilder.toString(); + } + + private static void initNativeObject(Bitmap bitmap){ + byte[] pixels = getPixels(bitmap); + if (pixels == null){ + return; + } + + nativeInitBitmapDC(bitmap.getWidth(), bitmap.getHeight(), pixels); + } + + private static byte[] getPixels(Bitmap bitmap){ + if (bitmap != null){ + byte[] pixels = new byte[bitmap.getWidth() * bitmap.getHeight() * 4]; + ByteBuffer buf = ByteBuffer.wrap(pixels); + buf.order(ByteOrder.nativeOrder()); + bitmap.copyPixelsToBuffer(buf); + return pixels; + } + + return null; + } + + private static native void nativeInitBitmapDC(int width, int height, byte[] pixels); + + private static int getFontSizeAccordingHeight(int height) + { + Paint paint = new Paint(); + Rect bounds = new Rect(); + + paint.setTypeface(Typeface.DEFAULT); + int incr_text_size = 1; + boolean found_desired_size = false; + + while (!found_desired_size) { + + paint.setTextSize(incr_text_size); + String text = "SghMNy"; + paint.getTextBounds(text, 0, text.length(), bounds); + + incr_text_size++; + + if (height - bounds.height() <= 2) { + found_desired_size = true; + } + Log.d("font size", "incr size:" + incr_text_size); + } + return incr_text_size; + } + + private static String getStringWithEllipsis(String originalText, float width, float fontSize){ + if(TextUtils.isEmpty(originalText)){ + return ""; + } + + TextPaint paint = new TextPaint(); + paint.setTypeface(Typeface.DEFAULT); + paint.setTextSize(fontSize); + + return TextUtils.ellipsize(originalText, paint, width, + TextUtils.TruncateAt.valueOf("END")).toString(); + } + +} diff --git a/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxEditBoxDialog.java b/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxEditBoxDialog.java new file mode 100755 index 0000000000..66e94e242c --- /dev/null +++ b/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxEditBoxDialog.java @@ -0,0 +1,338 @@ +/**************************************************************************** +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.lib; + +import android.app.Dialog; +import android.content.Context; +import android.graphics.drawable.ColorDrawable; +import android.os.Bundle; +import android.os.Handler; +import android.text.InputFilter; +import android.text.InputType; +import android.util.Log; +import android.util.TypedValue; +import android.view.KeyEvent; +import android.view.ViewGroup; +import android.view.WindowManager; +import android.view.inputmethod.EditorInfo; +import android.view.inputmethod.InputMethodManager; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.TextView; +import android.widget.TextView.OnEditorActionListener; + +public class Cocos2dxEditBoxDialog extends Dialog { + + /** + * The user is allowed to enter any text, including line breaks. + */ + private final int kEditBoxInputModeAny = 0; + + /** + * The user is allowed to enter an e-mail address. + */ + private final int kEditBoxInputModeEmailAddr = 1; + + /** + * The user is allowed to enter an integer value. + */ + private final int kEditBoxInputModeNumeric = 2; + + /** + * The user is allowed to enter a phone number. + */ + private final int kEditBoxInputModePhoneNumber = 3; + + /** + * The user is allowed to enter a URL. + */ + private final int kEditBoxInputModeUrl = 4; + + /** + * The user is allowed to enter a real number value. + * This extends kEditBoxInputModeNumeric by allowing a decimal point. + */ + private final int kEditBoxInputModeDecimal = 5; + + /** + * The user is allowed to enter any text, except for line breaks. + */ + private final int kEditBoxInputModeSingleLine = 6; + + + /** + * Indicates that the text entered is confidential data that should be + * obscured whenever possible. This implies EDIT_BOX_INPUT_FLAG_SENSITIVE. + */ + private final int kEditBoxInputFlagPassword = 0; + + /** + * Indicates that the text entered is sensitive data that the + * implementation must never store into a dictionary or table for use + * in predictive, auto-completing, or other accelerated input schemes. + * A credit card number is an example of sensitive data. + */ + private final int kEditBoxInputFlagSensitive = 1; + + /** + * This flag is a hint to the implementation that during text editing, + * the initial letter of each word should be capitalized. + */ + private final int kEditBoxInputFlagInitialCapsWord = 2; + + /** + * This flag is a hint to the implementation that during text editing, + * the initial letter of each sentence should be capitalized. + */ + private final int kEditBoxInputFlagInitialCapsSentence = 3; + + /** + * Capitalize all characters automatically. + */ + private final int kEditBoxInputFlagInitialCapsAllCharacters = 4; + + private final int kKeyboardReturnTypeDefault = 0; + private final int kKeyboardReturnTypeDone = 1; + private final int kKeyboardReturnTypeSend = 2; + private final int kKeyboardReturnTypeSearch = 3; + private final int kKeyboardReturnTypeGo = 4; + + // + private EditText mInputEditText = null; + private TextView mTextViewTitle = null; + private int mInputMode = 0; + private int mInputFlag = 0; + private int mReturnType = 0; + private int mMaxLength = -1; + + private int mInputFlagConstraints = 0x00000; + private int mInputModeContraints = 0x00000; + private boolean mIsMultiline = false; + private Cocos2dxActivity mParentActivity = null; + private EditBoxMessage mMsg = null; + + public Cocos2dxEditBoxDialog(Context context, EditBoxMessage msg) { + //super(context, R.style.Theme_Translucent); + super(context, android.R.style.Theme_Translucent_NoTitleBar_Fullscreen); + // TODO Auto-generated constructor stub + mParentActivity = (Cocos2dxActivity)context; + mMsg = msg; + } + + // Converting dips to pixels + private int convertDipsToPixels(float dips) + { + float scale = getContext().getResources().getDisplayMetrics().density; + return Math.round(dips * scale); + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + // TODO Auto-generated method stub + super.onCreate(savedInstanceState); + + getWindow().setBackgroundDrawable(new ColorDrawable(0x80000000)); + + LinearLayout layout = new LinearLayout(mParentActivity); + layout.setOrientation(LinearLayout.VERTICAL); + + LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup. + LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.FILL_PARENT); + + mTextViewTitle = new TextView(mParentActivity); + LinearLayout.LayoutParams textviewParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, + ViewGroup.LayoutParams.WRAP_CONTENT); + textviewParams.leftMargin = textviewParams.rightMargin = convertDipsToPixels(10); + mTextViewTitle.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20); + layout.addView(mTextViewTitle, textviewParams); + + mInputEditText = new EditText(mParentActivity); + LinearLayout.LayoutParams editTextParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, + ViewGroup.LayoutParams.WRAP_CONTENT); + editTextParams.leftMargin = editTextParams.rightMargin = convertDipsToPixels(10); + + layout.addView(mInputEditText, editTextParams); + + setContentView(layout, layoutParams); + + getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); + + mInputMode = mMsg.inputMode; + mInputFlag = mMsg.inputFlag; + mReturnType = mMsg.returnType; + mMaxLength = mMsg.maxLength; + + mTextViewTitle.setText(mMsg.title); + mInputEditText.setText(mMsg.content); + + int oldImeOptions = mInputEditText.getImeOptions(); + mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_FLAG_NO_EXTRACT_UI); + oldImeOptions = mInputEditText.getImeOptions(); + + switch (mInputMode) + { + case kEditBoxInputModeAny: + mInputModeContraints = + InputType.TYPE_CLASS_TEXT | + InputType.TYPE_TEXT_FLAG_MULTI_LINE; + break; + case kEditBoxInputModeEmailAddr: + mInputModeContraints = + InputType.TYPE_CLASS_TEXT | + InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS; + break; + case kEditBoxInputModeNumeric: + mInputModeContraints = + InputType.TYPE_CLASS_NUMBER | + InputType.TYPE_NUMBER_FLAG_SIGNED; + break; + case kEditBoxInputModePhoneNumber: + mInputModeContraints = InputType.TYPE_CLASS_PHONE; + break; + case kEditBoxInputModeUrl: + mInputModeContraints = + InputType.TYPE_CLASS_TEXT | + InputType.TYPE_TEXT_VARIATION_URI; + break; + case kEditBoxInputModeDecimal: + mInputModeContraints = + InputType.TYPE_CLASS_NUMBER | + InputType.TYPE_NUMBER_FLAG_DECIMAL | + InputType.TYPE_NUMBER_FLAG_SIGNED; + break; + case kEditBoxInputModeSingleLine: + mInputModeContraints = InputType.TYPE_CLASS_TEXT; + break; + default: + + break; + } + + if ( mIsMultiline ) { + mInputModeContraints |= InputType.TYPE_TEXT_FLAG_MULTI_LINE; + } + + mInputEditText.setInputType(mInputModeContraints | mInputFlagConstraints); + + switch (mInputFlag) + { + case kEditBoxInputFlagPassword: + mInputFlagConstraints = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD; + break; + case kEditBoxInputFlagSensitive: + mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS; + break; + case kEditBoxInputFlagInitialCapsWord: + mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_CAP_WORDS; + break; + case kEditBoxInputFlagInitialCapsSentence: + mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_CAP_SENTENCES; + break; + case kEditBoxInputFlagInitialCapsAllCharacters: + mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS; + break; + default: + break; + } + mInputEditText.setInputType(mInputFlagConstraints | mInputModeContraints); + + switch (mReturnType) { + case kKeyboardReturnTypeDefault: + mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_NONE); + break; + case kKeyboardReturnTypeDone: + mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_DONE); + break; + case kKeyboardReturnTypeSend: + mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_SEND); + break; + case kKeyboardReturnTypeSearch: + mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_SEARCH); + break; + case kKeyboardReturnTypeGo: + mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_GO); + break; + default: + mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_NONE); + break; + } + + if (mMaxLength > 0) { + mInputEditText.setFilters( + new InputFilter[] { + new InputFilter.LengthFilter(mMaxLength) + } + ); + } + + Handler initHandler = new Handler(); + initHandler.postDelayed(new Runnable() { + public void run() { + mInputEditText.requestFocus(); + mInputEditText.setSelection(mInputEditText.length()); + openKeyboard(); + } + }, 200); + + mInputEditText.setOnEditorActionListener(new OnEditorActionListener() { + @Override + public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { + // if user didn't set keyboard type, + // this callback will be invoked twice with 'KeyEvent.ACTION_DOWN' and 'KeyEvent.ACTION_UP' + if (actionId != EditorInfo.IME_NULL + || (actionId == EditorInfo.IME_NULL + && event != null + && event.getAction() == KeyEvent.ACTION_DOWN)) + { + //Log.d("EditBox", "actionId: "+actionId +",event: "+event); + mParentActivity.setEditBoxResult(mInputEditText.getText().toString()); + closeKeyboard(); + dismiss(); + return true; + } + return false; + } + }); + } + + private void openKeyboard() { + InputMethodManager imm = (InputMethodManager) mParentActivity.getSystemService(Context.INPUT_METHOD_SERVICE); + imm.showSoftInput(mInputEditText, 0); + Log.d("Cocos2dxEditBox", "openKeyboard"); + } + + private void closeKeyboard() { + InputMethodManager imm = (InputMethodManager) mParentActivity.getSystemService(Context.INPUT_METHOD_SERVICE); + imm.hideSoftInputFromWindow(mInputEditText.getWindowToken(), 0); + Log.d("Cocos2dxEditBox", "closeKeyboard"); + } + + @Override + protected void onStop() { + // TODO Auto-generated method stub + super.onStop(); + Log.d("EditBox", "onStop..."); + } +} diff --git a/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxEditText.java b/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxEditText.java new file mode 100644 index 0000000000..1c9778293f --- /dev/null +++ b/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxEditText.java @@ -0,0 +1,65 @@ +/**************************************************************************** +Copyright (c) 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.lib; + +import android.content.Context; +import android.util.AttributeSet; +import android.view.KeyEvent; +import android.widget.EditText; + +public class Cocos2dxEditText extends EditText { + + private Cocos2dxGLSurfaceView mView; + + public Cocos2dxEditText(Context context) { + super(context); + // TODO Auto-generated constructor stub + } + + public Cocos2dxEditText(Context context, AttributeSet attrs) { + super(context, attrs); + } + + public Cocos2dxEditText(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + } + + public void setMainView(Cocos2dxGLSurfaceView glSurfaceView) { + mView = glSurfaceView; + } + + /* + * Let GlSurfaceView get focus if back key is input + */ + public boolean onKeyDown(int keyCode, KeyEvent event) { + super.onKeyDown(keyCode, event); + + if (keyCode == KeyEvent.KEYCODE_BACK) { + mView.requestFocus(); + } + + return true; + } +} diff --git a/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java b/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java new file mode 100644 index 0000000000..e7c4721cf3 --- /dev/null +++ b/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java @@ -0,0 +1,417 @@ +/**************************************************************************** +Copyright (c) 2010-2011 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.lib; + +import android.content.Context; +import android.opengl.GLSurfaceView; +import android.os.Handler; +import android.os.Message; +import android.text.Editable; +import android.text.TextWatcher; +import android.util.AttributeSet; +import android.util.Log; +import android.view.KeyEvent; +import android.view.MotionEvent; +import android.view.inputmethod.InputMethodManager; +import android.widget.TextView; +import android.widget.TextView.OnEditorActionListener; + +class TextInputWraper implements TextWatcher, OnEditorActionListener { + + private static final Boolean debug = false; + private void LogD(String msg) { + if (debug) Log.d("TextInputFilter", msg); + } + + private Cocos2dxGLSurfaceView mMainView; + private String mText; + private String mOriginText; + + private Boolean isFullScreenEdit() { + InputMethodManager imm = (InputMethodManager)mMainView.getTextField().getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + return imm.isFullscreenMode(); + } + + public TextInputWraper(Cocos2dxGLSurfaceView view) { + mMainView = view; + } + + public void setOriginText(String text) { + mOriginText = text; + } + + @Override + public void afterTextChanged(Editable s) { + if (isFullScreenEdit()) { + return; + } + + LogD("afterTextChanged: " + s); + int nModified = s.length() - mText.length(); + if (nModified > 0) { + final String insertText = s.subSequence(mText.length(), s.length()).toString(); + mMainView.insertText(insertText); + LogD("insertText(" + insertText + ")"); + } + else { + for (; nModified < 0; ++nModified) { + mMainView.deleteBackward(); + LogD("deleteBackward"); + } + } + mText = s.toString(); + } + + @Override + public void beforeTextChanged(CharSequence s, int start, int count, + int after) { + LogD("beforeTextChanged(" + s + ")start: " + start + ",count: " + count + ",after: " + after); + mText = s.toString(); + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + } + + @Override + public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { + if (mMainView.getTextField() == v && isFullScreenEdit()) { + // user press the action button, delete all old text and insert new text + for (int i = mOriginText.length(); i > 0; --i) { + mMainView.deleteBackward(); + LogD("deleteBackward"); + } + String text = v.getText().toString(); + + /* + * If user input nothing, translate "\n" to engine. + */ + if (text.compareTo("") == 0){ + text = "\n"; + } + + if ('\n' != text.charAt(text.length() - 1)) { + text += '\n'; + } + + final String insertText = text; + mMainView.insertText(insertText); + LogD("insertText(" + insertText + ")"); + } + return false; + } +} + +public class Cocos2dxGLSurfaceView extends GLSurfaceView { + + static private Cocos2dxGLSurfaceView mainView; + + private static final String TAG = Cocos2dxGLSurfaceView.class.getCanonicalName(); + private Cocos2dxRenderer mRenderer; + + private static final boolean debug = false; + + /////////////////////////////////////////////////////////////////////////// + // for initialize + /////////////////////////////////////////////////////////////////////////// + public Cocos2dxGLSurfaceView(Context context) { + super(context); + initView(); + } + + public Cocos2dxGLSurfaceView(Context context, AttributeSet attrs) { + super(context, attrs); + initView(); + } + + public void setCocos2dxRenderer(Cocos2dxRenderer renderer){ + mRenderer = renderer; + setRenderer(mRenderer); + } + + protected void initView() { + setFocusableInTouchMode(true); + + textInputWraper = new TextInputWraper(this); + + handler = new Handler(){ + public void handleMessage(Message msg){ + switch(msg.what){ + case HANDLER_OPEN_IME_KEYBOARD: + if (null != mTextField && mTextField.requestFocus()) { + mTextField.removeTextChangedListener(textInputWraper); + mTextField.setText(""); + String text = (String)msg.obj; + mTextField.append(text); + textInputWraper.setOriginText(text); + mTextField.addTextChangedListener(textInputWraper); + InputMethodManager imm = (InputMethodManager)mainView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + imm.showSoftInput(mTextField, 0); + Log.d("GLSurfaceView", "showSoftInput"); + } + break; + + case HANDLER_CLOSE_IME_KEYBOARD: + if (null != mTextField) { + mTextField.removeTextChangedListener(textInputWraper); + InputMethodManager imm = (InputMethodManager)mainView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + imm.hideSoftInputFromWindow(mTextField.getWindowToken(), 0); + Log.d("GLSurfaceView", "HideSoftInput"); + } + break; + } + } + }; + + mainView = this; + } + + public void onPause(){ + queueEvent(new Runnable() { + @Override + public void run() { + mRenderer.handleOnPause(); + } + }); + + super.onPause(); + } + + public void onResume(){ + super.onResume(); + + queueEvent(new Runnable() { + @Override + public void run() { + mRenderer.handleOnResume(); + } + }); + } + + /////////////////////////////////////////////////////////////////////////// + // for text input + /////////////////////////////////////////////////////////////////////////// + private final static int HANDLER_OPEN_IME_KEYBOARD = 2; + private final static int HANDLER_CLOSE_IME_KEYBOARD = 3; + private static Handler handler; + private static TextInputWraper textInputWraper; + private Cocos2dxEditText mTextField; + + public TextView getTextField() { + return mTextField; + } + + public void setTextField(Cocos2dxEditText view) { + mTextField = view; + if (null != mTextField && null != textInputWraper) { + mTextField.setOnEditorActionListener(textInputWraper); + mTextField.setMainView(this); + this.requestFocus(); + } + } + + public static void openIMEKeyboard() { + Message msg = new Message(); + msg.what = HANDLER_OPEN_IME_KEYBOARD; + msg.obj = mainView.getContentText(); + handler.sendMessage(msg); + + } + + private String getContentText() { + return mRenderer.getContentText(); + } + + public static void closeIMEKeyboard() { + Message msg = new Message(); + msg.what = HANDLER_CLOSE_IME_KEYBOARD; + handler.sendMessage(msg); + } + + public void insertText(final String text) { + queueEvent(new Runnable() { + @Override + public void run() { + mRenderer.handleInsertText(text); + } + }); + } + + public void deleteBackward() { + queueEvent(new Runnable() { + @Override + public void run() { + mRenderer.handleDeleteBackward(); + } + }); + } + + /////////////////////////////////////////////////////////////////////////// + // for touch event + /////////////////////////////////////////////////////////////////////////// + + public boolean onTouchEvent(final MotionEvent event) { + // these data are used in ACTION_MOVE and ACTION_CANCEL + final int pointerNumber = event.getPointerCount(); + final int[] ids = new int[pointerNumber]; + final float[] xs = new float[pointerNumber]; + final float[] ys = new float[pointerNumber]; + + for (int i = 0; i < pointerNumber; i++) { + ids[i] = event.getPointerId(i); + xs[i] = event.getX(i); + ys[i] = event.getY(i); + } + + switch (event.getAction() & MotionEvent.ACTION_MASK) { + case MotionEvent.ACTION_POINTER_DOWN: + final int indexPointerDown = event.getAction() >> MotionEvent.ACTION_POINTER_ID_SHIFT; + final int idPointerDown = event.getPointerId(indexPointerDown); + final float xPointerDown = event.getX(indexPointerDown); + final float yPointerDown = event.getY(indexPointerDown); + + queueEvent(new Runnable() { + @Override + public void run() { + mRenderer.handleActionDown(idPointerDown, xPointerDown, yPointerDown); + } + }); + break; + + case MotionEvent.ACTION_DOWN: + // there are only one finger on the screen + final int idDown = event.getPointerId(0); + final float xDown = xs[0]; + final float yDown = ys[0]; + + queueEvent(new Runnable() { + @Override + public void run() { + mRenderer.handleActionDown(idDown, xDown, yDown); + } + }); + break; + + case MotionEvent.ACTION_MOVE: + queueEvent(new Runnable() { + @Override + public void run() { + mRenderer.handleActionMove(ids, xs, ys); + } + }); + break; + + case MotionEvent.ACTION_POINTER_UP: + final int indexPointUp = event.getAction() >> MotionEvent.ACTION_POINTER_ID_SHIFT; + final int idPointerUp = event.getPointerId(indexPointUp); + final float xPointerUp = event.getX(indexPointUp); + final float yPointerUp = event.getY(indexPointUp); + + queueEvent(new Runnable() { + @Override + public void run() { + mRenderer.handleActionUp(idPointerUp, xPointerUp, yPointerUp); + } + }); + break; + + case MotionEvent.ACTION_UP: + // there are only one finger on the screen + final int idUp = event.getPointerId(0); + final float xUp = xs[0]; + final float yUp = ys[0]; + + queueEvent(new Runnable() { + @Override + public void run() { + mRenderer.handleActionUp(idUp, xUp, yUp); + } + }); + break; + + case MotionEvent.ACTION_CANCEL: + queueEvent(new Runnable() { + @Override + public void run() { + mRenderer.handleActionCancel(ids, xs, ys); + } + }); + break; + } + + if (debug){ + dumpEvent(event); + } + return true; + } + + /* + * This function is called before Cocos2dxRenderer.nativeInit(), so the width and height is correct. + */ + protected void onSizeChanged(int w, int h, int oldw, int oldh){ + this.mRenderer.setScreenWidthAndHeight(w, h); + } + + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { + final int kc = keyCode; + if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_MENU) { + queueEvent(new Runnable() { + @Override + public void run() { + mRenderer.handleKeyDown(kc); + } + }); + return true; + } + return super.onKeyDown(keyCode, event); + } + + // Show an event in the LogCat view, for debugging + private void dumpEvent(MotionEvent event) { + String names[] = { "DOWN" , "UP" , "MOVE" , "CANCEL" , "OUTSIDE" , + "POINTER_DOWN" , "POINTER_UP" , "7?" , "8?" , "9?" }; + StringBuilder sb = new StringBuilder(); + int action = event.getAction(); + int actionCode = action & MotionEvent.ACTION_MASK; + sb.append("event ACTION_" ).append(names[actionCode]); + if (actionCode == MotionEvent.ACTION_POINTER_DOWN + || actionCode == MotionEvent.ACTION_POINTER_UP) { + sb.append("(pid " ).append( + action >> MotionEvent.ACTION_POINTER_ID_SHIFT); + sb.append(")" ); + } + sb.append("[" ); + for (int i = 0; i < event.getPointerCount(); i++) { + sb.append("#" ).append(i); + sb.append("(pid " ).append(event.getPointerId(i)); + sb.append(")=" ).append((int) event.getX(i)); + sb.append("," ).append((int) event.getY(i)); + if (i + 1 < event.getPointerCount()) + sb.append(";" ); + } + sb.append("]" ); + Log.d(TAG, sb.toString()); + } +} diff --git a/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxMusic.java b/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxMusic.java new file mode 100644 index 0000000000..10e3e5f3c6 --- /dev/null +++ b/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxMusic.java @@ -0,0 +1,228 @@ +/**************************************************************************** +Copyright (c) 2010-2011 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.lib; + +import android.content.Context; +import android.content.res.AssetFileDescriptor; +import android.media.MediaPlayer; +import android.util.Log; + +/** + * + * This class is used for controlling background music + * + */ +public class Cocos2dxMusic { + + private static final String TAG = "Cocos2dxMusic"; + private float mLeftVolume; + private float mRightVolume; + private Context mContext; + private MediaPlayer mBackgroundMediaPlayer; + private boolean mIsPaused; + private String mCurrentPath; + + public Cocos2dxMusic(Context context){ + this.mContext = context; + initData(); + } + + public void preloadBackgroundMusic(String path){ + if ((mCurrentPath == null) || (! mCurrentPath.equals(path))){ + // preload new background music + + // release old resource and create a new one + if (mBackgroundMediaPlayer != null){ + mBackgroundMediaPlayer.release(); + } + + mBackgroundMediaPlayer = createMediaplayerFromAssets(path); + + // record the path + mCurrentPath = path; + } + } + + public void playBackgroundMusic(String path, boolean isLoop){ + if (mCurrentPath == null){ + // it is the first time to play background music + // or end() was called + mBackgroundMediaPlayer = createMediaplayerFromAssets(path); + mCurrentPath = path; + } + else { + if (! mCurrentPath.equals(path)){ + // play new background music + + // release old resource and create a new one + if (mBackgroundMediaPlayer != null){ + mBackgroundMediaPlayer.release(); + } + mBackgroundMediaPlayer = createMediaplayerFromAssets(path); + + // record the path + mCurrentPath = path; + } + } + + if (mBackgroundMediaPlayer == null){ + Log.e(TAG, "playBackgroundMusic: background media player is null"); + } else { + // if the music is playing or paused, stop it + mBackgroundMediaPlayer.stop(); + + mBackgroundMediaPlayer.setLooping(isLoop); + + try { + mBackgroundMediaPlayer.prepare(); + mBackgroundMediaPlayer.seekTo(0); + mBackgroundMediaPlayer.start(); + + this.mIsPaused = false; + } catch (Exception e){ + Log.e(TAG, "playBackgroundMusic: error state"); + } + } + } + + public void stopBackgroundMusic(){ + if (mBackgroundMediaPlayer != null){ + mBackgroundMediaPlayer.stop(); + + // should set the state, if not , the following sequence will be error + // play -> pause -> stop -> resume + this.mIsPaused = false; + } + } + + public void pauseBackgroundMusic(){ + if (mBackgroundMediaPlayer != null && mBackgroundMediaPlayer.isPlaying()){ + mBackgroundMediaPlayer.pause(); + this.mIsPaused = true; + } + } + + public void resumeBackgroundMusic(){ + if (mBackgroundMediaPlayer != null && this.mIsPaused){ + mBackgroundMediaPlayer.start(); + this.mIsPaused = false; + } + } + + public void rewindBackgroundMusic(){ + if (mBackgroundMediaPlayer != null){ + mBackgroundMediaPlayer.stop(); + + try { + mBackgroundMediaPlayer.prepare(); + mBackgroundMediaPlayer.seekTo(0); + mBackgroundMediaPlayer.start(); + + this.mIsPaused = false; + } catch (Exception e){ + Log.e(TAG, "rewindBackgroundMusic: error state"); + } + } + } + + public boolean isBackgroundMusicPlaying(){ + boolean ret = false; + + if (mBackgroundMediaPlayer == null){ + ret = false; + } else { + ret = mBackgroundMediaPlayer.isPlaying(); + } + + return ret; + } + + public void end(){ + if (mBackgroundMediaPlayer != null){ + mBackgroundMediaPlayer.release(); + } + + initData(); + } + + public float getBackgroundVolume(){ + if (this.mBackgroundMediaPlayer != null){ + return (this.mLeftVolume + this.mRightVolume) / 2; + } else { + return 0.0f; + } + } + + public void setBackgroundVolume(float volume){ + if (volume < 0.0f){ + volume = 0.0f; + } + + if (volume > 1.0f){ + volume = 1.0f; + } + + this.mLeftVolume = this.mRightVolume = volume; + if (this.mBackgroundMediaPlayer != null){ + this.mBackgroundMediaPlayer.setVolume(this.mLeftVolume, this.mRightVolume); + } + } + + private void initData(){ + mLeftVolume =0.5f; + mRightVolume = 0.5f; + mBackgroundMediaPlayer = null; + mIsPaused = false; + mCurrentPath = null; + } + + /** + * create mediaplayer for music + * @param path the path relative to assets + * @return + */ + private MediaPlayer createMediaplayerFromAssets(String path){ + MediaPlayer mediaPlayer = new MediaPlayer(); + + try{ + if (path.startsWith("/")) { + mediaPlayer.setDataSource(path); + } + else { + AssetFileDescriptor assetFileDescritor = mContext.getAssets().openFd(path); + mediaPlayer.setDataSource(assetFileDescritor.getFileDescriptor(), + assetFileDescritor.getStartOffset(), assetFileDescritor.getLength()); + } + + mediaPlayer.prepare(); + + mediaPlayer.setVolume(mLeftVolume, mRightVolume); + }catch (Exception e) { + mediaPlayer = null; + Log.e(TAG, "error: " + e.getMessage(), e); + } + + return mediaPlayer; + } +} diff --git a/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxRenderer.java b/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxRenderer.java new file mode 100644 index 0000000000..fad0974f42 --- /dev/null +++ b/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxRenderer.java @@ -0,0 +1,137 @@ +/**************************************************************************** +Copyright (c) 2010-2011 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.lib; + +import javax.microedition.khronos.egl.EGLConfig; +import javax.microedition.khronos.opengles.GL10; + +import android.opengl.GLSurfaceView; + +public class Cocos2dxRenderer implements GLSurfaceView.Renderer { + private final static long NANOSECONDSPERSECOND = 1000000000L; + private final static long NANOSECONDSPERMINISECOND = 1000000; + private static long animationInterval = (long)(1.0 / 60 * NANOSECONDSPERSECOND); + private long last; + private int screenWidth; + private int screenHeight; + + public void onSurfaceCreated(GL10 gl, EGLConfig config) { + nativeInit(screenWidth, screenHeight); + last = System.nanoTime(); + } + + public void setScreenWidthAndHeight(int w, int h){ + this.screenWidth = w; + this.screenHeight = h; + } + + public void onSurfaceChanged(GL10 gl, int w, int h) { + } + + public void onDrawFrame(GL10 gl) { + + long now = System.nanoTime(); + long interval = now - last; + + // should render a frame when onDrawFrame() is called + // or there is a "ghost" + nativeRender(); + + // fps controlling + if (interval < animationInterval){ + try { + // because we render it before, so we should sleep twice time interval + Thread.sleep((animationInterval - interval) * 2 / NANOSECONDSPERMINISECOND); + } catch (Exception e){} + } + + last = now; + } + + public void handleActionDown(int id, float x, float y) + { + nativeTouchesBegin(id, x, y); + } + + public void handleActionUp(int id, float x, float y) + { + nativeTouchesEnd(id, x, y); + } + + public void handleActionCancel(int[] id, float[] x, float[] y) + { + nativeTouchesCancel(id, x, y); + } + + public void handleActionMove(int[] id, float[] x, float[] y) + { + nativeTouchesMove(id, x, y); + } + + public void handleKeyDown(int keyCode) + { + nativeKeyDown(keyCode); + } + + public void handleOnPause(){ + nativeOnPause(); + } + + public void handleOnResume(){ + nativeOnResume(); + } + + public static void setAnimationInterval(double interval){ + animationInterval = (long)(interval * NANOSECONDSPERSECOND); + } + private static native void nativeTouchesBegin(int id, float x, float y); + private static native void nativeTouchesEnd(int id, float x, float y); + private static native void nativeTouchesMove(int[] id, float[] x, float[] y); + private static native void nativeTouchesCancel(int[] id, float[] x, float[] y); + private static native boolean nativeKeyDown(int keyCode); + private static native void nativeRender(); + private static native void nativeInit(int w, int h); + private static native void nativeOnPause(); + private static native void nativeOnResume(); + + ///////////////////////////////////////////////////////////////////////////////// + // handle input method edit message + ///////////////////////////////////////////////////////////////////////////////// + + public void handleInsertText(final String text) { + nativeInsertText(text); + } + + public void handleDeleteBackward() { + nativeDeleteBackward(); + } + + public String getContentText() { + return nativeGetContentText(); + } + + private static native void nativeInsertText(String text); + private static native void nativeDeleteBackward(); + private static native String nativeGetContentText(); +} diff --git a/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxSound.java b/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxSound.java new file mode 100644 index 0000000000..e7061f74de --- /dev/null +++ b/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxSound.java @@ -0,0 +1,245 @@ +/**************************************************************************** +Copyright (c) 2010-2011 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.lib; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import android.content.Context; +import android.media.AudioManager; +import android.media.SoundPool; +import android.util.Log; + +/** + * + * This class is used for controlling effect + * + */ + +public class Cocos2dxSound { + private Context mContext; + private SoundPool mSoundPool; + private float mLeftVolume; + private float mRightVolume; + + // sound path and stream ids map + // a file may be played many times at the same time + // so there is an array map to a file path + private HashMap> mPathStreamIDsMap; + + private HashMap mPathSoundIdMap; + + private static final String TAG = "Cocos2dxSound"; + private static final int MAX_SIMULTANEOUS_STREAMS_DEFAULT = 5; + private static final float SOUND_RATE = 1.0f; + private static final int SOUND_PRIORITY = 1; + private static final int SOUND_QUALITY = 5; + + private final static int INVALID_SOUND_ID = -1; + private final static int INVALID_STREAM_ID = -1; + + public Cocos2dxSound(Context context){ + this.mContext = context; + initData(); + } + + public int preloadEffect(String path){ + Integer soundID = this.mPathSoundIdMap.get(path); + + if (soundID == null) { + soundID = createSoundIdFromAsset(path); + this.mPathSoundIdMap.put(path, soundID); + } + + return soundID; + } + + public void unloadEffect(String path){ + // stop effects + ArrayList streamIDs = this.mPathStreamIDsMap.get(path); + if (streamIDs != null) { + for (Integer streamID : streamIDs) { + this.mSoundPool.stop(streamID); + } + } + this.mPathStreamIDsMap.remove(path); + + // unload effect + Integer soundID = this.mPathSoundIdMap.get(path); + this.mSoundPool.unload(soundID); + this.mPathSoundIdMap.remove(path); + } + + public int playEffect(String path, boolean isLoop){ + Integer soundId = this.mPathSoundIdMap.get(path); + int streamId = INVALID_STREAM_ID; + + if (soundId != null){ + // play sound + streamId = this.mSoundPool.play(soundId.intValue(), this.mLeftVolume, + this.mRightVolume, SOUND_PRIORITY, isLoop ? -1 : 0, SOUND_RATE); + + // record stream id + ArrayList streamIds = this.mPathStreamIDsMap.get(path); + if (streamIds == null) { + streamIds = new ArrayList(); + this.mPathStreamIDsMap.put(path, streamIds); + } + streamIds.add(streamId); + } else { + // the effect is not prepared + soundId = preloadEffect(path); + if (soundId == INVALID_SOUND_ID){ + // can not preload effect + return 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. + */ + playEffect(path, isLoop); + } + + return streamId; + } + + public void stopEffect(int streamID){ + this.mSoundPool.stop(streamID); + + // remove record + for (String path : this.mPathStreamIDsMap.keySet()) { + if (this.mPathStreamIDsMap.get(path).contains(streamID)) { + this.mPathStreamIDsMap.get(path).remove(this.mPathStreamIDsMap.get(path).indexOf(streamID)); + break; + } + } + } + + public void pauseEffect(int streamID){ + this.mSoundPool.pause(streamID); + } + + public void resumeEffect(int streamID){ + this.mSoundPool.resume(streamID); + } + + public void pauseAllEffects(){ + this.mSoundPool.autoPause(); + } + + public void resumeAllEffects(){ + // autoPause() is available since level 8 + this.mSoundPool.autoResume(); + } + + @SuppressWarnings("unchecked") + public void stopAllEffects(){ + // stop effects + if (! this.mPathStreamIDsMap.isEmpty()) { + Iterator iter = this.mPathStreamIDsMap.entrySet().iterator(); + while (iter.hasNext()){ + Map.Entry> entry = (Map.Entry>)iter.next(); + for (int streamID : entry.getValue()) { + this.mSoundPool.stop(streamID); + } + } + } + + // remove records + this.mPathStreamIDsMap.clear(); + } + + public float getEffectsVolume(){ + return (this.mLeftVolume + this.mRightVolume) / 2; + } + + @SuppressWarnings("unchecked") + public void setEffectsVolume(float volume){ + // volume should be in [0, 1.0] + if (volume < 0){ + volume = 0; + } + if (volume > 1){ + volume = 1; + } + + this.mLeftVolume = this.mRightVolume = volume; + + // change the volume of playing sounds + if (! this.mPathStreamIDsMap.isEmpty()) { + Iterator iter = this.mPathStreamIDsMap.entrySet().iterator(); + while (iter.hasNext()){ + Map.Entry> entry = (Map.Entry>)iter.next(); + for (int streamID : entry.getValue()) { + this.mSoundPool.setVolume(streamID, mLeftVolume, mRightVolume); + } + } + } + } + + public void end(){ + this.mSoundPool.release(); + this.mPathStreamIDsMap.clear(); + this.mPathSoundIdMap.clear(); + + initData(); + } + + public int createSoundIdFromAsset(String path){ + int soundId = INVALID_SOUND_ID; + + try { + if (path.startsWith("/")){ + soundId = mSoundPool.load(path, 0); + } + else { + soundId = mSoundPool.load(mContext.getAssets().openFd(path), 0); + } + } catch(Exception e){ + soundId = INVALID_SOUND_ID; + Log.e(TAG, "error: " + e.getMessage(), e); + } + + return soundId; + } + + private void initData(){ + this.mPathStreamIDsMap = new HashMap>(); + this.mPathSoundIdMap = new HashMap(); + mSoundPool = new SoundPool(MAX_SIMULTANEOUS_STREAMS_DEFAULT, AudioManager.STREAM_MUSIC, SOUND_QUALITY); + + this.mLeftVolume = 0.5f; + this.mRightVolume = 0.5f; + } +} diff --git a/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxTypefaces.java b/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxTypefaces.java new file mode 100644 index 0000000000..79af1ed3af --- /dev/null +++ b/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxTypefaces.java @@ -0,0 +1,44 @@ +/**************************************************************************** +Copyright (c) 2010-2011 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.lib; + +import java.util.Hashtable; + +import android.content.Context; +import android.graphics.Typeface; + +public class Cocos2dxTypefaces { + private static final Hashtable cache = new Hashtable(); + + public static Typeface get(Context context, String name){ + synchronized(cache){ + if (! cache.containsKey(name)){ + Typeface t = Typeface.createFromAsset(context.getAssets(), name); + cache.put(name, t); + } + + return cache.get(name); + } + } +} diff --git a/SimpleGame/proj.android/src/org/cocos2dx/simplegame/SimpleGame.java b/SimpleGame/proj.android/src/org/cocos2dx/simplegame/SimpleGame.java new file mode 100644 index 0000000000..99171bd284 --- /dev/null +++ b/SimpleGame/proj.android/src/org/cocos2dx/simplegame/SimpleGame.java @@ -0,0 +1,108 @@ +/**************************************************************************** +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.simplegame; + +import org.cocos2dx.lib.Cocos2dxActivity; +import org.cocos2dx.lib.Cocos2dxEditText; +import org.cocos2dx.lib.Cocos2dxGLSurfaceView; +import org.cocos2dx.lib.Cocos2dxRenderer; + +import android.app.ActivityManager; +import android.content.Context; +import android.content.pm.ConfigurationInfo; +import android.os.Bundle; +import android.util.Log; +import android.widget.FrameLayout; +import android.view.ViewGroup; + +public class SimpleGame extends Cocos2dxActivity{ + + protected void onCreate(Bundle savedInstanceState){ + super.onCreate(savedInstanceState); + + if (detectOpenGLES20()) { + // get the packageName,it's used to set the resource path + String packageName = getApplication().getPackageName(); + super.setPackageName(packageName); + + // FrameLayout + ViewGroup.LayoutParams framelayout_params = + new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, + ViewGroup.LayoutParams.FILL_PARENT); + FrameLayout framelayout = new FrameLayout(this); + framelayout.setLayoutParams(framelayout_params); + + // Cocos2dxEditText layout + ViewGroup.LayoutParams edittext_layout_params = + new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, + ViewGroup.LayoutParams.WRAP_CONTENT); + Cocos2dxEditText edittext = new Cocos2dxEditText(this); + edittext.setLayoutParams(edittext_layout_params); + + // ...add to FrameLayout + framelayout.addView(edittext); + + // Cocos2dxGLSurfaceView + mGLView = new Cocos2dxGLSurfaceView(this); + + // ...add to FrameLayout + framelayout.addView(mGLView); + + mGLView.setEGLContextClientVersion(2); + mGLView.setCocos2dxRenderer(new Cocos2dxRenderer()); + mGLView.setTextField(edittext); + + // Set framelayout as the content view + setContentView(framelayout); + } + else { + Log.d("activity", "don't support gles2.0"); + finish(); + } + } + + @Override + protected void onPause() { + super.onPause(); + mGLView.onPause(); + } + + @Override + protected void onResume() { + super.onResume(); + mGLView.onResume(); + } + + private boolean detectOpenGLES20() + { + ActivityManager am = + (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); + ConfigurationInfo info = am.getDeviceConfigurationInfo(); + return (info.reqGlEsVersion >= 0x20000); + } + + static { + System.loadLibrary("game"); + } +} diff --git a/samples/SimpleGame/Classes/AppDelegate.cpp b/samples/SimpleGame/Classes/AppDelegate.cpp index 72e3dca794..74fcb1a83c 100644 --- a/samples/SimpleGame/Classes/AppDelegate.cpp +++ b/samples/SimpleGame/Classes/AppDelegate.cpp @@ -45,8 +45,8 @@ bool AppDelegate::applicationDidFinishLaunching() { { // android, windows, blackberry, linux or mac // use 960*640 resources as design resolution size - CCFileUtils::sharedFileUtils()->setResourceDirectory("hd"); - CCEGLView::sharedOpenGLView()->setDesignResolutionSize(960, 640, kResolutionNoBorder); + CCFileUtils::sharedFileUtils()->setResourceDirectory("sd"); + CCEGLView::sharedOpenGLView()->setDesignResolutionSize(480, 320, kResolutionNoBorder); } // turn on display FPS diff --git a/samples/SimpleGame/Classes/HelloWorldScene.cpp b/samples/SimpleGame/Classes/HelloWorldScene.cpp index e8f2e5f7d4..41587e8342 100755 --- a/samples/SimpleGame/Classes/HelloWorldScene.cpp +++ b/samples/SimpleGame/Classes/HelloWorldScene.cpp @@ -77,7 +77,8 @@ bool HelloWorld::init() CC_BREAK_IF(! pCloseItem); // Place the menu item bottom-right conner. - pCloseItem->setPosition(ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20)); + pCloseItem->setPosition(ccp(CCDirector::sharedDirector()->getVisibleSize().width - 20, + CCDirector::sharedDirector()->getVisibleOrigin().y + 20)); // Create a menu with the "close" menu item, it's an auto release object. CCMenu* pMenu = CCMenu::create(pCloseItem, NULL); @@ -90,7 +91,7 @@ bool HelloWorld::init() ///////////////////////////// // 2. add your codes below... - CCSize winSize = CCDirector::sharedDirector()->getWinSize(); + CCSize winSize = CCDirector::sharedDirector()->getVisibleSize(); CCSprite *player = CCSprite::create("Player.png", CCRectMake(0, 0, 27, 40) ); player->setPosition( ccp(player->getContentSize().width/2, winSize.height/2) ); this->addChild(player); @@ -126,7 +127,7 @@ void HelloWorld::addTarget() CCSprite *target = CCSprite::create("Target.png", CCRectMake(0,0,27,40) ); // Determine where to spawn the target along the Y axis - CCSize winSize = CCDirector::sharedDirector()->getWinSize(); + CCSize winSize = CCDirector::sharedDirector()->getVisibleSize(); float minY = target->getContentSize().height/2; float maxY = winSize.height - target->getContentSize().height/2; int rangeY = (int)(maxY - minY); @@ -137,7 +138,7 @@ void HelloWorld::addTarget() // and along a random position along the Y axis as calculated target->setPosition( ccp(winSize.width + (target->getContentSize().width/2), - actualY) ); + CCDirector::sharedDirector()->getVisibleOrigin().y + actualY) ); this->addChild(target); // Determine speed of the target @@ -194,7 +195,7 @@ void HelloWorld::ccTouchesEnded(CCSet* touches, CCEvent* event) CCLog("++++++++after x:%f, y:%f", location.x, location.y); // Set up initial location of projectile - CCSize winSize = CCDirector::sharedDirector()->getWinSize(); + CCSize winSize = CCDirector::sharedDirector()->getVisibleSize(); CCSprite *projectile = CCSprite::create("Projectile.png", CCRectMake(0, 0, 20, 20)); projectile->setPosition( ccp(20, winSize.height/2) ); diff --git a/samples/SimpleGame/proj.android/.classpath b/samples/SimpleGame/proj.android/.classpath new file mode 100644 index 0000000000..a4763d1eec --- /dev/null +++ b/samples/SimpleGame/proj.android/.classpath @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/samples/SimpleGame/proj.android/.project b/samples/SimpleGame/proj.android/.project new file mode 100644 index 0000000000..afc29d09d0 --- /dev/null +++ b/samples/SimpleGame/proj.android/.project @@ -0,0 +1,33 @@ + + + SimpleGame + + + + + + com.android.ide.eclipse.adt.ResourceManagerBuilder + + + + + com.android.ide.eclipse.adt.PreCompilerBuilder + + + + + org.eclipse.jdt.core.javabuilder + + + + + com.android.ide.eclipse.adt.ApkBuilder + + + + + + com.android.ide.eclipse.adt.AndroidNature + org.eclipse.jdt.core.javanature + + diff --git a/samples/SimpleGame/proj.android/AndroidManifest.xml b/samples/SimpleGame/proj.android/AndroidManifest.xml new file mode 100644 index 0000000000..8574ea3ceb --- /dev/null +++ b/samples/SimpleGame/proj.android/AndroidManifest.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + diff --git a/samples/SimpleGame/proj.android/ant.properties b/samples/SimpleGame/proj.android/ant.properties new file mode 100644 index 0000000000..b0971e891e --- /dev/null +++ b/samples/SimpleGame/proj.android/ant.properties @@ -0,0 +1,17 @@ +# This file is used to override default values used by the Ant build system. +# +# This file must be checked into Version Control Systems, as it is +# integral to the build system of your project. + +# This file is only used by the Ant script. + +# You can use this to override default values such as +# 'source.dir' for the location of your java source folder and +# 'out.dir' for the location of your output folder. + +# You can also use it define how the release builds are signed by declaring +# the following properties: +# 'key.store' for the location of your keystore and +# 'key.alias' for the name of the key to use. +# The password will be asked during the build when you use the 'release' target. + diff --git a/samples/SimpleGame/proj.android/build.xml b/samples/SimpleGame/proj.android/build.xml new file mode 100644 index 0000000000..e9678a9b14 --- /dev/null +++ b/samples/SimpleGame/proj.android/build.xml @@ -0,0 +1,92 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/samples/SimpleGame/proj.android/build_native.sh b/samples/SimpleGame/proj.android/build_native.sh new file mode 100755 index 0000000000..2672fb43ae --- /dev/null +++ b/samples/SimpleGame/proj.android/build_native.sh @@ -0,0 +1,91 @@ +APPNAME="SimpleGame" + +# options + +buildexternalsfromsource= + +usage(){ +cat << EOF +usage: $0 [options] + +Build C/C++ code for $APPNAME using Android NDK + +OPTIONS: +-s Build externals from source +-h this help +EOF +} + +while getopts "sh" OPTION; do +case "$OPTION" in +s) +buildexternalsfromsource=1 +;; +h) +usage +exit 0 +;; +esac +done + +# 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 "NDK_ROOT = $NDK_ROOT" +echo "COCOS2DX_ROOT = $COCOS2DX_ROOT" +echo "APP_ROOT = $APP_ROOT" +echo "APP_ANDROID_ROOT = $APP_ANDROID_ROOT" + +# 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 + +# copy icons (if they exist) +file="$APP_ANDROID_ROOT"/assets/Icon-72.png +if [ -f "$file" ]; then + cp "$file" "$APP_ANDROID_ROOT"/res/drawable-hdpi/icon.png +fi +file="$APP_ANDROID_ROOT"/assets/Icon-48.png +if [ -f "$file" ]; then + cp "$file" "$APP_ANDROID_ROOT"/res/drawable-mdpi/icon.png +fi +file="$APP_ANDROID_ROOT"/assets/Icon-32.png +if [ -f "$file" ]; then + cp "$file" "$APP_ANDROID_ROOT"/res/drawable-ldpi/icon.png +fi + + +if [[ "$buildexternalsfromsource" ]]; then + echo "Building external dependencies from source" + "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ + "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos2dx/platform/third_party/android/source" +else + echo "Using prebuilt externals" + "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ + "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos2dx/platform/third_party/android/prebuilt" +fi diff --git a/samples/SimpleGame/proj.android/jni/Android.mk b/samples/SimpleGame/proj.android/jni/Android.mk new file mode 100644 index 0000000000..1dab1b5a0a --- /dev/null +++ b/samples/SimpleGame/proj.android/jni/Android.mk @@ -0,0 +1,22 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE := game_shared + +LOCAL_MODULE_FILENAME := libgame + +LOCAL_SRC_FILES := hellocpp/main.cpp \ + ../../Classes/AppDelegate.cpp \ + ../../Classes/HelloWorldScene.cpp \ + ../../Classes/GameOverScene.cpp + +LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes + +LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static cocosdenshion_static cocos_extension_static + +include $(BUILD_SHARED_LIBRARY) + +$(call import-module,CocosDenshion/android) \ +$(call import-module,cocos2dx) \ +$(call import-module,extensions) diff --git a/samples/SimpleGame/proj.android/jni/Application.mk b/samples/SimpleGame/proj.android/jni/Application.mk new file mode 100644 index 0000000000..22d424dab7 --- /dev/null +++ b/samples/SimpleGame/proj.android/jni/Application.mk @@ -0,0 +1,2 @@ +APP_STL := gnustl_static +APP_CPPFLAGS := -frtti \ No newline at end of file diff --git a/samples/SimpleGame/proj.android/jni/hellocpp/main.cpp b/samples/SimpleGame/proj.android/jni/hellocpp/main.cpp new file mode 100644 index 0000000000..035fb201c4 --- /dev/null +++ b/samples/SimpleGame/proj.android/jni/hellocpp/main.cpp @@ -0,0 +1,45 @@ +#include "AppDelegate.h" +#include "platform/android/jni/JniHelper.h" +#include +#include + +#include "HelloWorldScene.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(); + } +} + +} diff --git a/samples/SimpleGame/proj.android/jni/list.sh b/samples/SimpleGame/proj.android/jni/list.sh new file mode 100644 index 0000000000..b95448ebbb --- /dev/null +++ b/samples/SimpleGame/proj.android/jni/list.sh @@ -0,0 +1,23 @@ +#!/bin/bash + +append_str=' \' + +list_alldir() +{ + for file in $1/* + do + if [ -f $file ]; then + echo $file$append_str | grep .cpp + fi + + if [ -d $file ]; then + list_alldir $file + fi + done +} + +if [ $# -gt 0 ]; then + list_alldir "$1" +else + list_alldir "." +fi \ No newline at end of file diff --git a/samples/SimpleGame/proj.android/proguard-project.txt b/samples/SimpleGame/proj.android/proguard-project.txt new file mode 100644 index 0000000000..f2fe1559a2 --- /dev/null +++ b/samples/SimpleGame/proj.android/proguard-project.txt @@ -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 *; +#} diff --git a/samples/SimpleGame/proj.android/project.properties b/samples/SimpleGame/proj.android/project.properties new file mode 100644 index 0000000000..85aac54016 --- /dev/null +++ b/samples/SimpleGame/proj.android/project.properties @@ -0,0 +1,14 @@ +# 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 edit +# "ant.properties", and override values to adapt the script to your +# project structure. +# +# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): +#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt + +# Project target. +target=android-8 diff --git a/samples/SimpleGame/proj.android/res/values/strings.xml b/samples/SimpleGame/proj.android/res/values/strings.xml new file mode 100644 index 0000000000..f197c895b7 --- /dev/null +++ b/samples/SimpleGame/proj.android/res/values/strings.xml @@ -0,0 +1,4 @@ + + + SimpleGame + diff --git a/samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxAccelerometer.java b/samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxAccelerometer.java new file mode 100644 index 0000000000..c515349cab --- /dev/null +++ b/samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxAccelerometer.java @@ -0,0 +1,107 @@ +/**************************************************************************** +Copyright (c) 2010-2011 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.lib; + +import android.content.Context; +import android.content.res.Configuration; +import android.hardware.Sensor; +import android.hardware.SensorEvent; +import android.hardware.SensorEventListener; +import android.hardware.SensorManager; +import android.view.Display; +import android.view.Surface; +import android.view.WindowManager; + +/** + * + * This class is used for controlling the Accelerometer + * + */ +public class Cocos2dxAccelerometer implements SensorEventListener { + + private static final String TAG = "Cocos2dxAccelerometer"; + private Context mContext; + private SensorManager mSensorManager; + private Sensor mAccelerometer; + private int mNaturalOrientation; + + public Cocos2dxAccelerometer(Context context){ + mContext = context; + + //Get an instance of the SensorManager + mSensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE); + mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); + + Display display = ((WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); + mNaturalOrientation = display.getOrientation(); + } + + public void enable() { + mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_GAME); + } + + public void disable () { + mSensorManager.unregisterListener(this); + } + + @Override + public void onSensorChanged(SensorEvent event) { + + if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER){ + return; + } + + float x = event.values[0]; + float y = event.values[1]; + float z = event.values[2]; + + /* + * Because the axes are not swapped when the device's screen orientation changes. + * So we should swap it here. + * In tablets such as Motorola Xoom, the default orientation is landscape, so should + * consider this. + */ + int orientation = mContext.getResources().getConfiguration().orientation; + if ((orientation == Configuration.ORIENTATION_LANDSCAPE) && (mNaturalOrientation != Surface.ROTATION_0)){ + float tmp = x; + x = -y; + y = tmp; + } + else if ((orientation == Configuration.ORIENTATION_PORTRAIT) && (mNaturalOrientation != Surface.ROTATION_0)) + { + float tmp = x; + x = y; + y = -tmp; + } + + onSensorChanged(x, y, z, event.timestamp); + // Log.d(TAG, "x = " + event.values[0] + " y = " + event.values[1] + " z = " + event.values[2]); + } + + @Override + public void onAccuracyChanged(Sensor sensor, int accuracy) { + } + + private static native void onSensorChanged(float x, float y, float z, long timeStamp); +} diff --git a/samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxActivity.java b/samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxActivity.java new file mode 100644 index 0000000000..952d5148fb --- /dev/null +++ b/samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxActivity.java @@ -0,0 +1,346 @@ +/**************************************************************************** +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.lib; + +import java.lang.ref.WeakReference; + +import android.app.Activity; +import android.app.AlertDialog; +import android.app.Dialog; +import android.content.DialogInterface; +import android.content.pm.ApplicationInfo; +import android.content.pm.PackageManager; +import android.content.pm.PackageManager.NameNotFoundException; +import android.content.res.AssetManager; +import android.os.Build; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.util.DisplayMetrics; +import android.util.Log; + +public class Cocos2dxActivity extends Activity{ + + protected Cocos2dxGLSurfaceView mGLView; + private static Cocos2dxMusic backgroundMusicPlayer; + private static Cocos2dxSound soundPlayer; + private static Cocos2dxAccelerometer accelerometer; + private static AssetManager assetManager; + private static boolean accelerometerEnabled = false; + private static Handler handler; + private final static int HANDLER_SHOW_DIALOG = 1; + private final static int HANDLER_SHOW_EDITBOX_DIALOG = 2; + + private static String packageName; + + private static native void nativeSetPaths(String apkPath); + private static native void nativeSetEditboxText(byte[] text); + + + static class ShowDialogHandler extends Handler { + WeakReference mActivity; + + ShowDialogHandler(Cocos2dxActivity activity) { + mActivity = new WeakReference(activity); + } + + @Override + public void handleMessage(Message msg) { + Cocos2dxActivity theActivity = mActivity.get(); + switch(msg.what) { + case HANDLER_SHOW_DIALOG: + theActivity.showDialog(((DialogMessage)msg.obj).title, ((DialogMessage)msg.obj).message); + break; + case HANDLER_SHOW_EDITBOX_DIALOG: + theActivity.onShowEditBoxDialog((EditBoxMessage)msg.obj); + break; + } + } + }; + + public Cocos2dxGLSurfaceView getGLView() { + return mGLView; + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + // get frame size + DisplayMetrics dm = new DisplayMetrics(); + getWindowManager().getDefaultDisplay().getMetrics(dm); + accelerometer = new Cocos2dxAccelerometer(this); + + // init media player and sound player + backgroundMusicPlayer = new Cocos2dxMusic(this); + soundPlayer = new Cocos2dxSound(this); + + // init asset manager for jni call + assetManager = getAssets(); + + // init bitmap context + Cocos2dxBitmap.setContext(this); + + handler = new ShowDialogHandler(this); + } + + public static String getDeviceModel(){ + return Build.MODEL; + } + + public static AssetManager getAssetManager() { + return assetManager; + } + + public static String getCurrentLanguage() { + String languageName = java.util.Locale.getDefault().getLanguage(); + return languageName; + } + + public static void showMessageBox(String title, String message){ + Message msg = new Message(); + msg.what = HANDLER_SHOW_DIALOG; + msg.obj = new DialogMessage(title, message); + + handler.sendMessage(msg); + } + + public static void enableAccelerometer() { + accelerometerEnabled = true; + accelerometer.enable(); + } + + public static void disableAccelerometer() { + accelerometerEnabled = false; + accelerometer.disable(); + } + + public static void preloadBackgroundMusic(String path){ + backgroundMusicPlayer.preloadBackgroundMusic(path); + } + + public static void playBackgroundMusic(String path, boolean isLoop){ + backgroundMusicPlayer.playBackgroundMusic(path, isLoop); + } + + public static void stopBackgroundMusic(){ + backgroundMusicPlayer.stopBackgroundMusic(); + } + + public static void pauseBackgroundMusic(){ + backgroundMusicPlayer.pauseBackgroundMusic(); + } + + public static void resumeBackgroundMusic(){ + backgroundMusicPlayer.resumeBackgroundMusic(); + } + + public static void rewindBackgroundMusic(){ + backgroundMusicPlayer.rewindBackgroundMusic(); + } + + public static boolean isBackgroundMusicPlaying(){ + return backgroundMusicPlayer.isBackgroundMusicPlaying(); + } + + public static float getBackgroundMusicVolume(){ + return backgroundMusicPlayer.getBackgroundVolume(); + } + + public static void setBackgroundMusicVolume(float volume){ + backgroundMusicPlayer.setBackgroundVolume(volume); + } + + public static int playEffect(String path, boolean isLoop){ + return soundPlayer.playEffect(path, isLoop); + } + + public static void stopEffect(int soundId){ + soundPlayer.stopEffect(soundId); + } + + public static void pauseEffect(int soundId){ + soundPlayer.pauseEffect(soundId); + } + + public static void resumeEffect(int soundId){ + soundPlayer.resumeEffect(soundId); + } + + public static float getEffectsVolume(){ + return soundPlayer.getEffectsVolume(); + } + + public static void setEffectsVolume(float volume){ + soundPlayer.setEffectsVolume(volume); + } + + public static void preloadEffect(String path){ + soundPlayer.preloadEffect(path); + } + + public static void unloadEffect(String path){ + soundPlayer.unloadEffect(path); + } + + public static void stopAllEffects(){ + soundPlayer.stopAllEffects(); + } + + public static void pauseAllEffects(){ + soundPlayer.pauseAllEffects(); + } + + public static void resumeAllEffects(){ + soundPlayer.resumeAllEffects(); + } + + public static void end(){ + backgroundMusicPlayer.end(); + soundPlayer.end(); + } + + public static String getCocos2dxPackageName(){ + return packageName; + } + + public static void terminateProcess(){ + android.os.Process.killProcess(android.os.Process.myPid()); + } + + @Override + protected void onResume() { + super.onResume(); + if (accelerometerEnabled) { + accelerometer.enable(); + } + } + + @Override + protected void onPause() { + super.onPause(); + if (accelerometerEnabled) { + accelerometer.disable(); + } + } + + protected void setPackageName(String packageName) { + Cocos2dxActivity.packageName = packageName; + + String apkFilePath = ""; + ApplicationInfo appInfo = null; + PackageManager packMgmr = getApplication().getPackageManager(); + try { + appInfo = packMgmr.getApplicationInfo(packageName, 0); + } catch (NameNotFoundException e) { + e.printStackTrace(); + throw new RuntimeException("Unable to locate assets, aborting..."); + } + apkFilePath = appInfo.sourceDir; + Log.w("apk path", apkFilePath); + + // add this link at the renderer class + nativeSetPaths(apkFilePath); + } + + private void showDialog(String title, String message){ + Dialog dialog = new AlertDialog.Builder(this) + .setTitle(title) + .setMessage(message) + .setPositiveButton("Ok", + new DialogInterface.OnClickListener() + { + public void onClick(DialogInterface dialog, int whichButton){ + + } + }).create(); + + dialog.show(); + } + + private static void showEditBoxDialog(String title, String content, int inputMode, int inputFlag, int returnType, int maxLength) + { + Message msg = new Message(); + msg.what = HANDLER_SHOW_EDITBOX_DIALOG; + msg.obj = new EditBoxMessage(title, content, inputMode, inputFlag, returnType, maxLength); + handler.sendMessage(msg); + } + + private void onShowEditBoxDialog(EditBoxMessage msg) + { + Dialog dialog = new Cocos2dxEditBoxDialog(this, msg); + dialog.show(); + } + + public void setEditBoxResult(String editResult) + { + Log.i("editbox_content", editResult); + + try + { + final byte[] bytesUTF8 = editResult.getBytes("UTF8"); + // pass utf8 string from editbox activity to native. + // Should invoke native method in GL thread. + mGLView.queueEvent(new Runnable() { + @Override + public void run() { + nativeSetEditboxText(bytesUTF8); + } + }); + } + catch (java.io.UnsupportedEncodingException e) + { + e.printStackTrace(); + } + } +} + +class DialogMessage { + public String title; + public String message; + + public DialogMessage(String title, String message){ + this.message = message; + this.title = title; + } +} + +class EditBoxMessage { + public String title; + public String content; + public int inputMode; + public int inputFlag; + public int returnType; + public int maxLength; + + public EditBoxMessage(String title, String content, int inputMode, int inputFlag, int returnType, int maxLength){ + this.content = content; + this.title = title; + this.inputMode = inputMode; + this.inputFlag = inputFlag; + this.returnType = returnType; + this.maxLength = maxLength; + } +} diff --git a/samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxBitmap.java b/samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxBitmap.java new file mode 100644 index 0000000000..395400b779 --- /dev/null +++ b/samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxBitmap.java @@ -0,0 +1,455 @@ +/**************************************************************************** +Copyright (c) 2010-2011 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.lib; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.LinkedList; + +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.graphics.Rect; +import android.graphics.Typeface; +import android.graphics.Paint.Align; +import android.graphics.Paint.FontMetricsInt; +import android.text.TextPaint; +import android.text.TextUtils; +import android.util.Log; + +public class Cocos2dxBitmap{ + /* + * The values are the same as cocos2dx/platform/CCImage.h. + */ + private static final int HALIGNCENTER = 3; + private static final int HALIGNLEFT = 1; + private static final int HALIGNRIGHT = 2; + // vertical alignment + private static final int VALIGNTOP = 1; + private static final int VALIGNBOTTOM = 2; + private static final int VALIGNCENTER = 3; + + private static Context context; + + public static void setContext(Context context){ + Cocos2dxBitmap.context = context; + } + + /* + * @width: the width to draw, it can be 0 + * @height: the height to draw, it can be 0 + */ + public static void createTextBitmap(String content, String fontName, + int fontSize, int alignment, int width, int height){ + + content = refactorString(content); + Paint paint = newPaint(fontName, fontSize, alignment); + + TextProperty textProperty = computeTextProperty(content, paint, width, height); + + int bitmapTotalHeight = (height == 0 ? textProperty.totalHeight:height); + + // Draw text to bitmap + Bitmap bitmap = Bitmap.createBitmap(textProperty.maxWidth, + bitmapTotalHeight, Bitmap.Config.ARGB_8888); + Canvas canvas = new Canvas(bitmap); + + // Draw string + FontMetricsInt fm = paint.getFontMetricsInt(); + int x = 0; + int y = computeY(fm, height, textProperty.totalHeight, alignment); + String[] lines = textProperty.lines; + for (String line : lines){ + x = computeX(paint, line, textProperty.maxWidth, alignment); + canvas.drawText(line, x, y, paint); + y += textProperty.heightPerLine; + } + + initNativeObject(bitmap); + } + + private static int computeX(Paint paint, String content, int w, int alignment){ + int ret = 0; + int hAlignment = alignment & 0x0F; + + switch (hAlignment){ + case HALIGNCENTER: + ret = w / 2; + break; + + // ret = 0 + case HALIGNLEFT: + break; + + case HALIGNRIGHT: + ret = w; + break; + + /* + * Default is align left. + * Should be same as newPaint(). + */ + default: + break; + } + + return ret; + } + + private static int computeY(FontMetricsInt fm, int constrainHeight, int totalHeight, int alignment) { + int y = -fm.top; + + if (constrainHeight > totalHeight) { + int vAlignment = (alignment >> 4) & 0x0F; + + switch (vAlignment) { + case VALIGNTOP: + y = -fm.top; + break; + case VALIGNCENTER: + y = -fm.top + (constrainHeight - totalHeight)/2; + break; + case VALIGNBOTTOM: + y = -fm.top + (constrainHeight - totalHeight); + break; + default: + break; + } + } + + return y; + } + + private static class TextProperty{ + // The max width of lines + int maxWidth; + // The height of all lines + int totalHeight; + int heightPerLine; + String[] lines; + + TextProperty(int w, int h, String[] lines){ + this.maxWidth = w; + this.heightPerLine = h; + this.totalHeight = h * lines.length; + this.lines = lines; + } + } + + private static TextProperty computeTextProperty(String content, Paint paint, + int maxWidth, int maxHeight){ + FontMetricsInt fm = paint.getFontMetricsInt(); + int h = (int)Math.ceil(fm.bottom - fm.top); + int maxContentWidth = 0; + + String[] lines = splitString(content, maxHeight, maxWidth, paint); + + if (maxWidth != 0){ + maxContentWidth = maxWidth; + } + else { + /* + * Compute the max width + */ + int temp = 0; + for (String line : lines){ + temp = (int)Math.ceil(paint.measureText(line, 0, line.length())); + if (temp > maxContentWidth){ + maxContentWidth = temp; + } + } + } + + return new TextProperty(maxContentWidth, h, lines); + } + + /* + * If maxWidth or maxHeight is not 0, + * split the string to fix the maxWidth and maxHeight. + */ + private static String[] splitString(String content, int maxHeight, int maxWidth, + Paint paint){ + String[] lines = content.split("\\n"); + String[] ret = null; + FontMetricsInt fm = paint.getFontMetricsInt(); + int heightPerLine = (int)Math.ceil(fm.bottom - fm.top); + int maxLines = maxHeight / heightPerLine; + + if (maxWidth != 0){ + LinkedList strList = new LinkedList(); + for (String line : lines){ + /* + * The width of line is exceed maxWidth, should divide it into + * two or more lines. + */ + int lineWidth = (int)Math.ceil(paint.measureText(line)); + if (lineWidth > maxWidth){ + strList.addAll(divideStringWithMaxWidth(paint, line, maxWidth)); + } + else{ + strList.add(line); + } + + /* + * Should not exceed the max height; + */ + if (maxLines > 0 && strList.size() >= maxLines){ + break; + } + } + + /* + * Remove exceeding lines + */ + if (maxLines > 0 && strList.size() > maxLines){ + while (strList.size() > maxLines){ + strList.removeLast(); + } + } + + ret = new String[strList.size()]; + strList.toArray(ret); + } else + if (maxHeight != 0 && lines.length > maxLines) { + /* + * Remove exceeding lines + */ + LinkedList strList = new LinkedList(); + for (int i = 0; i < maxLines; i++){ + strList.add(lines[i]); + } + ret = new String[strList.size()]; + strList.toArray(ret); + } + else { + ret = lines; + } + + return ret; + } + + private static LinkedList divideStringWithMaxWidth(Paint paint, String content, + int width){ + int charLength = content.length(); + int start = 0; + int tempWidth = 0; + LinkedList strList = new LinkedList(); + + /* + * Break a String into String[] by the width & should wrap the word + */ + for (int i = 1; i <= charLength; ++i){ + tempWidth = (int)Math.ceil(paint.measureText(content, start, i)); + if (tempWidth >= width){ + int lastIndexOfSpace = content.substring(0, i).lastIndexOf(" "); + + if (lastIndexOfSpace != -1 && lastIndexOfSpace > start){ + /** + * Should wrap the word + */ + strList.add(content.substring(start, lastIndexOfSpace)); + i = lastIndexOfSpace; + } + else { + /* + * Should not exceed the width + */ + if (tempWidth > width){ + strList.add(content.substring(start, i - 1)); + /* + * compute from previous char + */ + --i; + } + else { + strList.add(content.substring(start, i)); + } + } + + // remove spaces at the beginning of a new line + while(content.indexOf(i++) == ' ') { + } + + start = i; + } + } + + /* + * Add the last chars + */ + if (start < charLength){ + strList.add(content.substring(start)); + } + + return strList; + } + + private static Paint newPaint(String fontName, int fontSize, int alignment){ + Paint paint = new Paint(); + paint.setColor(Color.WHITE); + paint.setTextSize(fontSize); + paint.setAntiAlias(true); + + /* + * Set type face for paint, now it support .ttf file. + */ + if (fontName.endsWith(".ttf")){ + try { + //Typeface typeFace = Typeface.createFromAsset(context.getAssets(), fontName); + Typeface typeFace = Cocos2dxTypefaces.get(context, fontName); + paint.setTypeface(typeFace); + } catch (Exception e){ + Log.e("Cocos2dxBitmap", + "error to create ttf type face: " + fontName); + + /* + * The file may not find, use system font + */ + paint.setTypeface(Typeface.create(fontName, Typeface.NORMAL)); + } + } + else { + paint.setTypeface(Typeface.create(fontName, Typeface.NORMAL)); + } + + int hAlignment = alignment & 0x0F; + switch (hAlignment){ + case HALIGNCENTER: + paint.setTextAlign(Align.CENTER); + break; + + case HALIGNLEFT: + paint.setTextAlign(Align.LEFT); + break; + + case HALIGNRIGHT: + paint.setTextAlign(Align.RIGHT); + break; + + default: + paint.setTextAlign(Align.LEFT); + break; + } + + return paint; + } + + private static String refactorString(String str){ + // Avoid error when content is "" + if (str.compareTo("") == 0){ + return " "; + } + + /* + * If the font of "\n" is "" or "\n", insert " " in front of it. + * + * For example: + * "\nabc" -> " \nabc" + * "\nabc\n\n" -> " \nabc\n \n" + */ + StringBuilder strBuilder = new StringBuilder(str); + int start = 0; + int index = strBuilder.indexOf("\n"); + while (index != -1){ + if (index == 0 || strBuilder.charAt(index -1) == '\n'){ + strBuilder.insert(start, " "); + start = index + 2; + } else { + start = index + 1; + } + + if (start > strBuilder.length() || index == strBuilder.length()){ + break; + } + + index = strBuilder.indexOf("\n", start); + } + + return strBuilder.toString(); + } + + private static void initNativeObject(Bitmap bitmap){ + byte[] pixels = getPixels(bitmap); + if (pixels == null){ + return; + } + + nativeInitBitmapDC(bitmap.getWidth(), bitmap.getHeight(), pixels); + } + + private static byte[] getPixels(Bitmap bitmap){ + if (bitmap != null){ + byte[] pixels = new byte[bitmap.getWidth() * bitmap.getHeight() * 4]; + ByteBuffer buf = ByteBuffer.wrap(pixels); + buf.order(ByteOrder.nativeOrder()); + bitmap.copyPixelsToBuffer(buf); + return pixels; + } + + return null; + } + + private static native void nativeInitBitmapDC(int width, int height, byte[] pixels); + + private static int getFontSizeAccordingHeight(int height) + { + Paint paint = new Paint(); + Rect bounds = new Rect(); + + paint.setTypeface(Typeface.DEFAULT); + int incr_text_size = 1; + boolean found_desired_size = false; + + while (!found_desired_size) { + + paint.setTextSize(incr_text_size); + String text = "SghMNy"; + paint.getTextBounds(text, 0, text.length(), bounds); + + incr_text_size++; + + if (height - bounds.height() <= 2) { + found_desired_size = true; + } + Log.d("font size", "incr size:" + incr_text_size); + } + return incr_text_size; + } + + private static String getStringWithEllipsis(String originalText, float width, float fontSize){ + if(TextUtils.isEmpty(originalText)){ + return ""; + } + + TextPaint paint = new TextPaint(); + paint.setTypeface(Typeface.DEFAULT); + paint.setTextSize(fontSize); + + return TextUtils.ellipsize(originalText, paint, width, + TextUtils.TruncateAt.valueOf("END")).toString(); + } + +} diff --git a/samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxEditBoxDialog.java b/samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxEditBoxDialog.java new file mode 100755 index 0000000000..66e94e242c --- /dev/null +++ b/samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxEditBoxDialog.java @@ -0,0 +1,338 @@ +/**************************************************************************** +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.lib; + +import android.app.Dialog; +import android.content.Context; +import android.graphics.drawable.ColorDrawable; +import android.os.Bundle; +import android.os.Handler; +import android.text.InputFilter; +import android.text.InputType; +import android.util.Log; +import android.util.TypedValue; +import android.view.KeyEvent; +import android.view.ViewGroup; +import android.view.WindowManager; +import android.view.inputmethod.EditorInfo; +import android.view.inputmethod.InputMethodManager; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.TextView; +import android.widget.TextView.OnEditorActionListener; + +public class Cocos2dxEditBoxDialog extends Dialog { + + /** + * The user is allowed to enter any text, including line breaks. + */ + private final int kEditBoxInputModeAny = 0; + + /** + * The user is allowed to enter an e-mail address. + */ + private final int kEditBoxInputModeEmailAddr = 1; + + /** + * The user is allowed to enter an integer value. + */ + private final int kEditBoxInputModeNumeric = 2; + + /** + * The user is allowed to enter a phone number. + */ + private final int kEditBoxInputModePhoneNumber = 3; + + /** + * The user is allowed to enter a URL. + */ + private final int kEditBoxInputModeUrl = 4; + + /** + * The user is allowed to enter a real number value. + * This extends kEditBoxInputModeNumeric by allowing a decimal point. + */ + private final int kEditBoxInputModeDecimal = 5; + + /** + * The user is allowed to enter any text, except for line breaks. + */ + private final int kEditBoxInputModeSingleLine = 6; + + + /** + * Indicates that the text entered is confidential data that should be + * obscured whenever possible. This implies EDIT_BOX_INPUT_FLAG_SENSITIVE. + */ + private final int kEditBoxInputFlagPassword = 0; + + /** + * Indicates that the text entered is sensitive data that the + * implementation must never store into a dictionary or table for use + * in predictive, auto-completing, or other accelerated input schemes. + * A credit card number is an example of sensitive data. + */ + private final int kEditBoxInputFlagSensitive = 1; + + /** + * This flag is a hint to the implementation that during text editing, + * the initial letter of each word should be capitalized. + */ + private final int kEditBoxInputFlagInitialCapsWord = 2; + + /** + * This flag is a hint to the implementation that during text editing, + * the initial letter of each sentence should be capitalized. + */ + private final int kEditBoxInputFlagInitialCapsSentence = 3; + + /** + * Capitalize all characters automatically. + */ + private final int kEditBoxInputFlagInitialCapsAllCharacters = 4; + + private final int kKeyboardReturnTypeDefault = 0; + private final int kKeyboardReturnTypeDone = 1; + private final int kKeyboardReturnTypeSend = 2; + private final int kKeyboardReturnTypeSearch = 3; + private final int kKeyboardReturnTypeGo = 4; + + // + private EditText mInputEditText = null; + private TextView mTextViewTitle = null; + private int mInputMode = 0; + private int mInputFlag = 0; + private int mReturnType = 0; + private int mMaxLength = -1; + + private int mInputFlagConstraints = 0x00000; + private int mInputModeContraints = 0x00000; + private boolean mIsMultiline = false; + private Cocos2dxActivity mParentActivity = null; + private EditBoxMessage mMsg = null; + + public Cocos2dxEditBoxDialog(Context context, EditBoxMessage msg) { + //super(context, R.style.Theme_Translucent); + super(context, android.R.style.Theme_Translucent_NoTitleBar_Fullscreen); + // TODO Auto-generated constructor stub + mParentActivity = (Cocos2dxActivity)context; + mMsg = msg; + } + + // Converting dips to pixels + private int convertDipsToPixels(float dips) + { + float scale = getContext().getResources().getDisplayMetrics().density; + return Math.round(dips * scale); + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + // TODO Auto-generated method stub + super.onCreate(savedInstanceState); + + getWindow().setBackgroundDrawable(new ColorDrawable(0x80000000)); + + LinearLayout layout = new LinearLayout(mParentActivity); + layout.setOrientation(LinearLayout.VERTICAL); + + LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup. + LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.FILL_PARENT); + + mTextViewTitle = new TextView(mParentActivity); + LinearLayout.LayoutParams textviewParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, + ViewGroup.LayoutParams.WRAP_CONTENT); + textviewParams.leftMargin = textviewParams.rightMargin = convertDipsToPixels(10); + mTextViewTitle.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20); + layout.addView(mTextViewTitle, textviewParams); + + mInputEditText = new EditText(mParentActivity); + LinearLayout.LayoutParams editTextParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, + ViewGroup.LayoutParams.WRAP_CONTENT); + editTextParams.leftMargin = editTextParams.rightMargin = convertDipsToPixels(10); + + layout.addView(mInputEditText, editTextParams); + + setContentView(layout, layoutParams); + + getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); + + mInputMode = mMsg.inputMode; + mInputFlag = mMsg.inputFlag; + mReturnType = mMsg.returnType; + mMaxLength = mMsg.maxLength; + + mTextViewTitle.setText(mMsg.title); + mInputEditText.setText(mMsg.content); + + int oldImeOptions = mInputEditText.getImeOptions(); + mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_FLAG_NO_EXTRACT_UI); + oldImeOptions = mInputEditText.getImeOptions(); + + switch (mInputMode) + { + case kEditBoxInputModeAny: + mInputModeContraints = + InputType.TYPE_CLASS_TEXT | + InputType.TYPE_TEXT_FLAG_MULTI_LINE; + break; + case kEditBoxInputModeEmailAddr: + mInputModeContraints = + InputType.TYPE_CLASS_TEXT | + InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS; + break; + case kEditBoxInputModeNumeric: + mInputModeContraints = + InputType.TYPE_CLASS_NUMBER | + InputType.TYPE_NUMBER_FLAG_SIGNED; + break; + case kEditBoxInputModePhoneNumber: + mInputModeContraints = InputType.TYPE_CLASS_PHONE; + break; + case kEditBoxInputModeUrl: + mInputModeContraints = + InputType.TYPE_CLASS_TEXT | + InputType.TYPE_TEXT_VARIATION_URI; + break; + case kEditBoxInputModeDecimal: + mInputModeContraints = + InputType.TYPE_CLASS_NUMBER | + InputType.TYPE_NUMBER_FLAG_DECIMAL | + InputType.TYPE_NUMBER_FLAG_SIGNED; + break; + case kEditBoxInputModeSingleLine: + mInputModeContraints = InputType.TYPE_CLASS_TEXT; + break; + default: + + break; + } + + if ( mIsMultiline ) { + mInputModeContraints |= InputType.TYPE_TEXT_FLAG_MULTI_LINE; + } + + mInputEditText.setInputType(mInputModeContraints | mInputFlagConstraints); + + switch (mInputFlag) + { + case kEditBoxInputFlagPassword: + mInputFlagConstraints = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD; + break; + case kEditBoxInputFlagSensitive: + mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS; + break; + case kEditBoxInputFlagInitialCapsWord: + mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_CAP_WORDS; + break; + case kEditBoxInputFlagInitialCapsSentence: + mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_CAP_SENTENCES; + break; + case kEditBoxInputFlagInitialCapsAllCharacters: + mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS; + break; + default: + break; + } + mInputEditText.setInputType(mInputFlagConstraints | mInputModeContraints); + + switch (mReturnType) { + case kKeyboardReturnTypeDefault: + mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_NONE); + break; + case kKeyboardReturnTypeDone: + mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_DONE); + break; + case kKeyboardReturnTypeSend: + mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_SEND); + break; + case kKeyboardReturnTypeSearch: + mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_SEARCH); + break; + case kKeyboardReturnTypeGo: + mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_GO); + break; + default: + mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_NONE); + break; + } + + if (mMaxLength > 0) { + mInputEditText.setFilters( + new InputFilter[] { + new InputFilter.LengthFilter(mMaxLength) + } + ); + } + + Handler initHandler = new Handler(); + initHandler.postDelayed(new Runnable() { + public void run() { + mInputEditText.requestFocus(); + mInputEditText.setSelection(mInputEditText.length()); + openKeyboard(); + } + }, 200); + + mInputEditText.setOnEditorActionListener(new OnEditorActionListener() { + @Override + public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { + // if user didn't set keyboard type, + // this callback will be invoked twice with 'KeyEvent.ACTION_DOWN' and 'KeyEvent.ACTION_UP' + if (actionId != EditorInfo.IME_NULL + || (actionId == EditorInfo.IME_NULL + && event != null + && event.getAction() == KeyEvent.ACTION_DOWN)) + { + //Log.d("EditBox", "actionId: "+actionId +",event: "+event); + mParentActivity.setEditBoxResult(mInputEditText.getText().toString()); + closeKeyboard(); + dismiss(); + return true; + } + return false; + } + }); + } + + private void openKeyboard() { + InputMethodManager imm = (InputMethodManager) mParentActivity.getSystemService(Context.INPUT_METHOD_SERVICE); + imm.showSoftInput(mInputEditText, 0); + Log.d("Cocos2dxEditBox", "openKeyboard"); + } + + private void closeKeyboard() { + InputMethodManager imm = (InputMethodManager) mParentActivity.getSystemService(Context.INPUT_METHOD_SERVICE); + imm.hideSoftInputFromWindow(mInputEditText.getWindowToken(), 0); + Log.d("Cocos2dxEditBox", "closeKeyboard"); + } + + @Override + protected void onStop() { + // TODO Auto-generated method stub + super.onStop(); + Log.d("EditBox", "onStop..."); + } +} diff --git a/samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxEditText.java b/samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxEditText.java new file mode 100644 index 0000000000..1c9778293f --- /dev/null +++ b/samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxEditText.java @@ -0,0 +1,65 @@ +/**************************************************************************** +Copyright (c) 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.lib; + +import android.content.Context; +import android.util.AttributeSet; +import android.view.KeyEvent; +import android.widget.EditText; + +public class Cocos2dxEditText extends EditText { + + private Cocos2dxGLSurfaceView mView; + + public Cocos2dxEditText(Context context) { + super(context); + // TODO Auto-generated constructor stub + } + + public Cocos2dxEditText(Context context, AttributeSet attrs) { + super(context, attrs); + } + + public Cocos2dxEditText(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + } + + public void setMainView(Cocos2dxGLSurfaceView glSurfaceView) { + mView = glSurfaceView; + } + + /* + * Let GlSurfaceView get focus if back key is input + */ + public boolean onKeyDown(int keyCode, KeyEvent event) { + super.onKeyDown(keyCode, event); + + if (keyCode == KeyEvent.KEYCODE_BACK) { + mView.requestFocus(); + } + + return true; + } +} diff --git a/samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java b/samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java new file mode 100644 index 0000000000..e7c4721cf3 --- /dev/null +++ b/samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java @@ -0,0 +1,417 @@ +/**************************************************************************** +Copyright (c) 2010-2011 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.lib; + +import android.content.Context; +import android.opengl.GLSurfaceView; +import android.os.Handler; +import android.os.Message; +import android.text.Editable; +import android.text.TextWatcher; +import android.util.AttributeSet; +import android.util.Log; +import android.view.KeyEvent; +import android.view.MotionEvent; +import android.view.inputmethod.InputMethodManager; +import android.widget.TextView; +import android.widget.TextView.OnEditorActionListener; + +class TextInputWraper implements TextWatcher, OnEditorActionListener { + + private static final Boolean debug = false; + private void LogD(String msg) { + if (debug) Log.d("TextInputFilter", msg); + } + + private Cocos2dxGLSurfaceView mMainView; + private String mText; + private String mOriginText; + + private Boolean isFullScreenEdit() { + InputMethodManager imm = (InputMethodManager)mMainView.getTextField().getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + return imm.isFullscreenMode(); + } + + public TextInputWraper(Cocos2dxGLSurfaceView view) { + mMainView = view; + } + + public void setOriginText(String text) { + mOriginText = text; + } + + @Override + public void afterTextChanged(Editable s) { + if (isFullScreenEdit()) { + return; + } + + LogD("afterTextChanged: " + s); + int nModified = s.length() - mText.length(); + if (nModified > 0) { + final String insertText = s.subSequence(mText.length(), s.length()).toString(); + mMainView.insertText(insertText); + LogD("insertText(" + insertText + ")"); + } + else { + for (; nModified < 0; ++nModified) { + mMainView.deleteBackward(); + LogD("deleteBackward"); + } + } + mText = s.toString(); + } + + @Override + public void beforeTextChanged(CharSequence s, int start, int count, + int after) { + LogD("beforeTextChanged(" + s + ")start: " + start + ",count: " + count + ",after: " + after); + mText = s.toString(); + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + } + + @Override + public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { + if (mMainView.getTextField() == v && isFullScreenEdit()) { + // user press the action button, delete all old text and insert new text + for (int i = mOriginText.length(); i > 0; --i) { + mMainView.deleteBackward(); + LogD("deleteBackward"); + } + String text = v.getText().toString(); + + /* + * If user input nothing, translate "\n" to engine. + */ + if (text.compareTo("") == 0){ + text = "\n"; + } + + if ('\n' != text.charAt(text.length() - 1)) { + text += '\n'; + } + + final String insertText = text; + mMainView.insertText(insertText); + LogD("insertText(" + insertText + ")"); + } + return false; + } +} + +public class Cocos2dxGLSurfaceView extends GLSurfaceView { + + static private Cocos2dxGLSurfaceView mainView; + + private static final String TAG = Cocos2dxGLSurfaceView.class.getCanonicalName(); + private Cocos2dxRenderer mRenderer; + + private static final boolean debug = false; + + /////////////////////////////////////////////////////////////////////////// + // for initialize + /////////////////////////////////////////////////////////////////////////// + public Cocos2dxGLSurfaceView(Context context) { + super(context); + initView(); + } + + public Cocos2dxGLSurfaceView(Context context, AttributeSet attrs) { + super(context, attrs); + initView(); + } + + public void setCocos2dxRenderer(Cocos2dxRenderer renderer){ + mRenderer = renderer; + setRenderer(mRenderer); + } + + protected void initView() { + setFocusableInTouchMode(true); + + textInputWraper = new TextInputWraper(this); + + handler = new Handler(){ + public void handleMessage(Message msg){ + switch(msg.what){ + case HANDLER_OPEN_IME_KEYBOARD: + if (null != mTextField && mTextField.requestFocus()) { + mTextField.removeTextChangedListener(textInputWraper); + mTextField.setText(""); + String text = (String)msg.obj; + mTextField.append(text); + textInputWraper.setOriginText(text); + mTextField.addTextChangedListener(textInputWraper); + InputMethodManager imm = (InputMethodManager)mainView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + imm.showSoftInput(mTextField, 0); + Log.d("GLSurfaceView", "showSoftInput"); + } + break; + + case HANDLER_CLOSE_IME_KEYBOARD: + if (null != mTextField) { + mTextField.removeTextChangedListener(textInputWraper); + InputMethodManager imm = (InputMethodManager)mainView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + imm.hideSoftInputFromWindow(mTextField.getWindowToken(), 0); + Log.d("GLSurfaceView", "HideSoftInput"); + } + break; + } + } + }; + + mainView = this; + } + + public void onPause(){ + queueEvent(new Runnable() { + @Override + public void run() { + mRenderer.handleOnPause(); + } + }); + + super.onPause(); + } + + public void onResume(){ + super.onResume(); + + queueEvent(new Runnable() { + @Override + public void run() { + mRenderer.handleOnResume(); + } + }); + } + + /////////////////////////////////////////////////////////////////////////// + // for text input + /////////////////////////////////////////////////////////////////////////// + private final static int HANDLER_OPEN_IME_KEYBOARD = 2; + private final static int HANDLER_CLOSE_IME_KEYBOARD = 3; + private static Handler handler; + private static TextInputWraper textInputWraper; + private Cocos2dxEditText mTextField; + + public TextView getTextField() { + return mTextField; + } + + public void setTextField(Cocos2dxEditText view) { + mTextField = view; + if (null != mTextField && null != textInputWraper) { + mTextField.setOnEditorActionListener(textInputWraper); + mTextField.setMainView(this); + this.requestFocus(); + } + } + + public static void openIMEKeyboard() { + Message msg = new Message(); + msg.what = HANDLER_OPEN_IME_KEYBOARD; + msg.obj = mainView.getContentText(); + handler.sendMessage(msg); + + } + + private String getContentText() { + return mRenderer.getContentText(); + } + + public static void closeIMEKeyboard() { + Message msg = new Message(); + msg.what = HANDLER_CLOSE_IME_KEYBOARD; + handler.sendMessage(msg); + } + + public void insertText(final String text) { + queueEvent(new Runnable() { + @Override + public void run() { + mRenderer.handleInsertText(text); + } + }); + } + + public void deleteBackward() { + queueEvent(new Runnable() { + @Override + public void run() { + mRenderer.handleDeleteBackward(); + } + }); + } + + /////////////////////////////////////////////////////////////////////////// + // for touch event + /////////////////////////////////////////////////////////////////////////// + + public boolean onTouchEvent(final MotionEvent event) { + // these data are used in ACTION_MOVE and ACTION_CANCEL + final int pointerNumber = event.getPointerCount(); + final int[] ids = new int[pointerNumber]; + final float[] xs = new float[pointerNumber]; + final float[] ys = new float[pointerNumber]; + + for (int i = 0; i < pointerNumber; i++) { + ids[i] = event.getPointerId(i); + xs[i] = event.getX(i); + ys[i] = event.getY(i); + } + + switch (event.getAction() & MotionEvent.ACTION_MASK) { + case MotionEvent.ACTION_POINTER_DOWN: + final int indexPointerDown = event.getAction() >> MotionEvent.ACTION_POINTER_ID_SHIFT; + final int idPointerDown = event.getPointerId(indexPointerDown); + final float xPointerDown = event.getX(indexPointerDown); + final float yPointerDown = event.getY(indexPointerDown); + + queueEvent(new Runnable() { + @Override + public void run() { + mRenderer.handleActionDown(idPointerDown, xPointerDown, yPointerDown); + } + }); + break; + + case MotionEvent.ACTION_DOWN: + // there are only one finger on the screen + final int idDown = event.getPointerId(0); + final float xDown = xs[0]; + final float yDown = ys[0]; + + queueEvent(new Runnable() { + @Override + public void run() { + mRenderer.handleActionDown(idDown, xDown, yDown); + } + }); + break; + + case MotionEvent.ACTION_MOVE: + queueEvent(new Runnable() { + @Override + public void run() { + mRenderer.handleActionMove(ids, xs, ys); + } + }); + break; + + case MotionEvent.ACTION_POINTER_UP: + final int indexPointUp = event.getAction() >> MotionEvent.ACTION_POINTER_ID_SHIFT; + final int idPointerUp = event.getPointerId(indexPointUp); + final float xPointerUp = event.getX(indexPointUp); + final float yPointerUp = event.getY(indexPointUp); + + queueEvent(new Runnable() { + @Override + public void run() { + mRenderer.handleActionUp(idPointerUp, xPointerUp, yPointerUp); + } + }); + break; + + case MotionEvent.ACTION_UP: + // there are only one finger on the screen + final int idUp = event.getPointerId(0); + final float xUp = xs[0]; + final float yUp = ys[0]; + + queueEvent(new Runnable() { + @Override + public void run() { + mRenderer.handleActionUp(idUp, xUp, yUp); + } + }); + break; + + case MotionEvent.ACTION_CANCEL: + queueEvent(new Runnable() { + @Override + public void run() { + mRenderer.handleActionCancel(ids, xs, ys); + } + }); + break; + } + + if (debug){ + dumpEvent(event); + } + return true; + } + + /* + * This function is called before Cocos2dxRenderer.nativeInit(), so the width and height is correct. + */ + protected void onSizeChanged(int w, int h, int oldw, int oldh){ + this.mRenderer.setScreenWidthAndHeight(w, h); + } + + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { + final int kc = keyCode; + if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_MENU) { + queueEvent(new Runnable() { + @Override + public void run() { + mRenderer.handleKeyDown(kc); + } + }); + return true; + } + return super.onKeyDown(keyCode, event); + } + + // Show an event in the LogCat view, for debugging + private void dumpEvent(MotionEvent event) { + String names[] = { "DOWN" , "UP" , "MOVE" , "CANCEL" , "OUTSIDE" , + "POINTER_DOWN" , "POINTER_UP" , "7?" , "8?" , "9?" }; + StringBuilder sb = new StringBuilder(); + int action = event.getAction(); + int actionCode = action & MotionEvent.ACTION_MASK; + sb.append("event ACTION_" ).append(names[actionCode]); + if (actionCode == MotionEvent.ACTION_POINTER_DOWN + || actionCode == MotionEvent.ACTION_POINTER_UP) { + sb.append("(pid " ).append( + action >> MotionEvent.ACTION_POINTER_ID_SHIFT); + sb.append(")" ); + } + sb.append("[" ); + for (int i = 0; i < event.getPointerCount(); i++) { + sb.append("#" ).append(i); + sb.append("(pid " ).append(event.getPointerId(i)); + sb.append(")=" ).append((int) event.getX(i)); + sb.append("," ).append((int) event.getY(i)); + if (i + 1 < event.getPointerCount()) + sb.append(";" ); + } + sb.append("]" ); + Log.d(TAG, sb.toString()); + } +} diff --git a/samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxMusic.java b/samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxMusic.java new file mode 100644 index 0000000000..10e3e5f3c6 --- /dev/null +++ b/samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxMusic.java @@ -0,0 +1,228 @@ +/**************************************************************************** +Copyright (c) 2010-2011 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.lib; + +import android.content.Context; +import android.content.res.AssetFileDescriptor; +import android.media.MediaPlayer; +import android.util.Log; + +/** + * + * This class is used for controlling background music + * + */ +public class Cocos2dxMusic { + + private static final String TAG = "Cocos2dxMusic"; + private float mLeftVolume; + private float mRightVolume; + private Context mContext; + private MediaPlayer mBackgroundMediaPlayer; + private boolean mIsPaused; + private String mCurrentPath; + + public Cocos2dxMusic(Context context){ + this.mContext = context; + initData(); + } + + public void preloadBackgroundMusic(String path){ + if ((mCurrentPath == null) || (! mCurrentPath.equals(path))){ + // preload new background music + + // release old resource and create a new one + if (mBackgroundMediaPlayer != null){ + mBackgroundMediaPlayer.release(); + } + + mBackgroundMediaPlayer = createMediaplayerFromAssets(path); + + // record the path + mCurrentPath = path; + } + } + + public void playBackgroundMusic(String path, boolean isLoop){ + if (mCurrentPath == null){ + // it is the first time to play background music + // or end() was called + mBackgroundMediaPlayer = createMediaplayerFromAssets(path); + mCurrentPath = path; + } + else { + if (! mCurrentPath.equals(path)){ + // play new background music + + // release old resource and create a new one + if (mBackgroundMediaPlayer != null){ + mBackgroundMediaPlayer.release(); + } + mBackgroundMediaPlayer = createMediaplayerFromAssets(path); + + // record the path + mCurrentPath = path; + } + } + + if (mBackgroundMediaPlayer == null){ + Log.e(TAG, "playBackgroundMusic: background media player is null"); + } else { + // if the music is playing or paused, stop it + mBackgroundMediaPlayer.stop(); + + mBackgroundMediaPlayer.setLooping(isLoop); + + try { + mBackgroundMediaPlayer.prepare(); + mBackgroundMediaPlayer.seekTo(0); + mBackgroundMediaPlayer.start(); + + this.mIsPaused = false; + } catch (Exception e){ + Log.e(TAG, "playBackgroundMusic: error state"); + } + } + } + + public void stopBackgroundMusic(){ + if (mBackgroundMediaPlayer != null){ + mBackgroundMediaPlayer.stop(); + + // should set the state, if not , the following sequence will be error + // play -> pause -> stop -> resume + this.mIsPaused = false; + } + } + + public void pauseBackgroundMusic(){ + if (mBackgroundMediaPlayer != null && mBackgroundMediaPlayer.isPlaying()){ + mBackgroundMediaPlayer.pause(); + this.mIsPaused = true; + } + } + + public void resumeBackgroundMusic(){ + if (mBackgroundMediaPlayer != null && this.mIsPaused){ + mBackgroundMediaPlayer.start(); + this.mIsPaused = false; + } + } + + public void rewindBackgroundMusic(){ + if (mBackgroundMediaPlayer != null){ + mBackgroundMediaPlayer.stop(); + + try { + mBackgroundMediaPlayer.prepare(); + mBackgroundMediaPlayer.seekTo(0); + mBackgroundMediaPlayer.start(); + + this.mIsPaused = false; + } catch (Exception e){ + Log.e(TAG, "rewindBackgroundMusic: error state"); + } + } + } + + public boolean isBackgroundMusicPlaying(){ + boolean ret = false; + + if (mBackgroundMediaPlayer == null){ + ret = false; + } else { + ret = mBackgroundMediaPlayer.isPlaying(); + } + + return ret; + } + + public void end(){ + if (mBackgroundMediaPlayer != null){ + mBackgroundMediaPlayer.release(); + } + + initData(); + } + + public float getBackgroundVolume(){ + if (this.mBackgroundMediaPlayer != null){ + return (this.mLeftVolume + this.mRightVolume) / 2; + } else { + return 0.0f; + } + } + + public void setBackgroundVolume(float volume){ + if (volume < 0.0f){ + volume = 0.0f; + } + + if (volume > 1.0f){ + volume = 1.0f; + } + + this.mLeftVolume = this.mRightVolume = volume; + if (this.mBackgroundMediaPlayer != null){ + this.mBackgroundMediaPlayer.setVolume(this.mLeftVolume, this.mRightVolume); + } + } + + private void initData(){ + mLeftVolume =0.5f; + mRightVolume = 0.5f; + mBackgroundMediaPlayer = null; + mIsPaused = false; + mCurrentPath = null; + } + + /** + * create mediaplayer for music + * @param path the path relative to assets + * @return + */ + private MediaPlayer createMediaplayerFromAssets(String path){ + MediaPlayer mediaPlayer = new MediaPlayer(); + + try{ + if (path.startsWith("/")) { + mediaPlayer.setDataSource(path); + } + else { + AssetFileDescriptor assetFileDescritor = mContext.getAssets().openFd(path); + mediaPlayer.setDataSource(assetFileDescritor.getFileDescriptor(), + assetFileDescritor.getStartOffset(), assetFileDescritor.getLength()); + } + + mediaPlayer.prepare(); + + mediaPlayer.setVolume(mLeftVolume, mRightVolume); + }catch (Exception e) { + mediaPlayer = null; + Log.e(TAG, "error: " + e.getMessage(), e); + } + + return mediaPlayer; + } +} diff --git a/samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxRenderer.java b/samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxRenderer.java new file mode 100644 index 0000000000..fad0974f42 --- /dev/null +++ b/samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxRenderer.java @@ -0,0 +1,137 @@ +/**************************************************************************** +Copyright (c) 2010-2011 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.lib; + +import javax.microedition.khronos.egl.EGLConfig; +import javax.microedition.khronos.opengles.GL10; + +import android.opengl.GLSurfaceView; + +public class Cocos2dxRenderer implements GLSurfaceView.Renderer { + private final static long NANOSECONDSPERSECOND = 1000000000L; + private final static long NANOSECONDSPERMINISECOND = 1000000; + private static long animationInterval = (long)(1.0 / 60 * NANOSECONDSPERSECOND); + private long last; + private int screenWidth; + private int screenHeight; + + public void onSurfaceCreated(GL10 gl, EGLConfig config) { + nativeInit(screenWidth, screenHeight); + last = System.nanoTime(); + } + + public void setScreenWidthAndHeight(int w, int h){ + this.screenWidth = w; + this.screenHeight = h; + } + + public void onSurfaceChanged(GL10 gl, int w, int h) { + } + + public void onDrawFrame(GL10 gl) { + + long now = System.nanoTime(); + long interval = now - last; + + // should render a frame when onDrawFrame() is called + // or there is a "ghost" + nativeRender(); + + // fps controlling + if (interval < animationInterval){ + try { + // because we render it before, so we should sleep twice time interval + Thread.sleep((animationInterval - interval) * 2 / NANOSECONDSPERMINISECOND); + } catch (Exception e){} + } + + last = now; + } + + public void handleActionDown(int id, float x, float y) + { + nativeTouchesBegin(id, x, y); + } + + public void handleActionUp(int id, float x, float y) + { + nativeTouchesEnd(id, x, y); + } + + public void handleActionCancel(int[] id, float[] x, float[] y) + { + nativeTouchesCancel(id, x, y); + } + + public void handleActionMove(int[] id, float[] x, float[] y) + { + nativeTouchesMove(id, x, y); + } + + public void handleKeyDown(int keyCode) + { + nativeKeyDown(keyCode); + } + + public void handleOnPause(){ + nativeOnPause(); + } + + public void handleOnResume(){ + nativeOnResume(); + } + + public static void setAnimationInterval(double interval){ + animationInterval = (long)(interval * NANOSECONDSPERSECOND); + } + private static native void nativeTouchesBegin(int id, float x, float y); + private static native void nativeTouchesEnd(int id, float x, float y); + private static native void nativeTouchesMove(int[] id, float[] x, float[] y); + private static native void nativeTouchesCancel(int[] id, float[] x, float[] y); + private static native boolean nativeKeyDown(int keyCode); + private static native void nativeRender(); + private static native void nativeInit(int w, int h); + private static native void nativeOnPause(); + private static native void nativeOnResume(); + + ///////////////////////////////////////////////////////////////////////////////// + // handle input method edit message + ///////////////////////////////////////////////////////////////////////////////// + + public void handleInsertText(final String text) { + nativeInsertText(text); + } + + public void handleDeleteBackward() { + nativeDeleteBackward(); + } + + public String getContentText() { + return nativeGetContentText(); + } + + private static native void nativeInsertText(String text); + private static native void nativeDeleteBackward(); + private static native String nativeGetContentText(); +} diff --git a/samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxSound.java b/samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxSound.java new file mode 100644 index 0000000000..e7061f74de --- /dev/null +++ b/samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxSound.java @@ -0,0 +1,245 @@ +/**************************************************************************** +Copyright (c) 2010-2011 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.lib; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import android.content.Context; +import android.media.AudioManager; +import android.media.SoundPool; +import android.util.Log; + +/** + * + * This class is used for controlling effect + * + */ + +public class Cocos2dxSound { + private Context mContext; + private SoundPool mSoundPool; + private float mLeftVolume; + private float mRightVolume; + + // sound path and stream ids map + // a file may be played many times at the same time + // so there is an array map to a file path + private HashMap> mPathStreamIDsMap; + + private HashMap mPathSoundIdMap; + + private static final String TAG = "Cocos2dxSound"; + private static final int MAX_SIMULTANEOUS_STREAMS_DEFAULT = 5; + private static final float SOUND_RATE = 1.0f; + private static final int SOUND_PRIORITY = 1; + private static final int SOUND_QUALITY = 5; + + private final static int INVALID_SOUND_ID = -1; + private final static int INVALID_STREAM_ID = -1; + + public Cocos2dxSound(Context context){ + this.mContext = context; + initData(); + } + + public int preloadEffect(String path){ + Integer soundID = this.mPathSoundIdMap.get(path); + + if (soundID == null) { + soundID = createSoundIdFromAsset(path); + this.mPathSoundIdMap.put(path, soundID); + } + + return soundID; + } + + public void unloadEffect(String path){ + // stop effects + ArrayList streamIDs = this.mPathStreamIDsMap.get(path); + if (streamIDs != null) { + for (Integer streamID : streamIDs) { + this.mSoundPool.stop(streamID); + } + } + this.mPathStreamIDsMap.remove(path); + + // unload effect + Integer soundID = this.mPathSoundIdMap.get(path); + this.mSoundPool.unload(soundID); + this.mPathSoundIdMap.remove(path); + } + + public int playEffect(String path, boolean isLoop){ + Integer soundId = this.mPathSoundIdMap.get(path); + int streamId = INVALID_STREAM_ID; + + if (soundId != null){ + // play sound + streamId = this.mSoundPool.play(soundId.intValue(), this.mLeftVolume, + this.mRightVolume, SOUND_PRIORITY, isLoop ? -1 : 0, SOUND_RATE); + + // record stream id + ArrayList streamIds = this.mPathStreamIDsMap.get(path); + if (streamIds == null) { + streamIds = new ArrayList(); + this.mPathStreamIDsMap.put(path, streamIds); + } + streamIds.add(streamId); + } else { + // the effect is not prepared + soundId = preloadEffect(path); + if (soundId == INVALID_SOUND_ID){ + // can not preload effect + return 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. + */ + playEffect(path, isLoop); + } + + return streamId; + } + + public void stopEffect(int streamID){ + this.mSoundPool.stop(streamID); + + // remove record + for (String path : this.mPathStreamIDsMap.keySet()) { + if (this.mPathStreamIDsMap.get(path).contains(streamID)) { + this.mPathStreamIDsMap.get(path).remove(this.mPathStreamIDsMap.get(path).indexOf(streamID)); + break; + } + } + } + + public void pauseEffect(int streamID){ + this.mSoundPool.pause(streamID); + } + + public void resumeEffect(int streamID){ + this.mSoundPool.resume(streamID); + } + + public void pauseAllEffects(){ + this.mSoundPool.autoPause(); + } + + public void resumeAllEffects(){ + // autoPause() is available since level 8 + this.mSoundPool.autoResume(); + } + + @SuppressWarnings("unchecked") + public void stopAllEffects(){ + // stop effects + if (! this.mPathStreamIDsMap.isEmpty()) { + Iterator iter = this.mPathStreamIDsMap.entrySet().iterator(); + while (iter.hasNext()){ + Map.Entry> entry = (Map.Entry>)iter.next(); + for (int streamID : entry.getValue()) { + this.mSoundPool.stop(streamID); + } + } + } + + // remove records + this.mPathStreamIDsMap.clear(); + } + + public float getEffectsVolume(){ + return (this.mLeftVolume + this.mRightVolume) / 2; + } + + @SuppressWarnings("unchecked") + public void setEffectsVolume(float volume){ + // volume should be in [0, 1.0] + if (volume < 0){ + volume = 0; + } + if (volume > 1){ + volume = 1; + } + + this.mLeftVolume = this.mRightVolume = volume; + + // change the volume of playing sounds + if (! this.mPathStreamIDsMap.isEmpty()) { + Iterator iter = this.mPathStreamIDsMap.entrySet().iterator(); + while (iter.hasNext()){ + Map.Entry> entry = (Map.Entry>)iter.next(); + for (int streamID : entry.getValue()) { + this.mSoundPool.setVolume(streamID, mLeftVolume, mRightVolume); + } + } + } + } + + public void end(){ + this.mSoundPool.release(); + this.mPathStreamIDsMap.clear(); + this.mPathSoundIdMap.clear(); + + initData(); + } + + public int createSoundIdFromAsset(String path){ + int soundId = INVALID_SOUND_ID; + + try { + if (path.startsWith("/")){ + soundId = mSoundPool.load(path, 0); + } + else { + soundId = mSoundPool.load(mContext.getAssets().openFd(path), 0); + } + } catch(Exception e){ + soundId = INVALID_SOUND_ID; + Log.e(TAG, "error: " + e.getMessage(), e); + } + + return soundId; + } + + private void initData(){ + this.mPathStreamIDsMap = new HashMap>(); + this.mPathSoundIdMap = new HashMap(); + mSoundPool = new SoundPool(MAX_SIMULTANEOUS_STREAMS_DEFAULT, AudioManager.STREAM_MUSIC, SOUND_QUALITY); + + this.mLeftVolume = 0.5f; + this.mRightVolume = 0.5f; + } +} diff --git a/samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxTypefaces.java b/samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxTypefaces.java new file mode 100644 index 0000000000..79af1ed3af --- /dev/null +++ b/samples/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxTypefaces.java @@ -0,0 +1,44 @@ +/**************************************************************************** +Copyright (c) 2010-2011 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.lib; + +import java.util.Hashtable; + +import android.content.Context; +import android.graphics.Typeface; + +public class Cocos2dxTypefaces { + private static final Hashtable cache = new Hashtable(); + + public static Typeface get(Context context, String name){ + synchronized(cache){ + if (! cache.containsKey(name)){ + Typeface t = Typeface.createFromAsset(context.getAssets(), name); + cache.put(name, t); + } + + return cache.get(name); + } + } +} diff --git a/samples/SimpleGame/proj.android/src/org/cocos2dx/simplegame/SimpleGame.java b/samples/SimpleGame/proj.android/src/org/cocos2dx/simplegame/SimpleGame.java new file mode 100644 index 0000000000..99171bd284 --- /dev/null +++ b/samples/SimpleGame/proj.android/src/org/cocos2dx/simplegame/SimpleGame.java @@ -0,0 +1,108 @@ +/**************************************************************************** +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.simplegame; + +import org.cocos2dx.lib.Cocos2dxActivity; +import org.cocos2dx.lib.Cocos2dxEditText; +import org.cocos2dx.lib.Cocos2dxGLSurfaceView; +import org.cocos2dx.lib.Cocos2dxRenderer; + +import android.app.ActivityManager; +import android.content.Context; +import android.content.pm.ConfigurationInfo; +import android.os.Bundle; +import android.util.Log; +import android.widget.FrameLayout; +import android.view.ViewGroup; + +public class SimpleGame extends Cocos2dxActivity{ + + protected void onCreate(Bundle savedInstanceState){ + super.onCreate(savedInstanceState); + + if (detectOpenGLES20()) { + // get the packageName,it's used to set the resource path + String packageName = getApplication().getPackageName(); + super.setPackageName(packageName); + + // FrameLayout + ViewGroup.LayoutParams framelayout_params = + new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, + ViewGroup.LayoutParams.FILL_PARENT); + FrameLayout framelayout = new FrameLayout(this); + framelayout.setLayoutParams(framelayout_params); + + // Cocos2dxEditText layout + ViewGroup.LayoutParams edittext_layout_params = + new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, + ViewGroup.LayoutParams.WRAP_CONTENT); + Cocos2dxEditText edittext = new Cocos2dxEditText(this); + edittext.setLayoutParams(edittext_layout_params); + + // ...add to FrameLayout + framelayout.addView(edittext); + + // Cocos2dxGLSurfaceView + mGLView = new Cocos2dxGLSurfaceView(this); + + // ...add to FrameLayout + framelayout.addView(mGLView); + + mGLView.setEGLContextClientVersion(2); + mGLView.setCocos2dxRenderer(new Cocos2dxRenderer()); + mGLView.setTextField(edittext); + + // Set framelayout as the content view + setContentView(framelayout); + } + else { + Log.d("activity", "don't support gles2.0"); + finish(); + } + } + + @Override + protected void onPause() { + super.onPause(); + mGLView.onPause(); + } + + @Override + protected void onResume() { + super.onResume(); + mGLView.onResume(); + } + + private boolean detectOpenGLES20() + { + ActivityManager am = + (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); + ConfigurationInfo info = am.getDeviceConfigurationInfo(); + return (info.reqGlEsVersion >= 0x20000); + } + + static { + System.loadLibrary("game"); + } +} From d9cc8fa34678c5a0fc63683a61ba10f652ba02bc Mon Sep 17 00:00:00 2001 From: James Chen Date: Sun, 9 Sep 2012 22:34:32 +0800 Subject: [PATCH 07/15] issue #1458: Adding CCTableView support. Updated win32 project configuration. --- extensions/CCBReader/CCNodeLoader.cpp | 12 - extensions/CCBReader/CCNodeLoader.h | 12 + extensions/CCBReader/CCScrollViewLoader.cpp | 9 + extensions/CCBReader/CCScrollViewLoader.h | 2 +- extensions/GUI/CCScrollView/CCScrollView.cpp | 26 +- extensions/GUI/CCScrollView/CCScrollView.h | 3 +- extensions/GUI/CCScrollView/CCSorting.cpp | 175 +++++++ extensions/GUI/CCScrollView/CCSorting.h | 114 ++++ extensions/GUI/CCScrollView/CCTableView.cpp | 485 ++++++++++++++++++ extensions/GUI/CCScrollView/CCTableView.h | 231 +++++++++ .../GUI/CCScrollView/CCTableViewCell.cpp | 59 +++ extensions/GUI/CCScrollView/CCTableViewCell.h | 63 +++ extensions/cocos-ext.h | 1 + extensions/proj.win32/libExtensions.vcproj | 24 + .../Classes/ExtensionsTest/ExtensionsTest.cpp | 11 +- .../TableViewTest/CustomTableViewCell.cpp | 19 + .../TableViewTest/CustomTableViewCell.h | 14 + .../TableViewTest/TableViewTestScene.cpp | 99 ++++ .../TableViewTest/TableViewTestScene.h | 26 + samples/TestCpp/proj.win32/TestCpp.vcproj | 20 + 20 files changed, 1378 insertions(+), 27 deletions(-) create mode 100644 extensions/GUI/CCScrollView/CCSorting.cpp create mode 100644 extensions/GUI/CCScrollView/CCSorting.h create mode 100644 extensions/GUI/CCScrollView/CCTableView.cpp create mode 100644 extensions/GUI/CCScrollView/CCTableView.h create mode 100644 extensions/GUI/CCScrollView/CCTableViewCell.cpp create mode 100644 extensions/GUI/CCScrollView/CCTableViewCell.h create mode 100644 samples/TestCpp/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.cpp create mode 100644 samples/TestCpp/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.h create mode 100644 samples/TestCpp/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp create mode 100644 samples/TestCpp/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.h diff --git a/extensions/CCBReader/CCNodeLoader.cpp b/extensions/CCBReader/CCNodeLoader.cpp index 9a32f421e8..01c4b7d0f8 100644 --- a/extensions/CCBReader/CCNodeLoader.cpp +++ b/extensions/CCBReader/CCNodeLoader.cpp @@ -2,18 +2,6 @@ #include "CCBSelectorResolver.h" #include "CCBMemberVariableAssigner.h" -#define PROPERTY_POSITION "position" -#define PROPERTY_CONTENTSIZE "contentSize" -#define PROPERTY_ANCHORPOINT "anchorPoint" -#define PROPERTY_SCALE "scale" -#define PROPERTY_ROTATION "rotation" -#define PROPERTY_TAG "tag" -#define PROPERTY_IGNOREANCHORPOINTFORPOSITION "ignoreAnchorPointForPosition" -#define PROPERTY_VISIBLE "visible" - -#define ASSERT_FAIL_UNEXPECTED_PROPERTY(PROPERTY) CCLog("Unexpected property: '%s'!\n", PROPERTY->getCString()); assert(false) -#define ASSERT_FAIL_UNEXPECTED_PROPERTYTYPE(PROPERTYTYPE) CCLog("Unexpected property type: '%d'!\n", PROPERTYTYPE); assert(false) - USING_NS_CC; NS_CC_EXT_BEGIN diff --git a/extensions/CCBReader/CCNodeLoader.h b/extensions/CCBReader/CCNodeLoader.h index e74e7c012a..53d06bc1ea 100644 --- a/extensions/CCBReader/CCNodeLoader.h +++ b/extensions/CCBReader/CCNodeLoader.h @@ -7,6 +7,18 @@ NS_CC_EXT_BEGIN +#define PROPERTY_POSITION "position" +#define PROPERTY_CONTENTSIZE "contentSize" +#define PROPERTY_ANCHORPOINT "anchorPoint" +#define PROPERTY_SCALE "scale" +#define PROPERTY_ROTATION "rotation" +#define PROPERTY_TAG "tag" +#define PROPERTY_IGNOREANCHORPOINTFORPOSITION "ignoreAnchorPointForPosition" +#define PROPERTY_VISIBLE "visible" + +#define ASSERT_FAIL_UNEXPECTED_PROPERTY(PROPERTY) CCLog("Unexpected property: '%s'!\n", PROPERTY->getCString()); assert(false) +#define ASSERT_FAIL_UNEXPECTED_PROPERTYTYPE(PROPERTYTYPE) CCLog("Unexpected property type: '%d'!\n", PROPERTYTYPE); assert(false) + #define CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(T) virtual T * createCCNode(cocos2d::CCNode * pParent, cocos2d::extension::CCBReader * pCCBReader) { \ return T::create(); \ } diff --git a/extensions/CCBReader/CCScrollViewLoader.cpp b/extensions/CCBReader/CCScrollViewLoader.cpp index ed7ddd6448..b5c4a8830e 100644 --- a/extensions/CCBReader/CCScrollViewLoader.cpp +++ b/extensions/CCBReader/CCScrollViewLoader.cpp @@ -10,6 +10,14 @@ USING_NS_CC; NS_CC_EXT_BEGIN +void CCScrollViewLoader::onHandlePropTypeSize(CCNode * pNode, CCNode * pParent, CCString * pPropertyName, CCSize pSize, CCBReader * pCCBReader) { + if(pPropertyName->compare(PROPERTY_CONTENTSIZE) == 0) { + ((CCScrollView *)pNode)->setViewSize(pSize); + } else { + CCNodeLoader::onHandlePropTypeSize(pNode, pParent, pPropertyName, pSize, pCCBReader); + } +} + void CCScrollViewLoader::onHandlePropTypeCheck(CCNode * pNode, CCNode * pParent, CCString * pPropertyName, bool pCheck, CCBReader * pCCBReader) { if(pPropertyName->compare(PROPERTY_CLIPSTOBOUNDS) == 0) { ((CCScrollView *)pNode)->setClippingToBounds(pCheck); @@ -23,6 +31,7 @@ void CCScrollViewLoader::onHandlePropTypeCheck(CCNode * pNode, CCNode * pParent, void CCScrollViewLoader::onHandlePropTypeCCBFile(CCNode * pNode, CCNode * pParent, CCString * pPropertyName, CCNode * pCCBFileNode, CCBReader * pCCBReader) { if(pPropertyName->compare(PROPERTY_CONTAINER) == 0) { ((CCScrollView *)pNode)->setContainer(pCCBFileNode); + ((CCScrollView *)pNode)->setViewSize(CCSizeMake(240, 320)); } else { CCNodeLoader::onHandlePropTypeCCBFile(pNode, pParent, pPropertyName, pCCBFileNode, pCCBReader); } diff --git a/extensions/CCBReader/CCScrollViewLoader.h b/extensions/CCBReader/CCScrollViewLoader.h index b415e656b6..57baff99c3 100644 --- a/extensions/CCBReader/CCScrollViewLoader.h +++ b/extensions/CCBReader/CCScrollViewLoader.h @@ -16,7 +16,7 @@ class CCScrollViewLoader : public CCNodeLoader { protected: CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(CCScrollView); - + virtual void onHandlePropTypeSize(CCNode * pNode, CCNode * pParent, CCString * pPropertyName, CCSize pSize, CCBReader * pCCBReader); virtual void onHandlePropTypeCCBFile(CCNode * pNode, CCNode * pParent, CCString * pPropertyName, CCNode * pCCBFileNode, CCBReader * pCCBReader); virtual void onHandlePropTypeCheck(CCNode * pNode, CCNode * pParent, CCString * pPropertyName, bool pCheck, CCBReader * pCCBReader); virtual void onHandlePropTypeFloat(CCNode * pNode, CCNode * pParent, CCString * pPropertyName, float pFloat, CCBReader * pCCBReader); diff --git a/extensions/GUI/CCScrollView/CCScrollView.cpp b/extensions/GUI/CCScrollView/CCScrollView.cpp index 992408e495..45f1c0bef4 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.cpp +++ b/extensions/GUI/CCScrollView/CCScrollView.cpp @@ -118,6 +118,8 @@ bool CCScrollView::initWithViewSize(CCSize size, CCNode *container/* = NULL*/) if (!this->m_pContainer) { m_pContainer = CCLayer::create(); + this->m_pContainer->ignoreAnchorPointForPosition(false); + this->m_pContainer->setAnchorPoint(ccp(0.0f, 0.0f)); } this->setViewSize(size); @@ -309,17 +311,6 @@ void CCScrollView::setZoomScaleInDuration(float s, float dt) void CCScrollView::setViewSize(CCSize size) { m_tViewSize = size; - - if (this->m_pContainer != NULL) - { - m_fMaxInset = this->maxContainerOffset(); - m_fMaxInset = ccp(m_fMaxInset.x + m_tViewSize.width * INSET_RATIO, - m_fMaxInset.y + m_tViewSize.height * INSET_RATIO); - m_fMinInset = this->minContainerOffset(); - m_fMinInset = ccp(m_fMinInset.x - m_tViewSize.width * INSET_RATIO, - m_fMinInset.y - m_tViewSize.height * INSET_RATIO); - } - CCLayer::setContentSize(size); } @@ -456,7 +447,18 @@ const CCSize & CCScrollView::getContentSize() void CCScrollView::setContentSize(const CCSize & size) { - this->setViewSize(size); + // this->setViewSize(size); + if (this->getContainer() != NULL) + { + this->getContainer()->setContentSize(size); + + m_fMaxInset = this->maxContainerOffset(); + m_fMaxInset = ccp(m_fMaxInset.x + m_tViewSize.width * INSET_RATIO, + m_fMaxInset.y + m_tViewSize.height * INSET_RATIO); + m_fMinInset = this->minContainerOffset(); + m_fMinInset = ccp(m_fMinInset.x - m_tViewSize.width * INSET_RATIO, + m_fMinInset.y - m_tViewSize.height * INSET_RATIO); + } } /** * make sure all children go to the container diff --git a/extensions/GUI/CCScrollView/CCScrollView.h b/extensions/GUI/CCScrollView/CCScrollView.h index 1537245988..f5e98d5ac7 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.h +++ b/extensions/GUI/CCScrollView/CCScrollView.h @@ -42,6 +42,7 @@ NS_CC_EXT_BEGIN */ typedef enum { + CCScrollViewDirectionNone = -1, CCScrollViewDirectionHorizontal = 0, CCScrollViewDirectionVertical, CCScrollViewDirectionBoth @@ -195,7 +196,7 @@ public: * direction allowed to scroll. CCScrollViewDirectionBoth by default. */ CCScrollViewDirection getDirection() { return m_eDirection; } - void setDirection(CCScrollViewDirection eDirection) { m_eDirection = eDirection; } + virtual void setDirection(CCScrollViewDirection eDirection) { m_eDirection = eDirection; } CCScrollViewDelegate* getDelegate() { return m_pDelegate; } void setDelegate(CCScrollViewDelegate* pDelegate) { m_pDelegate = pDelegate; } diff --git a/extensions/GUI/CCScrollView/CCSorting.cpp b/extensions/GUI/CCScrollView/CCSorting.cpp new file mode 100644 index 0000000000..5b795d73a1 --- /dev/null +++ b/extensions/GUI/CCScrollView/CCSorting.cpp @@ -0,0 +1,175 @@ +// +// NSMutableArraySorting.m +// SWGameLib +// +// Copyright (c) 2012 cocos2d-x.org +// Copyright (c) 2010 Sangwoo Im +// +// 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. +// +// Created by Sangwoo Im on 10/10/09. +// Copyright 2009 Sangwoo Im. All rights reserved. +// + +#include "CCSorting.h" +//#include "SWDebug.h" + +NS_CC_EXT_BEGIN + +class CCSortedObject : public CCObject, public CCSortableObject +{ +public: + CCSortedObject() : objectID(0) {} + virtual void setObjectID(unsigned int objectID) { this->objectID = objectID; } + virtual unsigned int getObjectID() { return objectID; } +private: + unsigned int objectID; +}; + +static int _compareObject(const void * val1, const void * val2) +{ + CCSortableObject* operand1; + CCSortableObject* operand2; + + operand1 = (CCSortableObject*)val1; + operand2 = (CCSortableObject*)val2; + + if (operand1->getObjectID() > operand2->getObjectID()) + { + return 1; + } + else if (operand1->getObjectID() < operand2->getObjectID()) { + return -1; + } + return 0; +} + + +void CCArrayForObjectSorting::insertSortedObject(CCSortableObject* object) +{ + unsigned int idx; + CCObject* pObj = dynamic_cast(object); + CCAssert(pObj, "Invalid parameter."); + idx = this->indexOfSortedObject(object); + + this->insertObject(pObj, idx); +} + +void CCArrayForObjectSorting::removeSortedObject(CCSortableObject* object) +{ + if (this->count() == 0) { + return; + } + unsigned int idx; + CCSortableObject* foundObj; + idx = this->indexOfSortedObject(object); + + if (idx < this->count() && idx != CC_INVALID_INDEX) { + foundObj = dynamic_cast(this->objectAtIndex(idx)); + + if(foundObj->getObjectID() == object->getObjectID()) { + this->removeObjectAtIndex(idx); + } + } +} + +void CCArrayForObjectSorting::setObjectID_ofSortedObject(unsigned int tag, CCSortableObject* object) +{ + CCSortableObject* foundObj; + unsigned int idx; + + idx = this->indexOfSortedObject(object); + if (idx < this->count() && idx != CC_INVALID_INDEX) + { + foundObj = dynamic_cast(this->objectAtIndex(idx)); + CCObject* pObj = dynamic_cast(foundObj); + pObj->retain(); + + if(foundObj->getObjectID() == object->getObjectID()) { + this->removeObjectAtIndex(idx); + foundObj->setObjectID(tag); + this->insertSortedObject(foundObj); + pObj->release(); + } else { + pObj->release(); + } + } +} + +CCSortableObject* CCArrayForObjectSorting::objectWithObjectID(unsigned int tag) +{ + if (this->count() == 0) { + return NULL; + } + + unsigned int idx; + CCSortableObject* foundObj; + + foundObj = new CCSortedObject(); + foundObj->setObjectID(tag); + + idx = this->indexOfSortedObject(foundObj); + + ((CCSortedObject*)foundObj)->release(); + foundObj = NULL; + + if (idx < this->count() && idx != CC_INVALID_INDEX) + { + foundObj = dynamic_cast(this->objectAtIndex(idx)); + if (foundObj->getObjectID() != tag) { + foundObj = NULL; + } + } + + return foundObj; +} + +unsigned int CCArrayForObjectSorting::indexOfSortedObject(CCSortableObject* object) +{ + unsigned int idx = 0; + if (object) + { + // CCObject* pObj = (CCObject*)bsearch((CCObject*)&object, data->arr, data->num, sizeof(CCObject*), _compareObject); + // FIXME: need to use binary search to improve performance + CCObject* pObj = NULL; + unsigned int uPrevObjectID = 0; + unsigned int uOfSortObjectID = object->getObjectID(); + + CCARRAY_FOREACH(this, pObj) + { + CCSortableObject* pSortableObj = dynamic_cast(pObj); + unsigned int uCurObjectID = pSortableObj->getObjectID(); + if ( (uOfSortObjectID == uCurObjectID) + || (uOfSortObjectID >= uPrevObjectID && uOfSortObjectID < uCurObjectID)) + { + break; + } + + uPrevObjectID = uCurObjectID; + idx++; + } + } + else + { + idx = CC_INVALID_INDEX; + } + return idx; +} + +NS_CC_EXT_END diff --git a/extensions/GUI/CCScrollView/CCSorting.h b/extensions/GUI/CCScrollView/CCSorting.h new file mode 100644 index 0000000000..5fa0d3a614 --- /dev/null +++ b/extensions/GUI/CCScrollView/CCSorting.h @@ -0,0 +1,114 @@ +// +// NSMutableArraySorting.h +// SWGameLib +// +// Copyright (c) 2012 cocos2d-x.org +// Copyright (c) 2010 Sangwoo Im +// +// 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. +// +// Created by Sangwoo Im on 10/10/09. +// Copyright 2009 Sangwoo Im. All rights reserved. +// + +#ifndef __CCSORTING_H__ +#define __CCSORTING_H__ + +#include "cocoa/CCArray.h" +#include "ExtensionMacros.h" + +NS_CC_EXT_BEGIN + +class CCSortableObject +{ +public: + virtual ~CCSortableObject() {} + virtual void setObjectID(unsigned int objectID) = 0; + virtual unsigned int getObjectID() = 0; +}; + +class CCArrayForObjectSorting : public CCArray +{ +public: + CCArrayForObjectSorting() : CCArray() {} + /*! + * Inserts a given object into array. + * + * Inserts a given object into array with key and value that are used in + * sorting. "value" must respond to message, compare:, which returns + * (NSComparisonResult). If it does not respond to the message, it is appended. + * If the compare message does not result NSComparisonResult, sorting behavior + * is not defined. It ignores duplicate entries and inserts next to it. + * + * @param object to insert + */ + void insertSortedObject(CCSortableObject* object); + + /*! + * Removes an object in array. + * + * Removes an object with given key and value. If no object is found in array + * with the key and value, no action is taken. + * + * @param value to remove + */ + void removeSortedObject(CCSortableObject* object); + /*! + * Sets a new value of the key for the given object. + * + * In case where sorting value must be changed, this message must be sent to + * keep consistency of being sorted. If it is changed externally, it must be + * sorted completely again. + * + * @param value to set + * @param object the object which has the value + */ + void setObjectID_ofSortedObject(unsigned int tag, CCSortableObject* object); + + CCSortableObject* objectWithObjectID(unsigned int tag); + /*! + * Returns an object with given key and value. + * + * Returns an object with given key and value. If no object is found, + * it returns nil. + * + * @param value to locate object + * @return object found or nil. + */ + CCSortableObject* getObjectWithObjectID(unsigned int tag); + + /*! + * Returns an index of the object with given key and value. + * + * Returns the index of an object with given key and value. + * If no object is found, it returns an index at which the given object value + * would have been located. If object must be located at the end of array, + * it returns the length of the array, which is out of bound. + * + * @param value to locate object + * @return index of an object found + */ + unsigned int indexOfSortedObject(CCSortableObject* obj); + +}; + +NS_CC_EXT_END + +#endif /* __CCSORTING_H__ */ + diff --git a/extensions/GUI/CCScrollView/CCTableView.cpp b/extensions/GUI/CCScrollView/CCTableView.cpp new file mode 100644 index 0000000000..f520511dd0 --- /dev/null +++ b/extensions/GUI/CCScrollView/CCTableView.cpp @@ -0,0 +1,485 @@ +// +// SWTableView.m +// SWGameLib +// +// Copyright (c) 2012 cocos2d-x.org +// Copyright (c) 2010 Sangwoo Im +// +// 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. +// +// +// Created by Sangwoo Im on 6/3/10. +// Copyright 2010 Sangwoo Im. All rights reserved. +// +#include "cocos2d.h" +#include "CCTableView.h" +#include "CCTableViewCell.h" +#include "menu_nodes/CCMenu.h" +#include "support/CCPointExtension.h" +#include "CCSorting.h" +#include "layers_scenes_transitions_nodes/CCLayer.h" + +NS_CC_EXT_BEGIN + +CCTableView* CCTableView::viewWithDataSource(CCTableViewDataSource* dataSource, CCSize size) +{ + return CCTableView::viewWithDataSource(dataSource, size, NULL); +} + +CCTableView* CCTableView::viewWithDataSource(CCTableViewDataSource* dataSource, CCSize size, CCNode *container) +{ + CCTableView *table = new CCTableView(); + table->initWithViewSize(size, container); + table->autorelease(); + table->setDataSource(dataSource); + table->_updateContentSize(); + + return table; +} + +bool CCTableView::initWithViewSize(CCSize size, CCNode* container/* = NULL*/) +{ + if (CCScrollView::initWithViewSize(size,container)) + { + cellsUsed_ = new CCArrayForObjectSorting(); + cellsFreed_ = new CCArrayForObjectSorting(); + indices_ = new std::set(); + tDelegate_ = NULL; + vordering_ = CCTableViewFillBottomUp; + this->setDirection(CCScrollViewDirectionVertical); + + CCScrollView::setDelegate(this); + return true; + } + return false; +} + +CCTableView::CCTableView() +: indices_(NULL) +, cellsUsed_(NULL) +, cellsFreed_(NULL) +, dataSource_(NULL) +, tDelegate_(NULL) +, m_eOldDirection(CCScrollViewDirectionNone) +{ + +} + +CCTableView::~CCTableView() +{ + CC_SAFE_DELETE(indices_); + CC_SAFE_RELEASE(cellsUsed_); + CC_SAFE_RELEASE(cellsFreed_); +} + +void CCTableView::setVerticalFillOrder(CCTableViewVerticalFillOrder fillOrder) +{ + if (vordering_ != fillOrder) { + vordering_ = fillOrder; + if (cellsUsed_->count() > 0) { + this->reloadData(); + } + } +} + +CCTableViewVerticalFillOrder CCTableView::getVerticalFillOrder() +{ + return vordering_; +} + +void CCTableView::reloadData() +{ + CCObject* pObj = NULL; + CCARRAY_FOREACH(cellsUsed_, pObj) + { + CCTableViewCell* cell = (CCTableViewCell*)pObj; + cellsFreed_->addObject(cell); + cell->reset(); + if (cell->getParent() == this->getContainer()) + { + this->getContainer()->removeChild(cell, true); + } + } + + indices_->clear(); + cellsUsed_->release(); + cellsUsed_ = new CCArrayForObjectSorting(); + + this->_updateContentSize(); + if (dataSource_->numberOfCellsInTableView(this) > 0) + { + this->scrollViewDidScroll(this); + } +} + +CCTableViewCell *CCTableView::cellAtIndex(unsigned int idx) +{ + return this->_cellWithIndex(idx); +} + +void CCTableView::updateCellAtIndex(unsigned int idx) +{ + if (idx == CC_INVALID_INDEX || idx > dataSource_->numberOfCellsInTableView(this)-1) + { + return; + } + + CCTableViewCell *cell; + + cell = this->_cellWithIndex(idx); + if (cell) { + this->_moveCellOutOfSight(cell); + } + cell = dataSource_->tableCellAtIndex(this, idx); + this->_setIndexForCell(idx, cell); + this->_addCellIfNecessary(cell); +} + +void CCTableView::insertCellAtIndex(unsigned int idx) +{ + if (idx == CC_INVALID_INDEX || idx > dataSource_->numberOfCellsInTableView(this)-1) { + return; + } + CCTableViewCell *cell; + int newIdx; + + cell = (CCTableViewCell*)cellsUsed_->objectWithObjectID(idx); + if (cell) + { + newIdx = cellsUsed_->indexOfSortedObject(cell); + for (unsigned int i=newIdx; icount(); i++) + { + cell = (CCTableViewCell*)cellsUsed_->objectAtIndex(i); + this->_setIndexForCell(cell->getIdx()+1, cell); + } + } + + // [indices_ shiftIndexesStartingAtIndex:idx by:1]; + + //insert a new cell + cell = dataSource_->tableCellAtIndex(this, idx); + this->_setIndexForCell(idx, cell); + this->_addCellIfNecessary(cell); + + this->_updateContentSize(); +} + +void CCTableView::removeCellAtIndex(unsigned int idx) +{ + if (idx == CC_INVALID_INDEX || idx > dataSource_->numberOfCellsInTableView(this)-1) { + return; + } + + CCTableViewCell *cell; + unsigned int newIdx; + + cell = this->_cellWithIndex(idx); + if (!cell) { + return; + } + + newIdx = cellsUsed_->indexOfSortedObject(cell); + + //remove first + this->_moveCellOutOfSight(cell); + + indices_->erase(idx); +// [indices_ shiftIndexesStartingAtIndex:idx+1 by:-1]; + for (unsigned int i=cellsUsed_->count()-1; i > newIdx; i--) { + cell = (CCTableViewCell*)cellsUsed_->objectAtIndex(i); + this->_setIndexForCell(cell->getIdx()-1, cell); + } +} + +CCTableViewCell *CCTableView::dequeueCell() +{ + CCTableViewCell *cell; + + if (cellsFreed_->count() == 0) { + cell = NULL; + } else { + cell = (CCTableViewCell*)cellsFreed_->objectAtIndex(0); + cell->retain(); + cellsFreed_->removeObjectAtIndex(0); + cell->autorelease(); + } + return cell; +} + +void CCTableView::_addCellIfNecessary(CCTableViewCell * cell) +{ + if (cell->getParent() != this->getContainer()) + { + this->getContainer()->addChild(cell); + } + cellsUsed_->insertSortedObject(cell); + indices_->insert(cell->getIdx()); + // [indices_ addIndex:cell.idx]; +} + +void CCTableView::_updateContentSize() +{ + CCSize size, cellSize; + unsigned int cellCount; + + cellSize = dataSource_->cellSizeForTable(this); + cellCount = dataSource_->numberOfCellsInTableView(this); + + switch (this->getDirection()) + { + case CCScrollViewDirectionHorizontal: + size = CCSizeMake(cellCount * cellSize.width, cellSize.height); + break; + default: + size = CCSizeMake(cellSize.width, cellCount * cellSize.height); + break; + } + this->setContentSize(size); + + if (m_eOldDirection != m_eDirection) + { + if (m_eDirection == CCScrollViewDirectionHorizontal) + { + this->setContentOffset(ccp(0,0)); + } + else + { + this->setContentOffset(ccp(0,this->minContainerOffset().y)); + } + m_eOldDirection = m_eDirection; + } + +} + +CCPoint CCTableView::_offsetFromIndex(unsigned int index) +{ + CCPoint offset = this->__offsetFromIndex(index); + + const CCSize cellSize = dataSource_->cellSizeForTable(this); + if (vordering_ == CCTableViewFillTopDown) { + offset.y = this->getContainer()->getContentSize().height - offset.y - cellSize.height; + } + return offset; +} + +CCPoint CCTableView::__offsetFromIndex(unsigned int index) +{ + CCPoint offset; + CCSize cellSize; + + cellSize = dataSource_->cellSizeForTable(this); + switch (this->getDirection()) { + case CCScrollViewDirectionHorizontal: + offset = ccp(cellSize.width * index, 0.0f); + break; + default: + offset = ccp(0.0f, cellSize.height * index); + break; + } + + return offset; +} + +unsigned int CCTableView::_indexFromOffset(CCPoint offset) +{ + int index = 0; + const int maxIdx = dataSource_->numberOfCellsInTableView(this)-1; + + const CCSize cellSize = dataSource_->cellSizeForTable(this); + if (vordering_ == CCTableViewFillTopDown) { + offset.y = this->getContainer()->getContentSize().height - offset.y - cellSize.height; + } + index = MAX(0, this->__indexFromOffset(offset)); + index = MIN(index, maxIdx); + + return index; +} + +int CCTableView::__indexFromOffset(CCPoint offset) +{ + int index = 0; + CCSize cellSize; + + cellSize = dataSource_->cellSizeForTable(this); + + switch (this->getDirection()) { + case CCScrollViewDirectionHorizontal: + index = offset.x/cellSize.width; + break; + default: + index = offset.y/cellSize.height; + break; + } + + return index; +} + +CCTableViewCell* CCTableView::_cellWithIndex(unsigned int cellIndex) +{ + CCTableViewCell *found; + + found = NULL; + +// if ([indices_ containsIndex:cellIndex]) + if (indices_->find(cellIndex) != indices_->end()) + { + found = (CCTableViewCell *)cellsUsed_->objectWithObjectID(cellIndex); + } + + return found; +} + +void CCTableView::_moveCellOutOfSight(CCTableViewCell *cell) +{ + cellsFreed_->addObject(cell); + cellsUsed_->removeSortedObject(cell); + indices_->erase(cell->getIdx()); + // [indices_ removeIndex:cell.idx]; + cell->reset(); + if (cell->getParent() == this->getContainer()) { + this->getContainer()->removeChild(cell, true);; + } +} + +void CCTableView::_setIndexForCell(unsigned int index, CCTableViewCell *cell) +{ + cell->setAnchorPoint(ccp(0.0f, 0.0f)); + cell->setPosition(this->_offsetFromIndex(index)); + cell->setIdx(index); +} + +void CCTableView::scrollViewDidScroll(CCScrollView* view) +{ + CCLOG("container pos x = %f, y = %f", getContainer()->getPosition().x, getContainer()->getPosition().y); + unsigned int startIdx = 0, endIdx = 0, idx = 0, maxIdx = 0; + CCPoint offset; + + offset = ccpMult(this->getContentOffset(), -1); + maxIdx = MAX(dataSource_->numberOfCellsInTableView(this)-1, 0); + + const CCSize cellSize = dataSource_->cellSizeForTable(this); + + if (vordering_ == CCTableViewFillTopDown) { + offset.y = offset.y + m_tViewSize.height/this->getContainer()->getScaleY() - cellSize.height; + } + startIdx = this->_indexFromOffset(offset); + + if (vordering_ == CCTableViewFillTopDown) + { + offset.y -= m_tViewSize.height/this->getContainer()->getScaleY(); + } + else + { + offset.y += m_tViewSize.height/this->getContainer()->getScaleY(); + } + offset.x += m_tViewSize.width/this->getContainer()->getScaleX(); + + endIdx = this->_indexFromOffset(offset); + + CCObject* pObj; + int i = 0; + CCARRAY_FOREACH(cellsUsed_, pObj) + { + CCTableViewCell* pCell = (CCTableViewCell*)pObj; + CCLog("cells Used index %d, value = %d", i, pCell->getIdx()); + i++; + } + CCLog("---------------------------------------"); + i = 0; + CCARRAY_FOREACH(cellsFreed_, pObj) + { + CCTableViewCell* pCell = (CCTableViewCell*)pObj; + CCLog("cells freed index %d, value = %d", i, pCell->getIdx()); + i++; + } + CCLog("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); + if (cellsUsed_->count() > 0) + { + CCTableViewCell* cell = (CCTableViewCell*)cellsUsed_->objectAtIndex(0); + + idx = cell->getIdx(); + while(idx _moveCellOutOfSight(cell); + if (cellsUsed_->count() > 0) { + cell = (CCTableViewCell*)cellsUsed_->objectAtIndex(0); + idx = cell->getIdx(); + } else { + break; + } + CCLog("idx 0 = %d", idx); + } + } + if (cellsUsed_->count() > 0) + { + CCTableViewCell *cell = (CCTableViewCell*)cellsUsed_->lastObject(); + idx = cell->getIdx(); + + while(idx <= maxIdx && idx > endIdx) + { + this->_moveCellOutOfSight(cell); + if (cellsUsed_->count() > 0) + { + cell = (CCTableViewCell*)cellsUsed_->lastObject(); + idx = cell->getIdx(); + + } else { + break; + } + CCLog("idx 1 = %d, maxIdx = %d, endIdx = %d", idx, maxIdx, endIdx); + } + } + + for (unsigned int i=startIdx; i <= endIdx; i++) + { + //if ([indices_ containsIndex:i]) + if (indices_->find(i) != indices_->end()) + { + continue; + } + this->updateCellAtIndex(i); + } +} + +void CCTableView::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent) +{ + if (!this->isVisible()) { + return; + } + if (m_pTouches->count() == 1 && !this->isTouchMoved()) { + unsigned int index; + CCTableViewCell *cell; + CCPoint point; + + point = this->getContainer()->convertTouchToNodeSpace(pTouch); + if (vordering_ == CCTableViewFillTopDown) { + CCSize cellSize = dataSource_->cellSizeForTable(this); + point.y -= cellSize.height; + } + index = this->_indexFromOffset(point); + cell = this->_cellWithIndex(index); + + if (cell) { + tDelegate_->table_cellTouched(this, cell); + } + } + CCScrollView::ccTouchEnded(pTouch, pEvent); +} + +NS_CC_EXT_END diff --git a/extensions/GUI/CCScrollView/CCTableView.h b/extensions/GUI/CCScrollView/CCTableView.h new file mode 100644 index 0000000000..5b19efb655 --- /dev/null +++ b/extensions/GUI/CCScrollView/CCTableView.h @@ -0,0 +1,231 @@ +// +// SWTableView.h +// SWGameLib +// +// Copyright (c) 2012 cocos2d-x.org +// Copyright (c) 2010 Sangwoo Im +// +// 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. +// +// +// Created by Sangwoo Im on 6/3/10. +// Copyright 2010 Sangwoo Im. All rights reserved. +// + +#ifndef __CCTABLEVIEW_H__ +#define __CCTABLEVIEW_H__ + +#include "CCScrollView.h" +#include "CCTableViewCell.h" + +#include + +NS_CC_EXT_BEGIN + +class CCTableView; +class CCArrayForObjectSorting; + +typedef enum { + CCTableViewFillTopDown, + CCTableViewFillBottomUp +} CCTableViewVerticalFillOrder; + +/** + * Sole purpose of this delegate is to single touch event in this version. + */ +class CCTableViewDelegate : public CCScrollViewDelegate +{ +public: + /** + * Delegate to respond touch event + * + * @param table table contains the given cell + * @param cell cell that is touched + */ + virtual void table_cellTouched(CCTableView* table, CCTableViewCell* cell) = 0; +}; + + +/** + * Data source that governs table backend data. + */ +class CCTableViewDataSource +{ +public: + /** + * cell height for a given table. + * + * @param table table to hold the instances of Class + * @return cell size + */ + virtual CCSize cellSizeForTable(CCTableView *table) = 0; + /** + * a cell instance at a given index + * + * @param idx index to search for a cell + * @return cell found at idx + */ + virtual CCTableViewCell* tableCellAtIndex(CCTableView *table, unsigned int idx) = 0; + /** + * Returns number of cells in a given table view. + * + * @return number of cells + */ + virtual unsigned int numberOfCellsInTableView(CCTableView *table) = 0; + +}; + + +/** + * UITableView counterpart for cocos2d for iphone. + * + * this is a very basic, minimal implementation to bring UITableView-like component into cocos2d world. + * + */ +class CCTableView : public CCScrollView, public CCScrollViewDelegate +{ +public: + CCTableView(); + virtual ~CCTableView(); + /** + * vertical direction of cell filling + */ + CCTableViewVerticalFillOrder vordering_; + + /** + * data source + */ + CCTableViewDataSource* getDataSource() { return dataSource_; } + void setDataSource(CCTableViewDataSource* source) { dataSource_ = source; } + /** + * delegate + */ + CCTableViewDelegate* getDelegate() { return tDelegate_; } + void setDelegate(CCTableViewDelegate* pDelegate) { tDelegate_ = pDelegate; } + + /** + * determines how cell is ordered and filled in the view. + */ + void setVerticalFillOrder(CCTableViewVerticalFillOrder order); + CCTableViewVerticalFillOrder getVerticalFillOrder(); + + /** + * An intialized table view object + * + * @param dataSource data source + * @param size view size + * @return table view + */ + static CCTableView* viewWithDataSource(CCTableViewDataSource* dataSource, CCSize size); + /** + * An initialized table view object + * + * @param dataSource data source; + * @param size view size + * @param container parent object for cells + * @return table view + */ + static CCTableView* viewWithDataSource(CCTableViewDataSource* dataSource, CCSize size, CCNode *container); + + bool initWithViewSize(CCSize size, CCNode* container = NULL); + /** + * Updates the content of the cell at a given index. + * + * @param idx index to find a cell + */ + void updateCellAtIndex(unsigned int idx); + /** + * Inserts a new cell at a given index + * + * @param idx location to insert + */ + void insertCellAtIndex(unsigned int idx); + /** + * Removes a cell at a given index + * + * @param idx index to find a cell + */ + void removeCellAtIndex(unsigned int idx); + /** + * reloads data from data source. the view will be refreshed. + */ + void reloadData(); + /** + * Dequeues a free cell if available. nil if not. + * + * @return free cell + */ + CCTableViewCell *dequeueCell(); + + /** + * Returns an existing cell at a given index. Returns nil if a cell is nonexistent at the moment of query. + * + * @param idx index + * @return a cell at a given index + */ + CCTableViewCell *cellAtIndex(unsigned int idx); + + + virtual void scrollViewDidScroll(CCScrollView* view); + virtual void scrollViewDidZoom(CCScrollView* view) {} + virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent); + +protected: + /** + * index set to query the indexes of the cells used. + */ + std::set* indices_; + //NSMutableIndexSet *indices_; + /** + * cells that are currently in the table + */ + CCArrayForObjectSorting *cellsUsed_; + /** + * free list of cells + */ + CCArrayForObjectSorting *cellsFreed_; + /** + * weak link to the data source object + */ + CCTableViewDataSource* dataSource_; + /** + * weak link to the delegate object + */ + CCTableViewDelegate* tDelegate_; + + CCScrollViewDirection m_eOldDirection; + + int __indexFromOffset(CCPoint offset); + unsigned int _indexFromOffset(CCPoint offset); + CCPoint __offsetFromIndex(unsigned int index); + CCPoint _offsetFromIndex(unsigned int index); + void _updateContentSize(); + + CCTableViewCell *_cellWithIndex(unsigned int cellIndex); + void _moveCellOutOfSight(CCTableViewCell *cell); + void _setIndexForCell(unsigned int index, CCTableViewCell *cell); + void _addCellIfNecessary(CCTableViewCell * cell); + +}; + + +NS_CC_EXT_END + +#endif /* __CCTABLEVIEW_H__ */ + diff --git a/extensions/GUI/CCScrollView/CCTableViewCell.cpp b/extensions/GUI/CCScrollView/CCTableViewCell.cpp new file mode 100644 index 0000000000..304e7e1c73 --- /dev/null +++ b/extensions/GUI/CCScrollView/CCTableViewCell.cpp @@ -0,0 +1,59 @@ +// +// SWTableViewCell.m +// SWGameLib +// +// Copyright (c) 2012 cocos2d-x.org +// Copyright (c) 2010 Sangwoo Im +// +// 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. +// +// Created by Sangwoo Im on 6/3/10. +// Copyright 2010 Sangwoo Im. All rights reserved. +// + +#include "CCTableViewCell.h" + +NS_CC_EXT_BEGIN + +void CCTableViewCell::reset() +{ + m_uIdx = CC_INVALID_INDEX; +} + +void CCTableViewCell::setObjectID(unsigned int uIdx) +{ + m_uIdx = uIdx; +} + +unsigned int CCTableViewCell::getObjectID() +{ + return m_uIdx; +} + +unsigned int CCTableViewCell::getIdx() +{ + return m_uIdx; +} + +void CCTableViewCell::setIdx(unsigned int uIdx) +{ + m_uIdx = uIdx; +} + +NS_CC_EXT_END diff --git a/extensions/GUI/CCScrollView/CCTableViewCell.h b/extensions/GUI/CCScrollView/CCTableViewCell.h new file mode 100644 index 0000000000..b095a4da27 --- /dev/null +++ b/extensions/GUI/CCScrollView/CCTableViewCell.h @@ -0,0 +1,63 @@ +// +// SWTableViewCell.h +// SWGameLib +// +// Copyright (c) 2012 cocos2d-x.org +// Copyright (c) 2010 Sangwoo Im +// +// 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. +// +// Created by Sangwoo Im on 6/3/10. +// Copyright 2010 Sangwoo Im. All rights reserved. +// + +#ifndef __CCTABLEVIEWCELL_H__ +#define __CCTABLEVIEWCELL_H__ + +#include "base_nodes/CCNode.h" +#include "CCSorting.h" + +NS_CC_EXT_BEGIN + +/** + * Abstract class for SWTableView cell node + */ +class CCTableViewCell: public CCNode, public CCSortableObject +{ +public: + CCTableViewCell() {} + /** + * The index used internally by SWTableView and its subclasses + */ + unsigned int getIdx(); + void setIdx(unsigned int uIdx); + /** + * Cleans up any resources linked to this cell and resets idx property. + */ + void reset(); + + void setObjectID(unsigned int uIdx); + unsigned int getObjectID(); +private: + unsigned int m_uIdx; +}; + +NS_CC_EXT_END + +#endif /* __CCTABLEVIEWCELL_H__ */ diff --git a/extensions/cocos-ext.h b/extensions/cocos-ext.h index ac03fefe0b..8842b1ceeb 100644 --- a/extensions/cocos-ext.h +++ b/extensions/cocos-ext.h @@ -27,6 +27,7 @@ #include "GUI/CCControlExtension/CCControlExtensions.h" #include "GUI/CCScrollView/CCScrollView.h" +#include "GUI/CCScrollView/CCTableView.h" #include "GUI/CCEditBox/CCEditBox.h" #include "network/HttpRequest.h" diff --git a/extensions/proj.win32/libExtensions.vcproj b/extensions/proj.win32/libExtensions.vcproj index 81df3bbfce..36ad9bc313 100644 --- a/extensions/proj.win32/libExtensions.vcproj +++ b/extensions/proj.win32/libExtensions.vcproj @@ -421,6 +421,30 @@ RelativePath="..\GUI\CCScrollView\CCScrollView.h" > + + + + + + + + + + + + addChild(pLayer); + CCDirector::sharedDirector()->replaceScene(pScene); +} + +// on "init" you need to initialize your instance +bool TableViewTestLayer::init() +{ + if ( !CCLayer::init() ) + { + return false; + } + + CCSize winSize = CCDirector::sharedDirector()->getWinSize(); + + CCTableView* tableView = CCTableView::viewWithDataSource(this, CCSizeMake(250, 60)); + tableView->setDirection(CCScrollViewDirectionHorizontal); + tableView->setPosition(ccp(20,winSize.height/2-30)); + tableView->setDelegate(this); + this->addChild(tableView); + tableView->reloadData(); + + tableView = CCTableView::viewWithDataSource(this, CCSizeMake(60, 280)); + tableView->setDirection(CCScrollViewDirectionVertical); + tableView->setPosition(ccp(winSize.width-150,winSize.height/2-120)); + tableView->setDelegate(this); + tableView->setVerticalFillOrder(CCTableViewFillTopDown); + this->addChild(tableView); + tableView->reloadData(); + + // Back Menu + CCMenuItemFont *itemBack = CCMenuItemFont::create("Back", this, menu_selector(TableViewTestLayer::toExtensionsMainLayer)); + itemBack->setPosition(ccp(winSize.width - 50, 25)); + CCMenu *menuBack = CCMenu::create(itemBack, NULL); + menuBack->setPosition(CCPointZero); + addChild(menuBack); + + return true; +} + +void TableViewTestLayer::toExtensionsMainLayer(cocos2d::CCObject *sender) +{ + ExtensionsTestScene *pScene = new ExtensionsTestScene(); + pScene->runThisTest(); + pScene->release(); +} + +void TableViewTestLayer::table_cellTouched(CCTableView* table, CCTableViewCell* cell) +{ + CCLOG("cell touched at index: %i", cell->getIdx()); +} + +CCSize TableViewTestLayer::cellSizeForTable(CCTableView *table) +{ + return CCSizeMake(60, 60); +} + +CCTableViewCell* TableViewTestLayer::tableCellAtIndex(CCTableView *table, unsigned int idx) +{ + CCString *string = CCString::createWithFormat("%d", idx); + CCTableViewCell *cell = table->dequeueCell(); + if (!cell) { + cell = new CustomTableViewCell(); + cell->autorelease(); + CCSprite *sprite = CCSprite::create("Images/Icon.png"); + sprite->setAnchorPoint(CCPointZero); + sprite->setPosition(ccp(0, 0)); + cell->addChild(sprite); + + CCLabelTTF *label = CCLabelTTF::create(string->getCString(), "Helvetica", 20.0); + label->setPosition(CCPointZero); + label->setAnchorPoint(CCPointZero); + label->setTag(123); + cell->addChild(label); + } + else + { + CCLabelTTF *label = (CCLabelTTF*)cell->getChildByTag(123); + label->setString(string->getCString()); + } + + + return cell; +} + +unsigned int TableViewTestLayer::numberOfCellsInTableView(CCTableView *table) +{ + return 20; +} diff --git a/samples/TestCpp/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.h b/samples/TestCpp/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.h new file mode 100644 index 0000000000..3573f75744 --- /dev/null +++ b/samples/TestCpp/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.h @@ -0,0 +1,26 @@ +#ifndef __TABLEVIEWTESTSCENE_H__ +#define __TABLEVIEWTESTSCENE_H__ + +#include "cocos2d.h" +#include "cocos-ext.h" + +void runTableViewTest(); + +class TableViewTestLayer : public cocos2d::CCLayer, public cocos2d::extension::CCTableViewDataSource, public cocos2d::extension::CCTableViewDelegate +{ +public: + virtual bool init(); + + void toExtensionsMainLayer(cocos2d::CCObject *sender); + + CREATE_FUNC(TableViewTestLayer); + + virtual void scrollViewDidScroll(cocos2d::extension::CCScrollView* view) {}; + virtual void scrollViewDidZoom(cocos2d::extension::CCScrollView* view) {} + virtual void table_cellTouched(cocos2d::extension::CCTableView* table, cocos2d::extension::CCTableViewCell* cell); + virtual cocos2d::CCSize cellSizeForTable(cocos2d::extension::CCTableView *table); + virtual cocos2d::extension::CCTableViewCell* tableCellAtIndex(cocos2d::extension::CCTableView *table, unsigned int idx); + virtual unsigned int numberOfCellsInTableView(cocos2d::extension::CCTableView *table); +}; + +#endif // __TABLEVIEWTESTSCENE_H__ diff --git a/samples/TestCpp/proj.win32/TestCpp.vcproj b/samples/TestCpp/proj.win32/TestCpp.vcproj index 0ac12a7742..f664a59cc3 100644 --- a/samples/TestCpp/proj.win32/TestCpp.vcproj +++ b/samples/TestCpp/proj.win32/TestCpp.vcproj @@ -1023,6 +1023,26 @@ > + + + + + + + + + + Date: Sun, 9 Sep 2012 22:37:32 +0800 Subject: [PATCH 08/15] Reverted one line code. --- extensions/CCBReader/CCScrollViewLoader.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/extensions/CCBReader/CCScrollViewLoader.cpp b/extensions/CCBReader/CCScrollViewLoader.cpp index b5c4a8830e..b61622dd1c 100644 --- a/extensions/CCBReader/CCScrollViewLoader.cpp +++ b/extensions/CCBReader/CCScrollViewLoader.cpp @@ -31,7 +31,6 @@ void CCScrollViewLoader::onHandlePropTypeCheck(CCNode * pNode, CCNode * pParent, void CCScrollViewLoader::onHandlePropTypeCCBFile(CCNode * pNode, CCNode * pParent, CCString * pPropertyName, CCNode * pCCBFileNode, CCBReader * pCCBReader) { if(pPropertyName->compare(PROPERTY_CONTAINER) == 0) { ((CCScrollView *)pNode)->setContainer(pCCBFileNode); - ((CCScrollView *)pNode)->setViewSize(CCSizeMake(240, 320)); } else { CCNodeLoader::onHandlePropTypeCCBFile(pNode, pParent, pPropertyName, pCCBFileNode, pCCBReader); } From 554b1709c34a5c41cc3a1dbaddb4748c4a6ca551 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sun, 9 Sep 2012 22:46:31 +0800 Subject: [PATCH 09/15] issue #1458: Adding CCScrollView::updateInset. --- extensions/CCBReader/CCScrollViewLoader.cpp | 1 + extensions/GUI/CCScrollView/CCScrollView.cpp | 11 +++++++++-- extensions/GUI/CCScrollView/CCScrollView.h | 1 + 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/extensions/CCBReader/CCScrollViewLoader.cpp b/extensions/CCBReader/CCScrollViewLoader.cpp index b61622dd1c..387b01ada8 100644 --- a/extensions/CCBReader/CCScrollViewLoader.cpp +++ b/extensions/CCBReader/CCScrollViewLoader.cpp @@ -31,6 +31,7 @@ void CCScrollViewLoader::onHandlePropTypeCheck(CCNode * pNode, CCNode * pParent, void CCScrollViewLoader::onHandlePropTypeCCBFile(CCNode * pNode, CCNode * pParent, CCString * pPropertyName, CCNode * pCCBFileNode, CCBReader * pCCBReader) { if(pPropertyName->compare(PROPERTY_CONTAINER) == 0) { ((CCScrollView *)pNode)->setContainer(pCCBFileNode); + ((CCScrollView *)pNode)->updateInset(); } else { CCNodeLoader::onHandlePropTypeCCBFile(pNode, pParent, pPropertyName, pCCBFileNode, pCCBReader); } diff --git a/extensions/GUI/CCScrollView/CCScrollView.cpp b/extensions/GUI/CCScrollView/CCScrollView.cpp index 45f1c0bef4..587cae2d5b 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.cpp +++ b/extensions/GUI/CCScrollView/CCScrollView.cpp @@ -447,19 +447,26 @@ const CCSize & CCScrollView::getContentSize() void CCScrollView::setContentSize(const CCSize & size) { - // this->setViewSize(size); if (this->getContainer() != NULL) { this->getContainer()->setContentSize(size); + this->updateInset(); + } +} +void CCScrollView::updateInset() +{ + if (this->getContainer() != NULL) + { m_fMaxInset = this->maxContainerOffset(); m_fMaxInset = ccp(m_fMaxInset.x + m_tViewSize.width * INSET_RATIO, m_fMaxInset.y + m_tViewSize.height * INSET_RATIO); m_fMinInset = this->minContainerOffset(); m_fMinInset = ccp(m_fMinInset.x - m_tViewSize.width * INSET_RATIO, m_fMinInset.y - m_tViewSize.height * INSET_RATIO); - } + } } + /** * make sure all children go to the container */ diff --git a/extensions/GUI/CCScrollView/CCScrollView.h b/extensions/GUI/CCScrollView/CCScrollView.h index f5e98d5ac7..a156d580cd 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.h +++ b/extensions/GUI/CCScrollView/CCScrollView.h @@ -211,6 +211,7 @@ public: virtual void setContentSize(const CCSize & size); virtual const CCSize & getContentSize(); + void updateInset(); /** * Determines whether it clips its children or not. */ From 1460f4e42f1426801e9473d15165dbb79140920b Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 10 Sep 2012 13:39:12 +0800 Subject: [PATCH 10/15] issue #1458: Updated project configuration for all platforms. CCTableView::viewWithSource --> CCTableView::create, adding TableViewTest. --- cocos2dx/proj.linux/Makefile | 3 + .../project.pbxproj.REMOVED.git-id | 2 +- extensions/Android.mk | 3 + extensions/GUI/CCScrollView/CCScrollView.cpp | 21 +- extensions/GUI/CCScrollView/CCScrollView.h | 8 +- extensions/GUI/CCScrollView/CCTableView.cpp | 191 +++++++++--------- extensions/GUI/CCScrollView/CCTableView.h | 67 +++--- samples/TestCpp/Android.mk | 2 + .../TableViewTest/TableViewTestScene.cpp | 12 +- .../TableViewTest/TableViewTestScene.h | 2 +- .../project.pbxproj.REMOVED.git-id | 2 +- .../project.pbxproj.REMOVED.git-id | 2 +- 12 files changed, 166 insertions(+), 149 deletions(-) diff --git a/cocos2dx/proj.linux/Makefile b/cocos2dx/proj.linux/Makefile index 4129383b12..b5d02bbe8e 100644 --- a/cocos2dx/proj.linux/Makefile +++ b/cocos2dx/proj.linux/Makefile @@ -145,6 +145,9 @@ OBJECTS = ../actions/CCAction.o \ ../../extensions/CCBReader/CCSpriteLoader.o \ ../../extensions/CCBReader/CCLayerLoader.o \ ../../extensions/GUI/CCScrollView/CCScrollView.o \ + ../../extensions/GUI/CCScrollView/CCSorting.o \ + ../../extensions/GUI/CCScrollView/CCTableView.o \ + ../../extensions/GUI/CCScrollView/CCTableViewCell.o \ ../../extensions/GUI/CCControlExtension/CCControlButton.o \ ../../extensions/GUI/CCControlExtension/CCControlColourPicker.o \ ../../extensions/GUI/CCControlExtension/CCControl.o \ diff --git a/cocos2dx/proj.mac/cocos2dx.xcodeproj/project.pbxproj.REMOVED.git-id b/cocos2dx/proj.mac/cocos2dx.xcodeproj/project.pbxproj.REMOVED.git-id index 086c31b353..fc183b1527 100644 --- a/cocos2dx/proj.mac/cocos2dx.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/cocos2dx/proj.mac/cocos2dx.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -e78f546d2199a6e37906db590c8a47033f3febd8 \ No newline at end of file +6dfcf25474cd85fc1f77e3578c3b54357cdc0446 \ No newline at end of file diff --git a/extensions/Android.mk b/extensions/Android.mk index 5df1514fad..4df756463a 100644 --- a/extensions/Android.mk +++ b/extensions/Android.mk @@ -35,6 +35,9 @@ GUI/CCControlExtension/CCMenuPassive.cpp \ GUI/CCControlExtension/CCScale9Sprite.cpp \ GUI/CCControlExtension/CCSpacer.cpp \ GUI/CCScrollView/CCScrollView.cpp \ +GUI/CCScrollView/CCTableView.cpp \ +GUI/CCScrollView/CCTableViewCell.cpp \ +GUI/CCScrollView/CCSorting.cpp \ GUI/CCEditBox/CCEditBox.cpp \ GUI/CCEditBox/CCEditBoxImplAndroid.cpp \ network/HttpClient.cpp diff --git a/extensions/GUI/CCScrollView/CCScrollView.cpp b/extensions/GUI/CCScrollView/CCScrollView.cpp index 587cae2d5b..603cbab4a6 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.cpp +++ b/extensions/GUI/CCScrollView/CCScrollView.cpp @@ -37,6 +37,7 @@ #include "CCDirector.h" #include "kazmath/GL/matrix.h" #include "touch_dispatcher/CCTouch.h" +#include "CCEGLView.h" NS_CC_EXT_BEGIN @@ -53,7 +54,7 @@ CCScrollView::CCScrollView() , m_pDelegate(NULL) , m_bDragging(false) , m_bBounceable(false) -, m_eDirection(CCScrollViewDirectionBoth) +, m_eDirection(kCCScrollViewDirectionBoth) , m_bClippingToBounds(false) , m_pContainer(NULL) , m_bTouchMoved(false) @@ -130,7 +131,7 @@ bool CCScrollView::initWithViewSize(CCSize size, CCNode *container/* = NULL*/) m_bBounceable = true; m_bClippingToBounds = true; //m_pContainer->setContentSize(CCSizeZero); - m_eDirection = CCScrollViewDirectionBoth; + m_eDirection = kCCScrollViewDirectionBoth; m_pContainer->setPosition(ccp(0.0f, 0.0f)); m_fTouchLength = 0.0f; @@ -347,13 +348,13 @@ void CCScrollView::relocateContainer(bool animated) newX = oldPoint.x; newY = oldPoint.y; - if (m_eDirection == CCScrollViewDirectionBoth || m_eDirection == CCScrollViewDirectionHorizontal) + if (m_eDirection == kCCScrollViewDirectionBoth || m_eDirection == kCCScrollViewDirectionHorizontal) { newX = MIN(newX, max.x); newX = MAX(newX, min.x); } - if (m_eDirection == CCScrollViewDirectionBoth || m_eDirection == CCScrollViewDirectionVertical) + if (m_eDirection == kCCScrollViewDirectionBoth || m_eDirection == kCCScrollViewDirectionVertical) { newY = MIN(newY, max.y); newY = MAX(newY, min.y); @@ -504,10 +505,10 @@ void CCScrollView::beforeDraw() glEnable(GL_SCISSOR_TEST); float s = this->getScale(); - CCDirector *director = CCDirector::sharedDirector(); - s *= director->getContentScaleFactor(); - - glScissor((GLint)screenPos.x, (GLint)screenPos.y, (GLsizei)(m_tViewSize.width*s), (GLsizei)(m_tViewSize.height*s)); +// CCDirector *director = CCDirector::sharedDirector(); +// s *= director->getContentScaleFactor(); + CCEGLView::sharedOpenGLView()->setScissorInPoints(screenPos.x*s, screenPos.y*s, m_tViewSize.width*s, m_tViewSize.height*s); + //glScissor((GLint)screenPos.x, (GLint)screenPos.y, (GLsizei)(m_tViewSize.width*s), (GLsizei)(m_tViewSize.height*s)); } } @@ -657,10 +658,10 @@ void CCScrollView::ccTouchMoved(CCTouch* touch, CCEvent* event) { switch (m_eDirection) { - case CCScrollViewDirectionVertical: + case kCCScrollViewDirectionVertical: moveDistance = ccp(0.0f, moveDistance.y); break; - case CCScrollViewDirectionHorizontal: + case kCCScrollViewDirectionHorizontal: moveDistance = ccp(moveDistance.x, 0.0f); break; default: diff --git a/extensions/GUI/CCScrollView/CCScrollView.h b/extensions/GUI/CCScrollView/CCScrollView.h index a156d580cd..179e51d34a 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.h +++ b/extensions/GUI/CCScrollView/CCScrollView.h @@ -42,10 +42,10 @@ NS_CC_EXT_BEGIN */ typedef enum { - CCScrollViewDirectionNone = -1, - CCScrollViewDirectionHorizontal = 0, - CCScrollViewDirectionVertical, - CCScrollViewDirectionBoth + kCCScrollViewDirectionNone = -1, + kCCScrollViewDirectionHorizontal = 0, + kCCScrollViewDirectionVertical, + kCCScrollViewDirectionBoth } CCScrollViewDirection; class CCScrollView; diff --git a/extensions/GUI/CCScrollView/CCTableView.cpp b/extensions/GUI/CCScrollView/CCTableView.cpp index f520511dd0..c92da38e3d 100644 --- a/extensions/GUI/CCScrollView/CCTableView.cpp +++ b/extensions/GUI/CCScrollView/CCTableView.cpp @@ -37,12 +37,12 @@ NS_CC_EXT_BEGIN -CCTableView* CCTableView::viewWithDataSource(CCTableViewDataSource* dataSource, CCSize size) +CCTableView* CCTableView::create(CCTableViewDataSource* dataSource, CCSize size) { - return CCTableView::viewWithDataSource(dataSource, size, NULL); + return CCTableView::create(dataSource, size, NULL); } -CCTableView* CCTableView::viewWithDataSource(CCTableViewDataSource* dataSource, CCSize size, CCNode *container) +CCTableView* CCTableView::create(CCTableViewDataSource* dataSource, CCSize size, CCNode *container) { CCTableView *table = new CCTableView(); table->initWithViewSize(size, container); @@ -57,12 +57,12 @@ bool CCTableView::initWithViewSize(CCSize size, CCNode* container/* = NULL*/) { if (CCScrollView::initWithViewSize(size,container)) { - cellsUsed_ = new CCArrayForObjectSorting(); - cellsFreed_ = new CCArrayForObjectSorting(); - indices_ = new std::set(); - tDelegate_ = NULL; - vordering_ = CCTableViewFillBottomUp; - this->setDirection(CCScrollViewDirectionVertical); + m_pCellsUsed = new CCArrayForObjectSorting(); + m_pCellsFreed = new CCArrayForObjectSorting(); + m_pIndices = new std::set(); + m_pTableViewDelegate = NULL; + m_eVordering = kCCTableViewFillBottomUp; + this->setDirection(kCCScrollViewDirectionVertical); CCScrollView::setDelegate(this); return true; @@ -71,28 +71,28 @@ bool CCTableView::initWithViewSize(CCSize size, CCNode* container/* = NULL*/) } CCTableView::CCTableView() -: indices_(NULL) -, cellsUsed_(NULL) -, cellsFreed_(NULL) -, dataSource_(NULL) -, tDelegate_(NULL) -, m_eOldDirection(CCScrollViewDirectionNone) +: m_pIndices(NULL) +, m_pCellsUsed(NULL) +, m_pCellsFreed(NULL) +, m_pDataSource(NULL) +, m_pTableViewDelegate(NULL) +, m_eOldDirection(kCCScrollViewDirectionNone) { } CCTableView::~CCTableView() { - CC_SAFE_DELETE(indices_); - CC_SAFE_RELEASE(cellsUsed_); - CC_SAFE_RELEASE(cellsFreed_); + CC_SAFE_DELETE(m_pIndices); + CC_SAFE_RELEASE(m_pCellsUsed); + CC_SAFE_RELEASE(m_pCellsFreed); } void CCTableView::setVerticalFillOrder(CCTableViewVerticalFillOrder fillOrder) { - if (vordering_ != fillOrder) { - vordering_ = fillOrder; - if (cellsUsed_->count() > 0) { + if (m_eVordering != fillOrder) { + m_eVordering = fillOrder; + if (m_pCellsUsed->count() > 0) { this->reloadData(); } } @@ -100,16 +100,16 @@ void CCTableView::setVerticalFillOrder(CCTableViewVerticalFillOrder fillOrder) CCTableViewVerticalFillOrder CCTableView::getVerticalFillOrder() { - return vordering_; + return m_eVordering; } void CCTableView::reloadData() { CCObject* pObj = NULL; - CCARRAY_FOREACH(cellsUsed_, pObj) + CCARRAY_FOREACH(m_pCellsUsed, pObj) { CCTableViewCell* cell = (CCTableViewCell*)pObj; - cellsFreed_->addObject(cell); + m_pCellsFreed->addObject(cell); cell->reset(); if (cell->getParent() == this->getContainer()) { @@ -117,12 +117,12 @@ void CCTableView::reloadData() } } - indices_->clear(); - cellsUsed_->release(); - cellsUsed_ = new CCArrayForObjectSorting(); + m_pIndices->clear(); + m_pCellsUsed->release(); + m_pCellsUsed = new CCArrayForObjectSorting(); this->_updateContentSize(); - if (dataSource_->numberOfCellsInTableView(this) > 0) + if (m_pDataSource->numberOfCellsInTableView(this) > 0) { this->scrollViewDidScroll(this); } @@ -135,7 +135,7 @@ CCTableViewCell *CCTableView::cellAtIndex(unsigned int idx) void CCTableView::updateCellAtIndex(unsigned int idx) { - if (idx == CC_INVALID_INDEX || idx > dataSource_->numberOfCellsInTableView(this)-1) + if (idx == CC_INVALID_INDEX || idx > m_pDataSource->numberOfCellsInTableView(this)-1) { return; } @@ -146,34 +146,34 @@ void CCTableView::updateCellAtIndex(unsigned int idx) if (cell) { this->_moveCellOutOfSight(cell); } - cell = dataSource_->tableCellAtIndex(this, idx); + cell = m_pDataSource->tableCellAtIndex(this, idx); this->_setIndexForCell(idx, cell); this->_addCellIfNecessary(cell); } void CCTableView::insertCellAtIndex(unsigned int idx) { - if (idx == CC_INVALID_INDEX || idx > dataSource_->numberOfCellsInTableView(this)-1) { + if (idx == CC_INVALID_INDEX || idx > m_pDataSource->numberOfCellsInTableView(this)-1) { return; } CCTableViewCell *cell; int newIdx; - cell = (CCTableViewCell*)cellsUsed_->objectWithObjectID(idx); + cell = (CCTableViewCell*)m_pCellsUsed->objectWithObjectID(idx); if (cell) { - newIdx = cellsUsed_->indexOfSortedObject(cell); - for (unsigned int i=newIdx; icount(); i++) + newIdx = m_pCellsUsed->indexOfSortedObject(cell); + for (unsigned int i=newIdx; icount(); i++) { - cell = (CCTableViewCell*)cellsUsed_->objectAtIndex(i); + cell = (CCTableViewCell*)m_pCellsUsed->objectAtIndex(i); this->_setIndexForCell(cell->getIdx()+1, cell); } } - // [indices_ shiftIndexesStartingAtIndex:idx by:1]; + // [m_pIndices shiftIndexesStartingAtIndex:idx by:1]; //insert a new cell - cell = dataSource_->tableCellAtIndex(this, idx); + cell = m_pDataSource->tableCellAtIndex(this, idx); this->_setIndexForCell(idx, cell); this->_addCellIfNecessary(cell); @@ -182,7 +182,7 @@ void CCTableView::insertCellAtIndex(unsigned int idx) void CCTableView::removeCellAtIndex(unsigned int idx) { - if (idx == CC_INVALID_INDEX || idx > dataSource_->numberOfCellsInTableView(this)-1) { + if (idx == CC_INVALID_INDEX || idx > m_pDataSource->numberOfCellsInTableView(this)-1) { return; } @@ -194,15 +194,15 @@ void CCTableView::removeCellAtIndex(unsigned int idx) return; } - newIdx = cellsUsed_->indexOfSortedObject(cell); + newIdx = m_pCellsUsed->indexOfSortedObject(cell); //remove first this->_moveCellOutOfSight(cell); - indices_->erase(idx); -// [indices_ shiftIndexesStartingAtIndex:idx+1 by:-1]; - for (unsigned int i=cellsUsed_->count()-1; i > newIdx; i--) { - cell = (CCTableViewCell*)cellsUsed_->objectAtIndex(i); + m_pIndices->erase(idx); +// [m_pIndices shiftIndexesStartingAtIndex:idx+1 by:-1]; + for (unsigned int i=m_pCellsUsed->count()-1; i > newIdx; i--) { + cell = (CCTableViewCell*)m_pCellsUsed->objectAtIndex(i); this->_setIndexForCell(cell->getIdx()-1, cell); } } @@ -211,12 +211,12 @@ CCTableViewCell *CCTableView::dequeueCell() { CCTableViewCell *cell; - if (cellsFreed_->count() == 0) { + if (m_pCellsFreed->count() == 0) { cell = NULL; } else { - cell = (CCTableViewCell*)cellsFreed_->objectAtIndex(0); + cell = (CCTableViewCell*)m_pCellsFreed->objectAtIndex(0); cell->retain(); - cellsFreed_->removeObjectAtIndex(0); + m_pCellsFreed->removeObjectAtIndex(0); cell->autorelease(); } return cell; @@ -228,9 +228,9 @@ void CCTableView::_addCellIfNecessary(CCTableViewCell * cell) { this->getContainer()->addChild(cell); } - cellsUsed_->insertSortedObject(cell); - indices_->insert(cell->getIdx()); - // [indices_ addIndex:cell.idx]; + m_pCellsUsed->insertSortedObject(cell); + m_pIndices->insert(cell->getIdx()); + // [m_pIndices addIndex:cell.idx]; } void CCTableView::_updateContentSize() @@ -238,12 +238,12 @@ void CCTableView::_updateContentSize() CCSize size, cellSize; unsigned int cellCount; - cellSize = dataSource_->cellSizeForTable(this); - cellCount = dataSource_->numberOfCellsInTableView(this); + cellSize = m_pDataSource->cellSizeForTable(this); + cellCount = m_pDataSource->numberOfCellsInTableView(this); switch (this->getDirection()) { - case CCScrollViewDirectionHorizontal: + case kCCScrollViewDirectionHorizontal: size = CCSizeMake(cellCount * cellSize.width, cellSize.height); break; default: @@ -254,7 +254,7 @@ void CCTableView::_updateContentSize() if (m_eOldDirection != m_eDirection) { - if (m_eDirection == CCScrollViewDirectionHorizontal) + if (m_eDirection == kCCScrollViewDirectionHorizontal) { this->setContentOffset(ccp(0,0)); } @@ -271,8 +271,8 @@ CCPoint CCTableView::_offsetFromIndex(unsigned int index) { CCPoint offset = this->__offsetFromIndex(index); - const CCSize cellSize = dataSource_->cellSizeForTable(this); - if (vordering_ == CCTableViewFillTopDown) { + const CCSize cellSize = m_pDataSource->cellSizeForTable(this); + if (m_eVordering == kCCTableViewFillTopDown) { offset.y = this->getContainer()->getContentSize().height - offset.y - cellSize.height; } return offset; @@ -283,9 +283,9 @@ CCPoint CCTableView::__offsetFromIndex(unsigned int index) CCPoint offset; CCSize cellSize; - cellSize = dataSource_->cellSizeForTable(this); + cellSize = m_pDataSource->cellSizeForTable(this); switch (this->getDirection()) { - case CCScrollViewDirectionHorizontal: + case kCCScrollViewDirectionHorizontal: offset = ccp(cellSize.width * index, 0.0f); break; default: @@ -299,10 +299,10 @@ CCPoint CCTableView::__offsetFromIndex(unsigned int index) unsigned int CCTableView::_indexFromOffset(CCPoint offset) { int index = 0; - const int maxIdx = dataSource_->numberOfCellsInTableView(this)-1; + const int maxIdx = m_pDataSource->numberOfCellsInTableView(this)-1; - const CCSize cellSize = dataSource_->cellSizeForTable(this); - if (vordering_ == CCTableViewFillTopDown) { + const CCSize cellSize = m_pDataSource->cellSizeForTable(this); + if (m_eVordering == kCCTableViewFillTopDown) { offset.y = this->getContainer()->getContentSize().height - offset.y - cellSize.height; } index = MAX(0, this->__indexFromOffset(offset)); @@ -316,10 +316,10 @@ int CCTableView::__indexFromOffset(CCPoint offset) int index = 0; CCSize cellSize; - cellSize = dataSource_->cellSizeForTable(this); + cellSize = m_pDataSource->cellSizeForTable(this); switch (this->getDirection()) { - case CCScrollViewDirectionHorizontal: + case kCCScrollViewDirectionHorizontal: index = offset.x/cellSize.width; break; default: @@ -336,10 +336,10 @@ CCTableViewCell* CCTableView::_cellWithIndex(unsigned int cellIndex) found = NULL; -// if ([indices_ containsIndex:cellIndex]) - if (indices_->find(cellIndex) != indices_->end()) +// if ([m_pIndices containsIndex:cellIndex]) + if (m_pIndices->find(cellIndex) != m_pIndices->end()) { - found = (CCTableViewCell *)cellsUsed_->objectWithObjectID(cellIndex); + found = (CCTableViewCell *)m_pCellsUsed->objectWithObjectID(cellIndex); } return found; @@ -347,10 +347,10 @@ CCTableViewCell* CCTableView::_cellWithIndex(unsigned int cellIndex) void CCTableView::_moveCellOutOfSight(CCTableViewCell *cell) { - cellsFreed_->addObject(cell); - cellsUsed_->removeSortedObject(cell); - indices_->erase(cell->getIdx()); - // [indices_ removeIndex:cell.idx]; + m_pCellsFreed->addObject(cell); + m_pCellsUsed->removeSortedObject(cell); + m_pIndices->erase(cell->getIdx()); + // [m_pIndices removeIndex:cell.idx]; cell->reset(); if (cell->getParent() == this->getContainer()) { this->getContainer()->removeChild(cell, true);; @@ -366,21 +366,20 @@ void CCTableView::_setIndexForCell(unsigned int index, CCTableViewCell *cell) void CCTableView::scrollViewDidScroll(CCScrollView* view) { - CCLOG("container pos x = %f, y = %f", getContainer()->getPosition().x, getContainer()->getPosition().y); unsigned int startIdx = 0, endIdx = 0, idx = 0, maxIdx = 0; CCPoint offset; offset = ccpMult(this->getContentOffset(), -1); - maxIdx = MAX(dataSource_->numberOfCellsInTableView(this)-1, 0); + maxIdx = MAX(m_pDataSource->numberOfCellsInTableView(this)-1, 0); - const CCSize cellSize = dataSource_->cellSizeForTable(this); + const CCSize cellSize = m_pDataSource->cellSizeForTable(this); - if (vordering_ == CCTableViewFillTopDown) { + if (m_eVordering == kCCTableViewFillTopDown) { offset.y = offset.y + m_tViewSize.height/this->getContainer()->getScaleY() - cellSize.height; } startIdx = this->_indexFromOffset(offset); - if (vordering_ == CCTableViewFillTopDown) + if (m_eVordering == kCCTableViewFillTopDown) { offset.y -= m_tViewSize.height/this->getContainer()->getScaleY(); } @@ -392,9 +391,10 @@ void CCTableView::scrollViewDidScroll(CCScrollView* view) endIdx = this->_indexFromOffset(offset); +#if 0 // For Testing. CCObject* pObj; int i = 0; - CCARRAY_FOREACH(cellsUsed_, pObj) + CCARRAY_FOREACH(m_pCellsUsed, pObj) { CCTableViewCell* pCell = (CCTableViewCell*)pObj; CCLog("cells Used index %d, value = %d", i, pCell->getIdx()); @@ -402,54 +402,59 @@ void CCTableView::scrollViewDidScroll(CCScrollView* view) } CCLog("---------------------------------------"); i = 0; - CCARRAY_FOREACH(cellsFreed_, pObj) + CCARRAY_FOREACH(m_pCellsFreed, pObj) { CCTableViewCell* pCell = (CCTableViewCell*)pObj; CCLog("cells freed index %d, value = %d", i, pCell->getIdx()); i++; } CCLog("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); - if (cellsUsed_->count() > 0) +#endif + + if (m_pCellsUsed->count() > 0) { - CCTableViewCell* cell = (CCTableViewCell*)cellsUsed_->objectAtIndex(0); + CCTableViewCell* cell = (CCTableViewCell*)m_pCellsUsed->objectAtIndex(0); idx = cell->getIdx(); while(idx _moveCellOutOfSight(cell); - if (cellsUsed_->count() > 0) { - cell = (CCTableViewCell*)cellsUsed_->objectAtIndex(0); + if (m_pCellsUsed->count() > 0) + { + cell = (CCTableViewCell*)m_pCellsUsed->objectAtIndex(0); idx = cell->getIdx(); - } else { + } + else + { break; } - CCLog("idx 0 = %d", idx); } } - if (cellsUsed_->count() > 0) + if (m_pCellsUsed->count() > 0) { - CCTableViewCell *cell = (CCTableViewCell*)cellsUsed_->lastObject(); + CCTableViewCell *cell = (CCTableViewCell*)m_pCellsUsed->lastObject(); idx = cell->getIdx(); while(idx <= maxIdx && idx > endIdx) { this->_moveCellOutOfSight(cell); - if (cellsUsed_->count() > 0) + if (m_pCellsUsed->count() > 0) { - cell = (CCTableViewCell*)cellsUsed_->lastObject(); + cell = (CCTableViewCell*)m_pCellsUsed->lastObject(); idx = cell->getIdx(); - } else { + } + else + { break; } - CCLog("idx 1 = %d, maxIdx = %d, endIdx = %d", idx, maxIdx, endIdx); } } for (unsigned int i=startIdx; i <= endIdx; i++) { - //if ([indices_ containsIndex:i]) - if (indices_->find(i) != indices_->end()) + //if ([m_pIndices containsIndex:i]) + if (m_pIndices->find(i) != m_pIndices->end()) { continue; } @@ -468,15 +473,15 @@ void CCTableView::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent) CCPoint point; point = this->getContainer()->convertTouchToNodeSpace(pTouch); - if (vordering_ == CCTableViewFillTopDown) { - CCSize cellSize = dataSource_->cellSizeForTable(this); + if (m_eVordering == kCCTableViewFillTopDown) { + CCSize cellSize = m_pDataSource->cellSizeForTable(this); point.y -= cellSize.height; } index = this->_indexFromOffset(point); cell = this->_cellWithIndex(index); if (cell) { - tDelegate_->table_cellTouched(this, cell); + m_pTableViewDelegate->tableCellTouched(this, cell); } } CCScrollView::ccTouchEnded(pTouch, pEvent); diff --git a/extensions/GUI/CCScrollView/CCTableView.h b/extensions/GUI/CCScrollView/CCTableView.h index 5b19efb655..cb453b4163 100644 --- a/extensions/GUI/CCScrollView/CCTableView.h +++ b/extensions/GUI/CCScrollView/CCTableView.h @@ -42,8 +42,8 @@ class CCTableView; class CCArrayForObjectSorting; typedef enum { - CCTableViewFillTopDown, - CCTableViewFillBottomUp + kCCTableViewFillTopDown, + kCCTableViewFillBottomUp } CCTableViewVerticalFillOrder; /** @@ -58,7 +58,7 @@ public: * @param table table contains the given cell * @param cell cell that is touched */ - virtual void table_cellTouched(CCTableView* table, CCTableViewCell* cell) = 0; + virtual void tableCellTouched(CCTableView* table, CCTableViewCell* cell) = 0; }; @@ -103,27 +103,6 @@ class CCTableView : public CCScrollView, public CCScrollViewDelegate public: CCTableView(); virtual ~CCTableView(); - /** - * vertical direction of cell filling - */ - CCTableViewVerticalFillOrder vordering_; - - /** - * data source - */ - CCTableViewDataSource* getDataSource() { return dataSource_; } - void setDataSource(CCTableViewDataSource* source) { dataSource_ = source; } - /** - * delegate - */ - CCTableViewDelegate* getDelegate() { return tDelegate_; } - void setDelegate(CCTableViewDelegate* pDelegate) { tDelegate_ = pDelegate; } - - /** - * determines how cell is ordered and filled in the view. - */ - void setVerticalFillOrder(CCTableViewVerticalFillOrder order); - CCTableViewVerticalFillOrder getVerticalFillOrder(); /** * An intialized table view object @@ -132,7 +111,7 @@ public: * @param size view size * @return table view */ - static CCTableView* viewWithDataSource(CCTableViewDataSource* dataSource, CCSize size); + static CCTableView* create(CCTableViewDataSource* dataSource, CCSize size); /** * An initialized table view object * @@ -141,7 +120,25 @@ public: * @param container parent object for cells * @return table view */ - static CCTableView* viewWithDataSource(CCTableViewDataSource* dataSource, CCSize size, CCNode *container); + static CCTableView* create(CCTableViewDataSource* dataSource, CCSize size, CCNode *container); + + /** + * data source + */ + CCTableViewDataSource* getDataSource() { return m_pDataSource; } + void setDataSource(CCTableViewDataSource* source) { m_pDataSource = source; } + /** + * delegate + */ + CCTableViewDelegate* getDelegate() { return m_pTableViewDelegate; } + void setDelegate(CCTableViewDelegate* pDelegate) { m_pTableViewDelegate = pDelegate; } + + /** + * determines how cell is ordered and filled in the view. + */ + void setVerticalFillOrder(CCTableViewVerticalFillOrder order); + CCTableViewVerticalFillOrder getVerticalFillOrder(); + bool initWithViewSize(CCSize size, CCNode* container = NULL); /** @@ -187,27 +184,33 @@ public: virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent); protected: + + /** + * vertical direction of cell filling + */ + CCTableViewVerticalFillOrder m_eVordering; + /** * index set to query the indexes of the cells used. */ - std::set* indices_; + std::set* m_pIndices; //NSMutableIndexSet *indices_; /** * cells that are currently in the table */ - CCArrayForObjectSorting *cellsUsed_; + CCArrayForObjectSorting* m_pCellsUsed; /** * free list of cells */ - CCArrayForObjectSorting *cellsFreed_; + CCArrayForObjectSorting* m_pCellsFreed; /** * weak link to the data source object */ - CCTableViewDataSource* dataSource_; + CCTableViewDataSource* m_pDataSource; /** * weak link to the delegate object */ - CCTableViewDelegate* tDelegate_; + CCTableViewDelegate* m_pTableViewDelegate; CCScrollViewDirection m_eOldDirection; @@ -217,7 +220,7 @@ protected: CCPoint _offsetFromIndex(unsigned int index); void _updateContentSize(); - CCTableViewCell *_cellWithIndex(unsigned int cellIndex); + CCTableViewCell* _cellWithIndex(unsigned int cellIndex); void _moveCellOutOfSight(CCTableViewCell *cell); void _setIndexForCell(unsigned int index, CCTableViewCell *cell); void _addCellIfNecessary(CCTableViewCell * cell); diff --git a/samples/TestCpp/Android.mk b/samples/TestCpp/Android.mk index c28e3c8043..8ca97058ac 100644 --- a/samples/TestCpp/Android.mk +++ b/samples/TestCpp/Android.mk @@ -51,6 +51,8 @@ Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.cpp \ Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.cpp \ Classes/ExtensionsTest/NetworkTest/HttpClientTest.cpp \ Classes/ExtensionsTest/EditBoxTest/EditBoxTest.cpp \ +Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp \ +Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.cpp \ Classes/FontTest/FontTest.cpp \ Classes/IntervalTest/IntervalTest.cpp \ Classes/KeypadTest/KeypadTest.cpp \ diff --git a/samples/TestCpp/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp b/samples/TestCpp/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp index 72b1778cc4..daafeb6b38 100644 --- a/samples/TestCpp/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp +++ b/samples/TestCpp/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp @@ -23,18 +23,18 @@ bool TableViewTestLayer::init() CCSize winSize = CCDirector::sharedDirector()->getWinSize(); - CCTableView* tableView = CCTableView::viewWithDataSource(this, CCSizeMake(250, 60)); - tableView->setDirection(CCScrollViewDirectionHorizontal); + CCTableView* tableView = CCTableView::create(this, CCSizeMake(250, 60)); + tableView->setDirection(kCCScrollViewDirectionHorizontal); tableView->setPosition(ccp(20,winSize.height/2-30)); tableView->setDelegate(this); this->addChild(tableView); tableView->reloadData(); - tableView = CCTableView::viewWithDataSource(this, CCSizeMake(60, 280)); - tableView->setDirection(CCScrollViewDirectionVertical); + tableView = CCTableView::create(this, CCSizeMake(60, 280)); + tableView->setDirection(kCCScrollViewDirectionVertical); tableView->setPosition(ccp(winSize.width-150,winSize.height/2-120)); tableView->setDelegate(this); - tableView->setVerticalFillOrder(CCTableViewFillTopDown); + tableView->setVerticalFillOrder(kCCTableViewFillTopDown); this->addChild(tableView); tableView->reloadData(); @@ -55,7 +55,7 @@ void TableViewTestLayer::toExtensionsMainLayer(cocos2d::CCObject *sender) pScene->release(); } -void TableViewTestLayer::table_cellTouched(CCTableView* table, CCTableViewCell* cell) +void TableViewTestLayer::tableCellTouched(CCTableView* table, CCTableViewCell* cell) { CCLOG("cell touched at index: %i", cell->getIdx()); } diff --git a/samples/TestCpp/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.h b/samples/TestCpp/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.h index 3573f75744..c22c5c07b2 100644 --- a/samples/TestCpp/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.h +++ b/samples/TestCpp/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.h @@ -17,7 +17,7 @@ public: virtual void scrollViewDidScroll(cocos2d::extension::CCScrollView* view) {}; virtual void scrollViewDidZoom(cocos2d::extension::CCScrollView* view) {} - virtual void table_cellTouched(cocos2d::extension::CCTableView* table, cocos2d::extension::CCTableViewCell* cell); + virtual void tableCellTouched(cocos2d::extension::CCTableView* table, cocos2d::extension::CCTableViewCell* cell); virtual cocos2d::CCSize cellSizeForTable(cocos2d::extension::CCTableView *table); virtual cocos2d::extension::CCTableViewCell* tableCellAtIndex(cocos2d::extension::CCTableView *table, unsigned int idx); virtual unsigned int numberOfCellsInTableView(cocos2d::extension::CCTableView *table); diff --git a/samples/TestCpp/proj.ios/TestCpp.xcodeproj/project.pbxproj.REMOVED.git-id b/samples/TestCpp/proj.ios/TestCpp.xcodeproj/project.pbxproj.REMOVED.git-id index 9260c24d58..5fc33334fb 100644 --- a/samples/TestCpp/proj.ios/TestCpp.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/samples/TestCpp/proj.ios/TestCpp.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -13fb5118be504c0cb162fe003715353d23316944 \ No newline at end of file +48422011360e4d8706df417f7061b830a3b9613a \ No newline at end of file diff --git a/samples/TestCpp/proj.mac/TestCpp.xcodeproj/project.pbxproj.REMOVED.git-id b/samples/TestCpp/proj.mac/TestCpp.xcodeproj/project.pbxproj.REMOVED.git-id index 297ba803ea..9888556745 100644 --- a/samples/TestCpp/proj.mac/TestCpp.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/samples/TestCpp/proj.mac/TestCpp.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -f5750ec007bd00599c51249ab60343d337af43c9 \ No newline at end of file +05fb7e1549cf656c61a502a07712b042ff7eec9b \ No newline at end of file From 6f3ee0299a04e3847aa714d2b871f489565fe4eb Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 10 Sep 2012 14:05:44 +0800 Subject: [PATCH 11/15] issue #1458: Updated vs2010 project configuration. --- extensions/proj.win32/libExtensions.vcxproj | 6 ++++++ .../proj.win32/libExtensions.vcxproj.filters | 18 ++++++++++++++++++ samples/TestCpp/proj.win32/TestCpp.vcxproj | 4 ++++ .../TestCpp/proj.win32/TestCpp.vcxproj.filters | 15 +++++++++++++++ 4 files changed, 43 insertions(+) diff --git a/extensions/proj.win32/libExtensions.vcxproj b/extensions/proj.win32/libExtensions.vcxproj index 179c857b6a..dfa1658716 100644 --- a/extensions/proj.win32/libExtensions.vcxproj +++ b/extensions/proj.win32/libExtensions.vcxproj @@ -109,6 +109,9 @@ + + + @@ -149,6 +152,9 @@ + + + diff --git a/extensions/proj.win32/libExtensions.vcxproj.filters b/extensions/proj.win32/libExtensions.vcxproj.filters index 159ba81c79..3dfab3a3d7 100644 --- a/extensions/proj.win32/libExtensions.vcxproj.filters +++ b/extensions/proj.win32/libExtensions.vcxproj.filters @@ -111,6 +111,15 @@ GUI\network + + GUI\CCScrollView + + + GUI\CCScrollView + + + GUI\CCScrollView + @@ -229,5 +238,14 @@ GUI\network + + GUI\CCScrollView + + + GUI\CCScrollView + + + GUI\CCScrollView + \ No newline at end of file diff --git a/samples/TestCpp/proj.win32/TestCpp.vcxproj b/samples/TestCpp/proj.win32/TestCpp.vcxproj index 485246eb96..a2fc4033d9 100644 --- a/samples/TestCpp/proj.win32/TestCpp.vcxproj +++ b/samples/TestCpp/proj.win32/TestCpp.vcxproj @@ -108,6 +108,8 @@ + + @@ -190,6 +192,8 @@ + + diff --git a/samples/TestCpp/proj.win32/TestCpp.vcxproj.filters b/samples/TestCpp/proj.win32/TestCpp.vcxproj.filters index 59648259a0..0f76196539 100644 --- a/samples/TestCpp/proj.win32/TestCpp.vcxproj.filters +++ b/samples/TestCpp/proj.win32/TestCpp.vcxproj.filters @@ -190,6 +190,9 @@ {28e8af6a-0e73-4069-bdf4-735138ed886d} + + {2603ae57-b062-4281-9daf-c925634eaeb4} + @@ -432,6 +435,12 @@ Classes\ExtensionsTest\NetworkTest + + Classes\ExtensionsTest\TableViewTest + + + Classes\ExtensionsTest\TableViewTest + @@ -848,5 +857,11 @@ Classes\ExtensionsTest\NetworkTest + + Classes\ExtensionsTest\TableViewTest + + + Classes\ExtensionsTest\TableViewTest + \ No newline at end of file From a6acd90c290c6b905ec7ee5b89487bf5c47d036f Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 10 Sep 2012 14:13:55 +0800 Subject: [PATCH 12/15] fixed #1458: Updated copyright information for some files which are relative to CCTableView. --- extensions/GUI/CCScrollView/CCScrollView.cpp | 52 +++++++++--------- extensions/GUI/CCScrollView/CCScrollView.h | 53 +++++++++--------- extensions/GUI/CCScrollView/CCSorting.cpp | 53 +++++++++--------- extensions/GUI/CCScrollView/CCSorting.h | 52 +++++++++--------- extensions/GUI/CCScrollView/CCTableView.cpp | 54 +++++++++---------- extensions/GUI/CCScrollView/CCTableView.h | 53 +++++++++--------- .../GUI/CCScrollView/CCTableViewCell.cpp | 52 +++++++++--------- extensions/GUI/CCScrollView/CCTableViewCell.h | 52 +++++++++--------- 8 files changed, 193 insertions(+), 228 deletions(-) diff --git a/extensions/GUI/CCScrollView/CCScrollView.cpp b/extensions/GUI/CCScrollView/CCScrollView.cpp index 603cbab4a6..e08da8a74f 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.cpp +++ b/extensions/GUI/CCScrollView/CCScrollView.cpp @@ -1,31 +1,27 @@ -// -// SWScrollView.m -// SWGameLib -// -// Copyright (c) 2010-2012 cocos2d-x.org -// Copyright (c) 2010 Sangwoo Im -// -// 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 false 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. -// -// Created by Sangwoo Im on 6/3/10. -// Copyright 2010 Sangwoo Im. All rights reserved. -// +/**************************************************************************** + Copyright (c) 2012 cocos2d-x.org + Copyright (c) 2010 Sangwoo Im + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #include "CCScrollView.h" #include "actions/CCActionInterval.h" diff --git a/extensions/GUI/CCScrollView/CCScrollView.h b/extensions/GUI/CCScrollView/CCScrollView.h index 179e51d34a..93eb74096f 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.h +++ b/extensions/GUI/CCScrollView/CCScrollView.h @@ -1,32 +1,27 @@ -// -// SWScrollView.h -// SWGameLib -// -// Copyright (c) 2010-2012 cocos2d-x.org -// Copyright (c) 2010 Sangwoo Im -// -// 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. -// -// -// Created by Sangwoo Im on 6/3/10. -// Copyright 2010 Sangwoo Im. All rights reserved. -// +/**************************************************************************** + Copyright (c) 2012 cocos2d-x.org + Copyright (c) 2010 Sangwoo Im + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #ifndef __CCSCROLLVIEW_H__ #define __CCSCROLLVIEW_H__ diff --git a/extensions/GUI/CCScrollView/CCSorting.cpp b/extensions/GUI/CCScrollView/CCSorting.cpp index 5b795d73a1..77bb6a1d2a 100644 --- a/extensions/GUI/CCScrollView/CCSorting.cpp +++ b/extensions/GUI/CCScrollView/CCSorting.cpp @@ -1,34 +1,29 @@ -// -// NSMutableArraySorting.m -// SWGameLib -// -// Copyright (c) 2012 cocos2d-x.org -// Copyright (c) 2010 Sangwoo Im -// -// 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. -// -// Created by Sangwoo Im on 10/10/09. -// Copyright 2009 Sangwoo Im. All rights reserved. -// +/**************************************************************************** + Copyright (c) 2012 cocos2d-x.org + Copyright (c) 2010 Sangwoo Im + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #include "CCSorting.h" -//#include "SWDebug.h" NS_CC_EXT_BEGIN diff --git a/extensions/GUI/CCScrollView/CCSorting.h b/extensions/GUI/CCScrollView/CCSorting.h index 5fa0d3a614..553ddbdbb5 100644 --- a/extensions/GUI/CCScrollView/CCSorting.h +++ b/extensions/GUI/CCScrollView/CCSorting.h @@ -1,31 +1,27 @@ -// -// NSMutableArraySorting.h -// SWGameLib -// -// Copyright (c) 2012 cocos2d-x.org -// Copyright (c) 2010 Sangwoo Im -// -// 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. -// -// Created by Sangwoo Im on 10/10/09. -// Copyright 2009 Sangwoo Im. All rights reserved. -// +/**************************************************************************** + Copyright (c) 2012 cocos2d-x.org + Copyright (c) 2010 Sangwoo Im + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #ifndef __CCSORTING_H__ #define __CCSORTING_H__ diff --git a/extensions/GUI/CCScrollView/CCTableView.cpp b/extensions/GUI/CCScrollView/CCTableView.cpp index c92da38e3d..35a4cb5310 100644 --- a/extensions/GUI/CCScrollView/CCTableView.cpp +++ b/extensions/GUI/CCScrollView/CCTableView.cpp @@ -1,32 +1,28 @@ -// -// SWTableView.m -// SWGameLib -// -// Copyright (c) 2012 cocos2d-x.org -// Copyright (c) 2010 Sangwoo Im -// -// 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. -// -// -// Created by Sangwoo Im on 6/3/10. -// Copyright 2010 Sangwoo Im. All rights reserved. -// +/**************************************************************************** + Copyright (c) 2012 cocos2d-x.org + Copyright (c) 2010 Sangwoo Im + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + #include "cocos2d.h" #include "CCTableView.h" #include "CCTableViewCell.h" diff --git a/extensions/GUI/CCScrollView/CCTableView.h b/extensions/GUI/CCScrollView/CCTableView.h index cb453b4163..3aa6f32a28 100644 --- a/extensions/GUI/CCScrollView/CCTableView.h +++ b/extensions/GUI/CCScrollView/CCTableView.h @@ -1,32 +1,27 @@ -// -// SWTableView.h -// SWGameLib -// -// Copyright (c) 2012 cocos2d-x.org -// Copyright (c) 2010 Sangwoo Im -// -// 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. -// -// -// Created by Sangwoo Im on 6/3/10. -// Copyright 2010 Sangwoo Im. All rights reserved. -// +/**************************************************************************** + Copyright (c) 2012 cocos2d-x.org + Copyright (c) 2010 Sangwoo Im + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #ifndef __CCTABLEVIEW_H__ #define __CCTABLEVIEW_H__ diff --git a/extensions/GUI/CCScrollView/CCTableViewCell.cpp b/extensions/GUI/CCScrollView/CCTableViewCell.cpp index 304e7e1c73..965ca66ee9 100644 --- a/extensions/GUI/CCScrollView/CCTableViewCell.cpp +++ b/extensions/GUI/CCScrollView/CCTableViewCell.cpp @@ -1,31 +1,27 @@ -// -// SWTableViewCell.m -// SWGameLib -// -// Copyright (c) 2012 cocos2d-x.org -// Copyright (c) 2010 Sangwoo Im -// -// 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. -// -// Created by Sangwoo Im on 6/3/10. -// Copyright 2010 Sangwoo Im. All rights reserved. -// +/**************************************************************************** + Copyright (c) 2012 cocos2d-x.org + Copyright (c) 2010 Sangwoo Im + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #include "CCTableViewCell.h" diff --git a/extensions/GUI/CCScrollView/CCTableViewCell.h b/extensions/GUI/CCScrollView/CCTableViewCell.h index b095a4da27..19c08e224b 100644 --- a/extensions/GUI/CCScrollView/CCTableViewCell.h +++ b/extensions/GUI/CCScrollView/CCTableViewCell.h @@ -1,31 +1,27 @@ -// -// SWTableViewCell.h -// SWGameLib -// -// Copyright (c) 2012 cocos2d-x.org -// Copyright (c) 2010 Sangwoo Im -// -// 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. -// -// Created by Sangwoo Im on 6/3/10. -// Copyright 2010 Sangwoo Im. All rights reserved. -// +/**************************************************************************** + Copyright (c) 2012 cocos2d-x.org + Copyright (c) 2010 Sangwoo Im + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #ifndef __CCTABLEVIEWCELL_H__ #define __CCTABLEVIEWCELL_H__ From c9e1aa7adc6029c5df2f5ac013266233bcbf2c65 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 10 Sep 2012 14:50:19 +0800 Subject: [PATCH 13/15] fixed #1458: Updated TestCpp Makefile for linux port. --- samples/TestCpp/proj.linux/Makefile | 2 ++ 1 file changed, 2 insertions(+) diff --git a/samples/TestCpp/proj.linux/Makefile b/samples/TestCpp/proj.linux/Makefile index 12e381e1c0..67cdce1d3a 100644 --- a/samples/TestCpp/proj.linux/Makefile +++ b/samples/TestCpp/proj.linux/Makefile @@ -77,6 +77,8 @@ OBJECTS = ../Classes/AccelerometerTest/AccelerometerTest.o \ ../Classes/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.o \ ../Classes/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.o \ ../Classes/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.o \ + ../Classes/ExtensionsTest/TableViewTest/TableViewTestScene.o \ + ../Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.o \ ../Classes/ExtensionsTest/ExtensionsTest.o \ ../Classes/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.o \ ../Classes/ExtensionsTest/NetworkTest/HttpClientTest.o \ From b1572beb0b71dfaa3dff17326479b82c06a9e746 Mon Sep 17 00:00:00 2001 From: Walzer Date: Mon, 10 Sep 2012 15:05:56 +0800 Subject: [PATCH 14/15] fixed #1453, fix a typo in platform/ios/CCGL.h #include is fixed to #include --- cocos2dx/platform/ios/CCGL.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2dx/platform/ios/CCGL.h b/cocos2dx/platform/ios/CCGL.h index e1b95d5104..4e68e05fb8 100644 --- a/cocos2dx/platform/ios/CCGL.h +++ b/cocos2dx/platform/ios/CCGL.h @@ -32,7 +32,7 @@ THE SOFTWARE. #define CC_GL_DEPTH24_STENCIL8 GL_DEPTH24_STENCIL8_OES #include -#include +#include #endif // __CCGL_H__ From 4212b73c5fc7d6fabdb52a2424c68ad12e20d7d8 Mon Sep 17 00:00:00 2001 From: Walzer Date: Mon, 10 Sep 2012 19:00:25 +0800 Subject: [PATCH 15/15] remove the duplicated SimpleGame sorry I made a mistake in the last evening. --- SimpleGame/Classes/AppDelegate.cpp | 57 --- SimpleGame/Classes/AppDelegate.h | 38 -- SimpleGame/Classes/HelloWorldScene.cpp | 84 ---- SimpleGame/Classes/HelloWorldScene.h | 22 - .../Resources/HelloWorld.png.REMOVED.git-id | 1 - SimpleGame/proj.android/.classpath | 8 - SimpleGame/proj.android/.project | 33 -- SimpleGame/proj.android/AndroidManifest.xml | 28 -- SimpleGame/proj.android/ant.properties | 17 - SimpleGame/proj.android/build.xml | 92 ---- SimpleGame/proj.android/build_native.sh | 91 ---- SimpleGame/proj.android/jni/Android.mk | 21 - SimpleGame/proj.android/jni/Application.mk | 2 - SimpleGame/proj.android/jni/hellocpp/main.cpp | 45 -- SimpleGame/proj.android/jni/list.sh | 23 - SimpleGame/proj.android/proguard-project.txt | 20 - SimpleGame/proj.android/project.properties | 14 - .../proj.android/res/values/strings.xml | 4 - .../cocos2dx/lib/Cocos2dxAccelerometer.java | 107 ---- .../org/cocos2dx/lib/Cocos2dxActivity.java | 346 ------------- .../src/org/cocos2dx/lib/Cocos2dxBitmap.java | 455 ------------------ .../cocos2dx/lib/Cocos2dxEditBoxDialog.java | 338 ------------- .../org/cocos2dx/lib/Cocos2dxEditText.java | 65 --- .../cocos2dx/lib/Cocos2dxGLSurfaceView.java | 417 ---------------- .../src/org/cocos2dx/lib/Cocos2dxMusic.java | 228 --------- .../org/cocos2dx/lib/Cocos2dxRenderer.java | 137 ------ .../src/org/cocos2dx/lib/Cocos2dxSound.java | 245 ---------- .../org/cocos2dx/lib/Cocos2dxTypefaces.java | 44 -- .../org/cocos2dx/simplegame/SimpleGame.java | 108 ----- 29 files changed, 3090 deletions(-) delete mode 100644 SimpleGame/Classes/AppDelegate.cpp delete mode 100644 SimpleGame/Classes/AppDelegate.h delete mode 100644 SimpleGame/Classes/HelloWorldScene.cpp delete mode 100644 SimpleGame/Classes/HelloWorldScene.h delete mode 100644 SimpleGame/Resources/HelloWorld.png.REMOVED.git-id delete mode 100644 SimpleGame/proj.android/.classpath delete mode 100644 SimpleGame/proj.android/.project delete mode 100644 SimpleGame/proj.android/AndroidManifest.xml delete mode 100644 SimpleGame/proj.android/ant.properties delete mode 100644 SimpleGame/proj.android/build.xml delete mode 100755 SimpleGame/proj.android/build_native.sh delete mode 100644 SimpleGame/proj.android/jni/Android.mk delete mode 100644 SimpleGame/proj.android/jni/Application.mk delete mode 100644 SimpleGame/proj.android/jni/hellocpp/main.cpp delete mode 100644 SimpleGame/proj.android/jni/list.sh delete mode 100644 SimpleGame/proj.android/proguard-project.txt delete mode 100644 SimpleGame/proj.android/project.properties delete mode 100644 SimpleGame/proj.android/res/values/strings.xml delete mode 100644 SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxAccelerometer.java delete mode 100644 SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxActivity.java delete mode 100644 SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxBitmap.java delete mode 100755 SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxEditBoxDialog.java delete mode 100644 SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxEditText.java delete mode 100644 SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java delete mode 100644 SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxMusic.java delete mode 100644 SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxRenderer.java delete mode 100644 SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxSound.java delete mode 100644 SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxTypefaces.java delete mode 100644 SimpleGame/proj.android/src/org/cocos2dx/simplegame/SimpleGame.java diff --git a/SimpleGame/Classes/AppDelegate.cpp b/SimpleGame/Classes/AppDelegate.cpp deleted file mode 100644 index 447d84142f..0000000000 --- a/SimpleGame/Classes/AppDelegate.cpp +++ /dev/null @@ -1,57 +0,0 @@ -#include "AppDelegate.h" - -#include "cocos2d.h" -#include "HelloWorldScene.h" - -USING_NS_CC; - -AppDelegate::AppDelegate() -{ - -} - -AppDelegate::~AppDelegate() -{ -} - -bool AppDelegate::applicationDidFinishLaunching() -{ - // initialize director - CCDirector *pDirector = CCDirector::sharedDirector(); - pDirector->setOpenGLView(CCEGLView::sharedOpenGLView()); - - // 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); - - // create a scene. it's an autorelease object - CCScene *pScene = HelloWorld::scene(); - - // run - pDirector->runWithScene(pScene); - - return true; -} - -// 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()->pause(); - - // if you use SimpleAudioEngine, it must be pause - // SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic(); -} - -// this function will be called when the app is active again -void AppDelegate::applicationWillEnterForeground() -{ - CCDirector::sharedDirector()->resume(); - - // if you use SimpleAudioEngine, it must resume here - // SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic(); -} diff --git a/SimpleGame/Classes/AppDelegate.h b/SimpleGame/Classes/AppDelegate.h deleted file mode 100644 index 76c1c6089f..0000000000 --- a/SimpleGame/Classes/AppDelegate.h +++ /dev/null @@ -1,38 +0,0 @@ -#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_ - diff --git a/SimpleGame/Classes/HelloWorldScene.cpp b/SimpleGame/Classes/HelloWorldScene.cpp deleted file mode 100644 index a936549028..0000000000 --- a/SimpleGame/Classes/HelloWorldScene.cpp +++ /dev/null @@ -1,84 +0,0 @@ -#include "HelloWorldScene.h" -#include "SimpleAudioEngine.h" - -using namespace cocos2d; -using namespace CocosDenshion; - -CCScene* HelloWorld::scene() -{ - // 'scene' is an autorelease object - CCScene *scene = CCScene::create(); - - // 'layer' is an autorelease object - HelloWorld *layer = HelloWorld::create(); - - // add layer as a child to scene - scene->addChild(layer); - - // return the scene - return scene; -} - -// on "init" you need to initialize your instance -bool HelloWorld::init() -{ - ////////////////////////////// - // 1. super init first - if ( !CCLayer::init() ) - { - return false; - } - - ///////////////////////////// - // 2. add a menu item with "X" image, which is clicked to quit the program - // you may modify it. - - // add a "close" icon to exit the progress. it's an autorelease object - CCMenuItemImage *pCloseItem = CCMenuItemImage::create( - "CloseNormal.png", - "CloseSelected.png", - this, - menu_selector(HelloWorld::menuCloseCallback) ); - pCloseItem->setPosition( ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20) ); - - // create menu, it's an autorelease object - CCMenu* pMenu = CCMenu::create(pCloseItem, NULL); - pMenu->setPosition( CCPointZero ); - this->addChild(pMenu, 1); - - ///////////////////////////// - // 3. add your codes below... - - // add a label shows "Hello World" - // create and initialize a label - CCLabelTTF* pLabel = CCLabelTTF::create("Hello World", "Thonburi", 34); - - // ask director the window size - CCSize size = CCDirector::sharedDirector()->getWinSize(); - - // position the label on the center of the screen - pLabel->setPosition( ccp(size.width / 2, size.height - 20) ); - - // add the label as a child to this layer - this->addChild(pLabel, 1); - - // add "HelloWorld" splash screen" - CCSprite* pSprite = CCSprite::create("HelloWorld.png"); - - // position the sprite on the center of the screen - pSprite->setPosition( ccp(size.width/2, size.height/2) ); - - // add the sprite as a child to this layer - this->addChild(pSprite, 0); - - return true; -} - -void HelloWorld::menuCloseCallback(CCObject* pSender) -{ - CCDirector::sharedDirector()->end(); - -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) - exit(0); -#endif -} diff --git a/SimpleGame/Classes/HelloWorldScene.h b/SimpleGame/Classes/HelloWorldScene.h deleted file mode 100644 index e202b8c2c3..0000000000 --- a/SimpleGame/Classes/HelloWorldScene.h +++ /dev/null @@ -1,22 +0,0 @@ -#ifndef __HELLOWORLD_SCENE_H__ -#define __HELLOWORLD_SCENE_H__ - -#include "cocos2d.h" - -class HelloWorld : public cocos2d::CCLayer -{ -public: - // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone - virtual bool init(); - - // there's no 'id' in cpp, so we recommand to return the exactly class pointer - static cocos2d::CCScene* scene(); - - // a selector callback - void menuCloseCallback(CCObject* pSender); - - // implement the "static node()" method manually - CREATE_FUNC(HelloWorld); -}; - -#endif // __HELLOWORLD_SCENE_H__ diff --git a/SimpleGame/Resources/HelloWorld.png.REMOVED.git-id b/SimpleGame/Resources/HelloWorld.png.REMOVED.git-id deleted file mode 100644 index f02d84fd8f..0000000000 --- a/SimpleGame/Resources/HelloWorld.png.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -5fe89fb5bd58cedf13b0363f97b20e3ea7ff255d \ No newline at end of file diff --git a/SimpleGame/proj.android/.classpath b/SimpleGame/proj.android/.classpath deleted file mode 100644 index a4763d1eec..0000000000 --- a/SimpleGame/proj.android/.classpath +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/SimpleGame/proj.android/.project b/SimpleGame/proj.android/.project deleted file mode 100644 index afc29d09d0..0000000000 --- a/SimpleGame/proj.android/.project +++ /dev/null @@ -1,33 +0,0 @@ - - - SimpleGame - - - - - - com.android.ide.eclipse.adt.ResourceManagerBuilder - - - - - com.android.ide.eclipse.adt.PreCompilerBuilder - - - - - org.eclipse.jdt.core.javabuilder - - - - - com.android.ide.eclipse.adt.ApkBuilder - - - - - - com.android.ide.eclipse.adt.AndroidNature - org.eclipse.jdt.core.javanature - - diff --git a/SimpleGame/proj.android/AndroidManifest.xml b/SimpleGame/proj.android/AndroidManifest.xml deleted file mode 100644 index 8574ea3ceb..0000000000 --- a/SimpleGame/proj.android/AndroidManifest.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/SimpleGame/proj.android/ant.properties b/SimpleGame/proj.android/ant.properties deleted file mode 100644 index b0971e891e..0000000000 --- a/SimpleGame/proj.android/ant.properties +++ /dev/null @@ -1,17 +0,0 @@ -# This file is used to override default values used by the Ant build system. -# -# This file must be checked into Version Control Systems, as it is -# integral to the build system of your project. - -# This file is only used by the Ant script. - -# You can use this to override default values such as -# 'source.dir' for the location of your java source folder and -# 'out.dir' for the location of your output folder. - -# You can also use it define how the release builds are signed by declaring -# the following properties: -# 'key.store' for the location of your keystore and -# 'key.alias' for the name of the key to use. -# The password will be asked during the build when you use the 'release' target. - diff --git a/SimpleGame/proj.android/build.xml b/SimpleGame/proj.android/build.xml deleted file mode 100644 index e9678a9b14..0000000000 --- a/SimpleGame/proj.android/build.xml +++ /dev/null @@ -1,92 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/SimpleGame/proj.android/build_native.sh b/SimpleGame/proj.android/build_native.sh deleted file mode 100755 index 0078049efd..0000000000 --- a/SimpleGame/proj.android/build_native.sh +++ /dev/null @@ -1,91 +0,0 @@ -APPNAME="SimpleGame" - -# options - -buildexternalsfromsource= - -usage(){ -cat << EOF -usage: $0 [options] - -Build C/C++ code for $APPNAME using Android NDK - -OPTIONS: --s Build externals from source --h this help -EOF -} - -while getopts "sh" OPTION; do -case "$OPTION" in -s) -buildexternalsfromsource=1 -;; -h) -usage -exit 0 -;; -esac -done - -# 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 "NDK_ROOT = $NDK_ROOT" -echo "COCOS2DX_ROOT = $COCOS2DX_ROOT" -echo "APP_ROOT = $APP_ROOT" -echo "APP_ANDROID_ROOT = $APP_ANDROID_ROOT" - -# 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 - -# copy icons (if they exist) -file="$APP_ANDROID_ROOT"/assets/Icon-72.png -if [ -f "$file" ]; then - cp "$file" "$APP_ANDROID_ROOT"/res/drawable-hdpi/icon.png -fi -file="$APP_ANDROID_ROOT"/assets/Icon-48.png -if [ -f "$file" ]; then - cp "$file" "$APP_ANDROID_ROOT"/res/drawable-mdpi/icon.png -fi -file="$APP_ANDROID_ROOT"/assets/Icon-32.png -if [ -f "$file" ]; then - cp "$file" "$APP_ANDROID_ROOT"/res/drawable-ldpi/icon.png -fi - - -if [[ "$buildexternalsfromsource" ]]; then - echo "Building external dependencies from source" - "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos2dx/platform/third_party/android/source" -else - echo "Using prebuilt externals" - "$NDK_ROOT"/ndk-build -C "$APP_ANDROID_ROOT" $* \ - "NDK_MODULE_PATH=${COCOS2DX_ROOT}:${COCOS2DX_ROOT}/cocos2dx/platform/third_party/android/prebuilt" -fi diff --git a/SimpleGame/proj.android/jni/Android.mk b/SimpleGame/proj.android/jni/Android.mk deleted file mode 100644 index 61af0085d6..0000000000 --- a/SimpleGame/proj.android/jni/Android.mk +++ /dev/null @@ -1,21 +0,0 @@ -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) - -LOCAL_MODULE := game_shared - -LOCAL_MODULE_FILENAME := libgame - -LOCAL_SRC_FILES := hellocpp/main.cpp \ - ../../Classes/AppDelegate.cpp \ - ../../Classes/HelloWorldScene.cpp - -LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes - -LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static cocosdenshion_static cocos_extension_static - -include $(BUILD_SHARED_LIBRARY) - -$(call import-module,CocosDenshion/android) \ -$(call import-module,cocos2dx) \ -$(call import-module,extensions) diff --git a/SimpleGame/proj.android/jni/Application.mk b/SimpleGame/proj.android/jni/Application.mk deleted file mode 100644 index 22d424dab7..0000000000 --- a/SimpleGame/proj.android/jni/Application.mk +++ /dev/null @@ -1,2 +0,0 @@ -APP_STL := gnustl_static -APP_CPPFLAGS := -frtti \ No newline at end of file diff --git a/SimpleGame/proj.android/jni/hellocpp/main.cpp b/SimpleGame/proj.android/jni/hellocpp/main.cpp deleted file mode 100644 index 035fb201c4..0000000000 --- a/SimpleGame/proj.android/jni/hellocpp/main.cpp +++ /dev/null @@ -1,45 +0,0 @@ -#include "AppDelegate.h" -#include "platform/android/jni/JniHelper.h" -#include -#include - -#include "HelloWorldScene.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(); - } -} - -} diff --git a/SimpleGame/proj.android/jni/list.sh b/SimpleGame/proj.android/jni/list.sh deleted file mode 100644 index b95448ebbb..0000000000 --- a/SimpleGame/proj.android/jni/list.sh +++ /dev/null @@ -1,23 +0,0 @@ -#!/bin/bash - -append_str=' \' - -list_alldir() -{ - for file in $1/* - do - if [ -f $file ]; then - echo $file$append_str | grep .cpp - fi - - if [ -d $file ]; then - list_alldir $file - fi - done -} - -if [ $# -gt 0 ]; then - list_alldir "$1" -else - list_alldir "." -fi \ No newline at end of file diff --git a/SimpleGame/proj.android/proguard-project.txt b/SimpleGame/proj.android/proguard-project.txt deleted file mode 100644 index f2fe1559a2..0000000000 --- a/SimpleGame/proj.android/proguard-project.txt +++ /dev/null @@ -1,20 +0,0 @@ -# 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 *; -#} diff --git a/SimpleGame/proj.android/project.properties b/SimpleGame/proj.android/project.properties deleted file mode 100644 index 85aac54016..0000000000 --- a/SimpleGame/proj.android/project.properties +++ /dev/null @@ -1,14 +0,0 @@ -# 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 edit -# "ant.properties", and override values to adapt the script to your -# project structure. -# -# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): -#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt - -# Project target. -target=android-8 diff --git a/SimpleGame/proj.android/res/values/strings.xml b/SimpleGame/proj.android/res/values/strings.xml deleted file mode 100644 index f197c895b7..0000000000 --- a/SimpleGame/proj.android/res/values/strings.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - SimpleGame - diff --git a/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxAccelerometer.java b/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxAccelerometer.java deleted file mode 100644 index c515349cab..0000000000 --- a/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxAccelerometer.java +++ /dev/null @@ -1,107 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010-2011 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.lib; - -import android.content.Context; -import android.content.res.Configuration; -import android.hardware.Sensor; -import android.hardware.SensorEvent; -import android.hardware.SensorEventListener; -import android.hardware.SensorManager; -import android.view.Display; -import android.view.Surface; -import android.view.WindowManager; - -/** - * - * This class is used for controlling the Accelerometer - * - */ -public class Cocos2dxAccelerometer implements SensorEventListener { - - private static final String TAG = "Cocos2dxAccelerometer"; - private Context mContext; - private SensorManager mSensorManager; - private Sensor mAccelerometer; - private int mNaturalOrientation; - - public Cocos2dxAccelerometer(Context context){ - mContext = context; - - //Get an instance of the SensorManager - mSensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE); - mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); - - Display display = ((WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); - mNaturalOrientation = display.getOrientation(); - } - - public void enable() { - mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_GAME); - } - - public void disable () { - mSensorManager.unregisterListener(this); - } - - @Override - public void onSensorChanged(SensorEvent event) { - - if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER){ - return; - } - - float x = event.values[0]; - float y = event.values[1]; - float z = event.values[2]; - - /* - * Because the axes are not swapped when the device's screen orientation changes. - * So we should swap it here. - * In tablets such as Motorola Xoom, the default orientation is landscape, so should - * consider this. - */ - int orientation = mContext.getResources().getConfiguration().orientation; - if ((orientation == Configuration.ORIENTATION_LANDSCAPE) && (mNaturalOrientation != Surface.ROTATION_0)){ - float tmp = x; - x = -y; - y = tmp; - } - else if ((orientation == Configuration.ORIENTATION_PORTRAIT) && (mNaturalOrientation != Surface.ROTATION_0)) - { - float tmp = x; - x = y; - y = -tmp; - } - - onSensorChanged(x, y, z, event.timestamp); - // Log.d(TAG, "x = " + event.values[0] + " y = " + event.values[1] + " z = " + event.values[2]); - } - - @Override - public void onAccuracyChanged(Sensor sensor, int accuracy) { - } - - private static native void onSensorChanged(float x, float y, float z, long timeStamp); -} diff --git a/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxActivity.java b/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxActivity.java deleted file mode 100644 index 952d5148fb..0000000000 --- a/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxActivity.java +++ /dev/null @@ -1,346 +0,0 @@ -/**************************************************************************** -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.lib; - -import java.lang.ref.WeakReference; - -import android.app.Activity; -import android.app.AlertDialog; -import android.app.Dialog; -import android.content.DialogInterface; -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageManager; -import android.content.pm.PackageManager.NameNotFoundException; -import android.content.res.AssetManager; -import android.os.Build; -import android.os.Bundle; -import android.os.Handler; -import android.os.Message; -import android.util.DisplayMetrics; -import android.util.Log; - -public class Cocos2dxActivity extends Activity{ - - protected Cocos2dxGLSurfaceView mGLView; - private static Cocos2dxMusic backgroundMusicPlayer; - private static Cocos2dxSound soundPlayer; - private static Cocos2dxAccelerometer accelerometer; - private static AssetManager assetManager; - private static boolean accelerometerEnabled = false; - private static Handler handler; - private final static int HANDLER_SHOW_DIALOG = 1; - private final static int HANDLER_SHOW_EDITBOX_DIALOG = 2; - - private static String packageName; - - private static native void nativeSetPaths(String apkPath); - private static native void nativeSetEditboxText(byte[] text); - - - static class ShowDialogHandler extends Handler { - WeakReference mActivity; - - ShowDialogHandler(Cocos2dxActivity activity) { - mActivity = new WeakReference(activity); - } - - @Override - public void handleMessage(Message msg) { - Cocos2dxActivity theActivity = mActivity.get(); - switch(msg.what) { - case HANDLER_SHOW_DIALOG: - theActivity.showDialog(((DialogMessage)msg.obj).title, ((DialogMessage)msg.obj).message); - break; - case HANDLER_SHOW_EDITBOX_DIALOG: - theActivity.onShowEditBoxDialog((EditBoxMessage)msg.obj); - break; - } - } - }; - - public Cocos2dxGLSurfaceView getGLView() { - return mGLView; - } - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - // get frame size - DisplayMetrics dm = new DisplayMetrics(); - getWindowManager().getDefaultDisplay().getMetrics(dm); - accelerometer = new Cocos2dxAccelerometer(this); - - // init media player and sound player - backgroundMusicPlayer = new Cocos2dxMusic(this); - soundPlayer = new Cocos2dxSound(this); - - // init asset manager for jni call - assetManager = getAssets(); - - // init bitmap context - Cocos2dxBitmap.setContext(this); - - handler = new ShowDialogHandler(this); - } - - public static String getDeviceModel(){ - return Build.MODEL; - } - - public static AssetManager getAssetManager() { - return assetManager; - } - - public static String getCurrentLanguage() { - String languageName = java.util.Locale.getDefault().getLanguage(); - return languageName; - } - - public static void showMessageBox(String title, String message){ - Message msg = new Message(); - msg.what = HANDLER_SHOW_DIALOG; - msg.obj = new DialogMessage(title, message); - - handler.sendMessage(msg); - } - - public static void enableAccelerometer() { - accelerometerEnabled = true; - accelerometer.enable(); - } - - public static void disableAccelerometer() { - accelerometerEnabled = false; - accelerometer.disable(); - } - - public static void preloadBackgroundMusic(String path){ - backgroundMusicPlayer.preloadBackgroundMusic(path); - } - - public static void playBackgroundMusic(String path, boolean isLoop){ - backgroundMusicPlayer.playBackgroundMusic(path, isLoop); - } - - public static void stopBackgroundMusic(){ - backgroundMusicPlayer.stopBackgroundMusic(); - } - - public static void pauseBackgroundMusic(){ - backgroundMusicPlayer.pauseBackgroundMusic(); - } - - public static void resumeBackgroundMusic(){ - backgroundMusicPlayer.resumeBackgroundMusic(); - } - - public static void rewindBackgroundMusic(){ - backgroundMusicPlayer.rewindBackgroundMusic(); - } - - public static boolean isBackgroundMusicPlaying(){ - return backgroundMusicPlayer.isBackgroundMusicPlaying(); - } - - public static float getBackgroundMusicVolume(){ - return backgroundMusicPlayer.getBackgroundVolume(); - } - - public static void setBackgroundMusicVolume(float volume){ - backgroundMusicPlayer.setBackgroundVolume(volume); - } - - public static int playEffect(String path, boolean isLoop){ - return soundPlayer.playEffect(path, isLoop); - } - - public static void stopEffect(int soundId){ - soundPlayer.stopEffect(soundId); - } - - public static void pauseEffect(int soundId){ - soundPlayer.pauseEffect(soundId); - } - - public static void resumeEffect(int soundId){ - soundPlayer.resumeEffect(soundId); - } - - public static float getEffectsVolume(){ - return soundPlayer.getEffectsVolume(); - } - - public static void setEffectsVolume(float volume){ - soundPlayer.setEffectsVolume(volume); - } - - public static void preloadEffect(String path){ - soundPlayer.preloadEffect(path); - } - - public static void unloadEffect(String path){ - soundPlayer.unloadEffect(path); - } - - public static void stopAllEffects(){ - soundPlayer.stopAllEffects(); - } - - public static void pauseAllEffects(){ - soundPlayer.pauseAllEffects(); - } - - public static void resumeAllEffects(){ - soundPlayer.resumeAllEffects(); - } - - public static void end(){ - backgroundMusicPlayer.end(); - soundPlayer.end(); - } - - public static String getCocos2dxPackageName(){ - return packageName; - } - - public static void terminateProcess(){ - android.os.Process.killProcess(android.os.Process.myPid()); - } - - @Override - protected void onResume() { - super.onResume(); - if (accelerometerEnabled) { - accelerometer.enable(); - } - } - - @Override - protected void onPause() { - super.onPause(); - if (accelerometerEnabled) { - accelerometer.disable(); - } - } - - protected void setPackageName(String packageName) { - Cocos2dxActivity.packageName = packageName; - - String apkFilePath = ""; - ApplicationInfo appInfo = null; - PackageManager packMgmr = getApplication().getPackageManager(); - try { - appInfo = packMgmr.getApplicationInfo(packageName, 0); - } catch (NameNotFoundException e) { - e.printStackTrace(); - throw new RuntimeException("Unable to locate assets, aborting..."); - } - apkFilePath = appInfo.sourceDir; - Log.w("apk path", apkFilePath); - - // add this link at the renderer class - nativeSetPaths(apkFilePath); - } - - private void showDialog(String title, String message){ - Dialog dialog = new AlertDialog.Builder(this) - .setTitle(title) - .setMessage(message) - .setPositiveButton("Ok", - new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int whichButton){ - - } - }).create(); - - dialog.show(); - } - - private static void showEditBoxDialog(String title, String content, int inputMode, int inputFlag, int returnType, int maxLength) - { - Message msg = new Message(); - msg.what = HANDLER_SHOW_EDITBOX_DIALOG; - msg.obj = new EditBoxMessage(title, content, inputMode, inputFlag, returnType, maxLength); - handler.sendMessage(msg); - } - - private void onShowEditBoxDialog(EditBoxMessage msg) - { - Dialog dialog = new Cocos2dxEditBoxDialog(this, msg); - dialog.show(); - } - - public void setEditBoxResult(String editResult) - { - Log.i("editbox_content", editResult); - - try - { - final byte[] bytesUTF8 = editResult.getBytes("UTF8"); - // pass utf8 string from editbox activity to native. - // Should invoke native method in GL thread. - mGLView.queueEvent(new Runnable() { - @Override - public void run() { - nativeSetEditboxText(bytesUTF8); - } - }); - } - catch (java.io.UnsupportedEncodingException e) - { - e.printStackTrace(); - } - } -} - -class DialogMessage { - public String title; - public String message; - - public DialogMessage(String title, String message){ - this.message = message; - this.title = title; - } -} - -class EditBoxMessage { - public String title; - public String content; - public int inputMode; - public int inputFlag; - public int returnType; - public int maxLength; - - public EditBoxMessage(String title, String content, int inputMode, int inputFlag, int returnType, int maxLength){ - this.content = content; - this.title = title; - this.inputMode = inputMode; - this.inputFlag = inputFlag; - this.returnType = returnType; - this.maxLength = maxLength; - } -} diff --git a/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxBitmap.java b/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxBitmap.java deleted file mode 100644 index 395400b779..0000000000 --- a/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxBitmap.java +++ /dev/null @@ -1,455 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010-2011 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.lib; - -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.util.LinkedList; - -import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.Canvas; -import android.graphics.Color; -import android.graphics.Paint; -import android.graphics.Rect; -import android.graphics.Typeface; -import android.graphics.Paint.Align; -import android.graphics.Paint.FontMetricsInt; -import android.text.TextPaint; -import android.text.TextUtils; -import android.util.Log; - -public class Cocos2dxBitmap{ - /* - * The values are the same as cocos2dx/platform/CCImage.h. - */ - private static final int HALIGNCENTER = 3; - private static final int HALIGNLEFT = 1; - private static final int HALIGNRIGHT = 2; - // vertical alignment - private static final int VALIGNTOP = 1; - private static final int VALIGNBOTTOM = 2; - private static final int VALIGNCENTER = 3; - - private static Context context; - - public static void setContext(Context context){ - Cocos2dxBitmap.context = context; - } - - /* - * @width: the width to draw, it can be 0 - * @height: the height to draw, it can be 0 - */ - public static void createTextBitmap(String content, String fontName, - int fontSize, int alignment, int width, int height){ - - content = refactorString(content); - Paint paint = newPaint(fontName, fontSize, alignment); - - TextProperty textProperty = computeTextProperty(content, paint, width, height); - - int bitmapTotalHeight = (height == 0 ? textProperty.totalHeight:height); - - // Draw text to bitmap - Bitmap bitmap = Bitmap.createBitmap(textProperty.maxWidth, - bitmapTotalHeight, Bitmap.Config.ARGB_8888); - Canvas canvas = new Canvas(bitmap); - - // Draw string - FontMetricsInt fm = paint.getFontMetricsInt(); - int x = 0; - int y = computeY(fm, height, textProperty.totalHeight, alignment); - String[] lines = textProperty.lines; - for (String line : lines){ - x = computeX(paint, line, textProperty.maxWidth, alignment); - canvas.drawText(line, x, y, paint); - y += textProperty.heightPerLine; - } - - initNativeObject(bitmap); - } - - private static int computeX(Paint paint, String content, int w, int alignment){ - int ret = 0; - int hAlignment = alignment & 0x0F; - - switch (hAlignment){ - case HALIGNCENTER: - ret = w / 2; - break; - - // ret = 0 - case HALIGNLEFT: - break; - - case HALIGNRIGHT: - ret = w; - break; - - /* - * Default is align left. - * Should be same as newPaint(). - */ - default: - break; - } - - return ret; - } - - private static int computeY(FontMetricsInt fm, int constrainHeight, int totalHeight, int alignment) { - int y = -fm.top; - - if (constrainHeight > totalHeight) { - int vAlignment = (alignment >> 4) & 0x0F; - - switch (vAlignment) { - case VALIGNTOP: - y = -fm.top; - break; - case VALIGNCENTER: - y = -fm.top + (constrainHeight - totalHeight)/2; - break; - case VALIGNBOTTOM: - y = -fm.top + (constrainHeight - totalHeight); - break; - default: - break; - } - } - - return y; - } - - private static class TextProperty{ - // The max width of lines - int maxWidth; - // The height of all lines - int totalHeight; - int heightPerLine; - String[] lines; - - TextProperty(int w, int h, String[] lines){ - this.maxWidth = w; - this.heightPerLine = h; - this.totalHeight = h * lines.length; - this.lines = lines; - } - } - - private static TextProperty computeTextProperty(String content, Paint paint, - int maxWidth, int maxHeight){ - FontMetricsInt fm = paint.getFontMetricsInt(); - int h = (int)Math.ceil(fm.bottom - fm.top); - int maxContentWidth = 0; - - String[] lines = splitString(content, maxHeight, maxWidth, paint); - - if (maxWidth != 0){ - maxContentWidth = maxWidth; - } - else { - /* - * Compute the max width - */ - int temp = 0; - for (String line : lines){ - temp = (int)Math.ceil(paint.measureText(line, 0, line.length())); - if (temp > maxContentWidth){ - maxContentWidth = temp; - } - } - } - - return new TextProperty(maxContentWidth, h, lines); - } - - /* - * If maxWidth or maxHeight is not 0, - * split the string to fix the maxWidth and maxHeight. - */ - private static String[] splitString(String content, int maxHeight, int maxWidth, - Paint paint){ - String[] lines = content.split("\\n"); - String[] ret = null; - FontMetricsInt fm = paint.getFontMetricsInt(); - int heightPerLine = (int)Math.ceil(fm.bottom - fm.top); - int maxLines = maxHeight / heightPerLine; - - if (maxWidth != 0){ - LinkedList strList = new LinkedList(); - for (String line : lines){ - /* - * The width of line is exceed maxWidth, should divide it into - * two or more lines. - */ - int lineWidth = (int)Math.ceil(paint.measureText(line)); - if (lineWidth > maxWidth){ - strList.addAll(divideStringWithMaxWidth(paint, line, maxWidth)); - } - else{ - strList.add(line); - } - - /* - * Should not exceed the max height; - */ - if (maxLines > 0 && strList.size() >= maxLines){ - break; - } - } - - /* - * Remove exceeding lines - */ - if (maxLines > 0 && strList.size() > maxLines){ - while (strList.size() > maxLines){ - strList.removeLast(); - } - } - - ret = new String[strList.size()]; - strList.toArray(ret); - } else - if (maxHeight != 0 && lines.length > maxLines) { - /* - * Remove exceeding lines - */ - LinkedList strList = new LinkedList(); - for (int i = 0; i < maxLines; i++){ - strList.add(lines[i]); - } - ret = new String[strList.size()]; - strList.toArray(ret); - } - else { - ret = lines; - } - - return ret; - } - - private static LinkedList divideStringWithMaxWidth(Paint paint, String content, - int width){ - int charLength = content.length(); - int start = 0; - int tempWidth = 0; - LinkedList strList = new LinkedList(); - - /* - * Break a String into String[] by the width & should wrap the word - */ - for (int i = 1; i <= charLength; ++i){ - tempWidth = (int)Math.ceil(paint.measureText(content, start, i)); - if (tempWidth >= width){ - int lastIndexOfSpace = content.substring(0, i).lastIndexOf(" "); - - if (lastIndexOfSpace != -1 && lastIndexOfSpace > start){ - /** - * Should wrap the word - */ - strList.add(content.substring(start, lastIndexOfSpace)); - i = lastIndexOfSpace; - } - else { - /* - * Should not exceed the width - */ - if (tempWidth > width){ - strList.add(content.substring(start, i - 1)); - /* - * compute from previous char - */ - --i; - } - else { - strList.add(content.substring(start, i)); - } - } - - // remove spaces at the beginning of a new line - while(content.indexOf(i++) == ' ') { - } - - start = i; - } - } - - /* - * Add the last chars - */ - if (start < charLength){ - strList.add(content.substring(start)); - } - - return strList; - } - - private static Paint newPaint(String fontName, int fontSize, int alignment){ - Paint paint = new Paint(); - paint.setColor(Color.WHITE); - paint.setTextSize(fontSize); - paint.setAntiAlias(true); - - /* - * Set type face for paint, now it support .ttf file. - */ - if (fontName.endsWith(".ttf")){ - try { - //Typeface typeFace = Typeface.createFromAsset(context.getAssets(), fontName); - Typeface typeFace = Cocos2dxTypefaces.get(context, fontName); - paint.setTypeface(typeFace); - } catch (Exception e){ - Log.e("Cocos2dxBitmap", - "error to create ttf type face: " + fontName); - - /* - * The file may not find, use system font - */ - paint.setTypeface(Typeface.create(fontName, Typeface.NORMAL)); - } - } - else { - paint.setTypeface(Typeface.create(fontName, Typeface.NORMAL)); - } - - int hAlignment = alignment & 0x0F; - switch (hAlignment){ - case HALIGNCENTER: - paint.setTextAlign(Align.CENTER); - break; - - case HALIGNLEFT: - paint.setTextAlign(Align.LEFT); - break; - - case HALIGNRIGHT: - paint.setTextAlign(Align.RIGHT); - break; - - default: - paint.setTextAlign(Align.LEFT); - break; - } - - return paint; - } - - private static String refactorString(String str){ - // Avoid error when content is "" - if (str.compareTo("") == 0){ - return " "; - } - - /* - * If the font of "\n" is "" or "\n", insert " " in front of it. - * - * For example: - * "\nabc" -> " \nabc" - * "\nabc\n\n" -> " \nabc\n \n" - */ - StringBuilder strBuilder = new StringBuilder(str); - int start = 0; - int index = strBuilder.indexOf("\n"); - while (index != -1){ - if (index == 0 || strBuilder.charAt(index -1) == '\n'){ - strBuilder.insert(start, " "); - start = index + 2; - } else { - start = index + 1; - } - - if (start > strBuilder.length() || index == strBuilder.length()){ - break; - } - - index = strBuilder.indexOf("\n", start); - } - - return strBuilder.toString(); - } - - private static void initNativeObject(Bitmap bitmap){ - byte[] pixels = getPixels(bitmap); - if (pixels == null){ - return; - } - - nativeInitBitmapDC(bitmap.getWidth(), bitmap.getHeight(), pixels); - } - - private static byte[] getPixels(Bitmap bitmap){ - if (bitmap != null){ - byte[] pixels = new byte[bitmap.getWidth() * bitmap.getHeight() * 4]; - ByteBuffer buf = ByteBuffer.wrap(pixels); - buf.order(ByteOrder.nativeOrder()); - bitmap.copyPixelsToBuffer(buf); - return pixels; - } - - return null; - } - - private static native void nativeInitBitmapDC(int width, int height, byte[] pixels); - - private static int getFontSizeAccordingHeight(int height) - { - Paint paint = new Paint(); - Rect bounds = new Rect(); - - paint.setTypeface(Typeface.DEFAULT); - int incr_text_size = 1; - boolean found_desired_size = false; - - while (!found_desired_size) { - - paint.setTextSize(incr_text_size); - String text = "SghMNy"; - paint.getTextBounds(text, 0, text.length(), bounds); - - incr_text_size++; - - if (height - bounds.height() <= 2) { - found_desired_size = true; - } - Log.d("font size", "incr size:" + incr_text_size); - } - return incr_text_size; - } - - private static String getStringWithEllipsis(String originalText, float width, float fontSize){ - if(TextUtils.isEmpty(originalText)){ - return ""; - } - - TextPaint paint = new TextPaint(); - paint.setTypeface(Typeface.DEFAULT); - paint.setTextSize(fontSize); - - return TextUtils.ellipsize(originalText, paint, width, - TextUtils.TruncateAt.valueOf("END")).toString(); - } - -} diff --git a/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxEditBoxDialog.java b/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxEditBoxDialog.java deleted file mode 100755 index 66e94e242c..0000000000 --- a/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxEditBoxDialog.java +++ /dev/null @@ -1,338 +0,0 @@ -/**************************************************************************** -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.lib; - -import android.app.Dialog; -import android.content.Context; -import android.graphics.drawable.ColorDrawable; -import android.os.Bundle; -import android.os.Handler; -import android.text.InputFilter; -import android.text.InputType; -import android.util.Log; -import android.util.TypedValue; -import android.view.KeyEvent; -import android.view.ViewGroup; -import android.view.WindowManager; -import android.view.inputmethod.EditorInfo; -import android.view.inputmethod.InputMethodManager; -import android.widget.EditText; -import android.widget.LinearLayout; -import android.widget.TextView; -import android.widget.TextView.OnEditorActionListener; - -public class Cocos2dxEditBoxDialog extends Dialog { - - /** - * The user is allowed to enter any text, including line breaks. - */ - private final int kEditBoxInputModeAny = 0; - - /** - * The user is allowed to enter an e-mail address. - */ - private final int kEditBoxInputModeEmailAddr = 1; - - /** - * The user is allowed to enter an integer value. - */ - private final int kEditBoxInputModeNumeric = 2; - - /** - * The user is allowed to enter a phone number. - */ - private final int kEditBoxInputModePhoneNumber = 3; - - /** - * The user is allowed to enter a URL. - */ - private final int kEditBoxInputModeUrl = 4; - - /** - * The user is allowed to enter a real number value. - * This extends kEditBoxInputModeNumeric by allowing a decimal point. - */ - private final int kEditBoxInputModeDecimal = 5; - - /** - * The user is allowed to enter any text, except for line breaks. - */ - private final int kEditBoxInputModeSingleLine = 6; - - - /** - * Indicates that the text entered is confidential data that should be - * obscured whenever possible. This implies EDIT_BOX_INPUT_FLAG_SENSITIVE. - */ - private final int kEditBoxInputFlagPassword = 0; - - /** - * Indicates that the text entered is sensitive data that the - * implementation must never store into a dictionary or table for use - * in predictive, auto-completing, or other accelerated input schemes. - * A credit card number is an example of sensitive data. - */ - private final int kEditBoxInputFlagSensitive = 1; - - /** - * This flag is a hint to the implementation that during text editing, - * the initial letter of each word should be capitalized. - */ - private final int kEditBoxInputFlagInitialCapsWord = 2; - - /** - * This flag is a hint to the implementation that during text editing, - * the initial letter of each sentence should be capitalized. - */ - private final int kEditBoxInputFlagInitialCapsSentence = 3; - - /** - * Capitalize all characters automatically. - */ - private final int kEditBoxInputFlagInitialCapsAllCharacters = 4; - - private final int kKeyboardReturnTypeDefault = 0; - private final int kKeyboardReturnTypeDone = 1; - private final int kKeyboardReturnTypeSend = 2; - private final int kKeyboardReturnTypeSearch = 3; - private final int kKeyboardReturnTypeGo = 4; - - // - private EditText mInputEditText = null; - private TextView mTextViewTitle = null; - private int mInputMode = 0; - private int mInputFlag = 0; - private int mReturnType = 0; - private int mMaxLength = -1; - - private int mInputFlagConstraints = 0x00000; - private int mInputModeContraints = 0x00000; - private boolean mIsMultiline = false; - private Cocos2dxActivity mParentActivity = null; - private EditBoxMessage mMsg = null; - - public Cocos2dxEditBoxDialog(Context context, EditBoxMessage msg) { - //super(context, R.style.Theme_Translucent); - super(context, android.R.style.Theme_Translucent_NoTitleBar_Fullscreen); - // TODO Auto-generated constructor stub - mParentActivity = (Cocos2dxActivity)context; - mMsg = msg; - } - - // Converting dips to pixels - private int convertDipsToPixels(float dips) - { - float scale = getContext().getResources().getDisplayMetrics().density; - return Math.round(dips * scale); - } - - @Override - protected void onCreate(Bundle savedInstanceState) { - // TODO Auto-generated method stub - super.onCreate(savedInstanceState); - - getWindow().setBackgroundDrawable(new ColorDrawable(0x80000000)); - - LinearLayout layout = new LinearLayout(mParentActivity); - layout.setOrientation(LinearLayout.VERTICAL); - - LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup. - LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.FILL_PARENT); - - mTextViewTitle = new TextView(mParentActivity); - LinearLayout.LayoutParams textviewParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, - ViewGroup.LayoutParams.WRAP_CONTENT); - textviewParams.leftMargin = textviewParams.rightMargin = convertDipsToPixels(10); - mTextViewTitle.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20); - layout.addView(mTextViewTitle, textviewParams); - - mInputEditText = new EditText(mParentActivity); - LinearLayout.LayoutParams editTextParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, - ViewGroup.LayoutParams.WRAP_CONTENT); - editTextParams.leftMargin = editTextParams.rightMargin = convertDipsToPixels(10); - - layout.addView(mInputEditText, editTextParams); - - setContentView(layout, layoutParams); - - getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); - - mInputMode = mMsg.inputMode; - mInputFlag = mMsg.inputFlag; - mReturnType = mMsg.returnType; - mMaxLength = mMsg.maxLength; - - mTextViewTitle.setText(mMsg.title); - mInputEditText.setText(mMsg.content); - - int oldImeOptions = mInputEditText.getImeOptions(); - mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_FLAG_NO_EXTRACT_UI); - oldImeOptions = mInputEditText.getImeOptions(); - - switch (mInputMode) - { - case kEditBoxInputModeAny: - mInputModeContraints = - InputType.TYPE_CLASS_TEXT | - InputType.TYPE_TEXT_FLAG_MULTI_LINE; - break; - case kEditBoxInputModeEmailAddr: - mInputModeContraints = - InputType.TYPE_CLASS_TEXT | - InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS; - break; - case kEditBoxInputModeNumeric: - mInputModeContraints = - InputType.TYPE_CLASS_NUMBER | - InputType.TYPE_NUMBER_FLAG_SIGNED; - break; - case kEditBoxInputModePhoneNumber: - mInputModeContraints = InputType.TYPE_CLASS_PHONE; - break; - case kEditBoxInputModeUrl: - mInputModeContraints = - InputType.TYPE_CLASS_TEXT | - InputType.TYPE_TEXT_VARIATION_URI; - break; - case kEditBoxInputModeDecimal: - mInputModeContraints = - InputType.TYPE_CLASS_NUMBER | - InputType.TYPE_NUMBER_FLAG_DECIMAL | - InputType.TYPE_NUMBER_FLAG_SIGNED; - break; - case kEditBoxInputModeSingleLine: - mInputModeContraints = InputType.TYPE_CLASS_TEXT; - break; - default: - - break; - } - - if ( mIsMultiline ) { - mInputModeContraints |= InputType.TYPE_TEXT_FLAG_MULTI_LINE; - } - - mInputEditText.setInputType(mInputModeContraints | mInputFlagConstraints); - - switch (mInputFlag) - { - case kEditBoxInputFlagPassword: - mInputFlagConstraints = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD; - break; - case kEditBoxInputFlagSensitive: - mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS; - break; - case kEditBoxInputFlagInitialCapsWord: - mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_CAP_WORDS; - break; - case kEditBoxInputFlagInitialCapsSentence: - mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_CAP_SENTENCES; - break; - case kEditBoxInputFlagInitialCapsAllCharacters: - mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS; - break; - default: - break; - } - mInputEditText.setInputType(mInputFlagConstraints | mInputModeContraints); - - switch (mReturnType) { - case kKeyboardReturnTypeDefault: - mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_NONE); - break; - case kKeyboardReturnTypeDone: - mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_DONE); - break; - case kKeyboardReturnTypeSend: - mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_SEND); - break; - case kKeyboardReturnTypeSearch: - mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_SEARCH); - break; - case kKeyboardReturnTypeGo: - mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_GO); - break; - default: - mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_NONE); - break; - } - - if (mMaxLength > 0) { - mInputEditText.setFilters( - new InputFilter[] { - new InputFilter.LengthFilter(mMaxLength) - } - ); - } - - Handler initHandler = new Handler(); - initHandler.postDelayed(new Runnable() { - public void run() { - mInputEditText.requestFocus(); - mInputEditText.setSelection(mInputEditText.length()); - openKeyboard(); - } - }, 200); - - mInputEditText.setOnEditorActionListener(new OnEditorActionListener() { - @Override - public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { - // if user didn't set keyboard type, - // this callback will be invoked twice with 'KeyEvent.ACTION_DOWN' and 'KeyEvent.ACTION_UP' - if (actionId != EditorInfo.IME_NULL - || (actionId == EditorInfo.IME_NULL - && event != null - && event.getAction() == KeyEvent.ACTION_DOWN)) - { - //Log.d("EditBox", "actionId: "+actionId +",event: "+event); - mParentActivity.setEditBoxResult(mInputEditText.getText().toString()); - closeKeyboard(); - dismiss(); - return true; - } - return false; - } - }); - } - - private void openKeyboard() { - InputMethodManager imm = (InputMethodManager) mParentActivity.getSystemService(Context.INPUT_METHOD_SERVICE); - imm.showSoftInput(mInputEditText, 0); - Log.d("Cocos2dxEditBox", "openKeyboard"); - } - - private void closeKeyboard() { - InputMethodManager imm = (InputMethodManager) mParentActivity.getSystemService(Context.INPUT_METHOD_SERVICE); - imm.hideSoftInputFromWindow(mInputEditText.getWindowToken(), 0); - Log.d("Cocos2dxEditBox", "closeKeyboard"); - } - - @Override - protected void onStop() { - // TODO Auto-generated method stub - super.onStop(); - Log.d("EditBox", "onStop..."); - } -} diff --git a/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxEditText.java b/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxEditText.java deleted file mode 100644 index 1c9778293f..0000000000 --- a/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxEditText.java +++ /dev/null @@ -1,65 +0,0 @@ -/**************************************************************************** -Copyright (c) 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.lib; - -import android.content.Context; -import android.util.AttributeSet; -import android.view.KeyEvent; -import android.widget.EditText; - -public class Cocos2dxEditText extends EditText { - - private Cocos2dxGLSurfaceView mView; - - public Cocos2dxEditText(Context context) { - super(context); - // TODO Auto-generated constructor stub - } - - public Cocos2dxEditText(Context context, AttributeSet attrs) { - super(context, attrs); - } - - public Cocos2dxEditText(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - } - - public void setMainView(Cocos2dxGLSurfaceView glSurfaceView) { - mView = glSurfaceView; - } - - /* - * Let GlSurfaceView get focus if back key is input - */ - public boolean onKeyDown(int keyCode, KeyEvent event) { - super.onKeyDown(keyCode, event); - - if (keyCode == KeyEvent.KEYCODE_BACK) { - mView.requestFocus(); - } - - return true; - } -} diff --git a/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java b/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java deleted file mode 100644 index e7c4721cf3..0000000000 --- a/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java +++ /dev/null @@ -1,417 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010-2011 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.lib; - -import android.content.Context; -import android.opengl.GLSurfaceView; -import android.os.Handler; -import android.os.Message; -import android.text.Editable; -import android.text.TextWatcher; -import android.util.AttributeSet; -import android.util.Log; -import android.view.KeyEvent; -import android.view.MotionEvent; -import android.view.inputmethod.InputMethodManager; -import android.widget.TextView; -import android.widget.TextView.OnEditorActionListener; - -class TextInputWraper implements TextWatcher, OnEditorActionListener { - - private static final Boolean debug = false; - private void LogD(String msg) { - if (debug) Log.d("TextInputFilter", msg); - } - - private Cocos2dxGLSurfaceView mMainView; - private String mText; - private String mOriginText; - - private Boolean isFullScreenEdit() { - InputMethodManager imm = (InputMethodManager)mMainView.getTextField().getContext().getSystemService(Context.INPUT_METHOD_SERVICE); - return imm.isFullscreenMode(); - } - - public TextInputWraper(Cocos2dxGLSurfaceView view) { - mMainView = view; - } - - public void setOriginText(String text) { - mOriginText = text; - } - - @Override - public void afterTextChanged(Editable s) { - if (isFullScreenEdit()) { - return; - } - - LogD("afterTextChanged: " + s); - int nModified = s.length() - mText.length(); - if (nModified > 0) { - final String insertText = s.subSequence(mText.length(), s.length()).toString(); - mMainView.insertText(insertText); - LogD("insertText(" + insertText + ")"); - } - else { - for (; nModified < 0; ++nModified) { - mMainView.deleteBackward(); - LogD("deleteBackward"); - } - } - mText = s.toString(); - } - - @Override - public void beforeTextChanged(CharSequence s, int start, int count, - int after) { - LogD("beforeTextChanged(" + s + ")start: " + start + ",count: " + count + ",after: " + after); - mText = s.toString(); - } - - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - } - - @Override - public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { - if (mMainView.getTextField() == v && isFullScreenEdit()) { - // user press the action button, delete all old text and insert new text - for (int i = mOriginText.length(); i > 0; --i) { - mMainView.deleteBackward(); - LogD("deleteBackward"); - } - String text = v.getText().toString(); - - /* - * If user input nothing, translate "\n" to engine. - */ - if (text.compareTo("") == 0){ - text = "\n"; - } - - if ('\n' != text.charAt(text.length() - 1)) { - text += '\n'; - } - - final String insertText = text; - mMainView.insertText(insertText); - LogD("insertText(" + insertText + ")"); - } - return false; - } -} - -public class Cocos2dxGLSurfaceView extends GLSurfaceView { - - static private Cocos2dxGLSurfaceView mainView; - - private static final String TAG = Cocos2dxGLSurfaceView.class.getCanonicalName(); - private Cocos2dxRenderer mRenderer; - - private static final boolean debug = false; - - /////////////////////////////////////////////////////////////////////////// - // for initialize - /////////////////////////////////////////////////////////////////////////// - public Cocos2dxGLSurfaceView(Context context) { - super(context); - initView(); - } - - public Cocos2dxGLSurfaceView(Context context, AttributeSet attrs) { - super(context, attrs); - initView(); - } - - public void setCocos2dxRenderer(Cocos2dxRenderer renderer){ - mRenderer = renderer; - setRenderer(mRenderer); - } - - protected void initView() { - setFocusableInTouchMode(true); - - textInputWraper = new TextInputWraper(this); - - handler = new Handler(){ - public void handleMessage(Message msg){ - switch(msg.what){ - case HANDLER_OPEN_IME_KEYBOARD: - if (null != mTextField && mTextField.requestFocus()) { - mTextField.removeTextChangedListener(textInputWraper); - mTextField.setText(""); - String text = (String)msg.obj; - mTextField.append(text); - textInputWraper.setOriginText(text); - mTextField.addTextChangedListener(textInputWraper); - InputMethodManager imm = (InputMethodManager)mainView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); - imm.showSoftInput(mTextField, 0); - Log.d("GLSurfaceView", "showSoftInput"); - } - break; - - case HANDLER_CLOSE_IME_KEYBOARD: - if (null != mTextField) { - mTextField.removeTextChangedListener(textInputWraper); - InputMethodManager imm = (InputMethodManager)mainView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); - imm.hideSoftInputFromWindow(mTextField.getWindowToken(), 0); - Log.d("GLSurfaceView", "HideSoftInput"); - } - break; - } - } - }; - - mainView = this; - } - - public void onPause(){ - queueEvent(new Runnable() { - @Override - public void run() { - mRenderer.handleOnPause(); - } - }); - - super.onPause(); - } - - public void onResume(){ - super.onResume(); - - queueEvent(new Runnable() { - @Override - public void run() { - mRenderer.handleOnResume(); - } - }); - } - - /////////////////////////////////////////////////////////////////////////// - // for text input - /////////////////////////////////////////////////////////////////////////// - private final static int HANDLER_OPEN_IME_KEYBOARD = 2; - private final static int HANDLER_CLOSE_IME_KEYBOARD = 3; - private static Handler handler; - private static TextInputWraper textInputWraper; - private Cocos2dxEditText mTextField; - - public TextView getTextField() { - return mTextField; - } - - public void setTextField(Cocos2dxEditText view) { - mTextField = view; - if (null != mTextField && null != textInputWraper) { - mTextField.setOnEditorActionListener(textInputWraper); - mTextField.setMainView(this); - this.requestFocus(); - } - } - - public static void openIMEKeyboard() { - Message msg = new Message(); - msg.what = HANDLER_OPEN_IME_KEYBOARD; - msg.obj = mainView.getContentText(); - handler.sendMessage(msg); - - } - - private String getContentText() { - return mRenderer.getContentText(); - } - - public static void closeIMEKeyboard() { - Message msg = new Message(); - msg.what = HANDLER_CLOSE_IME_KEYBOARD; - handler.sendMessage(msg); - } - - public void insertText(final String text) { - queueEvent(new Runnable() { - @Override - public void run() { - mRenderer.handleInsertText(text); - } - }); - } - - public void deleteBackward() { - queueEvent(new Runnable() { - @Override - public void run() { - mRenderer.handleDeleteBackward(); - } - }); - } - - /////////////////////////////////////////////////////////////////////////// - // for touch event - /////////////////////////////////////////////////////////////////////////// - - public boolean onTouchEvent(final MotionEvent event) { - // these data are used in ACTION_MOVE and ACTION_CANCEL - final int pointerNumber = event.getPointerCount(); - final int[] ids = new int[pointerNumber]; - final float[] xs = new float[pointerNumber]; - final float[] ys = new float[pointerNumber]; - - for (int i = 0; i < pointerNumber; i++) { - ids[i] = event.getPointerId(i); - xs[i] = event.getX(i); - ys[i] = event.getY(i); - } - - switch (event.getAction() & MotionEvent.ACTION_MASK) { - case MotionEvent.ACTION_POINTER_DOWN: - final int indexPointerDown = event.getAction() >> MotionEvent.ACTION_POINTER_ID_SHIFT; - final int idPointerDown = event.getPointerId(indexPointerDown); - final float xPointerDown = event.getX(indexPointerDown); - final float yPointerDown = event.getY(indexPointerDown); - - queueEvent(new Runnable() { - @Override - public void run() { - mRenderer.handleActionDown(idPointerDown, xPointerDown, yPointerDown); - } - }); - break; - - case MotionEvent.ACTION_DOWN: - // there are only one finger on the screen - final int idDown = event.getPointerId(0); - final float xDown = xs[0]; - final float yDown = ys[0]; - - queueEvent(new Runnable() { - @Override - public void run() { - mRenderer.handleActionDown(idDown, xDown, yDown); - } - }); - break; - - case MotionEvent.ACTION_MOVE: - queueEvent(new Runnable() { - @Override - public void run() { - mRenderer.handleActionMove(ids, xs, ys); - } - }); - break; - - case MotionEvent.ACTION_POINTER_UP: - final int indexPointUp = event.getAction() >> MotionEvent.ACTION_POINTER_ID_SHIFT; - final int idPointerUp = event.getPointerId(indexPointUp); - final float xPointerUp = event.getX(indexPointUp); - final float yPointerUp = event.getY(indexPointUp); - - queueEvent(new Runnable() { - @Override - public void run() { - mRenderer.handleActionUp(idPointerUp, xPointerUp, yPointerUp); - } - }); - break; - - case MotionEvent.ACTION_UP: - // there are only one finger on the screen - final int idUp = event.getPointerId(0); - final float xUp = xs[0]; - final float yUp = ys[0]; - - queueEvent(new Runnable() { - @Override - public void run() { - mRenderer.handleActionUp(idUp, xUp, yUp); - } - }); - break; - - case MotionEvent.ACTION_CANCEL: - queueEvent(new Runnable() { - @Override - public void run() { - mRenderer.handleActionCancel(ids, xs, ys); - } - }); - break; - } - - if (debug){ - dumpEvent(event); - } - return true; - } - - /* - * This function is called before Cocos2dxRenderer.nativeInit(), so the width and height is correct. - */ - protected void onSizeChanged(int w, int h, int oldw, int oldh){ - this.mRenderer.setScreenWidthAndHeight(w, h); - } - - @Override - public boolean onKeyDown(int keyCode, KeyEvent event) { - final int kc = keyCode; - if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_MENU) { - queueEvent(new Runnable() { - @Override - public void run() { - mRenderer.handleKeyDown(kc); - } - }); - return true; - } - return super.onKeyDown(keyCode, event); - } - - // Show an event in the LogCat view, for debugging - private void dumpEvent(MotionEvent event) { - String names[] = { "DOWN" , "UP" , "MOVE" , "CANCEL" , "OUTSIDE" , - "POINTER_DOWN" , "POINTER_UP" , "7?" , "8?" , "9?" }; - StringBuilder sb = new StringBuilder(); - int action = event.getAction(); - int actionCode = action & MotionEvent.ACTION_MASK; - sb.append("event ACTION_" ).append(names[actionCode]); - if (actionCode == MotionEvent.ACTION_POINTER_DOWN - || actionCode == MotionEvent.ACTION_POINTER_UP) { - sb.append("(pid " ).append( - action >> MotionEvent.ACTION_POINTER_ID_SHIFT); - sb.append(")" ); - } - sb.append("[" ); - for (int i = 0; i < event.getPointerCount(); i++) { - sb.append("#" ).append(i); - sb.append("(pid " ).append(event.getPointerId(i)); - sb.append(")=" ).append((int) event.getX(i)); - sb.append("," ).append((int) event.getY(i)); - if (i + 1 < event.getPointerCount()) - sb.append(";" ); - } - sb.append("]" ); - Log.d(TAG, sb.toString()); - } -} diff --git a/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxMusic.java b/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxMusic.java deleted file mode 100644 index 10e3e5f3c6..0000000000 --- a/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxMusic.java +++ /dev/null @@ -1,228 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010-2011 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.lib; - -import android.content.Context; -import android.content.res.AssetFileDescriptor; -import android.media.MediaPlayer; -import android.util.Log; - -/** - * - * This class is used for controlling background music - * - */ -public class Cocos2dxMusic { - - private static final String TAG = "Cocos2dxMusic"; - private float mLeftVolume; - private float mRightVolume; - private Context mContext; - private MediaPlayer mBackgroundMediaPlayer; - private boolean mIsPaused; - private String mCurrentPath; - - public Cocos2dxMusic(Context context){ - this.mContext = context; - initData(); - } - - public void preloadBackgroundMusic(String path){ - if ((mCurrentPath == null) || (! mCurrentPath.equals(path))){ - // preload new background music - - // release old resource and create a new one - if (mBackgroundMediaPlayer != null){ - mBackgroundMediaPlayer.release(); - } - - mBackgroundMediaPlayer = createMediaplayerFromAssets(path); - - // record the path - mCurrentPath = path; - } - } - - public void playBackgroundMusic(String path, boolean isLoop){ - if (mCurrentPath == null){ - // it is the first time to play background music - // or end() was called - mBackgroundMediaPlayer = createMediaplayerFromAssets(path); - mCurrentPath = path; - } - else { - if (! mCurrentPath.equals(path)){ - // play new background music - - // release old resource and create a new one - if (mBackgroundMediaPlayer != null){ - mBackgroundMediaPlayer.release(); - } - mBackgroundMediaPlayer = createMediaplayerFromAssets(path); - - // record the path - mCurrentPath = path; - } - } - - if (mBackgroundMediaPlayer == null){ - Log.e(TAG, "playBackgroundMusic: background media player is null"); - } else { - // if the music is playing or paused, stop it - mBackgroundMediaPlayer.stop(); - - mBackgroundMediaPlayer.setLooping(isLoop); - - try { - mBackgroundMediaPlayer.prepare(); - mBackgroundMediaPlayer.seekTo(0); - mBackgroundMediaPlayer.start(); - - this.mIsPaused = false; - } catch (Exception e){ - Log.e(TAG, "playBackgroundMusic: error state"); - } - } - } - - public void stopBackgroundMusic(){ - if (mBackgroundMediaPlayer != null){ - mBackgroundMediaPlayer.stop(); - - // should set the state, if not , the following sequence will be error - // play -> pause -> stop -> resume - this.mIsPaused = false; - } - } - - public void pauseBackgroundMusic(){ - if (mBackgroundMediaPlayer != null && mBackgroundMediaPlayer.isPlaying()){ - mBackgroundMediaPlayer.pause(); - this.mIsPaused = true; - } - } - - public void resumeBackgroundMusic(){ - if (mBackgroundMediaPlayer != null && this.mIsPaused){ - mBackgroundMediaPlayer.start(); - this.mIsPaused = false; - } - } - - public void rewindBackgroundMusic(){ - if (mBackgroundMediaPlayer != null){ - mBackgroundMediaPlayer.stop(); - - try { - mBackgroundMediaPlayer.prepare(); - mBackgroundMediaPlayer.seekTo(0); - mBackgroundMediaPlayer.start(); - - this.mIsPaused = false; - } catch (Exception e){ - Log.e(TAG, "rewindBackgroundMusic: error state"); - } - } - } - - public boolean isBackgroundMusicPlaying(){ - boolean ret = false; - - if (mBackgroundMediaPlayer == null){ - ret = false; - } else { - ret = mBackgroundMediaPlayer.isPlaying(); - } - - return ret; - } - - public void end(){ - if (mBackgroundMediaPlayer != null){ - mBackgroundMediaPlayer.release(); - } - - initData(); - } - - public float getBackgroundVolume(){ - if (this.mBackgroundMediaPlayer != null){ - return (this.mLeftVolume + this.mRightVolume) / 2; - } else { - return 0.0f; - } - } - - public void setBackgroundVolume(float volume){ - if (volume < 0.0f){ - volume = 0.0f; - } - - if (volume > 1.0f){ - volume = 1.0f; - } - - this.mLeftVolume = this.mRightVolume = volume; - if (this.mBackgroundMediaPlayer != null){ - this.mBackgroundMediaPlayer.setVolume(this.mLeftVolume, this.mRightVolume); - } - } - - private void initData(){ - mLeftVolume =0.5f; - mRightVolume = 0.5f; - mBackgroundMediaPlayer = null; - mIsPaused = false; - mCurrentPath = null; - } - - /** - * create mediaplayer for music - * @param path the path relative to assets - * @return - */ - private MediaPlayer createMediaplayerFromAssets(String path){ - MediaPlayer mediaPlayer = new MediaPlayer(); - - try{ - if (path.startsWith("/")) { - mediaPlayer.setDataSource(path); - } - else { - AssetFileDescriptor assetFileDescritor = mContext.getAssets().openFd(path); - mediaPlayer.setDataSource(assetFileDescritor.getFileDescriptor(), - assetFileDescritor.getStartOffset(), assetFileDescritor.getLength()); - } - - mediaPlayer.prepare(); - - mediaPlayer.setVolume(mLeftVolume, mRightVolume); - }catch (Exception e) { - mediaPlayer = null; - Log.e(TAG, "error: " + e.getMessage(), e); - } - - return mediaPlayer; - } -} diff --git a/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxRenderer.java b/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxRenderer.java deleted file mode 100644 index fad0974f42..0000000000 --- a/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxRenderer.java +++ /dev/null @@ -1,137 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010-2011 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.lib; - -import javax.microedition.khronos.egl.EGLConfig; -import javax.microedition.khronos.opengles.GL10; - -import android.opengl.GLSurfaceView; - -public class Cocos2dxRenderer implements GLSurfaceView.Renderer { - private final static long NANOSECONDSPERSECOND = 1000000000L; - private final static long NANOSECONDSPERMINISECOND = 1000000; - private static long animationInterval = (long)(1.0 / 60 * NANOSECONDSPERSECOND); - private long last; - private int screenWidth; - private int screenHeight; - - public void onSurfaceCreated(GL10 gl, EGLConfig config) { - nativeInit(screenWidth, screenHeight); - last = System.nanoTime(); - } - - public void setScreenWidthAndHeight(int w, int h){ - this.screenWidth = w; - this.screenHeight = h; - } - - public void onSurfaceChanged(GL10 gl, int w, int h) { - } - - public void onDrawFrame(GL10 gl) { - - long now = System.nanoTime(); - long interval = now - last; - - // should render a frame when onDrawFrame() is called - // or there is a "ghost" - nativeRender(); - - // fps controlling - if (interval < animationInterval){ - try { - // because we render it before, so we should sleep twice time interval - Thread.sleep((animationInterval - interval) * 2 / NANOSECONDSPERMINISECOND); - } catch (Exception e){} - } - - last = now; - } - - public void handleActionDown(int id, float x, float y) - { - nativeTouchesBegin(id, x, y); - } - - public void handleActionUp(int id, float x, float y) - { - nativeTouchesEnd(id, x, y); - } - - public void handleActionCancel(int[] id, float[] x, float[] y) - { - nativeTouchesCancel(id, x, y); - } - - public void handleActionMove(int[] id, float[] x, float[] y) - { - nativeTouchesMove(id, x, y); - } - - public void handleKeyDown(int keyCode) - { - nativeKeyDown(keyCode); - } - - public void handleOnPause(){ - nativeOnPause(); - } - - public void handleOnResume(){ - nativeOnResume(); - } - - public static void setAnimationInterval(double interval){ - animationInterval = (long)(interval * NANOSECONDSPERSECOND); - } - private static native void nativeTouchesBegin(int id, float x, float y); - private static native void nativeTouchesEnd(int id, float x, float y); - private static native void nativeTouchesMove(int[] id, float[] x, float[] y); - private static native void nativeTouchesCancel(int[] id, float[] x, float[] y); - private static native boolean nativeKeyDown(int keyCode); - private static native void nativeRender(); - private static native void nativeInit(int w, int h); - private static native void nativeOnPause(); - private static native void nativeOnResume(); - - ///////////////////////////////////////////////////////////////////////////////// - // handle input method edit message - ///////////////////////////////////////////////////////////////////////////////// - - public void handleInsertText(final String text) { - nativeInsertText(text); - } - - public void handleDeleteBackward() { - nativeDeleteBackward(); - } - - public String getContentText() { - return nativeGetContentText(); - } - - private static native void nativeInsertText(String text); - private static native void nativeDeleteBackward(); - private static native String nativeGetContentText(); -} diff --git a/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxSound.java b/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxSound.java deleted file mode 100644 index e7061f74de..0000000000 --- a/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxSound.java +++ /dev/null @@ -1,245 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010-2011 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.lib; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import android.content.Context; -import android.media.AudioManager; -import android.media.SoundPool; -import android.util.Log; - -/** - * - * This class is used for controlling effect - * - */ - -public class Cocos2dxSound { - private Context mContext; - private SoundPool mSoundPool; - private float mLeftVolume; - private float mRightVolume; - - // sound path and stream ids map - // a file may be played many times at the same time - // so there is an array map to a file path - private HashMap> mPathStreamIDsMap; - - private HashMap mPathSoundIdMap; - - private static final String TAG = "Cocos2dxSound"; - private static final int MAX_SIMULTANEOUS_STREAMS_DEFAULT = 5; - private static final float SOUND_RATE = 1.0f; - private static final int SOUND_PRIORITY = 1; - private static final int SOUND_QUALITY = 5; - - private final static int INVALID_SOUND_ID = -1; - private final static int INVALID_STREAM_ID = -1; - - public Cocos2dxSound(Context context){ - this.mContext = context; - initData(); - } - - public int preloadEffect(String path){ - Integer soundID = this.mPathSoundIdMap.get(path); - - if (soundID == null) { - soundID = createSoundIdFromAsset(path); - this.mPathSoundIdMap.put(path, soundID); - } - - return soundID; - } - - public void unloadEffect(String path){ - // stop effects - ArrayList streamIDs = this.mPathStreamIDsMap.get(path); - if (streamIDs != null) { - for (Integer streamID : streamIDs) { - this.mSoundPool.stop(streamID); - } - } - this.mPathStreamIDsMap.remove(path); - - // unload effect - Integer soundID = this.mPathSoundIdMap.get(path); - this.mSoundPool.unload(soundID); - this.mPathSoundIdMap.remove(path); - } - - public int playEffect(String path, boolean isLoop){ - Integer soundId = this.mPathSoundIdMap.get(path); - int streamId = INVALID_STREAM_ID; - - if (soundId != null){ - // play sound - streamId = this.mSoundPool.play(soundId.intValue(), this.mLeftVolume, - this.mRightVolume, SOUND_PRIORITY, isLoop ? -1 : 0, SOUND_RATE); - - // record stream id - ArrayList streamIds = this.mPathStreamIDsMap.get(path); - if (streamIds == null) { - streamIds = new ArrayList(); - this.mPathStreamIDsMap.put(path, streamIds); - } - streamIds.add(streamId); - } else { - // the effect is not prepared - soundId = preloadEffect(path); - if (soundId == INVALID_SOUND_ID){ - // can not preload effect - return 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. - */ - playEffect(path, isLoop); - } - - return streamId; - } - - public void stopEffect(int streamID){ - this.mSoundPool.stop(streamID); - - // remove record - for (String path : this.mPathStreamIDsMap.keySet()) { - if (this.mPathStreamIDsMap.get(path).contains(streamID)) { - this.mPathStreamIDsMap.get(path).remove(this.mPathStreamIDsMap.get(path).indexOf(streamID)); - break; - } - } - } - - public void pauseEffect(int streamID){ - this.mSoundPool.pause(streamID); - } - - public void resumeEffect(int streamID){ - this.mSoundPool.resume(streamID); - } - - public void pauseAllEffects(){ - this.mSoundPool.autoPause(); - } - - public void resumeAllEffects(){ - // autoPause() is available since level 8 - this.mSoundPool.autoResume(); - } - - @SuppressWarnings("unchecked") - public void stopAllEffects(){ - // stop effects - if (! this.mPathStreamIDsMap.isEmpty()) { - Iterator iter = this.mPathStreamIDsMap.entrySet().iterator(); - while (iter.hasNext()){ - Map.Entry> entry = (Map.Entry>)iter.next(); - for (int streamID : entry.getValue()) { - this.mSoundPool.stop(streamID); - } - } - } - - // remove records - this.mPathStreamIDsMap.clear(); - } - - public float getEffectsVolume(){ - return (this.mLeftVolume + this.mRightVolume) / 2; - } - - @SuppressWarnings("unchecked") - public void setEffectsVolume(float volume){ - // volume should be in [0, 1.0] - if (volume < 0){ - volume = 0; - } - if (volume > 1){ - volume = 1; - } - - this.mLeftVolume = this.mRightVolume = volume; - - // change the volume of playing sounds - if (! this.mPathStreamIDsMap.isEmpty()) { - Iterator iter = this.mPathStreamIDsMap.entrySet().iterator(); - while (iter.hasNext()){ - Map.Entry> entry = (Map.Entry>)iter.next(); - for (int streamID : entry.getValue()) { - this.mSoundPool.setVolume(streamID, mLeftVolume, mRightVolume); - } - } - } - } - - public void end(){ - this.mSoundPool.release(); - this.mPathStreamIDsMap.clear(); - this.mPathSoundIdMap.clear(); - - initData(); - } - - public int createSoundIdFromAsset(String path){ - int soundId = INVALID_SOUND_ID; - - try { - if (path.startsWith("/")){ - soundId = mSoundPool.load(path, 0); - } - else { - soundId = mSoundPool.load(mContext.getAssets().openFd(path), 0); - } - } catch(Exception e){ - soundId = INVALID_SOUND_ID; - Log.e(TAG, "error: " + e.getMessage(), e); - } - - return soundId; - } - - private void initData(){ - this.mPathStreamIDsMap = new HashMap>(); - this.mPathSoundIdMap = new HashMap(); - mSoundPool = new SoundPool(MAX_SIMULTANEOUS_STREAMS_DEFAULT, AudioManager.STREAM_MUSIC, SOUND_QUALITY); - - this.mLeftVolume = 0.5f; - this.mRightVolume = 0.5f; - } -} diff --git a/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxTypefaces.java b/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxTypefaces.java deleted file mode 100644 index 79af1ed3af..0000000000 --- a/SimpleGame/proj.android/src/org/cocos2dx/lib/Cocos2dxTypefaces.java +++ /dev/null @@ -1,44 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010-2011 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.lib; - -import java.util.Hashtable; - -import android.content.Context; -import android.graphics.Typeface; - -public class Cocos2dxTypefaces { - private static final Hashtable cache = new Hashtable(); - - public static Typeface get(Context context, String name){ - synchronized(cache){ - if (! cache.containsKey(name)){ - Typeface t = Typeface.createFromAsset(context.getAssets(), name); - cache.put(name, t); - } - - return cache.get(name); - } - } -} diff --git a/SimpleGame/proj.android/src/org/cocos2dx/simplegame/SimpleGame.java b/SimpleGame/proj.android/src/org/cocos2dx/simplegame/SimpleGame.java deleted file mode 100644 index 99171bd284..0000000000 --- a/SimpleGame/proj.android/src/org/cocos2dx/simplegame/SimpleGame.java +++ /dev/null @@ -1,108 +0,0 @@ -/**************************************************************************** -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.simplegame; - -import org.cocos2dx.lib.Cocos2dxActivity; -import org.cocos2dx.lib.Cocos2dxEditText; -import org.cocos2dx.lib.Cocos2dxGLSurfaceView; -import org.cocos2dx.lib.Cocos2dxRenderer; - -import android.app.ActivityManager; -import android.content.Context; -import android.content.pm.ConfigurationInfo; -import android.os.Bundle; -import android.util.Log; -import android.widget.FrameLayout; -import android.view.ViewGroup; - -public class SimpleGame extends Cocos2dxActivity{ - - protected void onCreate(Bundle savedInstanceState){ - super.onCreate(savedInstanceState); - - if (detectOpenGLES20()) { - // get the packageName,it's used to set the resource path - String packageName = getApplication().getPackageName(); - super.setPackageName(packageName); - - // FrameLayout - ViewGroup.LayoutParams framelayout_params = - new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, - ViewGroup.LayoutParams.FILL_PARENT); - FrameLayout framelayout = new FrameLayout(this); - framelayout.setLayoutParams(framelayout_params); - - // Cocos2dxEditText layout - ViewGroup.LayoutParams edittext_layout_params = - new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, - ViewGroup.LayoutParams.WRAP_CONTENT); - Cocos2dxEditText edittext = new Cocos2dxEditText(this); - edittext.setLayoutParams(edittext_layout_params); - - // ...add to FrameLayout - framelayout.addView(edittext); - - // Cocos2dxGLSurfaceView - mGLView = new Cocos2dxGLSurfaceView(this); - - // ...add to FrameLayout - framelayout.addView(mGLView); - - mGLView.setEGLContextClientVersion(2); - mGLView.setCocos2dxRenderer(new Cocos2dxRenderer()); - mGLView.setTextField(edittext); - - // Set framelayout as the content view - setContentView(framelayout); - } - else { - Log.d("activity", "don't support gles2.0"); - finish(); - } - } - - @Override - protected void onPause() { - super.onPause(); - mGLView.onPause(); - } - - @Override - protected void onResume() { - super.onResume(); - mGLView.onResume(); - } - - private boolean detectOpenGLES20() - { - ActivityManager am = - (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); - ConfigurationInfo info = am.getDeviceConfigurationInfo(); - return (info.reqGlEsVersion >= 0x20000); - } - - static { - System.loadLibrary("game"); - } -}