diff --git a/CHANGELOG b/CHANGELOG index 546f4d6574..609b4923b0 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,6 +1,14 @@ +cocos2d-x-3.4 ?? + [NEW] UI:LoadingBar: add TextureResType to LoadingBar's create method + [NEW] Allocator: add custom allocator support, global, default, fixed block, object pool. + + [FIX] FileUtils: WebP format with alpha channel displayed wrong + [FIX] Label: content size of Label is incorrect if the string is set to empty string + cocos2d-x-3.3 Dec.12 [FIX] Billboard: allow billboard rotate along z axis [FIX] Bundle3D: create aabb for mesh whose aabb does not exist (user custom mesh) + [FIX] EditBox: text position and move animation error on iPhone6 Plus [FIX] FileUtils: createDirectory(): doesn't invoke closedir() after opendir on platforms other than WP8/WinRT/Windows cocos2d-x-3.3-rc2 Dec.5 diff --git a/README.md b/README.md index bdab36e479..f16b8c80c7 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,12 @@ Run $ cocos run -p win32 +### Build and run new project for Windows 8.1 and Windows Phone 8.1 ### + + $ cocos new MyGame -p com.bar.foo -l cpp -d projects + +With the Cocos2d-x v3.3, you can create Universal App (Two projects at the same time: Windows(Tablet) and Windows Phone 8.1 ) +See more info on How to install and Create games on Windows RT (Windows and Windows Phone 8.1) at http://msopentech.github.io/cocos2d-x/ Main features ------------- @@ -123,16 +129,19 @@ Build Requirements * or Ubuntu 12.10+, CMake 2.6+ * or Windows 7+, VS 2012+ * Python 2.7.5 -* NDK r9d is required to build Android games +* NDK r10c+ is required to build Android games +* Windows Phone/Store 8.0 VS 2012+ +* Windows Phone/Store 8.1 VS 2013 Update 3+ Runtime Requirements -------------------- * iOS 5.0+ for iPhone / iPad games * Android 2.3+ for Android games - * Windows Phone 8+ for Windows Phone games + * Windows Phone 8 and 8.1 for Windows Phone games * OS X v10.6+ for Mac games * Windows 7+ for Win games + * Windows 8+ for WinRT games (Modern Apps) Running Tests diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj b/build/cocos2d_libs.xcodeproj/project.pbxproj index 56e3084ff2..c026346655 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj @@ -1927,6 +1927,30 @@ B60C5BD519AC68B10056FBDE /* CCBillBoard.cpp in Sources */ = {isa = PBXBuildFile; fileRef = B60C5BD219AC68B10056FBDE /* CCBillBoard.cpp */; }; B60C5BD619AC68B10056FBDE /* CCBillBoard.h in Headers */ = {isa = PBXBuildFile; fileRef = B60C5BD319AC68B10056FBDE /* CCBillBoard.h */; }; B60C5BD719AC68B10056FBDE /* CCBillBoard.h in Headers */ = {isa = PBXBuildFile; fileRef = B60C5BD319AC68B10056FBDE /* CCBillBoard.h */; }; + D0FD03491A3B51AA00825BB5 /* CCAllocatorBase.h in Headers */ = {isa = PBXBuildFile; fileRef = D0FD033B1A3B51AA00825BB5 /* CCAllocatorBase.h */; }; + D0FD034A1A3B51AA00825BB5 /* CCAllocatorBase.h in Headers */ = {isa = PBXBuildFile; fileRef = D0FD033B1A3B51AA00825BB5 /* CCAllocatorBase.h */; }; + D0FD034B1A3B51AA00825BB5 /* CCAllocatorDiagnostics.cpp in Sources */ = {isa = PBXBuildFile; fileRef = D0FD033C1A3B51AA00825BB5 /* CCAllocatorDiagnostics.cpp */; }; + D0FD034C1A3B51AA00825BB5 /* CCAllocatorDiagnostics.cpp in Sources */ = {isa = PBXBuildFile; fileRef = D0FD033C1A3B51AA00825BB5 /* CCAllocatorDiagnostics.cpp */; }; + D0FD034D1A3B51AA00825BB5 /* CCAllocatorDiagnostics.h in Headers */ = {isa = PBXBuildFile; fileRef = D0FD033D1A3B51AA00825BB5 /* CCAllocatorDiagnostics.h */; }; + D0FD034E1A3B51AA00825BB5 /* CCAllocatorDiagnostics.h in Headers */ = {isa = PBXBuildFile; fileRef = D0FD033D1A3B51AA00825BB5 /* CCAllocatorDiagnostics.h */; }; + D0FD034F1A3B51AA00825BB5 /* CCAllocatorGlobal.cpp in Sources */ = {isa = PBXBuildFile; fileRef = D0FD033E1A3B51AA00825BB5 /* CCAllocatorGlobal.cpp */; }; + D0FD03501A3B51AA00825BB5 /* CCAllocatorGlobal.cpp in Sources */ = {isa = PBXBuildFile; fileRef = D0FD033E1A3B51AA00825BB5 /* CCAllocatorGlobal.cpp */; }; + D0FD03511A3B51AA00825BB5 /* CCAllocatorGlobal.h in Headers */ = {isa = PBXBuildFile; fileRef = D0FD033F1A3B51AA00825BB5 /* CCAllocatorGlobal.h */; }; + D0FD03521A3B51AA00825BB5 /* CCAllocatorGlobal.h in Headers */ = {isa = PBXBuildFile; fileRef = D0FD033F1A3B51AA00825BB5 /* CCAllocatorGlobal.h */; }; + D0FD03531A3B51AA00825BB5 /* CCAllocatorGlobalNewDelete.cpp in Sources */ = {isa = PBXBuildFile; fileRef = D0FD03401A3B51AA00825BB5 /* CCAllocatorGlobalNewDelete.cpp */; }; + D0FD03541A3B51AA00825BB5 /* CCAllocatorGlobalNewDelete.cpp in Sources */ = {isa = PBXBuildFile; fileRef = D0FD03401A3B51AA00825BB5 /* CCAllocatorGlobalNewDelete.cpp */; }; + D0FD03551A3B51AA00825BB5 /* CCAllocatorMacros.h in Headers */ = {isa = PBXBuildFile; fileRef = D0FD03411A3B51AA00825BB5 /* CCAllocatorMacros.h */; }; + D0FD03561A3B51AA00825BB5 /* CCAllocatorMacros.h in Headers */ = {isa = PBXBuildFile; fileRef = D0FD03411A3B51AA00825BB5 /* CCAllocatorMacros.h */; }; + D0FD03571A3B51AA00825BB5 /* CCAllocatorMutex.h in Headers */ = {isa = PBXBuildFile; fileRef = D0FD03421A3B51AA00825BB5 /* CCAllocatorMutex.h */; }; + D0FD03581A3B51AA00825BB5 /* CCAllocatorMutex.h in Headers */ = {isa = PBXBuildFile; fileRef = D0FD03421A3B51AA00825BB5 /* CCAllocatorMutex.h */; }; + D0FD03591A3B51AA00825BB5 /* CCAllocatorStrategyDefault.h in Headers */ = {isa = PBXBuildFile; fileRef = D0FD03431A3B51AA00825BB5 /* CCAllocatorStrategyDefault.h */; }; + D0FD035A1A3B51AA00825BB5 /* CCAllocatorStrategyDefault.h in Headers */ = {isa = PBXBuildFile; fileRef = D0FD03431A3B51AA00825BB5 /* CCAllocatorStrategyDefault.h */; }; + D0FD035B1A3B51AA00825BB5 /* CCAllocatorStrategyFixedBlock.h in Headers */ = {isa = PBXBuildFile; fileRef = D0FD03441A3B51AA00825BB5 /* CCAllocatorStrategyFixedBlock.h */; }; + D0FD035C1A3B51AA00825BB5 /* CCAllocatorStrategyFixedBlock.h in Headers */ = {isa = PBXBuildFile; fileRef = D0FD03441A3B51AA00825BB5 /* CCAllocatorStrategyFixedBlock.h */; }; + D0FD035D1A3B51AA00825BB5 /* CCAllocatorStrategyGlobalSmallBlock.h in Headers */ = {isa = PBXBuildFile; fileRef = D0FD03451A3B51AA00825BB5 /* CCAllocatorStrategyGlobalSmallBlock.h */; }; + D0FD035E1A3B51AA00825BB5 /* CCAllocatorStrategyGlobalSmallBlock.h in Headers */ = {isa = PBXBuildFile; fileRef = D0FD03451A3B51AA00825BB5 /* CCAllocatorStrategyGlobalSmallBlock.h */; }; + D0FD035F1A3B51AA00825BB5 /* CCAllocatorStrategyPool.h in Headers */ = {isa = PBXBuildFile; fileRef = D0FD03461A3B51AA00825BB5 /* CCAllocatorStrategyPool.h */; }; + D0FD03601A3B51AA00825BB5 /* CCAllocatorStrategyPool.h in Headers */ = {isa = PBXBuildFile; fileRef = D0FD03461A3B51AA00825BB5 /* CCAllocatorStrategyPool.h */; }; DA8C62A219E52C6400000516 /* ioapi_mem.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DA8C62A019E52C6400000516 /* ioapi_mem.cpp */; }; DA8C62A319E52C6400000516 /* ioapi_mem.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DA8C62A019E52C6400000516 /* ioapi_mem.cpp */; }; DA8C62A419E52C6400000516 /* ioapi_mem.h in Headers */ = {isa = PBXBuildFile; fileRef = DA8C62A119E52C6400000516 /* ioapi_mem.h */; }; @@ -2985,6 +3009,18 @@ B67C624319D4186F00F11FC6 /* ccShader_3D_ColorNormal.frag */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.glsl; path = ccShader_3D_ColorNormal.frag; sourceTree = ""; }; B67C624419D4186F00F11FC6 /* ccShader_3D_ColorNormalTex.frag */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.glsl; path = ccShader_3D_ColorNormalTex.frag; sourceTree = ""; }; B67C624519D4186F00F11FC6 /* ccShader_3D_PositionNormalTex.vert */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.glsl; path = ccShader_3D_PositionNormalTex.vert; sourceTree = ""; }; + D0FD033B1A3B51AA00825BB5 /* CCAllocatorBase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCAllocatorBase.h; sourceTree = ""; }; + D0FD033C1A3B51AA00825BB5 /* CCAllocatorDiagnostics.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCAllocatorDiagnostics.cpp; sourceTree = ""; }; + D0FD033D1A3B51AA00825BB5 /* CCAllocatorDiagnostics.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCAllocatorDiagnostics.h; sourceTree = ""; }; + D0FD033E1A3B51AA00825BB5 /* CCAllocatorGlobal.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCAllocatorGlobal.cpp; sourceTree = ""; }; + D0FD033F1A3B51AA00825BB5 /* CCAllocatorGlobal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCAllocatorGlobal.h; sourceTree = ""; }; + D0FD03401A3B51AA00825BB5 /* CCAllocatorGlobalNewDelete.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCAllocatorGlobalNewDelete.cpp; sourceTree = ""; }; + D0FD03411A3B51AA00825BB5 /* CCAllocatorMacros.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCAllocatorMacros.h; sourceTree = ""; }; + D0FD03421A3B51AA00825BB5 /* CCAllocatorMutex.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCAllocatorMutex.h; sourceTree = ""; }; + D0FD03431A3B51AA00825BB5 /* CCAllocatorStrategyDefault.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCAllocatorStrategyDefault.h; sourceTree = ""; }; + D0FD03441A3B51AA00825BB5 /* CCAllocatorStrategyFixedBlock.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCAllocatorStrategyFixedBlock.h; sourceTree = ""; }; + D0FD03451A3B51AA00825BB5 /* CCAllocatorStrategyGlobalSmallBlock.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCAllocatorStrategyGlobalSmallBlock.h; sourceTree = ""; }; + D0FD03461A3B51AA00825BB5 /* CCAllocatorStrategyPool.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCAllocatorStrategyPool.h; sourceTree = ""; }; DA8C62A019E52C6400000516 /* ioapi_mem.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ioapi_mem.cpp; sourceTree = ""; }; DA8C62A119E52C6400000516 /* ioapi_mem.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ioapi_mem.h; sourceTree = ""; }; DABC9FA719E7DFA900FA252C /* CCClippingRectangleNode.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCClippingRectangleNode.cpp; sourceTree = ""; }; @@ -3195,6 +3231,7 @@ 1A5700A2180BC5E60088DEC7 /* base */ = { isa = PBXGroup; children = ( + D0FD03391A3B51AA00825BB5 /* allocator */, 299CF1F919A434BC00C378C1 /* ccRandom.cpp */, 299CF1FA19A434BC00C378C1 /* ccRandom.h */, 464AD6E3197EBB1400E502D8 /* pvr.cpp */, @@ -5118,6 +5155,26 @@ path = ../cocos/3d; sourceTree = ""; }; + D0FD03391A3B51AA00825BB5 /* allocator */ = { + isa = PBXGroup; + children = ( + D0FD033B1A3B51AA00825BB5 /* CCAllocatorBase.h */, + D0FD033C1A3B51AA00825BB5 /* CCAllocatorDiagnostics.cpp */, + D0FD033D1A3B51AA00825BB5 /* CCAllocatorDiagnostics.h */, + D0FD033E1A3B51AA00825BB5 /* CCAllocatorGlobal.cpp */, + D0FD033F1A3B51AA00825BB5 /* CCAllocatorGlobal.h */, + D0FD03401A3B51AA00825BB5 /* CCAllocatorGlobalNewDelete.cpp */, + D0FD03411A3B51AA00825BB5 /* CCAllocatorMacros.h */, + D0FD03421A3B51AA00825BB5 /* CCAllocatorMutex.h */, + D0FD03431A3B51AA00825BB5 /* CCAllocatorStrategyDefault.h */, + D0FD03441A3B51AA00825BB5 /* CCAllocatorStrategyFixedBlock.h */, + D0FD03451A3B51AA00825BB5 /* CCAllocatorStrategyGlobalSmallBlock.h */, + D0FD03461A3B51AA00825BB5 /* CCAllocatorStrategyPool.h */, + ); + name = allocator; + path = ../base/allocator; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXHeadersBuildPhase section */ @@ -5132,6 +5189,7 @@ 5034CA39191D591100CE6051 /* ccShader_PositionColorLengthTexture.frag in Headers */, 292DB14B19B4574100A80320 /* UIEditBoxImpl-mac.h in Headers */, B29A7E3F19EE1B7700872B35 /* AnimationState.h in Headers */, + D0FD03591A3B51AA00825BB5 /* CCAllocatorStrategyDefault.h in Headers */, 50ABBE891925AB6F00A911A9 /* CCMap.h in Headers */, 50ABBE8D1925AB6F00A911A9 /* CCNS.h in Headers */, B29A7DFD19EE1B7700872B35 /* IkConstraintData.h in Headers */, @@ -5155,6 +5213,7 @@ 15AE1A8119AAD40300C27E9E /* b2FrictionJoint.h in Headers */, 15AE18DD19AAD35000C27E9E /* CocoLoader.h in Headers */, 46A170EB1807CECA005B8026 /* CCPhysicsJoint.h in Headers */, + D0FD03511A3B51AA00825BB5 /* CCAllocatorGlobal.h in Headers */, 15AE191E19AAD35000C27E9E /* CCTween.h in Headers */, 15AE184619AAD2F700C27E9E /* CCSprite3DMaterial.h in Headers */, 50ABBD3E1925AB0000A911A9 /* CCGeometry.h in Headers */, @@ -5238,6 +5297,7 @@ 29394CF419B01DBA00D2DE1A /* UIWebViewImpl-ios.h in Headers */, B29A7E1719EE1B7700872B35 /* Atlas.h in Headers */, 1A57009A180BC5C10088DEC7 /* CCAtlasNode.h in Headers */, + D0FD035B1A3B51AA00825BB5 /* CCAllocatorStrategyFixedBlock.h in Headers */, 15AE190819AAD35000C27E9E /* CCDatas.h in Headers */, B29A7E1119EE1B7700872B35 /* EventData.h in Headers */, 1A5700A0180BC5D20088DEC7 /* CCNode.h in Headers */, @@ -5290,8 +5350,10 @@ 15AE186419AAD31D00C27E9E /* CDConfig.h in Headers */, 15AE1BB819AADFEF00C27E9E /* WebSocket.h in Headers */, 1A5701B7180BCB5A0088DEC7 /* CCFontFreeType.h in Headers */, + D0FD03551A3B51AA00825BB5 /* CCAllocatorMacros.h in Headers */, 3823842A1A2590F9002C4610 /* NodeReader.h in Headers */, 1A5701BB180BCB5A0088DEC7 /* CCLabel.h in Headers */, + D0FD035D1A3B51AA00825BB5 /* CCAllocatorStrategyGlobalSmallBlock.h in Headers */, 15AE182619AAD2F700C27E9E /* CCMesh.h in Headers */, 15AE192019AAD35000C27E9E /* CCUtilMath.h in Headers */, 15AE1BC119AADFFB00C27E9E /* cocos-ext.h in Headers */, @@ -5439,6 +5501,7 @@ 15AE181E19AAD2F700C27E9E /* CCBundle3DData.h in Headers */, 1A5702F8180BCE750088DEC7 /* CCTMXTiledMap.h in Headers */, 5034CA21191D591100CE6051 /* ccShader_PositionTextureColorAlphaTest.frag in Headers */, + D0FD03491A3B51AA00825BB5 /* CCAllocatorBase.h in Headers */, 15AE1A2419AAD3D500C27E9E /* b2BroadPhase.h in Headers */, B29A7E3919EE1B7700872B35 /* Animation.h in Headers */, 382384381A259126002C4610 /* ProjectNodeReader.h in Headers */, @@ -5603,8 +5666,10 @@ 50ABBDB31925AB4100A911A9 /* ccShaders.h in Headers */, 50ABBDAB1925AB4100A911A9 /* CCRenderCommandPool.h in Headers */, 5034CA45191D591100CE6051 /* ccShader_Label_outline.frag in Headers */, + D0FD035F1A3B51AA00825BB5 /* CCAllocatorStrategyPool.h in Headers */, 50ABBEB11925AB6F00A911A9 /* CCUserDefault.h in Headers */, B29A7DEF19EE1B7700872B35 /* SkeletonBounds.h in Headers */, + D0FD034D1A3B51AA00825BB5 /* CCAllocatorDiagnostics.h in Headers */, 50ABBEC71925AB6F00A911A9 /* etc1.h in Headers */, B29A7E3519EE1B7700872B35 /* AnimationStateData.h in Headers */, 15AE1BC619AAE00000C27E9E /* AssetsManager.h in Headers */, @@ -5620,6 +5685,7 @@ 3EACC9A219F5014D00EB3C5E /* CCCamera.h in Headers */, 50ABBECD1925AB6F00A911A9 /* s3tc.h in Headers */, 15AE1BD119AAE01E00C27E9E /* CCControlHuePicker.h in Headers */, + D0FD03571A3B51AA00825BB5 /* CCAllocatorMutex.h in Headers */, 50ABBE771925AB6F00A911A9 /* CCEventListenerTouch.h in Headers */, 5034CA33191D591100CE6051 /* ccShader_PositionTexture_uColor.frag in Headers */, 50ABC0171926664800A911A9 /* CCImage.h in Headers */, @@ -5657,6 +5723,7 @@ 15AE1B8119AADA9A00C27E9E /* UITextAtlas.h in Headers */, B29A7E3A19EE1B7700872B35 /* Animation.h in Headers */, 15B3708319EE414C00ABE682 /* CCEventListenerAssetsManagerEx.h in Headers */, + D0FD03521A3B51AA00825BB5 /* CCAllocatorGlobal.h in Headers */, 50ABBE7C1925AB6F00A911A9 /* CCEventMouse.h in Headers */, B29A7E2C19EE1B7700872B35 /* AtlasAttachmentLoader.h in Headers */, 46A171011807CECB005B8026 /* CCPhysicsJoint.h in Headers */, @@ -5713,6 +5780,7 @@ 1A57006C180BC5A10088DEC7 /* CCActionCatmullRom.h in Headers */, 15AE195C19AAD35100C27E9E /* CCSGUIReader.h in Headers */, 5034CA3A191D591100CE6051 /* ccShader_PositionColorLengthTexture.frag in Headers */, + D0FD034E1A3B51AA00825BB5 /* CCAllocatorDiagnostics.h in Headers */, DABC9FAC19E7DFA900FA252C /* CCClippingRectangleNode.h in Headers */, 50ABBEC41925AB6F00A911A9 /* CCVector.h in Headers */, 50ABBE501925AB6F00A911A9 /* CCEventCustom.h in Headers */, @@ -5787,6 +5855,7 @@ 15AE1A4F19AAD3D500C27E9E /* b2Shape.h in Headers */, 29394CF519B01DBA00D2DE1A /* UIWebViewImpl-ios.h in Headers */, 50ABBD5B1925AB0000A911A9 /* Vec2.h in Headers */, + D0FD035E1A3B51AA00825BB5 /* CCAllocatorStrategyGlobalSmallBlock.h in Headers */, 50ABBD411925AB0000A911A9 /* CCMath.h in Headers */, 1A5701A0180BCB590088DEC7 /* CCFont.h in Headers */, 292DB14819B4574100A80320 /* UIEditBoxImpl-ios.h in Headers */, @@ -5802,6 +5871,7 @@ 15AE1ACB19AAD40300C27E9E /* b2MouseJoint.h in Headers */, 50ABBD3F1925AB0000A911A9 /* CCGeometry.h in Headers */, B29A7DD019EE1B7700872B35 /* RegionAttachment.h in Headers */, + D0FD034A1A3B51AA00825BB5 /* CCAllocatorBase.h in Headers */, 15AE1AD319AAD40300C27E9E /* b2RopeJoint.h in Headers */, 50ABBFFE1926664800A911A9 /* CCFileUtils-apple.h in Headers */, 15AE1AAD19AAD40300C27E9E /* b2WorldCallbacks.h in Headers */, @@ -5855,6 +5925,7 @@ 3EACC9A719F5014D00EB3C5E /* CCLight.h in Headers */, 15AE194E19AAD35100C27E9E /* CCDataReaderHelper.h in Headers */, 15AE1ADB19AAD41000C27E9E /* b2Rope.h in Headers */, + D0FD03561A3B51AA00825BB5 /* CCAllocatorMacros.h in Headers */, 1A5701CE180BCB5A0088DEC7 /* CCLabelTTF.h in Headers */, 15AE1AB119AAD40300C27E9E /* b2ChainAndPolygonContact.h in Headers */, 1A5701E1180BCB8C0088DEC7 /* CCLayer.h in Headers */, @@ -5949,6 +6020,7 @@ 15AE18D119AAD33D00C27E9E /* CCNodeLoaderLibrary.h in Headers */, 15AE1AC319AAD40300C27E9E /* b2DistanceJoint.h in Headers */, 50ABBE741925AB6F00A911A9 /* CCEventListenerMouse.h in Headers */, + D0FD03581A3B51AA00825BB5 /* CCAllocatorMutex.h in Headers */, B29A7E1219EE1B7700872B35 /* EventData.h in Headers */, 1A5702CB180BCE370088DEC7 /* CCTextFieldTTF.h in Headers */, 1A5702ED180BCE750088DEC7 /* CCTileMapAtlas.h in Headers */, @@ -5979,6 +6051,7 @@ B375107F1823ACA100B3BA6A /* CCPhysicsContactInfo_chipmunk.h in Headers */, 15AE185D19AAD31200C27E9E /* CocosDenshion.h in Headers */, 15AE194319AAD35100C27E9E /* CCColliderDetector.h in Headers */, + D0FD035C1A3B51AA00825BB5 /* CCAllocatorStrategyFixedBlock.h in Headers */, 15AE1BC419AADFFB00C27E9E /* ExtensionMacros.h in Headers */, 15AE185A19AAD31200C27E9E /* CDConfig.h in Headers */, B29A7DE819EE1B7700872B35 /* spine.h in Headers */, @@ -6047,6 +6120,7 @@ 50ABC0081926664800A911A9 /* CCApplicationProtocol.h in Headers */, 1ABA68B11888D700007D1BB4 /* CCFontCharMap.h in Headers */, 15AE1ACF19AAD40300C27E9E /* b2PulleyJoint.h in Headers */, + D0FD03601A3B51AA00825BB5 /* CCAllocatorStrategyPool.h in Headers */, 15AE198019AAD35700C27E9E /* CCTimeLine.h in Headers */, 38B8E2E419E671D2002D7CE7 /* UILayoutComponent.h in Headers */, 50ABBD4F1925AB0000A911A9 /* MathUtil.h in Headers */, @@ -6076,6 +6150,7 @@ 50CB247619D9C5A100687767 /* AudioCache.h in Headers */, B29A7DDA19EE1B7700872B35 /* SkeletonRenderer.h in Headers */, 15AE194119AAD35100C27E9E /* CCBone.h in Headers */, + D0FD035A1A3B51AA00825BB5 /* CCAllocatorStrategyDefault.h in Headers */, 50ABBD471925AB0000A911A9 /* CCVertex.h in Headers */, 15AE195A19AAD35100C27E9E /* CCProcessBase.h in Headers */, 15AE193D19AAD35100C27E9E /* CCArmatureDefine.h in Headers */, @@ -6332,6 +6407,7 @@ 15AE1B5F19AADA9900C27E9E /* UITextField.cpp in Sources */, 15AE187C19AAD33D00C27E9E /* CCBFileLoader.cpp in Sources */, 50ABBE651925AB6F00A911A9 /* CCEventListenerCustom.cpp in Sources */, + D0FD034B1A3B51AA00825BB5 /* CCAllocatorDiagnostics.cpp in Sources */, 15AE189B19AAD33D00C27E9E /* CCNode+CCBRelativePositioning.cpp in Sources */, 15AE183819AAD2F700C27E9E /* CCRay.cpp in Sources */, B37510781823AC9F00B3BA6A /* CCPhysicsShapeInfo_chipmunk.cpp in Sources */, @@ -6597,6 +6673,7 @@ DABC9FA919E7DFA900FA252C /* CCClippingRectangleNode.cpp in Sources */, 3E2F27A619CFBFE100E7C490 /* AudioEngine.cpp in Sources */, 15AE1A3619AAD3D500C27E9E /* b2PolygonShape.cpp in Sources */, + D0FD03531A3B51AA00825BB5 /* CCAllocatorGlobalNewDelete.cpp in Sources */, 50ABBD9B1925AB4100A911A9 /* ccGLStateCache.cpp in Sources */, 15AE188119AAD33D00C27E9E /* CCBReader.cpp in Sources */, 50ABBDB91925AB4100A911A9 /* CCTextureAtlas.cpp in Sources */, @@ -6609,6 +6686,7 @@ 50ABBECF1925AB6F00A911A9 /* TGAlib.cpp in Sources */, 15AE199E19AAD39600C27E9E /* SliderReader.cpp in Sources */, 50ABBE451925AB6F00A911A9 /* CCEvent.cpp in Sources */, + D0FD034F1A3B51AA00825BB5 /* CCAllocatorGlobal.cpp in Sources */, 50ABBE611925AB6F00A911A9 /* CCEventListenerAcceleration.cpp in Sources */, 50ABBD9F1925AB4100A911A9 /* CCGroupCommand.cpp in Sources */, 15AE1A8E19AAD40300C27E9E /* b2RopeJoint.cpp in Sources */, @@ -6669,6 +6747,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + D0FD03541A3B51AA00825BB5 /* CCAllocatorGlobalNewDelete.cpp in Sources */, 15AE1B9819AADAA100C27E9E /* UIVideoPlayer-ios.mm in Sources */, 15AE1C0519AAE01E00C27E9E /* CCTableViewCell.cpp in Sources */, 15AE198A19AAD36A00C27E9E /* ButtonReader.cpp in Sources */, @@ -6990,6 +7069,7 @@ 50ABBE8C1925AB6F00A911A9 /* CCNS.cpp in Sources */, B29A7DE019EE1B7700872B35 /* IkConstraintData.c in Sources */, B29A7DFC19EE1B7700872B35 /* spine-cocos2dx.cpp in Sources */, + D0FD03501A3B51AA00825BB5 /* CCAllocatorGlobal.cpp in Sources */, 15AE1BA919AADFDF00C27E9E /* UIVBox.cpp in Sources */, 50ABBDAE1925AB4100A911A9 /* CCRenderer.cpp in Sources */, 382383FB1A258FA7002C4610 /* idl_gen_go.cpp in Sources */, @@ -7102,6 +7182,7 @@ 15AE196519AAD35100C27E9E /* CCTween.cpp in Sources */, 46C02E0818E91123004B7456 /* xxhash.c in Sources */, 15AE183519AAD2F700C27E9E /* CCObjLoader.cpp in Sources */, + D0FD034C1A3B51AA00825BB5 /* CCAllocatorDiagnostics.cpp in Sources */, 50ABBED01925AB6F00A911A9 /* TGAlib.cpp in Sources */, 1A01C68518F57BE800EFE3A6 /* CCArray.cpp in Sources */, B29A7E2219EE1B7700872B35 /* PolygonBatch.cpp in Sources */, diff --git a/build/cocos2d_tests.xcodeproj/project.pbxproj b/build/cocos2d_tests.xcodeproj/project.pbxproj index 0ef5c1eb2f..7ed84eeb22 100644 --- a/build/cocos2d_tests.xcodeproj/project.pbxproj +++ b/build/cocos2d_tests.xcodeproj/project.pbxproj @@ -821,6 +821,8 @@ C08689C218D370C90093E810 /* background.caf in Resources */ = {isa = PBXBuildFile; fileRef = C08689C018D370C90093E810 /* background.caf */; }; C08689C318D370C90093E810 /* background.caf in Resources */ = {isa = PBXBuildFile; fileRef = C08689C018D370C90093E810 /* background.caf */; }; C08689C418D370C90093E810 /* background.caf in Resources */ = {isa = PBXBuildFile; fileRef = C08689C018D370C90093E810 /* background.caf */; }; + D0FD03641A3B546400825BB5 /* AllocatorTest.cpp in Sources */ = {isa = PBXBuildFile; fileRef = D0FD03621A3B546400825BB5 /* AllocatorTest.cpp */; }; + D0FD03651A3B546400825BB5 /* AllocatorTest.cpp in Sources */ = {isa = PBXBuildFile; fileRef = D0FD03621A3B546400825BB5 /* AllocatorTest.cpp */; }; D60AE43417F7FFE100757E4B /* CoreMotion.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D60AE43317F7FFE100757E4B /* CoreMotion.framework */; }; EDCC747F17C455FD007B692C /* IOKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EDCC747E17C455FD007B692C /* IOKit.framework */; }; /* End PBXBuildFile section */ @@ -1744,6 +1746,8 @@ C04F93581941B05400E9FEAB /* TileMapTest2.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = TileMapTest2.cpp; sourceTree = ""; }; C04F93591941B05400E9FEAB /* TileMapTest2.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TileMapTest2.h; sourceTree = ""; }; C08689C018D370C90093E810 /* background.caf */ = {isa = PBXFileReference; lastKnownFileType = file; name = background.caf; path = "../tests/cpp-tests/Resources/background.caf"; sourceTree = ""; }; + D0FD03621A3B546400825BB5 /* AllocatorTest.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = AllocatorTest.cpp; path = AllocatorTest/AllocatorTest.cpp; sourceTree = ""; }; + D0FD03631A3B546400825BB5 /* AllocatorTest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AllocatorTest.h; path = AllocatorTest/AllocatorTest.h; sourceTree = ""; }; D60AE43317F7FFE100757E4B /* CoreMotion.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreMotion.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS7.0.sdk/System/Library/Frameworks/CoreMotion.framework; sourceTree = DEVELOPER_DIR; }; EDCC747E17C455FD007B692C /* IOKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = IOKit.framework; path = System/Library/Frameworks/IOKit.framework; sourceTree = SDKROOT; }; /* End PBXFileReference section */ @@ -2151,6 +2155,7 @@ 1AC3592418CECF0A00F37B72 /* Classes */ = { isa = PBXGroup; children = ( + D0FD03611A3B543700825BB5 /* AllocatorTest */, B6C039D619C95D28007207DC /* LightTest */, B609E67019C18D90003D0074 /* BillBoardTest */, 3E2BDACD19BEA3410055CDCD /* NewAudioEngineTest */, @@ -3933,6 +3938,15 @@ name = LightTest; sourceTree = ""; }; + D0FD03611A3B543700825BB5 /* AllocatorTest */ = { + isa = PBXGroup; + children = ( + D0FD03621A3B546400825BB5 /* AllocatorTest.cpp */, + D0FD03631A3B546400825BB5 /* AllocatorTest.h */, + ); + name = AllocatorTest; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -4798,6 +4812,7 @@ 1AC35BE718CECF0C00F37B72 /* CCControlScene.cpp in Sources */, B609E67319C18DAD003D0074 /* BillBoardTest.cpp in Sources */, 292CF01419A1965E00E8E6A0 /* UIEditBoxTest.cpp in Sources */, + D0FD03641A3B546400825BB5 /* AllocatorTest.cpp in Sources */, 29080DBF191B595E0066F8DF /* UIPageViewTest_Editor.cpp in Sources */, 1AC35B5F18CECF0C00F37B72 /* DataVisitorTest.cpp in Sources */, 1AC35B5D18CECF0C00F37B72 /* CurrentLanguageTest.cpp in Sources */, @@ -4980,6 +4995,7 @@ 1AC35B6218CECF0C00F37B72 /* DrawPrimitivesTest.cpp in Sources */, 29080DDC191B595E0066F8DF /* UITextFieldTest.cpp in Sources */, 1AC35C1818CECF0C00F37B72 /* MotionStreakTest.cpp in Sources */, + D0FD03651A3B546400825BB5 /* AllocatorTest.cpp in Sources */, 1AC35C0618CECF0C00F37B72 /* FontTest.cpp in Sources */, 1AC35C3818CECF0C00F37B72 /* PerformanceTest.cpp in Sources */, 1F33635018E37E840074764D /* RefPtrTest.cpp in Sources */, diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index b812d793d2..24365d63f1 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -583,6 +583,7 @@ void Label::alignText() { if (_fontAtlas == nullptr || _currentUTF16String.empty()) { + setContentSize(Size::ZERO); return; } diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index dbf4ec2789..e756ae32ba 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -93,6 +93,7 @@ Node::Node(void) , _anchorPointInPoints(Vec2::ZERO) , _anchorPoint(Vec2::ZERO) , _contentSize(Size::ZERO) +, _contentSizeDirty(true) , _transformDirty(true) , _inverseDirty(true) , _useAdditionalTransform(false) diff --git a/cocos/2d/libcocos2d.vcxproj b/cocos/2d/libcocos2d.vcxproj index 86b3c636ea..a4cc8ee226 100644 --- a/cocos/2d/libcocos2d.vcxproj +++ b/cocos/2d/libcocos2d.vcxproj @@ -243,6 +243,9 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\chipmunk\prebuilt\win32\release-lib\*.* + + + @@ -611,6 +614,15 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\chipmunk\prebuilt\win32\release-lib\*.* + + + + + + + + + diff --git a/cocos/2d/libcocos2d.vcxproj.filters b/cocos/2d/libcocos2d.vcxproj.filters index e57722ffab..7026a625b9 100644 --- a/cocos/2d/libcocos2d.vcxproj.filters +++ b/cocos/2d/libcocos2d.vcxproj.filters @@ -238,6 +238,9 @@ {9aee531c-f935-4836-bf84-be42e78e38bb} + + {92ff4e66-3943-47da-a439-c8f182bb871a} + @@ -1292,6 +1295,15 @@ cocostudio\TimelineAction + + base\allocator + + + base\allocator + + + base\allocator + @@ -2511,6 +2523,33 @@ cocostudio\TimelineAction + + base\allocator + + + base\allocator + + + base\allocator + + + base\allocator + + + base\allocator + + + base\allocator + + + base\allocator + + + base\allocator + + + base\allocator + diff --git a/cocos/Android.mk b/cocos/Android.mk index 518c888e31..662e3a9687 100644 --- a/cocos/Android.mk +++ b/cocos/Android.mk @@ -140,6 +140,9 @@ base/pvr.cpp \ base/s3tc.cpp \ base/CCController.cpp \ base/CCController-android.cpp \ +base/allocator/CCAllocatorDiagnostics.cpp \ +base/allocator/CCAllocatorGlobal.cpp \ +base/allocator/CCAllocatorGlobalNewDelete.cpp \ base/ObjectFactory.cpp \ renderer/CCBatchCommand.cpp \ renderer/CCCustomCommand.cpp \ diff --git a/cocos/base/CCConsole.cpp b/cocos/base/CCConsole.cpp index 673cefc62b..198d25cfe7 100644 --- a/cocos/base/CCConsole.cpp +++ b/cocos/base/CCConsole.cpp @@ -63,6 +63,7 @@ #include "renderer/CCTextureCache.h" #include "base/base64.h" #include "base/ccUtils.h" +#include "base/allocator/CCAllocatorDiagnostics.h" NS_CC_BEGIN extern const char* cocos2dVersion(void); @@ -261,6 +262,7 @@ Console::Console() { // VS2012 doesn't support initializer list, so we create a new array and assign its elements to '_command'. Command commands[] = { + { "allocator", "Display allocator diagnostics for all allocators", std::bind(&Console::commandAllocator, this, std::placeholders::_1, std::placeholders::_2) }, { "config", "Print the Configuration object", std::bind(&Console::commandConfig, this, std::placeholders::_1, std::placeholders::_2) }, { "debugmsg", "Whether or not to forward the debug messages on the console. Args: [on | off]", [&](int fd, const std::string& args) { if( args.compare("on")==0 || args.compare("off")==0) { @@ -771,6 +773,16 @@ void Console::commandTouch(int fd, const std::string& args) } } +void Console::commandAllocator(int fd, const std::string& args) +{ +#if CC_ENABLE_ALLOCATOR_DIAGNOSTICS + auto info = allocator::AllocatorDiagnostics::instance()->diagnostics(); + mydprintf(fd, info.c_str()); +#else + mydprintf(fd, "allocator diagnostics not available. CC_ENABLE_ALLOCATOR_DIAGNOSTICS must be set to 1 in ccConfig.h"); +#endif +} + static char invalid_filename_char[] = {':', '/', '\\', '?', '%', '*', '<', '>', '"', '|', '\r', '\n', '\t'}; void Console::commandUpload(int fd) diff --git a/cocos/base/CCConsole.h b/cocos/base/CCConsole.h index f8fa0b2b03..1c82486a19 100644 --- a/cocos/base/CCConsole.h +++ b/cocos/base/CCConsole.h @@ -122,6 +122,7 @@ protected: void commandDirector(int fd, const std::string &args); void commandTouch(int fd, const std::string &args); void commandUpload(int fd); + void commandAllocator(int fd, const std::string &args); // file descriptor: socket, console, etc. int _listenfd; int _maxfd; diff --git a/cocos/base/CCEventKeyboard.h b/cocos/base/CCEventKeyboard.h index b13f1d3f52..d06594d6d9 100644 --- a/cocos/base/CCEventKeyboard.h +++ b/cocos/base/CCEventKeyboard.h @@ -52,8 +52,14 @@ public: KEY_RETURN, KEY_CAPS_LOCK, KEY_SHIFT, + KEY_LEFT_SHIFT = KEY_SHIFT, + KEY_RIGHT_SHIFT, KEY_CTRL, + KEY_LEFT_CTRL = KEY_CTRL, + KEY_RIGHT_CTRL, KEY_ALT, + KEY_LEFT_ALT = KEY_ALT, + KEY_RIGHT_ALT, KEY_MENU, KEY_HYPER, KEY_INSERT, @@ -201,13 +207,7 @@ public: KEY_DPAD_DOWN, KEY_DPAD_CENTER, KEY_ENTER, - KEY_PLAY, - KEY_LEFT_CTRL, - KEY_RIGHT_CTRL, - KEY_LEFT_ALT, - KEY_RIGHT_ALT, - KEY_LEFT_SHIFT, - KEY_RIGHT_SHIFT + KEY_PLAY }; EventKeyboard(KeyCode keyCode, bool isPressed); diff --git a/cocos/base/CCEventMouse.cpp b/cocos/base/CCEventMouse.cpp index 5c90e1c1ee..abbed78f5c 100644 --- a/cocos/base/CCEventMouse.cpp +++ b/cocos/base/CCEventMouse.cpp @@ -36,6 +36,7 @@ EventMouse::EventMouse(MouseEventType mouseEventCode) , _y(0.0f) , _scrollX(0.0f) , _scrollY(0.0f) +, _startPointCaptured(false) { }; diff --git a/cocos/base/CMakeLists.txt b/cocos/base/CMakeLists.txt index 2c4dd88b97..a5bbc7e2e7 100644 --- a/cocos/base/CMakeLists.txt +++ b/cocos/base/CMakeLists.txt @@ -8,6 +8,9 @@ endif() # todo: also base/CCController-android.cpp set(COCOS_BASE_SRC + base/allocator/CCAllocatorDiagnostics.cpp + base/allocator/CCAllocatorGlobal.cpp + base/allocator/CCAllocatorGlobalNewDelete.cpp base/ccFPSImages.c base/CCAutoreleasePool.cpp base/CCConfiguration.cpp diff --git a/cocos/base/allocator/CCAllocatorBase.h b/cocos/base/allocator/CCAllocatorBase.h new file mode 100644 index 0000000000..d6c82a548e --- /dev/null +++ b/cocos/base/allocator/CCAllocatorBase.h @@ -0,0 +1,113 @@ + +#ifndef CC_ALLOCATOR_BASE_H +#define CC_ALLOCATOR_BASE_H + +/**************************************************************************** + Copyright (c) 2014 Chukong Technologies Inc. + Author: Justin Graham (https://github.com/mannewalis) + + 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 + +#include "platform/CCPlatformMacros.h" +#include "base/allocator/CCAllocatorMacros.h" + +NS_CC_BEGIN +NS_CC_ALLOCATOR_BEGIN + +// @brief +// AllocatorBase +// Provides a base that contains a few methods and definitions that are helpful to all allocation strategies. +// Also provides a common base that can be used to point to all allocators generically. +class AllocatorBase +{ +public: + + typedef void* pointer; + + enum { kDefaultAlignment = 16 }; + + // this must be true for SSE instructions to be 16 byte aligned + // we can now use kDefault alignment as our smallest alloc size + static_assert(sizeof(uintptr_t) <= kDefaultAlignment, "pointer size must be smaller than default alignment"); + +#if CC_ENABLE_ALLOCATOR_DIAGNOSTICS + AllocatorBase() + : _next_allocator(nullptr) + {} +#endif + + virtual ~AllocatorBase() + {} + + // @brief + // Given an address and alignment in bytes, returns an address aligned to the number of bytes + // For example, if the alignment is 4 which is standard, then the address is divisible evenly by 4. + CC_ALLOCATOR_INLINE pointer aligned(const pointer address, const size_t alignment = kDefaultAlignment) const + { + return (pointer) (((intptr_t)address + (alignment - 1)) & ~(alignment - 1)); + } + + // @brief Calculate the next power of two for a given size. + // Most blocks requested are already a power of two. For small block alloc + // this means we cannot add overhead, hence the slightly less performant + // searching of fixed block pages to determine size if none is specified. + CC_ALLOCATOR_INLINE size_t nextPow2BlockSize(size_t size) const + { + --size; + size |= size >> 1; + size |= size >> 2; + size |= size >> 4; + size |= size >> 8; + size |= size >> 16; + return ++size; + } + +#if CC_ENABLE_ALLOCATOR_DIAGNOSTICS + void setTag(const char* tag) + { + strncpy(_tag, tag, sizeof(_tag)-1); + } + + const char* tag() const + { + return _tag; + } + + // cannot use std::string as it allocates memory. + // for some allocator this tag is set before the new/delete allocator has finished initializing. + char _tag[1000]; + + // @brief return any diagnostic info for this allocator + virtual std::string diagnostics() const + { + return ""; + } + AllocatorBase* _next_allocator; +#endif//CC_ENABLE_ALLOCATOR_DIAGNOSTICS +}; + +NS_CC_ALLOCATOR_END +NS_CC_END + +#endif//CC_ALLOCATOR_BASE_H diff --git a/cocos/base/allocator/CCAllocatorDiagnostics.cpp b/cocos/base/allocator/CCAllocatorDiagnostics.cpp new file mode 100644 index 0000000000..66d53554c9 --- /dev/null +++ b/cocos/base/allocator/CCAllocatorDiagnostics.cpp @@ -0,0 +1,89 @@ + +/**************************************************************************** + Copyright (c) 2014 Chukong Technologies Inc. + Author: Justin Graham (https://github.com/mannewalis) + + 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 "CCAllocatorDiagnostics.h" +#include "CCAllocatorGlobal.h" + +NS_CC_BEGIN +NS_CC_ALLOCATOR_BEGIN + +#if CC_ENABLE_ALLOCATOR_DIAGNOSTICS +AllocatorDiagnostics::AllocatorDiagnostics() + : _allocators(nullptr) +{} + +AllocatorDiagnostics* AllocatorDiagnostics::instance() +{ + static AllocatorDiagnostics* _this = nullptr; + if (nullptr == _this) + { + // have to use global allocator because none of the constructors will have been called. + _this = (AllocatorDiagnostics*)ccAllocatorGlobal.allocate(sizeof(AllocatorDiagnostics)); + new (_this) AllocatorDiagnostics(); + } + return _this; +} + +void AllocatorDiagnostics::trackAllocator(AllocatorBase* allocator) +{ + LOCK(_mutex); + auto p = _allocators; + for (; nullptr != p; p = p->_next_allocator) + { + CC_ASSERT(p != allocator); + } + allocator->_next_allocator = _allocators; + _allocators = allocator; + UNLOCK(_mutex); +} + +void AllocatorDiagnostics::untrackAllocator(AllocatorBase* allocator) +{ + LOCK(_mutex); + auto pp = &_allocators; + for (; *pp != allocator; pp = &(*pp)->_next_allocator); + if (*pp == allocator) + *pp = (*pp)->_next_allocator; + UNLOCK(_mutex); +} + +std::string AllocatorDiagnostics::diagnostics() +{ + std::string data; + LOCK(_mutex); + auto a = _allocators; + while (a) + { + data += a->diagnostics(); + a = a->_next_allocator; + } + UNLOCK(_mutex); + return data; +} +#endif//CC_ENABLE_ALLOCATOR_DIAGNOSTICS + +NS_CC_ALLOCATOR_END +NS_CC_END diff --git a/cocos/base/allocator/CCAllocatorDiagnostics.h b/cocos/base/allocator/CCAllocatorDiagnostics.h new file mode 100644 index 0000000000..c4ea934e09 --- /dev/null +++ b/cocos/base/allocator/CCAllocatorDiagnostics.h @@ -0,0 +1,61 @@ + +#ifndef CC_ALLOCATOR_DIAGNOSTICS_H +#define CC_ALLOCATOR_DIAGNOSTICS_H + +/**************************************************************************** + Copyright (c) 2014 Chukong Technologies Inc. + Author: Justin Graham (https://github.com/mannewalis) + + 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 + +#include "base/allocator/CCAllocatorMacros.h" +#include "base/allocator/CCAllocatorMutex.h" +#include "base/allocator/CCAllocatorBase.h" + +NS_CC_BEGIN +NS_CC_ALLOCATOR_BEGIN + +#if CC_ENABLE_ALLOCATOR_DIAGNOSTICS +class AllocatorBase; +class AllocatorDiagnostics +{ +public: + + AllocatorDiagnostics(); + static AllocatorDiagnostics* instance(); + void trackAllocator(AllocatorBase* allocator); + void untrackAllocator(AllocatorBase* allocator); + std::string diagnostics(); + +protected: + + AllocatorMutex _mutex; + AllocatorBase* _allocators; +}; +#endif//CC_ENABLE_ALLOCATOR_DIAGNOSTICS + +NS_CC_ALLOCATOR_END +NS_CC_END + +#endif//CC_ALLOCATOR_DIAGNOSTICS_H diff --git a/cocos/base/allocator/CCAllocatorGlobal.cpp b/cocos/base/allocator/CCAllocatorGlobal.cpp new file mode 100644 index 0000000000..99cd2c91aa --- /dev/null +++ b/cocos/base/allocator/CCAllocatorGlobal.cpp @@ -0,0 +1,40 @@ + +/**************************************************************************** + Copyright (c) 2014 Chukong Technologies Inc. + Author: Justin Graham (https://github.com/mannewalis) + + 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 "base/allocator/CCAllocatorGlobal.h" + +#if CC_ENABLE_ALLOCATOR + +NS_CC_BEGIN +NS_CC_ALLOCATOR_BEGIN + +// @brief Declare the global allocator instance +CC_ALLOCATOR_GLOBAL ccAllocatorGlobal; + +NS_CC_ALLOCATOR_END +NS_CC_END + +#endif // CC_ENABLE_ALLOCATOR diff --git a/cocos/base/allocator/CCAllocatorGlobal.h b/cocos/base/allocator/CCAllocatorGlobal.h new file mode 100644 index 0000000000..8751f34973 --- /dev/null +++ b/cocos/base/allocator/CCAllocatorGlobal.h @@ -0,0 +1,42 @@ + +#ifndef CC_ALLOCATOR_GLOBAL_H +#define CC_ALLOCATOR_GLOBAL_H + +/**************************************************************************** + Copyright (c) 2014 Chukong Technologies Inc. + Author: Justin Graham (https://github.com/mannewalis) + + 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 "base/allocator/CCAllocatorMacros.h" +#include "base/allocator/CCAllocatorStrategyDefault.h" + +NS_CC_BEGIN +NS_CC_ALLOCATOR_BEGIN + +// @brief Make visible at the global scope. +extern CC_ALLOCATOR_GLOBAL ccAllocatorGlobal; + +NS_CC_ALLOCATOR_END +NS_CC_END + +#endif//CC_ALLOCATOR_GLOBAL_H diff --git a/cocos/base/allocator/CCAllocatorGlobalNewDelete.cpp b/cocos/base/allocator/CCAllocatorGlobalNewDelete.cpp new file mode 100644 index 0000000000..72098a1375 --- /dev/null +++ b/cocos/base/allocator/CCAllocatorGlobalNewDelete.cpp @@ -0,0 +1,72 @@ + +/**************************************************************************** + Copyright (c) 2014 Chukong Technologies Inc. + Author: Justin Graham (https://github.com/mannewalis) + + 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 "base/allocator/CCAllocatorStrategyGlobalSmallBlock.h" +#include +#include + +USING_NS_CC_ALLOCATOR; + +#if CC_ENABLE_ALLOCATOR +#if CC_ENABLE_ALLOCATOR_GLOBAL_NEW_DELETE + +namespace +{ + // @brief Declare the allocator for global new/delete + static CC_ALLOCATOR_GLOBAL_NEW_DELETE global; +} + +// @brief overrides global operator new array +void* operator new[] (std::size_t size) +{ + void* ptr = global.allocate(size); +#if CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID + if (nullptr == ptr) + throw std::bad_alloc(); +#endif + return ptr; +} + +// @brief overrides global operator new +void* operator new(std::size_t size) +{ + void* ptr = global.allocate(size); +#if CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID + if (nullptr == ptr) + throw std::bad_alloc(); +#endif + return ptr; +} + +// @brief overrides global operator delete +void operator delete(void* p) throw() +{ + if (p) + global.deallocate(p); +} + +#endif // CC_ENABLE_ALLOCATOR_GLOBAL_NEW_DELETE +#endif // CC_ENABLE_ALLOCATOR diff --git a/cocos/base/allocator/CCAllocatorMacros.h b/cocos/base/allocator/CCAllocatorMacros.h new file mode 100644 index 0000000000..056bef4bd1 --- /dev/null +++ b/cocos/base/allocator/CCAllocatorMacros.h @@ -0,0 +1,130 @@ + +#ifndef CC_ALLOCATOR_MACROS_H +#define CC_ALLOCATOR_MACROS_H + +/**************************************************************************** + Copyright (c) 2014 Chukong Technologies Inc. + Author: Justin Graham (https://github.com/mannewalis) + + 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 "base/ccConfig.h" +#include "platform/CCPlatformMacros.h" + +// namespace allocator {} +#ifdef __cplusplus + #define NS_CC_ALLOCATOR_BEGIN namespace allocator { + #define NS_CC_ALLOCATOR_END } + #define USING_NS_CC_ALLOCATOR using namespace cocos2d::allocator + #define NS_CC_ALLOCATOR ::cocos2d::allocator +#else + #define NS_CC_ALLOCATOR_BEGIN + #define NS_CC_ALLOCATOR_END + #define USING_NS_CC_ALLOCATOR + #define NS_CC_ALLOCATOR +#endif + +#if COCOS2D_DEBUG + + // @brief CC_ALLOCATOR_INLINE + // Turn off inlining of methods when debugging to make stack traces readable and stepping through code sane. + #define CC_ALLOCATOR_INLINE + + // printf is safe to use + #define LOG printf + +#else + + #define CC_ALLOCATOR_INLINE inline + #define LOG + +#endif + +// allocator macros +#if CC_ENABLE_ALLOCATOR + + // @brief macros for new/delete + // we let global new/delete handle these as they are overridden. + #define CC_NEW(klass, ...) new klass(__VAR_ARGS__) + #define CC_DELETE(object) delete object; + + // @brief macros for malloc/free + // these will use the global allocator + #define CC_MALLOC(size) ccAllocatorGlobal.allocate(size) + #define CC_FREE(address) ccAllocatorGlobal.deallocate(address) + + // alloc on the stack + #define CC_ALLOCA(size) alloca(size) + + // @brief helper macro for overriding new/delete operators for a class. + // This correctly passes the size in the deallocate method which is needed. + #define CC_USE_ALLOCATOR_POOL(T, A) \ + CC_ALLOCATOR_INLINE void* operator new (size_t size) \ + { \ + return (void*)A.allocate(size); \ + } \ + CC_ALLOCATOR_INLINE void operator delete (void* object, size_t size) \ + { \ + A.deallocate((T*)object, size); \ + } + +#else + + // macros for new/delete + // these will use a general thread safe allocator + #define CC_NEW(klass, ...) new klass(__VAR_ARGS__) + #define CC_DELETE(object) delete object + + // macros for malloc/free + // these will use a general thread safe allocator + #define CC_MALLOC(size) malloc(size) + #define CC_FREE(address) free(address) + + // alloc on the stack + #define CC_ALLOCA(size) alloca(size) + + // throw these away if not enabled + #define CC_USE_ALLOCATOR_POOL(...) + #define CC_OVERRIDE_GLOBAL_NEWDELETE_WITH_ALLOCATOR(...) + +#endif + +// @ brief Quick and dirty macro to dump an area of memory +// useful for debugging blocks of memory from allocators. +#define DUMP(a, l, C) \ +{ \ + LOG("> %p len %zu\n", a, l); \ + uint8_t* p = (uint8_t*)a; \ + uint8_t* e = p + l; \ + while (p < e) \ + { \ + LOG("%p ", p); \ + for (int i = 0; i < C && &p[i] < e; ++i) \ + LOG("%02x ", p[i]); \ + for (int i = 0; i < C && &p[i] < e; ++i) \ + LOG("%c ", isalnum(p[i]) ? p[i] : '.'); \ + LOG("\n"); \ + p = p + C > e ? e : p + C; \ + } \ +} + +#endif//CC_ALLOCATOR_MACROS_H diff --git a/cocos/base/allocator/CCAllocatorMutex.h b/cocos/base/allocator/CCAllocatorMutex.h new file mode 100644 index 0000000000..c7a54bd098 --- /dev/null +++ b/cocos/base/allocator/CCAllocatorMutex.h @@ -0,0 +1,113 @@ + +#ifndef CC_ALLOCATOR_MUTEX_H +#define CC_ALLOCATOR_MUTEX_H + +/**************************************************************************** + Copyright (c) 2014 Chukong Technologies Inc. + Author: Justin Graham (https://github.com/mannewalis) + + 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 "platform/CCPlatformMacros.h" + +#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_LINUX +#include "pthread.h" +#define MUTEX pthread_mutex_t +#define MUTEX_INIT(m) \ + pthread_mutexattr_t mta; \ + pthread_mutexattr_init(&mta); \ + pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_RECURSIVE); \ + pthread_mutex_init(&m, &mta) +#define MUTEX_LOCK(m) \ + pthread_mutex_lock(&m); +#define MUTEX_UNLOCK(m) \ + pthread_mutex_unlock(&m); +#elif CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 +#include "windows.h" +#define MUTEX HANDLE +#define MUTEX_INIT(m) \ + m = CreateMutex(0, FALSE, 0) +#define MUTEX_LOCK(m) \ + WaitForSingleObject(m, INFINITE) +#define MUTEX_UNLOCK(m) \ + ReleaseMutex(m) +#else +#error "Unsupported platform for AllocatorMutex" +#endif + +NS_CC_BEGIN +NS_CC_ALLOCATOR_BEGIN + +// so we cannot use std::mutex because it allocates memory +// which causes an infinite loop of death and exceptions. +class AllocatorMutex +{ +public: + + AllocatorMutex() + { + MUTEX_INIT(_mutex); + } + + void lock() + { + MUTEX_LOCK(_mutex); + } + + void unlock() + { + MUTEX_UNLOCK(_mutex); + } + +protected: + + MUTEX _mutex; +}; + +#define LOCK(m) m.lock() +#define UNLOCK(m) m.unlock() + +// @param implementation that provides a mutex with locking semantics. +struct locking_semantics +{ + AllocatorMutex _mutex; + CC_ALLOCATOR_INLINE void lock() + { + LOCK(_mutex); + } + CC_ALLOCATOR_INLINE void unlock() + { + UNLOCK(_mutex); + } +}; + +// @param implementation that provides lockless semantics that should optimize away. +struct lockless_semantics +{ + CC_ALLOCATOR_INLINE void lock() {} + CC_ALLOCATOR_INLINE void unlock() {} +}; + +NS_CC_ALLOCATOR_END +NS_CC_END + +#endif//CC_ALLOCATOR_MUTEX_H diff --git a/cocos/base/allocator/CCAllocatorStrategyDefault.h b/cocos/base/allocator/CCAllocatorStrategyDefault.h new file mode 100644 index 0000000000..09a87fa819 --- /dev/null +++ b/cocos/base/allocator/CCAllocatorStrategyDefault.h @@ -0,0 +1,58 @@ + +#ifndef CC_ALLOCATOR_STRATEGY_DEFAULT_H +#define CC_ALLOCATOR_STRATEGY_DEFAULT_H + +/**************************************************************************** + Copyright (c) 2014 Chukong Technologies Inc. + Author: Justin Graham (https://github.com/mannewalis) + + 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 "base/allocator/CCAllocatorMacros.h" +#include "base/allocator/CCAllocatorBase.h" + +NS_CC_BEGIN +NS_CC_ALLOCATOR_BEGIN + +// @brief +// The default allocation strategy that just falls through to malloc and free +class AllocatorStrategyDefault + : public AllocatorBase +{ +public: + + CC_ALLOCATOR_INLINE void* allocate(size_t size) + { + return malloc(size); + } + + CC_ALLOCATOR_INLINE void deallocate(void* address, size_t size = 0) + { + if (nullptr != address) + free(address); + } +}; + +NS_CC_ALLOCATOR_END +NS_CC_END + +#endif//CC_ALLOCATOR_STRATEGY_DEFAULT_H diff --git a/cocos/base/allocator/CCAllocatorStrategyFixedBlock.h b/cocos/base/allocator/CCAllocatorStrategyFixedBlock.h new file mode 100644 index 0000000000..22773e73b7 --- /dev/null +++ b/cocos/base/allocator/CCAllocatorStrategyFixedBlock.h @@ -0,0 +1,276 @@ + +#ifndef CC_ALLOCATOR_STRATEGY_FIXED_BLOCK_H +#define CC_ALLOCATOR_STRATEGY_FIXED_BLOCK_H + +/**************************************************************************** + Copyright (c) 2014 Chukong Technologies Inc. + Author: Justin Graham (https://github.com/mannewalis) + + 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. + ****************************************************************************/ + +/**************************************************************************** + WARNING! + Do not use Console::log or any other methods that use NEW inside of this + allocator. Failure to do so will result in recursive memory allocation. + ****************************************************************************/ + +#include +#include +#include +#include + +#include "base/allocator/CCAllocatorBase.h" +#include "base/allocator/CCAllocatorMacros.h" +#include "base/allocator/CCAllocatorGlobal.h" +#include "base/allocator/CCAllocatorMutex.h" +#include "base/allocator/CCAllocatorDiagnostics.h" + +NS_CC_BEGIN +NS_CC_ALLOCATOR_BEGIN + +// @brief define this to cause this allocator to fallback to the global allocator +// this is just for testing purposes to see if this allocator is broken. +//#define FALLBACK_TO_GLOBAL + +// @brief +// Fixed sized block allocator strategy for allocating blocks +// of memory that are the same size. +// Optionally takes a page size which determines how many blocks +// are added when the allocator needs more storage. +// @param _block_size the size of the fixed block allocated by this allocator. +// @param _page_size the number of blocks to allocate when growing the free list. +// @param _alignment the alignment size in bytes of each block. +// @param locking_semantics which locking strategy to use. +template +class AllocatorStrategyFixedBlock + : public AllocatorBase + , public lock_traits +{ +public: + + static const size_t block_size = _block_size; + static const size_t alignment = _alignment; + + AllocatorStrategyFixedBlock(const char* tag = nullptr, size_t pageSize = 100) + : _list(nullptr) + , _pages(nullptr) + , _pageSize(pageSize) + , _allocated(0) + { +#if CC_ENABLE_ALLOCATOR_DIAGNOSTICS + _highestCount = 0; + AllocatorDiagnostics::instance()->trackAllocator(this); + AllocatorBase::setTag(tag ? tag : typeid(AllocatorStrategyFixedBlock).name()); +#endif + } + + virtual ~AllocatorStrategyFixedBlock() + { +#if CC_ENABLE_ALLOCATOR_DIAGNOSTICS + AllocatorDiagnostics::instance()->untrackAllocator(this); +#endif + + do + { + intptr_t* page = (intptr_t*)_pages; + intptr_t* next = (intptr_t*)*page; + ccAllocatorGlobal.deallocate(page); + _pages = (void*)next; + } + while (_pages); + } + + // @brief + // allocate a block of memory by returning the first item in the list or if empty + // then allocate a new page of blocks, and return the first element and store the rest. + // if _block_size does not match the requested size, then we assert. + CC_ALLOCATOR_INLINE void* allocate(size_t size) + { + CC_ASSERT(block_size == size); +#ifdef FALLBACK_TO_GLOBAL + return ccAllocatorGlobal.allocate(size); +#else + lock_traits::lock(); + auto r = pop_front(); + lock_traits::unlock(); + return r; +#endif + } + + // @brief Deallocate a block by pushing it on the head of a linked list of free blocks. + CC_ALLOCATOR_INLINE void deallocate(void* address, size_t size = 0) + { + CC_ASSERT(0 == size || block_size == size); +#ifdef FALLBACK_TO_GLOBAL + ccAllocatorGlobal.deallocate(address); +#else + lock_traits::lock(); + push_front(address); + lock_traits::unlock(); +#endif + } + + // @brief Checks allocated pages to determine whether or not a block + // is owned by this allocator. This should be reasonably fast + // for properly configured allocators with few large pages. + CC_ALLOCATOR_INLINE bool owns(const void* const address) + { +#ifdef FALLBACK_TO_GLOBAL + return true; // since everything uses the global allocator, we can just lie and say we own this address. +#else + lock_traits::lock(); + + const uint8_t* const a = (const uint8_t* const)address; + const uint8_t* p = (uint8_t*)_pages; + const size_t pSize = pageSize(); + while (p) + { + if (a >= p && a < (p + pSize)) + { + lock_traits::unlock(); + return true; + } + p = (uint8_t*)(*(uintptr_t*)p); + } + lock_traits::unlock(); + return false; +#endif + } + +#if CC_ENABLE_ALLOCATOR_DIAGNOSTICS + std::string diagnostics() const + { + std::stringstream s; + s << AllocatorBase::tag() << " initial:" << _pageSize << " count:" << _allocated << " highest:" << _highestCount << "\n"; + return s.str(); + } + size_t _highestCount; +#endif + +protected: + + // @brief Method to push an allocated block onto the free list. + // No check is made that the block hasn't been already added to this allocator. + CC_ALLOCATOR_INLINE void push_front(void* block) + { + CC_ASSERT(block); + CC_ASSERT(block_size < AllocatorBase::kDefaultAlignment || 0 == ((intptr_t)block & (AllocatorBase::kDefaultAlignment - 1))); + +#if COCOS2D_DEBUG + // additional debug build checks + CC_ASSERT(true == owns(block)); +#endif + + if (nullptr == _list) + { + _list = block; + *(uintptr_t*)block = 0; + } + else + { + uintptr_t* p = (uintptr_t*)(block); + *p = (uintptr_t)_list; + _list = block; + } + CC_ASSERT(_allocated > 0); + --_allocated; + } + + // @brief Method to pop a block off the free list. + // If no blocks are available, then the list is grown by _page_size + // Tuning of the page size is critical to getting good performance. + // Ideally you would use a page size that is around the high water mark + // for the number of blocks of this size being allocated. + CC_ALLOCATOR_INLINE void* pop_front() + { + if (nullptr == _list) + { + allocatePage(); + } + auto next = (void*)*(uintptr_t*)_list; + auto block = _list; + _list = next; + ++_allocated; + +#if CC_ENABLE_ALLOCATOR_DIAGNOSTICS + if (_allocated > _highestCount) + _highestCount = _allocated; +#endif + CC_ASSERT(block_size < AllocatorBase::kDefaultAlignment || 0 == ((intptr_t)block & (AllocatorBase::kDefaultAlignment - 1))); + return block; + } + +protected: + + // @brief Returns the size of a page in bytes + overhead. + const size_t pageSize() const + { + return AllocatorBase::kDefaultAlignment + AllocatorBase::nextPow2BlockSize(block_size) * _pageSize; + } + + // @brief Allocates a new page from the global allocator, + // and adds all the blocks to the free list. + CC_ALLOCATOR_INLINE void allocatePage() + { + uint8_t* p = (uint8_t*)AllocatorBase::aligned(ccAllocatorGlobal.allocate(pageSize())); + intptr_t* page = (intptr_t*)p; + if (nullptr == _pages) + { + _pages = page; + *page = 0; + } + else + { + *page = (intptr_t)_pages; + _pages = page; + } + + p += AllocatorBase::kDefaultAlignment; // step past the linked list node + + _allocated += _pageSize; + size_t aligned_size = AllocatorBase::nextPow2BlockSize(block_size); + uint8_t* block = (uint8_t*)p; + for (int i = 0; i < _pageSize; ++i, block += aligned_size) + { + push_front(block); + } + } + +protected: + + // @brief Linked list of free blocks. + void* _list; + + // @brief Linked list of allocated pages. + void* _pages; + + // @brief number of blocks per page. + size_t _pageSize; + + // @brief Number of blocks that are currently allocated. + size_t _allocated; +}; + +NS_CC_ALLOCATOR_END +NS_CC_END + +#endif//CC_ALLOCATOR_STRATEGY_FIXED_BLOCK_H diff --git a/cocos/base/allocator/CCAllocatorStrategyGlobalSmallBlock.h b/cocos/base/allocator/CCAllocatorStrategyGlobalSmallBlock.h new file mode 100644 index 0000000000..9d5e4cd0e2 --- /dev/null +++ b/cocos/base/allocator/CCAllocatorStrategyGlobalSmallBlock.h @@ -0,0 +1,318 @@ + +#ifndef CC_ALLOCATOR_STRATEGY_GLOBAL_SMALL_BLOCK_H +#define CC_ALLOCATOR_STRATEGY_GLOBAL_SMALL_BLOCK_H + +/**************************************************************************** + Copyright (c) 2014 Chukong Technologies Inc. + Author: Justin Graham (https://github.com/mannewalis) + + 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. + ****************************************************************************/ + +/**************************************************************************** + WARNING! + Do not use Console::log or any other methods that use NEW inside of this + allocator. Failure to do so will result in recursive memory allocation. + ****************************************************************************/ + +#include "base/allocator/CCAllocatorMacros.h" +#include "base/allocator/CCAllocatorBase.h" +#include "base/allocator/CCAllocatorGlobal.h" +#include "base/allocator/CCAllocatorStrategyFixedBlock.h" + +NS_CC_BEGIN +NS_CC_ALLOCATOR_BEGIN + +#if CC_ENABLE_ALLOCATOR_DIAGNOSTICS +#define TRACK(slot, size, op) _smallBlockAllocations[slot] op size +#else +#define TRACK(...) +#endif + +// @brief +class AllocatorStrategyGlobalSmallBlock + : public AllocatorBase +{ +public: + + // default number of block to allocate per page. + static const size_t kDefaultSmallBlockCount = 100; + + // default max small block size pool. + static const size_t kMaxSmallBlockPower = 13; // 2^13 8kb + + // @brief define for allocator strategy, cannot be typedef because we want to eval at use +#define SType(size) AllocatorStrategyFixedBlock + + void _lazy_init() + { + // this gets called before static constructors + // so make sure we only get called once. + static bool once = true; + if (once) + { + once = false; + + // call our own constructor. Global new can be called before the constructors are called. + // Make sure it gets called by having it done lazily in the call to allocate. + new (this) AllocatorStrategyGlobalSmallBlock(); + } + } + + AllocatorStrategyGlobalSmallBlock() + { + // this gets called before static constructors + // so make sure we only get called once. + static bool once = true; + if (once) + { + once = false; + + _maxBlockSize = 1 << kMaxSmallBlockPower; + +#if CC_ENABLE_ALLOCATOR_DIAGNOSTICS + AllocatorDiagnostics::instance()->trackAllocator(this); + AllocatorBase::setTag("GlobalSmallBlock"); +#endif + + memset(_smallBlockAllocators, 0, sizeof(_smallBlockAllocators)); +#if CC_ENABLE_ALLOCATOR_DIAGNOSTICS + memset(_smallBlockAllocations, 0, sizeof(_smallBlockAllocations)); +#endif + // cannot call new on the allocator here because it will recurse + // so instead we allocate from the global allocator and construct in place. + #define SBA(n, size) \ + if (size <= _maxBlockSize) \ + { \ + auto v = ccAllocatorGlobal.allocate(sizeof(SType(size))); \ + _smallBlockAllocators[n] = (AllocatorBase*)(new (v) SType(size)("GlobalSmallBlock::"#size)); \ + } + + SBA(2, 4) + SBA(3, 8); + SBA(4, 16); + SBA(5, 32); + SBA(6, 64); + SBA(7, 128); + SBA(8, 256); + SBA(9, 512); + SBA(10, 1024); + SBA(11, 2048); + SBA(12, 4096); + SBA(13, 8192); + + #undef SBA + } + } + + virtual ~AllocatorStrategyGlobalSmallBlock() + { + for (int i = 0; i <= kMaxSmallBlockPower; ++i) + if (_smallBlockAllocators[i]) + ccAllocatorGlobal.deallocate(_smallBlockAllocators[i]); + +#if CC_ENABLE_ALLOCATOR_DIAGNOSTICS + AllocatorDiagnostics::instance()->untrackAllocator(this); +#endif + } + + // @brief Allocate a block of some size. If the block is <= 8192 it is allocated out of an array + // of fixed size block allocators. If larger, then we default back to the global allocator. + // @param size Size of block to allocate. This will be rounded to the next power of two. + CC_ALLOCATOR_INLINE void* allocate(size_t size) + { + _lazy_init(); + + if (size < sizeof(intptr_t)) // always allocate at least enough space to store a pointer. this is + size = sizeof(intptr_t); // so we can link the empty blocks together in the block allocator. + + // if the size is greater than what we determine to be a small block + // size then fall through to calling the global allocator instead. + if (size > _maxBlockSize) + return ccAllocatorGlobal.allocate(size); + + // make sure the size fits into one of the + // fixed sized block allocators we have above. + size_t adjusted_size = AllocatorBase::nextPow2BlockSize(size); + + #define ALLOCATE(slot, size) \ + case size: \ + { \ + void* v = _smallBlockAllocators[slot]; \ + CC_ASSERT(nullptr != v); \ + auto a = (SType(size)*)v; \ + address = a->allocate(adjusted_size); \ + TRACK(slot, size, +=); \ + } \ + break; + + void* address; + + switch (adjusted_size) + { + ALLOCATE(2, 4); + ALLOCATE(3, 8); + ALLOCATE(4, 16); + ALLOCATE(5, 32); + ALLOCATE(6, 64); + ALLOCATE(7, 128); + ALLOCATE(8, 256); + ALLOCATE(9, 512); + ALLOCATE(10, 1024); + ALLOCATE(11, 2048); + ALLOCATE(12, 4096); + ALLOCATE(13, 8192); + default: + CC_ASSERT(false); + break; + } + + #undef ALLOCATE + + CC_ASSERT(adjusted_size < AllocatorBase::kDefaultAlignment || 0 == ((intptr_t)address & (AllocatorBase::kDefaultAlignment - 1))); + CC_ASSERT(nullptr != address); + + return address; + } + + // @brief Deallocate a block by choosing one of the fixed size block allocators + // or defaulting to the global allocator if we do not own this block. + CC_ALLOCATOR_INLINE void deallocate(void* address, size_t size = 0) + { + // if we didn't get a size, then we need to find the allocator + // by asking each if they own the block. For allocators that + // have few large pages, this is extremely fast. + if (0 == size) + { + #define OWNS(slot, S, address) \ + case S: \ + { \ + void* v = _smallBlockAllocators[slot]; \ + if (v) \ + { \ + auto a = (SType(S)*)v; \ + if (a->owns(address)) \ + { \ + size = SType(S)::block_size; \ + break; \ + } \ + } \ + } + + // falls through until found + switch (sizeof(uint32_t)) + { + OWNS(2, 4, address); + OWNS(3, 8, address); + OWNS(4, 16, address); + OWNS(5, 32, address); + OWNS(6, 64, address); + OWNS(7, 128, address); + OWNS(8, 256, address); + OWNS(9, 512, address); + OWNS(10, 1024, address); + OWNS(11, 2048, address); + OWNS(12, 4096, address); + OWNS(13, 8192, address); + } + } + + // if the size is greater than what we determine to be a small block + // size then default to calling the global allocator instead. + if (0 == size || size > _maxBlockSize) + return ccAllocatorGlobal.deallocate(address, size); + + if (size < sizeof(intptr_t)) // always allocate at least enough space to store a pointer. this is + size = sizeof(intptr_t); // so we can link the empty blocks together in the block allocator. + + // make sure the size fits into one of the + // fixed sized block allocators we have above. + size_t adjusted_size = AllocatorBase::nextPow2BlockSize(size); + + #define DEALLOCATE(slot, size, address) \ + case size: \ + { \ + void* v = _smallBlockAllocators[slot]; \ + CC_ASSERT(nullptr != v); \ + auto a = (SType(size)*)v; \ + a->deallocate(address, size); \ + TRACK(slot, size, -=); \ + } \ + break; + + switch (adjusted_size) + { + DEALLOCATE(2, 4, address); + DEALLOCATE(3, 8, address); + DEALLOCATE(4, 16, address); + DEALLOCATE(5, 32, address); + DEALLOCATE(6, 64, address); + DEALLOCATE(7, 128, address); + DEALLOCATE(8, 256, address); + DEALLOCATE(9, 512, address); + DEALLOCATE(10, 1024, address); + DEALLOCATE(11, 2048, address); + DEALLOCATE(12, 4096, address); + DEALLOCATE(13, 8192, address); + default: + CC_ASSERT(false); + } + + #undef DEALLOCATE + } + +#if CC_ENABLE_ALLOCATOR_DIAGNOSTICS + std::string diagnostics() const + { + std::stringstream s; + size_t total = 0; + for (auto i = 2; i <= kMaxSmallBlockPower; ++i) + { + auto a = _smallBlockAllocators[i]; + if (a) + { + total += _smallBlockAllocations[i]; + s << a->tag() << " allocated:" << _smallBlockAllocations[i] << "\n"; + } + } + s << "Total:" << total << "\n"; + return s.str(); + } + size_t _highestCount; +#endif + +protected: + + // @brief the max size of a block this allocator will pool before using global allocator + size_t _maxBlockSize; + + // @brief array of small block allocators from 2^0 -> 2^kMaxSmallBlockPower + AllocatorBase* _smallBlockAllocators[kMaxSmallBlockPower + 1]; + +#if CC_ENABLE_ALLOCATOR_DIAGNOSTICS + size_t _smallBlockAllocations[kMaxSmallBlockPower + 1]; +#endif +}; + +NS_CC_ALLOCATOR_END +NS_CC_END + +#endif//CC_ALLOCATOR_STRATEGY_GLOBAL_SMALL_BLOCK_H diff --git a/cocos/base/allocator/CCAllocatorStrategyPool.h b/cocos/base/allocator/CCAllocatorStrategyPool.h new file mode 100644 index 0000000000..3838a1186f --- /dev/null +++ b/cocos/base/allocator/CCAllocatorStrategyPool.h @@ -0,0 +1,160 @@ + +#ifndef CC_ALLOCATOR_STRATEGY_POOL_H +#define CC_ALLOCATOR_STRATEGY_POOL_H + +/**************************************************************************** + Copyright (c) 2014 Chukong Technologies Inc. + Author: Justin Graham (https://github.com/mannewalis) + + 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 +#include +#include + +#include "base/allocator/CCAllocatorMacros.h" +#include "base/allocator/CCAllocatorGlobal.h" +#include "base/allocator/CCAllocatorStrategyFixedBlock.h" +#include "base/allocator/CCAllocatorDiagnostics.h" +#include "base/CCConfiguration.h" + +NS_CC_BEGIN +NS_CC_ALLOCATOR_BEGIN + +// @brief ObjectTraits describes an allocatable object +// Templated class that represents a default allocatable object. +// Provide custom implementations to change the constructor/destructor behavior, +// or to change the default alignment of the object in memory. +// @param T Type of object +// @param _alignment Alignment of object T +template +class ObjectTraits +{ +public: + + typedef T value_type; + + static const size_t alignment = _alignment; + + virtual ~ObjectTraits() + {} + + // @brief constructor implementation for type T + void construct(T* address) + { + ::new(address) T(); + } + + // @brief destructor implementation for type T + void destroy(T* address) + { + address->~T(); + } + + // @brief returns the name of this object type T + const char* name() const + { + return typeid(T).name(); + } +}; + + +// @brief +// Fixed sized pool allocator strategy for objects of type T +// Optionally takes a page size which determines how many objects +// are added when the allocator needs more storage. +// ObjectTraits allows you to control the alignment, construction +// and destruction of an object in the pool. +// @param T Type of object. +// @param _page_size Number of objects of T in each page. +// @param O ObjectTraits for type T +// @see CC_USE_ALLOCATOR_POOL +template , typename locking_traits = lockless_semantics> +class AllocatorStrategyPool + : public AllocatorStrategyFixedBlock + , public O +{ +public: + + typedef T value_type; + typedef value_type* pointer; + + // ugh wish I knew a way that I could declare this just once + typedef AllocatorStrategyFixedBlock tParentStrategy; + + AllocatorStrategyPool(const char* tag = nullptr, size_t poolSize = 100) + : tParentStrategy(tag) + { + poolSize = Configuration::getInstance()->getValue(tag, Value((int)poolSize)).asInt(); + tParentStrategy::_pageSize = poolSize; + } + + // @brief Allocate block of size T + // if size does not match sizeof(T) then the global allocator is called instead. + // @see CC_USE_ALLOCATOR_POOL + CC_ALLOCATOR_INLINE void* allocate(size_t size) + { + T* object; + if (sizeof(T) == size) + { + object = (pointer)tParentStrategy::allocate(sizeof(T)); + } + else + { + object = (T*)ccAllocatorGlobal.allocate(size); + } + O::construct(object); + return object; + } + + // @brief Deallocate block of size T + // if size does not match sizeof(T) then the global allocator is called instead. + // @see CC_USE_ALLOCATOR_POOL + CC_ALLOCATOR_INLINE void deallocate(void* address, size_t size = 0) + { + if (address) + { + O::destroy((T*)address); + if (sizeof(T) == size) + { + tParentStrategy::deallocate(address, sizeof(T)); + } + else + { + ccAllocatorGlobal.deallocate(address, size); + } + } + } + +#if CC_ENABLE_ALLOCATOR_DIAGNOSTICS + std::string diagnostics() const + { + std::stringstream s; + s << AllocatorBase::tag() << " initial:" << tParentStrategy::_pageSize << " count:" << tParentStrategy::_allocated << " highest:" << tParentStrategy::_highestCount << "\n"; + return s.str(); + } +#endif +}; + +NS_CC_ALLOCATOR_END +NS_CC_END + +#endif//CC_ALLOCATOR_STRATEGY_POOL_H diff --git a/cocos/base/ccConfig.h b/cocos/base/ccConfig.h index 443da7a9ef..3949d5591c 100644 --- a/cocos/base/ccConfig.h +++ b/cocos/base/ccConfig.h @@ -301,5 +301,43 @@ To enable set it to a value different than 0. Disabled by default. #ifndef CC_CONSTRUCTOR_ACCESS #define CC_CONSTRUCTOR_ACCESS protected #endif - + +/** @def CC_ENABLE_ALLOCATOR + Turn on creation of global allocator and pool allocators + as specified by CC_ALLOCATOR_GLOBAL below. + */ +#ifndef CC_ENABLE_ALLOCATOR +# define CC_ENABLE_ALLOCATOR 0 +#endif + +/** @def CC_ENABLE_ALLOCATOR_DIAGNOSTICS + Turn on debugging of allocators. This is slower, uses + more memory, and should not be used for production builds. + */ +#ifndef CC_ENABLE_ALLOCATOR_DIAGNOSTICS +# define CC_ENABLE_ALLOCATOR_DIAGNOSTICS CC_ENABLE_ALLOCATOR +#endif + +/** @def CC_ENABLE_ALLOCATOR_GLOBAL_NEW_DELETE + Turn on override of global new and delete + as specified by CC_ALLOCATOR_GLOBAL_NEW_DELETE below. + */ +#ifndef CC_ENABLE_ALLOCATOR_GLOBAL_NEW_DELETE +# define CC_ENABLE_ALLOCATOR_GLOBAL_NEW_DELETE 0 +# endif//CC_ENABLE_ALLOCATOR_GLOBAL_NEW_DELETE + +/** @def CC_ALLOCATOR_GLOBAL + Specify allocator to use for global allocator + */ +#ifndef CC_ALLOCATOR_GLOBAL +# define CC_ALLOCATOR_GLOBAL cocos2d::allocator::AllocatorStrategyDefault +#endif + +/** @def CC_ALLOCATOR_GLOBAL_NEW_DELETE + Specify allocator to use when overriding of new and delete + */ +#ifndef CC_ALLOCATOR_GLOBAL_NEW_DELETE +# define CC_ALLOCATOR_GLOBAL_NEW_DELETE cocos2d::allocator::AllocatorStrategyGlobalSmallBlock +#endif + #endif // __CCCONFIG_H__ diff --git a/cocos/cocos2d.cpp b/cocos/cocos2d.cpp index 66f67327b1..fab01b53d1 100644 --- a/cocos/cocos2d.cpp +++ b/cocos/cocos2d.cpp @@ -31,7 +31,7 @@ NS_CC_BEGIN CC_DLL const char* cocos2dVersion() { - return "cocos2d-x 3.3rc2"; + return "cocos2d-x 3.3"; } NS_CC_END diff --git a/cocos/editor-support/cocostudio/ActionTimeline/CCActionTimelineCache.cpp b/cocos/editor-support/cocostudio/ActionTimeline/CCActionTimelineCache.cpp index 33867af24b..bb3c9e9d40 100644 --- a/cocos/editor-support/cocostudio/ActionTimeline/CCActionTimelineCache.cpp +++ b/cocos/editor-support/cocostudio/ActionTimeline/CCActionTimelineCache.cpp @@ -33,7 +33,7 @@ THE SOFTWARE. #include "cocostudio/CSParseBinary_generated.h" -#include "tinyxml2/tinyxml2.h" +#include "tinyxml2.h" #include "flatbuffers/flatbuffers.h" #include "flatbuffers/util.h" @@ -668,6 +668,9 @@ Frame* ActionTimelineCache::loadColorFrameWithFlatBuffers(const flatbuffers::Tim Color3B color(f_color->r(), f_color->g(), f_color->b()); frame->setColor(color); + int alpha = f_color->a(); + frame->setAlpha(alpha); + int frameIndex = flatbuffers->frameIndex(); frame->setFrameIndex(frameIndex); @@ -679,18 +682,51 @@ Frame* ActionTimelineCache::loadColorFrameWithFlatBuffers(const flatbuffers::Tim Frame* ActionTimelineCache::loadTextureFrameWithFlatBuffers(const flatbuffers::TimeLineTextureFrame *flatbuffers) { + std::string path = ""; + int resourceType = 0; + std::string plist = ""; + TextureFrame* frame = TextureFrame::create(); - std::string path = flatbuffers->path()->c_str(); - if (FileUtils::getInstance()->isFileExist(path)) + auto fileNameData = flatbuffers->fileNameData(); + + resourceType = fileNameData->resourceType(); + switch (resourceType) { - std::string fullPath = FileUtils::getInstance()->fullPathForFilename(path); - path = fullPath; - } - else - { - path = ""; + case 0: + { + path = fileNameData->path()->c_str(); + if (FileUtils::getInstance()->isFileExist(path)) + { + std::string fullPath = FileUtils::getInstance()->fullPathForFilename(path); + path = fullPath; + } + else + { + path = ""; + } + break; + } + + case 1: + { + plist = fileNameData->plistFile()->c_str(); + if (FileUtils::getInstance()->isFileExist(plist)) + { + path = fileNameData->path()->c_str(); + } + else + { + path = ""; + } + break; + } + + default: + break; } + + frame->setTextureName(path); int frameIndex = flatbuffers->frameIndex(); diff --git a/cocos/editor-support/cocostudio/ActionTimeline/CCActionTimelineCache.h b/cocos/editor-support/cocostudio/ActionTimeline/CCActionTimelineCache.h index 7151498a85..08612740db 100644 --- a/cocos/editor-support/cocostudio/ActionTimeline/CCActionTimelineCache.h +++ b/cocos/editor-support/cocostudio/ActionTimeline/CCActionTimelineCache.h @@ -34,7 +34,7 @@ THE SOFTWARE. namespace flatbuffers { - struct FlatBufferBuilder; + class FlatBufferBuilder; struct NodeAction; struct TimeLine; diff --git a/cocos/editor-support/cocostudio/ActionTimeline/CCFrame.cpp b/cocos/editor-support/cocostudio/ActionTimeline/CCFrame.cpp index a959680716..dc0595fbf0 100644 --- a/cocos/editor-support/cocostudio/ActionTimeline/CCFrame.cpp +++ b/cocos/editor-support/cocostudio/ActionTimeline/CCFrame.cpp @@ -570,12 +570,22 @@ void EventFrame::init() EventFrame::EventFrame() : _event("") + , _action(nullptr) { } +void EventFrame::setNode(cocos2d::Node* node) +{ + Frame::setNode(node); + _action = _timeline->getActionTimeline(); +} + void EventFrame::onEnter(Frame *nextFrame, int currentFrameIndex) { - if(currentFrameIndex>=_frameIndex) + if(_frameIndex < _action->getStartFrame() || _frameIndex > _action->getEndFrame()) + return; + + if(currentFrameIndex >= _frameIndex) emitEvent(); } diff --git a/cocos/editor-support/cocostudio/ActionTimeline/CCFrame.h b/cocos/editor-support/cocostudio/ActionTimeline/CCFrame.h index 2be52adfb4..e5d411f159 100644 --- a/cocos/editor-support/cocostudio/ActionTimeline/CCFrame.h +++ b/cocos/editor-support/cocostudio/ActionTimeline/CCFrame.h @@ -37,6 +37,7 @@ THE SOFTWARE. NS_TIMELINE_BEGIN class Timeline; +class ActionTimeline; class CC_STUDIO_DLL Frame : public cocos2d::Ref { @@ -307,6 +308,8 @@ public: EventFrame(); + virtual void setNode(cocos2d::Node* node); + virtual void onEnter(Frame *nextFrame, int currentFrameIndex) override; virtual Frame* clone() override; @@ -315,6 +318,7 @@ public: protected: std::string _event; + ActionTimeline* _action; }; class CC_STUDIO_DLL ZOrderFrame : public Frame diff --git a/cocos/editor-support/cocostudio/ActionTimeline/CSLoader.cpp b/cocos/editor-support/cocostudio/ActionTimeline/CSLoader.cpp index ffe19600b4..dab51accaa 100644 --- a/cocos/editor-support/cocostudio/ActionTimeline/CSLoader.cpp +++ b/cocos/editor-support/cocostudio/ActionTimeline/CSLoader.cpp @@ -755,13 +755,11 @@ Node* CSLoader::nodeWithFlatBuffersFile(const std::string &fileName) // decode plist auto textures = csparsebinary->textures(); - auto texturePngs = csparsebinary->texturePngs(); int textureSize = csparsebinary->textures()->size(); CCLOG("textureSize = %d", textureSize); for (int i = 0; i < textureSize; ++i) { - SpriteFrameCache::getInstance()->addSpriteFramesWithFile(textures->Get(i)->c_str(), - texturePngs->Get(i)->c_str()); + SpriteFrameCache::getInstance()->addSpriteFramesWithFile(textures->Get(i)->c_str()); } Node* node = nodeWithFlatBuffers(csparsebinary->nodeTree()); diff --git a/cocos/editor-support/cocostudio/ActionTimeline/CSLoader.h b/cocos/editor-support/cocostudio/ActionTimeline/CSLoader.h index e246e15452..7513554a1b 100644 --- a/cocos/editor-support/cocostudio/ActionTimeline/CSLoader.h +++ b/cocos/editor-support/cocostudio/ActionTimeline/CSLoader.h @@ -32,7 +32,7 @@ namespace flatbuffers { - struct FlatBufferBuilder; + class FlatBufferBuilder; struct NodeTree; diff --git a/cocos/editor-support/cocostudio/CCActionManagerEx.cpp b/cocos/editor-support/cocostudio/CCActionManagerEx.cpp index 5369ddbc0e..6faed2ed76 100644 --- a/cocos/editor-support/cocostudio/CCActionManagerEx.cpp +++ b/cocos/editor-support/cocostudio/CCActionManagerEx.cpp @@ -155,6 +155,16 @@ ActionObject* ActionManagerEx::playActionByName(const char* jsonName,const char* } return action; } + +ActionObject* ActionManagerEx::stopActionByName(const char* jsonName,const char* actionName) +{ + ActionObject* action = getActionByName(jsonName,actionName); + if (action) + { + action->stop(); + } + return action; +} void ActionManagerEx::releaseActions() { diff --git a/cocos/editor-support/cocostudio/CCActionManagerEx.h b/cocos/editor-support/cocostudio/CCActionManagerEx.h index 5b4622c6cd..bf2fde8b6c 100644 --- a/cocos/editor-support/cocostudio/CCActionManagerEx.h +++ b/cocos/editor-support/cocostudio/CCActionManagerEx.h @@ -98,6 +98,17 @@ public: */ ActionObject* playActionByName(const char* jsonName,const char* actionName, cocos2d::CallFunc* func); + /** + * Stop an Action with a name. + * + * @param jsonName UI file name + * + * @param actionName action name in teh UIfile. + * + * @return ActionObject which named as the param name + */ + ActionObject* stopActionByName(const char* jsonName,const char* actionName); + /*init properties with json dictionay*/ void initWithDictionary(const char* jsonName,const rapidjson::Value &dic, Ref* root); void initWithBinary(const char* file, Ref* root, CocoLoader* cocoLoader, stExpCocoNode* pCocoNode); diff --git a/cocos/editor-support/cocostudio/CSParseBinary_generated.h b/cocos/editor-support/cocostudio/CSParseBinary_generated.h index 93517520fb..d4360f64a0 100644 --- a/cocos/editor-support/cocostudio/CSParseBinary_generated.h +++ b/cocos/editor-support/cocostudio/CSParseBinary_generated.h @@ -1447,8 +1447,10 @@ struct ListViewOptions : private flatbuffers::Table { const FlatSize *innerSize() const { return GetStruct(28); } int32_t direction() const { return GetField(30, 0); } uint8_t bounceEnabled() const { return GetField(32, 0); } - int32_t gravity() const { return GetField(34, 0); } - int32_t itemMargin() const { return GetField(36, 0); } + int32_t itemMargin() const { return GetField(34, 0); } + const flatbuffers::String *directionType() const { return GetPointer(36); } + const flatbuffers::String *horizontalType() const { return GetPointer(38); } + const flatbuffers::String *verticalType() const { return GetPointer(40); } bool Verify(flatbuffers::Verifier &verifier) const { return VerifyTableStart(verifier) && VerifyField(verifier, 4 /* widgetOptions */) && @@ -1468,8 +1470,13 @@ struct ListViewOptions : private flatbuffers::Table { VerifyField(verifier, 28 /* innerSize */) && VerifyField(verifier, 30 /* direction */) && VerifyField(verifier, 32 /* bounceEnabled */) && - VerifyField(verifier, 34 /* gravity */) && - VerifyField(verifier, 36 /* itemMargin */) && + VerifyField(verifier, 34 /* itemMargin */) && + VerifyField(verifier, 36 /* directionType */) && + verifier.Verify(directionType()) && + VerifyField(verifier, 38 /* horizontalType */) && + verifier.Verify(horizontalType()) && + VerifyField(verifier, 40 /* verticalType */) && + verifier.Verify(verticalType()) && verifier.EndTable(); } }; @@ -1492,12 +1499,14 @@ struct ListViewOptionsBuilder { void add_innerSize(const FlatSize *innerSize) { fbb_.AddStruct(28, innerSize); } void add_direction(int32_t direction) { fbb_.AddElement(30, direction, 0); } void add_bounceEnabled(uint8_t bounceEnabled) { fbb_.AddElement(32, bounceEnabled, 0); } - void add_gravity(int32_t gravity) { fbb_.AddElement(34, gravity, 0); } - void add_itemMargin(int32_t itemMargin) { fbb_.AddElement(36, itemMargin, 0); } + void add_itemMargin(int32_t itemMargin) { fbb_.AddElement(34, itemMargin, 0); } + void add_directionType(flatbuffers::Offset directionType) { fbb_.AddOffset(36, directionType); } + void add_horizontalType(flatbuffers::Offset horizontalType) { fbb_.AddOffset(38, horizontalType); } + void add_verticalType(flatbuffers::Offset verticalType) { fbb_.AddOffset(40, verticalType); } ListViewOptionsBuilder(flatbuffers::FlatBufferBuilder &_fbb) : fbb_(_fbb) { start_ = fbb_.StartTable(); } ListViewOptionsBuilder &operator=(const ListViewOptionsBuilder &); flatbuffers::Offset Finish() { - auto o = flatbuffers::Offset(fbb_.EndTable(start_, 17)); + auto o = flatbuffers::Offset(fbb_.EndTable(start_, 19)); return o; } }; @@ -1518,11 +1527,15 @@ inline flatbuffers::Offset CreateListViewOptions(flatbuffers::F const FlatSize *innerSize = 0, int32_t direction = 0, uint8_t bounceEnabled = 0, - int32_t gravity = 0, - int32_t itemMargin = 0) { + int32_t itemMargin = 0, + flatbuffers::Offset directionType = 0, + flatbuffers::Offset horizontalType = 0, + flatbuffers::Offset verticalType = 0) { ListViewOptionsBuilder builder_(_fbb); + builder_.add_verticalType(verticalType); + builder_.add_horizontalType(horizontalType); + builder_.add_directionType(directionType); builder_.add_itemMargin(itemMargin); - builder_.add_gravity(gravity); builder_.add_direction(direction); builder_.add_innerSize(innerSize); builder_.add_scale9Size(scale9Size); @@ -2025,13 +2038,13 @@ inline flatbuffers::Offset CreateTimeLineColorFrame(flatbuff struct TimeLineTextureFrame : private flatbuffers::Table { int32_t frameIndex() const { return GetField(4, 0); } uint8_t tween() const { return GetField(6, 1); } - const flatbuffers::String *path() const { return GetPointer(8); } + const ResourceData *fileNameData() const { return GetPointer(8); } bool Verify(flatbuffers::Verifier &verifier) const { return VerifyTableStart(verifier) && VerifyField(verifier, 4 /* frameIndex */) && VerifyField(verifier, 6 /* tween */) && - VerifyField(verifier, 8 /* path */) && - verifier.Verify(path()) && + VerifyField(verifier, 8 /* fileNameData */) && + verifier.VerifyTable(fileNameData()) && verifier.EndTable(); } }; @@ -2041,7 +2054,7 @@ struct TimeLineTextureFrameBuilder { flatbuffers::uoffset_t start_; void add_frameIndex(int32_t frameIndex) { fbb_.AddElement(4, frameIndex, 0); } void add_tween(uint8_t tween) { fbb_.AddElement(6, tween, 1); } - void add_path(flatbuffers::Offset path) { fbb_.AddOffset(8, path); } + void add_fileNameData(flatbuffers::Offset fileNameData) { fbb_.AddOffset(8, fileNameData); } TimeLineTextureFrameBuilder(flatbuffers::FlatBufferBuilder &_fbb) : fbb_(_fbb) { start_ = fbb_.StartTable(); } TimeLineTextureFrameBuilder &operator=(const TimeLineTextureFrameBuilder &); flatbuffers::Offset Finish() { @@ -2053,9 +2066,9 @@ struct TimeLineTextureFrameBuilder { inline flatbuffers::Offset CreateTimeLineTextureFrame(flatbuffers::FlatBufferBuilder &_fbb, int32_t frameIndex = 0, uint8_t tween = 1, - flatbuffers::Offset path = 0) { + flatbuffers::Offset fileNameData = 0) { TimeLineTextureFrameBuilder builder_(_fbb); - builder_.add_path(path); + builder_.add_fileNameData(fileNameData); builder_.add_frameIndex(frameIndex); builder_.add_tween(tween); return builder_.Finish(); diff --git a/cocos/editor-support/cocostudio/FlatBuffersSerialize.cpp b/cocos/editor-support/cocostudio/FlatBuffersSerialize.cpp index ae15eca275..d3c135a831 100644 --- a/cocos/editor-support/cocostudio/FlatBuffersSerialize.cpp +++ b/cocos/editor-support/cocostudio/FlatBuffersSerialize.cpp @@ -54,11 +54,12 @@ #include "WidgetReader/PageViewReader/PageViewReader.h" #include "WidgetReader/ListViewReader/ListViewReader.h" -#include "tinyxml2/tinyxml2.h" +#include "tinyxml2.h" #include "flatbuffers/flatbuffers.h" #include "flatbuffers/util.h" + USING_NS_CC; using namespace cocos2d::ui; using namespace cocostudio; @@ -77,6 +78,8 @@ static const char* FrameType_TextureFrame = "TextureFrame"; static const char* FrameType_EventFrame = "EventFrame"; static const char* FrameType_ZOrderFrame = "ZOrderFrame"; +static FlatBuffersSerialize* _instanceFlatBuffersSerialize = nullptr; + FlatBuffersSerialize::FlatBuffersSerialize() : _isSimulator(false) , _builder(nullptr) @@ -87,7 +90,7 @@ FlatBuffersSerialize::FlatBuffersSerialize() CREATE_CLASS_NODE_READER_INFO(SpriteReader); CREATE_CLASS_NODE_READER_INFO(ParticleReader); CREATE_CLASS_NODE_READER_INFO(GameMapReader); - + CREATE_CLASS_NODE_READER_INFO(ButtonReader); CREATE_CLASS_NODE_READER_INFO(CheckBoxReader); CREATE_CLASS_NODE_READER_INFO(ImageViewReader); @@ -108,12 +111,10 @@ FlatBuffersSerialize::~FlatBuffersSerialize() { purge(); } - -static FlatBuffersSerialize* _instanceFlatBuffersSerialize = nullptr; FlatBuffersSerialize* FlatBuffersSerialize::getInstance() { - if (_instanceFlatBuffersSerialize == nullptr) + if (!_instanceFlatBuffersSerialize) { _instanceFlatBuffersSerialize = new FlatBuffersSerialize(); } @@ -124,6 +125,16 @@ FlatBuffersSerialize* FlatBuffersSerialize::getInstance() void FlatBuffersSerialize::purge() { CC_SAFE_DELETE(_instanceFlatBuffersSerialize); + +} + +void FlatBuffersSerialize::deleteFlatBufferBuilder() +{ + if (_builder != nullptr) + { + _builder->Clear(); + CC_SAFE_DELETE(_builder); + } } std::string FlatBuffersSerialize::serializeFlatBuffersWithXMLFile(const std::string &xmlFileName, @@ -146,7 +157,7 @@ std::string FlatBuffersSerialize::serializeFlatBuffersWithXMLFile(const std::str document->Parse(content.c_str()); const tinyxml2::XMLElement* rootElement = document->RootElement();// Root - CCLOG("rootElement name = %s", rootElement->Name()); +// CCLOG("rootElement name = %s", rootElement->Name()); const tinyxml2::XMLElement* element = rootElement->FirstChildElement(); @@ -155,7 +166,7 @@ std::string FlatBuffersSerialize::serializeFlatBuffersWithXMLFile(const std::str while (element) { - CCLOG("entity name = %s", element->Name()); +// CCLOG("entity name = %s", element->Name()); if (strcmp("Content", element->Name()) == 0) { @@ -209,8 +220,7 @@ std::string FlatBuffersSerialize::serializeFlatBuffersWithXMLFile(const std::str if (serializeEnabled) { - FlatBufferBuilder builder; - _builder = &builder; + _builder = new FlatBufferBuilder(); Offset nodeTree; Offset aciton; @@ -236,12 +246,12 @@ std::string FlatBuffersSerialize::serializeFlatBuffersWithXMLFile(const std::str child = child->NextSiblingElement(); } - auto csparsebinary = CreateCSParseBinary(builder, - builder.CreateVector(_textures), - builder.CreateVector(_texturePngs), + auto csparsebinary = CreateCSParseBinary(*_builder, + _builder->CreateVector(_textures), + _builder->CreateVector(_texturePngs), nodeTree, aciton); - builder.Finish(csparsebinary); + _builder->Finish(csparsebinary); _textures.clear(); _texturePngs.clear(); @@ -251,13 +261,15 @@ std::string FlatBuffersSerialize::serializeFlatBuffersWithXMLFile(const std::str size_t pos = outFullPath.find_last_of('.'); std::string convert = outFullPath.substr(0, pos).append(".csb"); auto save = flatbuffers::SaveFile(convert.c_str(), - reinterpret_cast(builder.GetBufferPointer()), - builder.GetSize(), + reinterpret_cast(_builder->GetBufferPointer()), + _builder->GetSize(), true); if (!save) { return "couldn't save files!"; } + + deleteFlatBufferBuilder(); } return ""; @@ -268,7 +280,7 @@ Offset FlatBuffersSerialize::createNodeTree(const tinyxml2::XMLElement std::string classType) { std::string classname = classType.substr(0, classType.find("ObjectData")); - CCLOG("classname = %s", classname.c_str()); +// CCLOG("classname = %s", classname.c_str()); std::string name = ""; @@ -301,7 +313,7 @@ Offset FlatBuffersSerialize::createNodeTree(const tinyxml2::XMLElement while (child) { - CCLOG("child name = %s", child->Name()); +// CCLOG("child name = %s", child->Name()); if (strcmp("Children", child->Name()) == 0) { @@ -315,7 +327,7 @@ Offset FlatBuffersSerialize::createNodeTree(const tinyxml2::XMLElement if (containChildrenElement) { child = child->FirstChildElement(); - CCLOG("element name = %s", child->Name()); +// CCLOG("element name = %s", child->Name()); while (child) { @@ -368,259 +380,7 @@ Offset FlatBuffersSerialize::createNodeTree(const tinyxml2::XMLElement _builder->CreateVector(children), options, _builder->CreateString(customClassName)); -} -FlatBufferBuilder* FlatBuffersSerialize::createFlatBuffersWithXMLFileForSimulator(const std::string &xmlFileName) -{ - std::string inFullpath = FileUtils::getInstance()->fullPathForFilename(xmlFileName).c_str(); - - // xml read - if (!FileUtils::getInstance()->isFileExist(inFullpath)) - { - CCLOG(".csd file doesn not exists "); - } - - ssize_t size; - std::string content =(char*)FileUtils::getInstance()->getFileData(inFullpath, "r", &size); - - // xml parse - tinyxml2::XMLDocument* document = new tinyxml2::XMLDocument(); - document->Parse(content.c_str()); - - const tinyxml2::XMLElement* rootElement = document->RootElement();// Root - CCLOG("rootElement name = %s", rootElement->Name()); - - const tinyxml2::XMLElement* element = rootElement->FirstChildElement(); - - bool serializeEnabled = false; - std::string rootType = ""; - - while (element) - { - CCLOG("entity name = %s", element->Name()); - - if (strcmp("Content", element->Name()) == 0) - { - const tinyxml2::XMLAttribute* attribute = element->FirstAttribute(); - - // - if (!attribute) - { - serializeEnabled = true; - rootType = "NodeObjectData"; - } - } - - if (serializeEnabled) - { - break; - } - - const tinyxml2::XMLElement* child = element->FirstChildElement(); - if (child) - { - element = child; - } - else - { - element = element->NextSiblingElement(); - } - } - - if (serializeEnabled) - { - _builder = new FlatBufferBuilder(); - - Offset nodeTree; - Offset aciton; - - - const tinyxml2::XMLElement* child = element->FirstChildElement(); - - while (child) - { - std::string name = child->Name(); - - if (name == "Animation") // action - { - const tinyxml2::XMLElement* animation = child; - aciton = createNodeAction(animation); - } - else if (name == "ObjectData") // nodeTree - { - const tinyxml2::XMLElement* objectData = child; - nodeTree = createNodeTreeForSimulator(objectData, rootType); - } - - child = child->NextSiblingElement(); - } - - auto csparsebinary = CreateCSParseBinary(*_builder, - _builder->CreateVector(_textures), - _builder->CreateVector(_texturePngs), - nodeTree, - aciton); - _builder->Finish(csparsebinary); - - _textures.clear(); - _texturePngs.clear(); - } - return _builder; -} - -Offset FlatBuffersSerialize::createNodeTreeForSimulator(const tinyxml2::XMLElement *objectData, - std::string classType) -{ - std::string classname = classType.substr(0, classType.find("ObjectData")); - CCLOG("classname = %s", classname.c_str()); - - std::string name = ""; - - Offset options; - std::vector> children; - - if (classname == "ProjectNode") - { - auto projectNodeOptions = createProjectNodeOptionsForSimulator(objectData); - options = CreateOptions(*_builder, *(Offset*)(&projectNodeOptions)); - } - else if (classname == "SimpleAudio") - { - auto reader = ComAudioReader::getInstance(); - options = CreateOptions(*_builder, reader->createOptionsWithFlatBuffers(objectData, _builder)); - } - else - { - std::string readername = getGUIClassName(classname); - readername.append("Reader"); - - NodeReaderProtocol* reader = dynamic_cast(ObjectFactory::getInstance()->createObject(readername)); - options = CreateOptions(*_builder, reader->createOptionsWithFlatBuffers(objectData, _builder)); - } - - - // children - bool containChildrenElement = false; - const tinyxml2::XMLElement* child = objectData->FirstChildElement(); - - while (child) - { - CCLOG("child name = %s", child->Name()); - - if (strcmp("Children", child->Name()) == 0) - { - containChildrenElement = true; - break; - } - - child = child->NextSiblingElement(); - } - - if (containChildrenElement) - { - child = child->FirstChildElement(); - CCLOG("element name = %s", child->Name()); - - while (child) - { - const tinyxml2::XMLAttribute* attribute = child->FirstAttribute(); - bool bHasType = false; - while (attribute) - { - std::string attriname = attribute->Name(); - std::string value = attribute->Value(); - - if (attriname == "ctype") - { - children.push_back(createNodeTreeForSimulator(child, value)); - - bHasType = true; - break; - } - - attribute = attribute->Next(); - } - - if(!bHasType) - { - children.push_back(createNodeTreeForSimulator(child, "NodeObjectData")); - } - - child = child->NextSiblingElement(); - } - } - // - - - std::string customClassName = ""; - const tinyxml2::XMLAttribute* attribute = objectData->FirstAttribute(); - while (attribute) - { - std::string attriname = attribute->Name(); - std::string value = attribute->Value(); - - if (attriname == "CustomClassName") - { - customClassName = value; - break; - } - - attribute = attribute->Next(); - } - - return CreateNodeTree(*_builder, - _builder->CreateString(classname), - _builder->CreateVector(children), - options, - _builder->CreateString(customClassName)); -} - -Offset FlatBuffersSerialize::createProjectNodeOptionsForSimulator(const tinyxml2::XMLElement *objectData) -{ - auto temp = NodeReader::getInstance()->createOptionsWithFlatBuffers(objectData, _builder); - auto nodeOptions = *(Offset*)(&temp); - - std::string filename = ""; - - // FileData - const tinyxml2::XMLElement* child = objectData->FirstChildElement(); - while (child) - { - std::string name = child->Name(); - - if (name == "FileData") - { - const tinyxml2::XMLAttribute* attribute = child->FirstAttribute(); - - while (attribute) - { - name = attribute->Name(); - std::string value = attribute->Value(); - - if (name == "Path") - { - filename = value; - } - - attribute = attribute->Next(); - } - } - - child = child->NextSiblingElement(); - } - - return CreateProjectNodeOptions(*_builder, - nodeOptions, - _builder->CreateString(filename)); -} - -void FlatBuffersSerialize::deleteFlatBufferBuilder() -{ - if (_builder != nullptr) - { - _builder->Clear(); - CC_SAFE_DELETE(_builder); - } } int FlatBuffersSerialize::getResourceType(std::string key) @@ -639,7 +399,7 @@ int FlatBuffersSerialize::getResourceType(std::string key) } return 1; } - + std::string FlatBuffersSerialize::getGUIClassName(const std::string &name) { std::string convertedClassName = name; @@ -737,6 +497,7 @@ std::string FlatBuffersSerialize::getWidgetReaderClassName(Widget* widget) return readerName; } +// // NodeAction @@ -745,7 +506,7 @@ Offset FlatBuffersSerialize::createNodeAction(const tinyxml2::XMLEle int duration = 0; float speed = 0.0f; - CCLOG("animation name = %s", objectData->Name()); +// CCLOG("animation name = %s", objectData->Name()); // ActionTimeline const tinyxml2::XMLAttribute* attribute = objectData->FirstAttribute(); @@ -822,17 +583,13 @@ Offset FlatBuffersSerialize::createTimeLine(const tinyxml2::XMLElement auto visibleFrame = createTimeLineBoolFrame(frameElement); frame = CreateFrame(*_builder, visibleFrame); - - frames.push_back(frame); } else if (frameType == FrameType_ZOrderFrame) { - auto zOrderFrame = createTimeLineIntFrame(objectData); + auto zOrderFrame = createTimeLineIntFrame(frameElement); frame = CreateFrame(*_builder, 0, // VisibleFrame zOrderFrame); - - frames.push_back(frame); } else if (frameType == FrameType_RotationSkewFrame) { @@ -841,8 +598,6 @@ Offset FlatBuffersSerialize::createTimeLine(const tinyxml2::XMLElement 0, // VisibleFrame 0, // ZOrderFrame rotationSkewFrame); - - frames.push_back(frame); } else if (frameType == FrameType_EventFrame) { @@ -852,8 +607,6 @@ Offset FlatBuffersSerialize::createTimeLine(const tinyxml2::XMLElement 0, // ZOrderFrame 0, // RotationSkewFrame eventFrame); - - frames.push_back(frame); } else if (frameType == FrameType_AnchorFrame) { @@ -864,8 +617,6 @@ Offset FlatBuffersSerialize::createTimeLine(const tinyxml2::XMLElement 0, // RotationSkewFrame 0, // EventFrame anchorPointFrame); - - frames.push_back(frame); } else if (frameType == FrameType_PositionFrame) { @@ -877,12 +628,10 @@ Offset FlatBuffersSerialize::createTimeLine(const tinyxml2::XMLElement 0, // EventFrame 0, // AnchorPointFrame positionFrame); - - frames.push_back(frame); } else if (frameType == FrameType_ScaleFrame) { - auto scaleFrame = createTimeLinePointFrame(objectData); + auto scaleFrame = createTimeLinePointFrame(frameElement); frame = CreateFrame(*_builder, 0, // VisibleFrame 0, // ZOrderFrame @@ -894,7 +643,7 @@ Offset FlatBuffersSerialize::createTimeLine(const tinyxml2::XMLElement } else if (frameType == FrameType_ColorFrame) { - auto colorFrame = createTimeLineColorFrame(objectData); + auto colorFrame = createTimeLineColorFrame(frameElement); frame = CreateFrame(*_builder, 0, // VisibleFrame 0, // ZOrderFrame @@ -907,7 +656,7 @@ Offset FlatBuffersSerialize::createTimeLine(const tinyxml2::XMLElement } else if (frameType == FrameType_TextureFrame) { - auto textureFrame = createTimeLineTextureFrame(objectData); + auto textureFrame = createTimeLineTextureFrame(frameElement); frame = CreateFrame(*_builder, 0, // VisibleFrame 0, // ZOrderFrame @@ -919,6 +668,7 @@ Offset FlatBuffersSerialize::createTimeLine(const tinyxml2::XMLElement 0, // ColorFrame textureFrame); } + frames.push_back(frame); frameElement = frameElement->NextSiblingElement(); } @@ -1136,83 +886,323 @@ Offset FlatBuffersSerialize::createTimeLineColorFrame(const &f_color); } -Offset FlatBuffersSerialize::createTimeLineTextureFrame(const tinyxml2::XMLElement *objectData) + Offset FlatBuffersSerialize::createTimeLineTextureFrame(const tinyxml2::XMLElement *objectData) + { + int frameIndex = 0; + bool tween = true; + + std::string path = ""; + std::string plistFile = ""; + int resourceType = 0; + + std::string texture = ""; + std::string texturePng = ""; + + const tinyxml2::XMLAttribute* attribute = objectData->FirstAttribute(); + while (attribute) + { + std::string attriname = attribute->Name(); + std::string value = attribute->Value(); + + if (attriname == "FrameIndex") + { + frameIndex = atoi(value.c_str()); + } + else if (attriname == "Tween") + { + tween = (value == "True") ? true : false; + } + + attribute = attribute->Next(); + } + + const tinyxml2::XMLElement* child = objectData->FirstChildElement(); + while (child) + { + attribute = child->FirstAttribute(); + while (attribute) + { + std::string attriname = attribute->Name(); + std::string value = attribute->Value(); + + if (attriname == "Path") + { + path = value; + } + else if (attriname == "Type") + { + resourceType = getResourceType(value); + } + else if (attriname == "Plist") + { + plistFile = value; + texture = value; + } + + attribute = attribute->Next(); + } + + if (resourceType == 1) + { + _textures.push_back(_builder->CreateString(texture)); + } + + child = child->NextSiblingElement(); + } + + return CreateTimeLineTextureFrame(*_builder, + frameIndex, + tween, + CreateResourceData(*_builder, + _builder->CreateString(path), + _builder->CreateString(plistFile), + resourceType)); + } + +/* create flat buffers with XML */ +FlatBufferBuilder* FlatBuffersSerialize::createFlatBuffersWithXMLFileForSimulator(const std::string &xmlFileName) +{ + std::string inFullpath = FileUtils::getInstance()->fullPathForFilename(xmlFileName).c_str(); + + // xml read + if (!FileUtils::getInstance()->isFileExist(inFullpath)) + { +// CCLOG(".csd file doesn not exists "); + } + + ssize_t size; + std::string content =(char*)FileUtils::getInstance()->getFileData(inFullpath, "r", &size); + + // xml parse + tinyxml2::XMLDocument* document = new tinyxml2::XMLDocument(); + document->Parse(content.c_str()); + + const tinyxml2::XMLElement* rootElement = document->RootElement();// Root +// CCLOG("rootElement name = %s", rootElement->Name()); + + const tinyxml2::XMLElement* element = rootElement->FirstChildElement(); + + bool serializeEnabled = false; + std::string rootType = ""; + + while (element) + { +// CCLOG("entity name = %s", element->Name()); + + if (strcmp("Content", element->Name()) == 0) + { + const tinyxml2::XMLAttribute* attribute = element->FirstAttribute(); + + // + if (!attribute) + { + serializeEnabled = true; + rootType = "NodeObjectData"; + } + } + + if (serializeEnabled) + { + break; + } + + const tinyxml2::XMLElement* child = element->FirstChildElement(); + if (child) + { + element = child; + } + else + { + element = element->NextSiblingElement(); + } + } + + if (serializeEnabled) + { + _builder = new FlatBufferBuilder(); + + Offset nodeTree; + Offset aciton; + + + const tinyxml2::XMLElement* child = element->FirstChildElement(); + + while (child) + { + std::string name = child->Name(); + + if (name == "Animation") // action + { + const tinyxml2::XMLElement* animation = child; + aciton = createNodeAction(animation); + } + else if (name == "ObjectData") // nodeTree + { + const tinyxml2::XMLElement* objectData = child; + nodeTree = createNodeTreeForSimulator(objectData, rootType); + } + + child = child->NextSiblingElement(); + } + + auto csparsebinary = CreateCSParseBinary(*_builder, + _builder->CreateVector(_textures), + _builder->CreateVector(_texturePngs), + nodeTree, + aciton); + _builder->Finish(csparsebinary); + + _textures.clear(); + _texturePngs.clear(); + } + return _builder; +} + +Offset FlatBuffersSerialize::createNodeTreeForSimulator(const tinyxml2::XMLElement *objectData, + std::string classType) { - int frameIndex = 0; - bool tween = true; + std::string classname = classType.substr(0, classType.find("ObjectData")); +// CCLOG("classname = %s", classname.c_str()); - std::string path = ""; - std::string plistFile = ""; - int resourceType = 0; + std::string name = ""; + Offset options; + std::vector> children; + + if (classname == "ProjectNode") + { + auto projectNodeOptions = createProjectNodeOptionsForSimulator(objectData); + options = CreateOptions(*_builder, *(Offset
*)(&projectNodeOptions)); + } + else if (classname == "SimpleAudio") + { + auto reader = ComAudioReader::getInstance(); + options = CreateOptions(*_builder, reader->createOptionsWithFlatBuffers(objectData, _builder)); + } + else + { + std::string readername = getGUIClassName(classname); + readername.append("Reader"); + + NodeReaderProtocol* reader = dynamic_cast(ObjectFactory::getInstance()->createObject(readername)); + options = CreateOptions(*_builder, reader->createOptionsWithFlatBuffers(objectData, _builder)); + } + + + // children + bool containChildrenElement = false; + const tinyxml2::XMLElement* child = objectData->FirstChildElement(); + + while (child) + { +// CCLOG("child name = %s", child->Name()); + + if (strcmp("Children", child->Name()) == 0) + { + containChildrenElement = true; + break; + } + + child = child->NextSiblingElement(); + } + + if (containChildrenElement) + { + child = child->FirstChildElement(); +// CCLOG("element name = %s", child->Name()); + + while (child) + { + const tinyxml2::XMLAttribute* attribute = child->FirstAttribute(); + bool bHasType = false; + while (attribute) + { + std::string attriname = attribute->Name(); + std::string value = attribute->Value(); + + if (attriname == "ctype") + { + children.push_back(createNodeTreeForSimulator(child, value)); + + bHasType = true; + break; + } + + attribute = attribute->Next(); + } + + if(!bHasType) + { + children.push_back(createNodeTreeForSimulator(child, "NodeObjectData")); + } + + child = child->NextSiblingElement(); + } + } + // + + + std::string customClassName = ""; const tinyxml2::XMLAttribute* attribute = objectData->FirstAttribute(); while (attribute) { std::string attriname = attribute->Name(); std::string value = attribute->Value(); - if (attriname == "FrameIndex") + if (attriname == "CustomClassName") { - frameIndex = atoi(value.c_str()); - } - else if (attriname == "Tween") - { - tween = (value == "True") ? true : false; + customClassName = value; + break; } attribute = attribute->Next(); } + return CreateNodeTree(*_builder, + _builder->CreateString(classname), + _builder->CreateVector(children), + options, + _builder->CreateString(customClassName)); +} + +Offset FlatBuffersSerialize::createProjectNodeOptionsForSimulator(const tinyxml2::XMLElement *objectData) +{ + auto temp = NodeReader::getInstance()->createOptionsWithFlatBuffers(objectData, _builder); + auto nodeOptions = *(Offset*)(&temp); + + std::string filename = ""; + + // FileData const tinyxml2::XMLElement* child = objectData->FirstChildElement(); while (child) { - attribute = child->FirstAttribute(); - while (attribute) + std::string name = child->Name(); + + if (name == "FileData") { - std::string attriname = attribute->Name(); - std::string value = attribute->Value(); + const tinyxml2::XMLAttribute* attribute = child->FirstAttribute(); - if (attriname == "Path") + while (attribute) { - std::string inFullpath = FileUtils::getInstance()->fullPathForFilename(value).c_str(); - - // xml read - if (!FileUtils::getInstance()->isFileExist(inFullpath)) - path = ""; - else - path = value; - } - else if (attriname == "Type") - { - resourceType = getResourceType(value); - } - else if (attriname == "Plist") - { - plistFile = value; - - std::string inFullpath = FileUtils::getInstance()->fullPathForFilename(value).c_str(); - - // xml read - if (!FileUtils::getInstance()->isFileExist(inFullpath)) + name = attribute->Name(); + std::string value = attribute->Value(); + + if (name == "Path") { - path = ""; - plistFile = ""; + filename = value; } - else - plistFile = value; + + attribute = attribute->Next(); } - - attribute = attribute->Next(); } child = child->NextSiblingElement(); } - return CreateTimeLineTextureFrame(*_builder, - frameIndex, - tween, - _builder->CreateString(path)); + return CreateProjectNodeOptions(*_builder, + nodeOptions, + _builder->CreateString(filename)); } } -/**/ \ No newline at end of file +/**/ diff --git a/cocos/editor-support/cocostudio/FlatBuffersSerialize.h b/cocos/editor-support/cocostudio/FlatBuffersSerialize.h index a1fb2f82a1..f514a8f38f 100644 --- a/cocos/editor-support/cocostudio/FlatBuffersSerialize.h +++ b/cocos/editor-support/cocostudio/FlatBuffersSerialize.h @@ -28,7 +28,6 @@ #include "cocos2d.h" #include "ExtensionMacros.h" #include "cocostudio/CocosStudioExport.h" -#include "tinyxml2/tinyxml2.h" namespace flatbuffers { @@ -78,18 +77,27 @@ namespace flatbuffers struct TimeLineTextureFrame; } -namespace cocostudio { +namespace tinyxml2 +{ + class XMLElement; +} +namespace cocostudio { + class CC_STUDIO_DLL FlatBuffersSerialize { public: + static FlatBuffersSerialize* getInstance(); + static void purge(); FlatBuffersSerialize(); ~FlatBuffersSerialize(); - static FlatBuffersSerialize* getInstance(); - static void purge(); + void deleteFlatBufferBuilder(); + + std::string test(const std::string& xmlFileName, + const std::string& flatbuffersFileName); /* serialize flat buffers with XML */ std::string serializeFlatBuffersWithXMLFile(const std::string& xmlFileName, @@ -97,7 +105,7 @@ public: // NodeTree flatbuffers::Offset createNodeTree(const tinyxml2::XMLElement* objectData, - std::string classType); + std::string classType); // NodeAction flatbuffers::Offset createNodeAction(const tinyxml2::XMLElement* objectData); @@ -110,17 +118,17 @@ public: flatbuffers::Offset createTimeLineTextureFrame(const tinyxml2::XMLElement* objectData); /**/ - flatbuffers::FlatBufferBuilder* createFlatBuffersWithXMLFileForSimulator(const std::string& xmlFileName); - flatbuffers::Offset createNodeTreeForSimulator(const tinyxml2::XMLElement* objectData, - std::string classType); - flatbuffers::Offset createProjectNodeOptionsForSimulator(const tinyxml2::XMLElement* objectData); - - void deleteFlatBufferBuilder(); - int getResourceType(std::string key); std::string getGUIClassName(const std::string &name); std::string getWidgetReaderClassName(cocos2d::ui::Widget *widget); + /* create flat buffers with XML */ + flatbuffers::FlatBufferBuilder* createFlatBuffersWithXMLFileForSimulator(const std::string& xmlFileName); + flatbuffers::Offset createNodeTreeForSimulator(const tinyxml2::XMLElement* objectData, + std::string classType); + flatbuffers::Offset createProjectNodeOptionsForSimulator(const tinyxml2::XMLElement* objectData); + /**/ + public: std::vector> _textures; std::vector> _texturePngs; @@ -131,7 +139,6 @@ private: flatbuffers::Offset* _csparsebinary; }; - } #endif /* defined(__cocos2d_libs__FlatBuffersSerialize__) */ diff --git a/cocos/editor-support/cocostudio/WidgetReader/ButtonReader/ButtonReader.cpp b/cocos/editor-support/cocostudio/WidgetReader/ButtonReader/ButtonReader.cpp index 7bb18720b6..e4136795a5 100644 --- a/cocos/editor-support/cocostudio/WidgetReader/ButtonReader/ButtonReader.cpp +++ b/cocos/editor-support/cocostudio/WidgetReader/ButtonReader/ButtonReader.cpp @@ -7,7 +7,7 @@ #include "cocostudio/CSParseBinary_generated.h" #include "cocostudio/FlatBuffersSerialize.h" -#include "tinyxml2/tinyxml2.h" +#include "tinyxml2.h" #include "flatbuffers/flatbuffers.h" USING_NS_CC; @@ -232,7 +232,7 @@ namespace cocostudio button->setTitleFontSize(DICTOOL->getIntValue_json(options, P_FontSize,14)); - button->setTitleFontName(DICTOOL->getStringValue_json(options, P_FontName,"微软雅黑")); + button->setTitleFontName(DICTOOL->getStringValue_json(options, P_FontName, "")); @@ -403,9 +403,6 @@ namespace cocostudio { FlatBuffersSerialize* fbs = FlatBuffersSerialize::getInstance(); fbs->_textures.push_back(builder->CreateString(texture)); - - texturePng = texture.substr(0, texture.find_last_of('.')).append(".png"); - fbs->_texturePngs.push_back(builder->CreateString(texturePng)); } } else if (name == "PressedFileData") @@ -440,10 +437,7 @@ namespace cocostudio if (pressedResourceType == 1) { FlatBuffersSerialize* fbs = FlatBuffersSerialize::getInstance(); - fbs->_textures.push_back(builder->CreateString(texture)); - - texturePng = texture.substr(0, texture.find_last_of('.')).append(".png"); - fbs->_texturePngs.push_back(builder->CreateString(texturePng)); + fbs->_textures.push_back(builder->CreateString(texture)); } } else if (name == "NormalFileData") @@ -478,10 +472,7 @@ namespace cocostudio if (normalResourceType == 1) { FlatBuffersSerialize* fbs = FlatBuffersSerialize::getInstance(); - fbs->_textures.push_back(builder->CreateString(texture)); - - texturePng = texture.substr(0, texture.find_last_of('.')).append(".png"); - fbs->_texturePngs.push_back(builder->CreateString(texturePng)); + fbs->_textures.push_back(builder->CreateString(texture)); } } else if (name == "FontResource") @@ -556,33 +547,194 @@ namespace cocostudio bool scale9Enabled = options->scale9Enabled(); button->setScale9Enabled(scale9Enabled); - + bool normalFileExist = false; + std::string normalErrorFilePath = ""; auto normalDic = options->normalData(); int normalType = normalDic->resourceType(); - std::string normalTexturePath = normalDic->path()->c_str(); - button->loadTextureNormal(normalTexturePath, (Widget::TextureResType)normalType); + std::string normalTexturePath = this->getResourcePath(normalDic->path()->c_str(), (Widget::TextureResType)normalType); + switch (normalType) + { + case 0: + if (FileUtils::getInstance()->isFileExist(normalTexturePath)) + { + normalFileExist = true; + } + else + { + normalErrorFilePath = normalTexturePath; + normalFileExist = false; + } + break; + + case 1: + { + std::string plist = normalDic->plistFile()->c_str(); + SpriteFrame* spriteFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(normalTexturePath); + if (spriteFrame) + { + normalFileExist = true; + } + else + { + if (FileUtils::getInstance()->isFileExist(plist)) + { + ValueMap value = FileUtils::getInstance()->getValueMapFromFile(plist); + ValueMap metadata = value["metadata"].asValueMap(); + std::string textureFileName = metadata["textureFileName"].asString(); + if (!FileUtils::getInstance()->isFileExist(textureFileName)) + { + normalErrorFilePath = textureFileName; + } + } + else + { + normalErrorFilePath = plist; + } + normalFileExist = false; + } + break; + } + + default: + break; + } + if (normalFileExist) + { + button->loadTextureNormal(normalTexturePath, (Widget::TextureResType)normalType); + } + else + { + auto label = Label::create(); + label->setString(__String::createWithFormat("%s missed", normalErrorFilePath.c_str())->getCString()); + button->addChild(label); + } + bool pressedFileExist = false; + std::string pressedErrorFilePath = ""; auto pressedDic = options->pressedData(); int pressedType = pressedDic->resourceType(); - std::string pressedTexturePath = pressedDic->path()->c_str(); - button->loadTexturePressed(pressedTexturePath, (Widget::TextureResType)pressedType); + std::string pressedTexturePath = this->getResourcePath(pressedDic->path()->c_str(), (Widget::TextureResType)pressedType); + switch (pressedType) + { + case 0: + { + if (FileUtils::getInstance()->isFileExist(pressedTexturePath)) + { + pressedFileExist = true; + } + else + { + pressedErrorFilePath = pressedTexturePath; + pressedFileExist = false; + } + break; + } + + case 1: + { + std::string plist = pressedDic->plistFile()->c_str(); + SpriteFrame* spriteFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(pressedTexturePath); + if (spriteFrame) + { + pressedFileExist = true; + } + else + { + if (FileUtils::getInstance()->isFileExist(plist)) + { + ValueMap value = FileUtils::getInstance()->getValueMapFromFile(plist); + ValueMap metadata = value["metadata"].asValueMap(); + std::string textureFileName = metadata["textureFileName"].asString(); + if (!FileUtils::getInstance()->isFileExist(textureFileName)) + { + pressedErrorFilePath = textureFileName; + } + } + else + { + pressedErrorFilePath = plist; + } + pressedFileExist = false; + } + break; + } + + default: + break; + } + if (pressedFileExist) + { + button->loadTexturePressed(pressedTexturePath, (Widget::TextureResType)pressedType); + } + else + { + auto label = Label::create(); + label->setString(__String::createWithFormat("%s missed", pressedErrorFilePath.c_str())->getCString()); + button->addChild(label); + } + bool disabledFileExist = false; + std::string disabledErrorFilePath = ""; auto disabledDic = options->disabledData(); int disabledType = disabledDic->resourceType(); - std::string disabledTexturePath = disabledDic->path()->c_str(); - button->loadTextureDisabled(disabledTexturePath, (Widget::TextureResType)disabledType); - - if (scale9Enabled) + std::string disabledTexturePath = this->getResourcePath(disabledDic->path()->c_str(), (Widget::TextureResType)disabledType); + switch (disabledType) { - button->setUnifySizeEnabled(false); - button->ignoreContentAdaptWithSize(false); - - auto f_capInsets = options->capInsets(); - Rect capInsets(f_capInsets->x(), f_capInsets->y(), f_capInsets->width(), f_capInsets->height()); - button->setCapInsets(capInsets); - - Size scale9Size(options->scale9Size()->width(), options->scale9Size()->height()); - button->setContentSize(scale9Size); + case 0: + { + if (FileUtils::getInstance()->isFileExist(disabledTexturePath)) + { + disabledFileExist = true; + } + else + { + disabledErrorFilePath = disabledTexturePath; + disabledFileExist = false; + } + break; + } + + case 1: + { + std::string plist = disabledDic->plistFile()->c_str(); + SpriteFrame* spriteFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(disabledTexturePath); + if (spriteFrame) + { + disabledFileExist = true; + } + else + { + if (FileUtils::getInstance()->isFileExist(plist)) + { + ValueMap value = FileUtils::getInstance()->getValueMapFromFile(plist); + ValueMap metadata = value["metadata"].asValueMap(); + std::string textureFileName = metadata["textureFileName"].asString(); + if (!FileUtils::getInstance()->isFileExist(textureFileName)) + { + disabledErrorFilePath = textureFileName; + } + } + else + { + disabledErrorFilePath = plist; + } + disabledFileExist = false; + } + break; + } + + default: + break; + } + if (disabledFileExist) + { + button->loadTextureDisabled(disabledTexturePath, (Widget::TextureResType)disabledType); + } + else + { + auto label = Label::create(); + label->setString(__String::createWithFormat("%s missed", disabledErrorFilePath.c_str())->getCString()); + button->addChild(label); } std::string titleText = options->text()->c_str(); @@ -599,29 +751,50 @@ namespace cocostudio button->setTitleFontName(titleFontName); auto resourceData = options->fontResource(); + bool fileExist = false; + std::string errorFilePath = ""; std::string path = resourceData->path()->c_str(); if (path != "") { - button->setTitleFontName(path); + if (FileUtils::getInstance()->isFileExist(path)) + { + fileExist = true; + } + else + { + errorFilePath = path; + fileExist = false; + } + if (fileExist) + { + button->setTitleFontName(path); + } + else + { + auto label = Label::create(); + label->setString(__String::createWithFormat("%s missed", errorFilePath.c_str())->getCString()); + button->addChild(label); + } } bool displaystate = options->displaystate(); button->setBright(displaystate); button->setEnabled(displaystate); - Size contentSize; - if (!button->isScale9Enabled()) - { - button->setUnifySizeEnabled(true); - contentSize = button->getVirtualRendererSize(); - } - auto widgetReader = WidgetReader::getInstance(); widgetReader->setPropsWithFlatBuffers(node, (Table*)options->widgetOptions()); - - if (!button->isScale9Enabled()) + + if (scale9Enabled) { - button->setContentSize(contentSize); + button->setUnifySizeEnabled(false); + button->ignoreContentAdaptWithSize(false); + + auto f_capInsets = options->capInsets(); + Rect capInsets(f_capInsets->x(), f_capInsets->y(), f_capInsets->width(), f_capInsets->height()); + button->setCapInsets(capInsets); + + Size scale9Size(options->scale9Size()->width(), options->scale9Size()->height()); + button->setContentSize(scale9Size); } } diff --git a/cocos/editor-support/cocostudio/WidgetReader/CheckBoxReader/CheckBoxReader.cpp b/cocos/editor-support/cocostudio/WidgetReader/CheckBoxReader/CheckBoxReader.cpp index 55daff5570..8d5fdfc592 100644 --- a/cocos/editor-support/cocostudio/WidgetReader/CheckBoxReader/CheckBoxReader.cpp +++ b/cocos/editor-support/cocostudio/WidgetReader/CheckBoxReader/CheckBoxReader.cpp @@ -7,7 +7,7 @@ #include "cocostudio/CSParseBinary_generated.h" #include "cocostudio/FlatBuffersSerialize.h" -#include "tinyxml2/tinyxml2.h" +#include "tinyxml2.h" #include "flatbuffers/flatbuffers.h" USING_NS_CC; @@ -164,7 +164,7 @@ namespace cocostudio auto temp = WidgetReader::getInstance()->createOptionsWithFlatBuffers(objectData, builder); auto widgetOptions = *(Offset*)(&temp); - bool selectedState = true; + bool selectedState = false; bool displaystate = true; int backgroundboxResourceType = 0; @@ -245,9 +245,6 @@ namespace cocostudio { FlatBuffersSerialize* fbs = FlatBuffersSerialize::getInstance(); fbs->_textures.push_back(builder->CreateString(texture)); - - texturePng = texture.substr(0, texture.find_last_of('.')).append(".png"); - fbs->_texturePngs.push_back(builder->CreateString(texturePng)); } } else if (name == "PressedBackFileData") @@ -283,9 +280,6 @@ namespace cocostudio { FlatBuffersSerialize* fbs = FlatBuffersSerialize::getInstance(); fbs->_textures.push_back(builder->CreateString(texture)); - - texturePng = texture.substr(0, texture.find_last_of('.')).append(".png"); - fbs->_texturePngs.push_back(builder->CreateString(texturePng)); } } else if (name == "NodeNormalFileData") @@ -321,9 +315,6 @@ namespace cocostudio { FlatBuffersSerialize* fbs = FlatBuffersSerialize::getInstance(); fbs->_textures.push_back(builder->CreateString(texture)); - - texturePng = texture.substr(0, texture.find_last_of('.')).append(".png"); - fbs->_texturePngs.push_back(builder->CreateString(texturePng)); } } else if (name == "DisableBackFileData") @@ -358,10 +349,7 @@ namespace cocostudio if (backGroundBoxDisabledResourceType == 1) { FlatBuffersSerialize* fbs = FlatBuffersSerialize::getInstance(); - fbs->_textures.push_back(builder->CreateString(texture)); - - texturePng = texture.substr(0, texture.find_last_of('.')).append(".png"); - fbs->_texturePngs.push_back(builder->CreateString(texturePng)); + fbs->_textures.push_back(builder->CreateString(texture)); } } else if (name == "NodeDisableFileData") @@ -396,10 +384,7 @@ namespace cocostudio if (frontCrossDisabledResourceType == 1) { FlatBuffersSerialize* fbs = FlatBuffersSerialize::getInstance(); - fbs->_textures.push_back(builder->CreateString(texture)); - - texturePng = texture.substr(0, texture.find_last_of('.')).append(".png"); - fbs->_texturePngs.push_back(builder->CreateString(texturePng)); + fbs->_textures.push_back(builder->CreateString(texture)); } } @@ -444,34 +429,329 @@ namespace cocostudio CheckBox* checkBox = static_cast(node); //load background image + bool backGroundFileExist = false; + std::string backGroundErrorFilePath = ""; auto backGroundDic = options->backGroundBoxData(); int backGroundType = backGroundDic->resourceType(); - std::string backGroundTexturePath = backGroundDic->path()->c_str(); - checkBox->loadTextureBackGround(backGroundTexturePath, (Widget::TextureResType)backGroundType); + std::string backGroundTexturePath = this->getResourcePath(backGroundDic->path()->c_str(), (Widget::TextureResType)backGroundType); + switch (backGroundType) + { + case 0: + { + if (FileUtils::getInstance()->isFileExist(backGroundTexturePath)) + { + backGroundFileExist = true; + } + else + { + backGroundErrorFilePath = backGroundTexturePath; + backGroundFileExist = false; + } + break; + } + + case 1: + { + std::string plist = backGroundDic->plistFile()->c_str(); + SpriteFrame* spriteFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(backGroundTexturePath); + if (spriteFrame) + { + backGroundFileExist = true; + } + else + { + if (FileUtils::getInstance()->isFileExist(plist)) + { + ValueMap value = FileUtils::getInstance()->getValueMapFromFile(plist); + ValueMap metadata = value["metadata"].asValueMap(); + std::string textureFileName = metadata["textureFileName"].asString(); + if (!FileUtils::getInstance()->isFileExist(textureFileName)) + { + backGroundErrorFilePath = textureFileName; + } + } + else + { + backGroundErrorFilePath = plist; + } + backGroundFileExist = false; + } + break; + } + + default: + break; + } + if (backGroundFileExist) + { + checkBox->loadTextureBackGround(backGroundTexturePath, (Widget::TextureResType)backGroundType); + } + else + { + auto label = Label::create(); + label->setString(__String::createWithFormat("%s missed", backGroundErrorFilePath.c_str())->getCString()); + checkBox->addChild(label); + } //load background selected image + bool backGroundSelectedfileExist = false; + std::string backGroundSelectedErrorFilePath = ""; auto backGroundSelectedDic = options->backGroundBoxSelectedData(); int backGroundSelectedType = backGroundSelectedDic->resourceType(); - std::string backGroundSelectedTexturePath = backGroundSelectedDic->path()->c_str(); - checkBox->loadTextureBackGroundSelected(backGroundSelectedTexturePath, (Widget::TextureResType)backGroundSelectedType); + std::string backGroundSelectedTexturePath = this->getResourcePath(backGroundSelectedDic->path()->c_str(), (Widget::TextureResType)backGroundSelectedType); + switch (backGroundSelectedType) + { + case 0: + { + if (FileUtils::getInstance()->isFileExist(backGroundSelectedTexturePath)) + { + backGroundSelectedfileExist = true; + } + else + { + backGroundSelectedErrorFilePath = backGroundSelectedTexturePath; + backGroundSelectedfileExist = false; + } + break; + } + + case 1: + { + std::string plist = backGroundSelectedDic->plistFile()->c_str(); + SpriteFrame* spriteFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(backGroundSelectedTexturePath); + if (spriteFrame) + { + backGroundSelectedfileExist = true; + } + else + { + if (FileUtils::getInstance()->isFileExist(plist)) + { + ValueMap value = FileUtils::getInstance()->getValueMapFromFile(plist); + ValueMap metadata = value["metadata"].asValueMap(); + std::string textureFileName = metadata["textureFileName"].asString(); + if (!FileUtils::getInstance()->isFileExist(textureFileName)) + { + backGroundSelectedErrorFilePath = textureFileName; + } + } + else + { + backGroundSelectedErrorFilePath = plist; + } + backGroundSelectedfileExist = false; + } + break; + } + + default: + break; + } + if (backGroundSelectedfileExist) + { + checkBox->loadTextureBackGroundSelected(backGroundSelectedTexturePath, (Widget::TextureResType)backGroundSelectedType); + } + else + { + auto label = Label::create(); + label->setString(__String::createWithFormat("%s missed", backGroundSelectedErrorFilePath.c_str())->getCString()); + checkBox->addChild(label); + } //load frontCross image + bool frontCrossFileExist = false; + std::string frontCrossErrorFilePath = ""; auto frontCrossDic = options->frontCrossData(); int frontCrossType = frontCrossDic->resourceType(); - std::string frontCrossFileName = frontCrossDic->path()->c_str(); - checkBox->loadTextureFrontCross(frontCrossFileName, (Widget::TextureResType)frontCrossType); + std::string frontCrossFileName = this->getResourcePath(frontCrossDic->path()->c_str(), (Widget::TextureResType)frontCrossType); + switch (frontCrossType) + { + case 0: + { + if (FileUtils::getInstance()->isFileExist(frontCrossFileName)) + { + frontCrossFileExist = true; + } + else + { + frontCrossErrorFilePath = frontCrossFileName; + frontCrossFileExist = false; + } + break; + } + + case 1: + { + std::string plist = frontCrossDic->plistFile()->c_str(); + SpriteFrame* spriteFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(frontCrossFileName); + if (spriteFrame) + { + frontCrossFileExist = true; + } + else + { + if (FileUtils::getInstance()->isFileExist(plist)) + { + ValueMap value = FileUtils::getInstance()->getValueMapFromFile(plist); + ValueMap metadata = value["metadata"].asValueMap(); + std::string textureFileName = metadata["textureFileName"].asString(); + if (!FileUtils::getInstance()->isFileExist(textureFileName)) + { + frontCrossErrorFilePath = textureFileName; + } + } + else + { + frontCrossErrorFilePath = plist; + } + frontCrossFileExist = false; + } + break; + } + + default: + break; + } + if (frontCrossFileExist) + { + checkBox->loadTextureFrontCross(frontCrossFileName, (Widget::TextureResType)frontCrossType); + } + else + { + auto label = Label::create(); + label->setString(__String::createWithFormat("%s missed", frontCrossErrorFilePath.c_str())->getCString()); + checkBox->addChild(label); + } //load backGroundBoxDisabledData + bool backGroundBoxDisabledFileExist = false; + std::string backGroundBoxDisabledErrorFilePath = ""; auto backGroundDisabledDic = options->backGroundBoxDisabledData(); int backGroundDisabledType = backGroundDisabledDic->resourceType(); - std::string backGroundDisabledFileName = backGroundDisabledDic->path()->c_str(); - checkBox->loadTextureBackGroundDisabled(backGroundDisabledFileName, (Widget::TextureResType)backGroundDisabledType); + std::string backGroundDisabledFileName = this->getResourcePath(backGroundDisabledDic->path()->c_str(), (Widget::TextureResType)backGroundDisabledType); + switch (backGroundDisabledType) + { + case 0: + { + if (FileUtils::getInstance()->isFileExist(backGroundDisabledFileName)) + { + backGroundBoxDisabledFileExist = true; + } + else + { + backGroundBoxDisabledErrorFilePath = backGroundDisabledFileName; + backGroundBoxDisabledFileExist = false; + } + break; + } + + case 1: + { + std::string plist = backGroundDisabledDic->plistFile()->c_str(); + SpriteFrame* spriteFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(backGroundDisabledFileName); + if (spriteFrame) + { + backGroundBoxDisabledFileExist = true; + } + else + { + if (FileUtils::getInstance()->isFileExist(plist)) + { + ValueMap value = FileUtils::getInstance()->getValueMapFromFile(plist); + ValueMap metadata = value["metadata"].asValueMap(); + std::string textureFileName = metadata["textureFileName"].asString(); + if (!FileUtils::getInstance()->isFileExist(textureFileName)) + { + backGroundBoxDisabledErrorFilePath = textureFileName; + } + } + else + { + backGroundBoxDisabledErrorFilePath = plist; + } + backGroundBoxDisabledFileExist = false; + } + break; + } + + default: + break; + } + if (backGroundBoxDisabledFileExist) + { + checkBox->loadTextureBackGroundDisabled(backGroundDisabledFileName, (Widget::TextureResType)backGroundDisabledType); + } + else + { + auto label = Label::create(); + label->setString(__String::createWithFormat("%s missed", backGroundBoxDisabledErrorFilePath.c_str())->getCString()); + checkBox->addChild(label); + } ///load frontCrossDisabledData + bool frontCrossDisabledFileExist = false; + std::string frontCrossDisabledErrorFilePath = ""; auto frontCrossDisabledDic = options->frontCrossDisabledData(); int frontCrossDisabledType = frontCrossDisabledDic->resourceType(); - std::string frontCrossDisabledFileName = frontCrossDisabledDic->path()->c_str(); - checkBox->loadTextureFrontCrossDisabled(frontCrossDisabledFileName, (Widget::TextureResType)frontCrossDisabledType); + std::string frontCrossDisabledFileName = this->getResourcePath(frontCrossDisabledDic->path()->c_str(), (Widget::TextureResType)frontCrossDisabledType); + switch (frontCrossDisabledType) + { + case 0: + { + if (FileUtils::getInstance()->isFileExist(frontCrossDisabledFileName)) + { + frontCrossDisabledFileExist = true; + } + else + { + frontCrossDisabledErrorFilePath = frontCrossDisabledFileName; + frontCrossDisabledFileExist = false; + } + break; + } + + case 1: + { + std::string plist = frontCrossDisabledDic->plistFile()->c_str(); + SpriteFrame* spriteFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(frontCrossDisabledFileName); + if (spriteFrame) + { + frontCrossDisabledFileExist = true; + } + else + { + if (FileUtils::getInstance()->isFileExist(plist)) + { + ValueMap value = FileUtils::getInstance()->getValueMapFromFile(plist); + ValueMap metadata = value["metadata"].asValueMap(); + std::string textureFileName = metadata["textureFileName"].asString(); + if (!FileUtils::getInstance()->isFileExist(textureFileName)) + { + frontCrossDisabledErrorFilePath = textureFileName; + } + } + else + { + frontCrossDisabledErrorFilePath = plist; + } + frontCrossDisabledFileExist = false; + } + break; + } + + default: + break; + } + if (frontCrossDisabledFileExist) + { + checkBox->loadTextureFrontCrossDisabled(frontCrossDisabledFileName, (Widget::TextureResType)frontCrossDisabledType); + } + else + { + auto label = Label::create(); + label->setString(__String::createWithFormat("%s missed", frontCrossDisabledErrorFilePath.c_str())->getCString()); + checkBox->addChild(label); + } bool selectedstate = options->selectedState(); checkBox->setSelected(selectedstate); diff --git a/cocos/editor-support/cocostudio/WidgetReader/ComAudioReader/ComAudioReader.cpp b/cocos/editor-support/cocostudio/WidgetReader/ComAudioReader/ComAudioReader.cpp index b552c26e38..005b322257 100644 --- a/cocos/editor-support/cocostudio/WidgetReader/ComAudioReader/ComAudioReader.cpp +++ b/cocos/editor-support/cocostudio/WidgetReader/ComAudioReader/ComAudioReader.cpp @@ -28,7 +28,7 @@ #include "cocostudio/CSParseBinary_generated.h" #include "cocostudio/WidgetReader/NodeReader/NodeReader.h" -#include "tinyxml2/tinyxml2.h" +#include "tinyxml2.h" #include "flatbuffers/flatbuffers.h" USING_NS_CC; @@ -190,4 +190,4 @@ namespace cocostudio return component; } -} \ No newline at end of file +} diff --git a/cocos/editor-support/cocostudio/WidgetReader/GameMapReader/GameMapReader.cpp b/cocos/editor-support/cocostudio/WidgetReader/GameMapReader/GameMapReader.cpp index 5c52871542..8f4a642f3d 100644 --- a/cocos/editor-support/cocostudio/WidgetReader/GameMapReader/GameMapReader.cpp +++ b/cocos/editor-support/cocostudio/WidgetReader/GameMapReader/GameMapReader.cpp @@ -27,7 +27,7 @@ #include "cocostudio/CSParseBinary_generated.h" #include "cocostudio/WidgetReader/NodeReader/NodeReader.h" -#include "tinyxml2/tinyxml2.h" +#include "tinyxml2.h" #include "flatbuffers/flatbuffers.h" USING_NS_CC; @@ -134,17 +134,22 @@ namespace cocostudio auto options = (GameMapOptions*)gameMapOptions; auto fileNameData = options->fileNameData(); + bool fileExist = false; + std::string errorFilePath = ""; + std::string path = fileNameData->path()->c_str(); int resourceType = fileNameData->resourceType(); switch (resourceType) { case 0: { - std::string path = fileNameData->path()->c_str(); - const char* tmxFile = path.c_str(); - - if (tmxFile && strcmp("", tmxFile) != 0) + if (FileUtils::getInstance()->isFileExist(path)) { - tmx = TMXTiledMap::create(tmxFile); + fileExist = true; + } + else + { + errorFilePath = path; + fileExist = false; } break; } @@ -152,10 +157,22 @@ namespace cocostudio default: break; } - - if (tmx) + if (fileExist) { - setPropsWithFlatBuffers(tmx, (Table*)gameMapOptions); + tmx = TMXTiledMap::create(path); + if (tmx) + { + setPropsWithFlatBuffers(tmx, (Table*)gameMapOptions); + } + } + else + { + Node* node = Node::create(); + setPropsWithFlatBuffers(node, (Table*)gameMapOptions); + auto label = Label::create(); + label->setString(__String::createWithFormat("%s missed", errorFilePath.c_str())->getCString()); + node->addChild(label); + return node; } return tmx; diff --git a/cocos/editor-support/cocostudio/WidgetReader/ImageViewReader/ImageViewReader.cpp b/cocos/editor-support/cocostudio/WidgetReader/ImageViewReader/ImageViewReader.cpp index 0491b0d99d..1fbd8da0ac 100644 --- a/cocos/editor-support/cocostudio/WidgetReader/ImageViewReader/ImageViewReader.cpp +++ b/cocos/editor-support/cocostudio/WidgetReader/ImageViewReader/ImageViewReader.cpp @@ -7,7 +7,7 @@ #include "cocostudio/CSParseBinary_generated.h" #include "cocostudio/FlatBuffersSerialize.h" -#include "tinyxml2/tinyxml2.h" +#include "tinyxml2.h" #include "flatbuffers/flatbuffers.h" USING_NS_CC; @@ -262,10 +262,7 @@ namespace cocostudio if (resourceType == 1) { FlatBuffersSerialize* fbs = FlatBuffersSerialize::getInstance(); - fbs->_textures.push_back(builder->CreateString(texture)); - - texturePng = texture.substr(0, texture.find_last_of('.')).append(".png"); - fbs->_texturePngs.push_back(builder->CreateString(texturePng)); + fbs->_textures.push_back(builder->CreateString(texture)); } } @@ -294,14 +291,75 @@ namespace cocostudio auto options = (ImageViewOptions*)imageViewOptions; + bool fileExist = false; + std::string errorFilePath = ""; auto imageFileNameDic = options->fileNameData(); int imageFileNameType = imageFileNameDic->resourceType(); - std::string imageFileName = imageFileNameDic->path()->c_str(); - imageView->loadTexture(imageFileName, (Widget::TextureResType)imageFileNameType); + std::string imageFileName = this->getResourcePath(imageFileNameDic->path()->c_str(), (Widget::TextureResType)imageFileNameType); + switch (imageFileNameType) + { + case 0: + { + if (FileUtils::getInstance()->isFileExist(imageFileName)) + { + fileExist = true; + } + else + { + errorFilePath = imageFileName; + fileExist = false; + } + break; + } + + case 1: + { + std::string plist = imageFileNameDic->plistFile()->c_str(); + SpriteFrame* spriteFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(imageFileName); + if (spriteFrame) + { + fileExist = true; + } + else + { + if (FileUtils::getInstance()->isFileExist(plist)) + { + ValueMap value = FileUtils::getInstance()->getValueMapFromFile(plist); + ValueMap metadata = value["metadata"].asValueMap(); + std::string textureFileName = metadata["textureFileName"].asString(); + if (!FileUtils::getInstance()->isFileExist(textureFileName)) + { + errorFilePath = textureFileName; + } + } + else + { + errorFilePath = plist; + } + fileExist = false; + } + break; + } + + default: + break; + } + if (fileExist) + { + imageView->loadTexture(imageFileName, (Widget::TextureResType)imageFileNameType); + } + else + { + auto label = Label::create(); + label->setString(__String::createWithFormat("%s missed", errorFilePath.c_str())->getCString()); + imageView->addChild(label); + } bool scale9Enabled = options->scale9Enabled(); imageView->setScale9Enabled(scale9Enabled); + auto widgetReader = WidgetReader::getInstance(); + widgetReader->setPropsWithFlatBuffers(node, (Table*)options->widgetOptions()); if (scale9Enabled) { @@ -318,9 +376,6 @@ namespace cocostudio imageView->setCapInsets(capInsets); } - auto widgetReader = WidgetReader::getInstance(); - widgetReader->setPropsWithFlatBuffers(node, (Table*)options->widgetOptions()); - } Node* ImageViewReader::createNodeWithFlatBuffers(const flatbuffers::Table *imageViewOptions) diff --git a/cocos/editor-support/cocostudio/WidgetReader/LayoutReader/LayoutReader.cpp b/cocos/editor-support/cocostudio/WidgetReader/LayoutReader/LayoutReader.cpp index a0d078c723..1d840e3fbd 100644 --- a/cocos/editor-support/cocostudio/WidgetReader/LayoutReader/LayoutReader.cpp +++ b/cocos/editor-support/cocostudio/WidgetReader/LayoutReader/LayoutReader.cpp @@ -10,7 +10,7 @@ #include "cocostudio/CSParseBinary_generated.h" #include "cocostudio/FlatBuffersSerialize.h" -#include "tinyxml2/tinyxml2.h" +#include "tinyxml2.h" #include "flatbuffers/flatbuffers.h" USING_NS_CC; @@ -531,10 +531,7 @@ namespace cocostudio if (resourceType == 1) { FlatBuffersSerialize* fbs = FlatBuffersSerialize::getInstance(); - fbs->_textures.push_back(builder->CreateString(texture)); - - texturePng = texture.substr(0, texture.find_last_of('.')).append(".png"); - fbs->_texturePngs.push_back(builder->CreateString(texturePng)); + fbs->_textures.push_back(builder->CreateString(texture)); } } @@ -601,21 +598,71 @@ namespace cocostudio panel->setBackGroundColorOpacity(bgColorOpacity); + bool fileExist = false; + std::string errorFilePath = ""; auto imageFileNameDic = options->backGroundImageData(); int imageFileNameType = imageFileNameDic->resourceType(); - std::string imageFileName = imageFileNameDic->path()->c_str(); - panel->setBackGroundImage(imageFileName, (Widget::TextureResType)imageFileNameType); - - - if (backGroundScale9Enabled) + std::string imageFileName = this->getResourcePath(imageFileNameDic->path()->c_str(), (Widget::TextureResType)imageFileNameType); + if (imageFileName != "") { - auto f_capInsets = options->capInsets(); - Rect capInsets(f_capInsets->x(), f_capInsets->y(), f_capInsets->width(), f_capInsets->height()); - panel->setBackGroundImageCapInsets(capInsets); - - auto f_scale9Size = options->scale9Size(); - Size scale9Size(f_scale9Size->width(), f_scale9Size->height()); - panel->setContentSize(scale9Size); + switch (imageFileNameType) + { + case 0: + { + if (FileUtils::getInstance()->isFileExist(imageFileName)) + { + fileExist = true; + } + else + { + errorFilePath = imageFileName; + fileExist = false; + } + break; + } + + case 1: + { + std::string plist = imageFileNameDic->plistFile()->c_str(); + SpriteFrame* spriteFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(imageFileName); + if (spriteFrame) + { + fileExist = true; + } + else + { + if (FileUtils::getInstance()->isFileExist(plist)) + { + ValueMap value = FileUtils::getInstance()->getValueMapFromFile(plist); + ValueMap metadata = value["metadata"].asValueMap(); + std::string textureFileName = metadata["textureFileName"].asString(); + if (!FileUtils::getInstance()->isFileExist(textureFileName)) + { + errorFilePath = textureFileName; + } + } + else + { + errorFilePath = plist; + } + fileExist = false; + } + break; + } + + default: + break; + } + if (fileExist) + { + panel->setBackGroundImage(imageFileName, (Widget::TextureResType)imageFileNameType); + } + else + { + auto label = Label::create(); + label->setString(__String::createWithFormat("%s missed", errorFilePath.c_str())->getCString()); + panel->addChild(label); + } } auto widgetOptions = options->widgetOptions(); @@ -629,6 +676,26 @@ namespace cocostudio auto widgetReader = WidgetReader::getInstance(); widgetReader->setPropsWithFlatBuffers(node, (Table*)options->widgetOptions()); + + if (backGroundScale9Enabled) + { + auto f_capInsets = options->capInsets(); + Rect capInsets(f_capInsets->x(), f_capInsets->y(), f_capInsets->width(), f_capInsets->height()); + panel->setBackGroundImageCapInsets(capInsets); + + auto f_scale9Size = options->scale9Size(); + Size scale9Size(f_scale9Size->width(), f_scale9Size->height()); + panel->setContentSize(scale9Size); + } + else + { + if (!panel->isIgnoreContentAdaptWithSize()) + { + Size contentSize(widgetOptions->size()->width(), widgetOptions->size()->height()); + panel->setContentSize(contentSize); + } + } + } Node* LayoutReader::createNodeWithFlatBuffers(const flatbuffers::Table *layoutOptions) diff --git a/cocos/editor-support/cocostudio/WidgetReader/ListViewReader/ListViewReader.cpp b/cocos/editor-support/cocostudio/WidgetReader/ListViewReader/ListViewReader.cpp index a9cf8e36c2..4272f4b14a 100644 --- a/cocos/editor-support/cocostudio/WidgetReader/ListViewReader/ListViewReader.cpp +++ b/cocos/editor-support/cocostudio/WidgetReader/ListViewReader/ListViewReader.cpp @@ -7,7 +7,7 @@ #include "cocostudio/CSParseBinary_generated.h" #include "cocostudio/FlatBuffersSerialize.h" -#include "tinyxml2/tinyxml2.h" +#include "tinyxml2.h" #include "flatbuffers/flatbuffers.h" USING_NS_CC; @@ -89,8 +89,8 @@ namespace cocostudio auto temp = WidgetReader::getInstance()->createOptionsWithFlatBuffers(objectData, builder); auto widgetOptions = *(Offset*)(&temp); - std::string path = ""; - std::string plistFile = ""; + std::string path; + std::string plistFile; int resourceType = 0; bool clipEnabled = false; @@ -106,12 +106,13 @@ namespace cocostudio Size innerSize(200, 300); int direction = 0; bool bounceEnabled = false; - int gravity = 0; int itemMargin = 0; - + std::string directionType; + std::string horizontalType; + std::string verticalType; // attributes - const tinyxml2::XMLAttribute* attribute = objectData->FirstAttribute(); + auto attribute = objectData->FirstAttribute(); while (attribute) { std::string name = attribute->Name(); @@ -154,64 +155,15 @@ namespace cocostudio } else if (name == "DirectionType") { - if (value == "Vertical") - { - direction = 1; - - attribute = objectData->FirstAttribute(); - while (attribute) - { - name = attribute->Name(); - value = attribute->Value(); - - if (name == "HorizontalType") - { - if (value == "HORIZONTAL_LEFT") - { - gravity = 0; - } - else if (value == "HORIZONTAL_RIGHT") - { - gravity = 1; - } - else if (value == "HORIZONTAL_CENTER") - { - gravity = 2; - } - } - - attribute = attribute->Next(); - } - } - else if (value == "Horizontal") - { - direction = 2; - - attribute = objectData->FirstAttribute(); - while (attribute) - { - name = attribute->Name(); - value = attribute->Value(); - - if (name == "VerticalType") - { - if (value == "VERTICAL_TOP") - { - gravity = 3; - } - else if (value == "VERTICAL_BOTTOM") - { - gravity = 4; - } - else if (value == "VERTICAL_CENTER") - { - gravity = 5; - } - } - - attribute = attribute->Next(); - } - } + directionType = value; + } + else if (name == "HorizontalType") + { + horizontalType = value; + } + else if (name == "VerticalType") + { + verticalType = value; } else if (name == "IsBounceEnabled") { @@ -233,7 +185,7 @@ namespace cocostudio if (name == "InnerNodeSize") { - attribute = child->FirstAttribute(); + auto attribute = child->FirstAttribute(); while (attribute) { name = attribute->Name(); @@ -253,7 +205,7 @@ namespace cocostudio } else if (name == "Size" && backGroundScale9Enabled) { - attribute = child->FirstAttribute(); + auto attribute = child->FirstAttribute(); while (attribute) { @@ -274,7 +226,7 @@ namespace cocostudio } else if (name == "SingleColor") { - attribute = child->FirstAttribute(); + auto attribute = child->FirstAttribute(); while (attribute) { @@ -299,7 +251,7 @@ namespace cocostudio } else if (name == "EndColor") { - attribute = child->FirstAttribute(); + auto attribute = child->FirstAttribute(); while (attribute) { @@ -324,7 +276,7 @@ namespace cocostudio } else if (name == "FirstColor") { - attribute = child->FirstAttribute(); + auto attribute = child->FirstAttribute(); while (attribute) { @@ -349,7 +301,7 @@ namespace cocostudio } else if (name == "ColorVector") { - attribute = child->FirstAttribute(); + auto attribute = child->FirstAttribute(); while (attribute) { name = attribute->Name(); @@ -369,10 +321,10 @@ namespace cocostudio } else if (name == "FileData") { - std::string texture = ""; - std::string texturePng = ""; + std::string texture; + std::string texturePng; - attribute = child->FirstAttribute(); + auto attribute = child->FirstAttribute(); while (attribute) { @@ -399,10 +351,7 @@ namespace cocostudio if (resourceType == 1) { FlatBuffersSerialize* fbs = FlatBuffersSerialize::getInstance(); - fbs->_textures.push_back(builder->CreateString(texture)); - - texturePng = texture.substr(0, texture.find_last_of('.')).append(".png"); - fbs->_texturePngs.push_back(builder->CreateString(texturePng)); + fbs->_textures.push_back(builder->CreateString(texture)); } } @@ -436,8 +385,10 @@ namespace cocostudio &f_innerSize, direction, bounceEnabled, - gravity, - itemMargin); + itemMargin, + builder->CreateString(directionType), + builder->CreateString(horizontalType), + builder->CreateString(verticalType)); return *(Offset
*)(&options); } @@ -475,21 +426,71 @@ namespace cocostudio listView->setBackGroundColorOpacity(bgColorOpacity); + bool fileExist = false; + std::string errorFilePath = ""; auto imageFileNameDic = options->backGroundImageData(); int imageFileNameType = imageFileNameDic->resourceType(); std::string imageFileName = imageFileNameDic->path()->c_str(); - listView->setBackGroundImage(imageFileName, (Widget::TextureResType)imageFileNameType); - - - if (backGroundScale9Enabled) + if (imageFileName != "") { - auto f_capInsets = options->capInsets(); - Rect capInsets(f_capInsets->x(), f_capInsets->y(), f_capInsets->width(), f_capInsets->height()); - listView->setBackGroundImageCapInsets(capInsets); - - auto f_scale9Size = options->scale9Size(); - Size scale9Size(f_scale9Size->width(), f_scale9Size->height()); - listView->setContentSize(scale9Size); + switch (imageFileNameType) + { + case 0: + { + if (FileUtils::getInstance()->isFileExist(imageFileName)) + { + fileExist = true; + } + else + { + errorFilePath = imageFileName; + fileExist = false; + } + break; + } + + case 1: + { + std::string plist = imageFileNameDic->plistFile()->c_str(); + SpriteFrame* spriteFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(imageFileName); + if (spriteFrame) + { + fileExist = true; + } + else + { + if (FileUtils::getInstance()->isFileExist(plist)) + { + ValueMap value = FileUtils::getInstance()->getValueMapFromFile(plist); + ValueMap metadata = value["metadata"].asValueMap(); + std::string textureFileName = metadata["textureFileName"].asString(); + if (!FileUtils::getInstance()->isFileExist(textureFileName)) + { + errorFilePath = textureFileName; + } + } + else + { + errorFilePath = plist; + } + fileExist = false; + } + break; + } + + default: + break; + } + if (fileExist) + { + listView->setBackGroundImage(imageFileName, (Widget::TextureResType)imageFileNameType); + } + else + { + auto label = Label::create(); + label->setString(__String::createWithFormat("%s missed", errorFilePath.c_str())->getCString()); + listView->addChild(label); + } } auto widgetOptions = options->widgetOptions(); @@ -503,22 +504,75 @@ namespace cocostudio auto f_innerSize = options->innerSize(); Size innerSize(f_innerSize->width(), f_innerSize->height()); listView->setInnerContainerSize(innerSize); - int direction = options->direction(); - listView->setDirection((ScrollView::Direction)direction); + // int direction = options->direction(); + // listView->setDirection((ScrollView::Direction)direction); bool bounceEnabled = options->bounceEnabled(); listView->setBounceEnabled(bounceEnabled); - int gravityValue = options->gravity(); - ListView::Gravity gravity = (ListView::Gravity)gravityValue; - listView->setGravity(gravity); + // int gravityValue = options->gravity(); + // ListView::Gravity gravity = (ListView::Gravity)gravityValue; + // listView->setGravity(gravity); + + std::string directionType = options->directionType()->c_str(); + if (directionType == "") + { + listView->setDirection(ListView::Direction::HORIZONTAL); + std::string verticalType = options->verticalType()->c_str(); + if (verticalType == "") + { + listView->setGravity(ListView::Gravity::TOP); + } + else if (verticalType == "Align_Bottom") + { + listView->setGravity(ListView::Gravity::BOTTOM); + } + else if (verticalType == "Align_VerticalCenter") + { + listView->setGravity(ListView::Gravity::CENTER_VERTICAL); + } + } + else if (directionType == "Vertical") + { + listView->setDirection(ListView::Direction::VERTICAL); + std::string horizontalType = options->horizontalType()->c_str(); + if (horizontalType == "") + { + listView->setGravity(ListView::Gravity::LEFT); + } + else if (horizontalType == "Align_Right") + { + listView->setGravity(ListView::Gravity::RIGHT); + } + else if (horizontalType == "Align_HorizontalCenter") + { + listView->setGravity(ListView::Gravity::CENTER_HORIZONTAL); + } + } float itemMargin = options->itemMargin(); listView->setItemsMargin(itemMargin); - auto widgetReader = WidgetReader::getInstance(); widgetReader->setPropsWithFlatBuffers(node, (Table*)options->widgetOptions()); + if (backGroundScale9Enabled) + { + auto f_capInsets = options->capInsets(); + Rect capInsets(f_capInsets->x(), f_capInsets->y(), f_capInsets->width(), f_capInsets->height()); + listView->setBackGroundImageCapInsets(capInsets); + + auto f_scale9Size = options->scale9Size(); + Size scale9Size(f_scale9Size->width(), f_scale9Size->height()); + listView->setContentSize(scale9Size); + } + else + { + if (!listView->isIgnoreContentAdaptWithSize()) + { + Size contentSize(widgetOptions->size()->width(), widgetOptions->size()->height()); + listView->setContentSize(contentSize); + } + } } Node* ListViewReader::createNodeWithFlatBuffers(const flatbuffers::Table *listViewOptions) diff --git a/cocos/editor-support/cocostudio/WidgetReader/LoadingBarReader/LoadingBarReader.cpp b/cocos/editor-support/cocostudio/WidgetReader/LoadingBarReader/LoadingBarReader.cpp index b6afa4d7ba..76d198e1d7 100644 --- a/cocos/editor-support/cocostudio/WidgetReader/LoadingBarReader/LoadingBarReader.cpp +++ b/cocos/editor-support/cocostudio/WidgetReader/LoadingBarReader/LoadingBarReader.cpp @@ -7,7 +7,7 @@ #include "cocostudio/CSParseBinary_generated.h" #include "cocostudio/FlatBuffersSerialize.h" -#include "tinyxml2/tinyxml2.h" +#include "tinyxml2.h" #include "flatbuffers/flatbuffers.h" USING_NS_CC; @@ -217,10 +217,7 @@ namespace cocostudio if (resourceType == 1) { FlatBuffersSerialize* fbs = FlatBuffersSerialize::getInstance(); - fbs->_textures.push_back(builder->CreateString(texture)); - - texturePng = texture.substr(0, texture.find_last_of('.')).append(".png"); - fbs->_texturePngs.push_back(builder->CreateString(texturePng)); + fbs->_textures.push_back(builder->CreateString(texture)); } } @@ -244,10 +241,69 @@ namespace cocostudio LoadingBar* loadingBar = static_cast(node); auto options = (LoadingBarOptions*)loadingBarOptions; + bool fileExist = false; + std::string errorFilePath = ""; auto imageFileNameDic = options->textureData(); int imageFileNameType = imageFileNameDic->resourceType(); - std::string imageFileName = imageFileNameDic->path()->c_str(); - loadingBar->loadTexture(imageFileName, (Widget::TextureResType)imageFileNameType); + std::string imageFileName = this->getResourcePath(imageFileNameDic->path()->c_str(), (Widget::TextureResType)imageFileNameType); + switch (imageFileNameType) + { + case 0: + { + if (FileUtils::getInstance()->isFileExist(imageFileName)) + { + fileExist = true; + } + else + { + errorFilePath = imageFileName; + fileExist = false; + } + break; + } + + case 1: + { + std::string plist = imageFileNameDic->plistFile()->c_str(); + SpriteFrame* spriteFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(imageFileName); + if (spriteFrame) + { + fileExist = true; + } + else + { + if (FileUtils::getInstance()->isFileExist(plist)) + { + ValueMap value = FileUtils::getInstance()->getValueMapFromFile(plist); + ValueMap metadata = value["metadata"].asValueMap(); + std::string textureFileName = metadata["textureFileName"].asString(); + if (!FileUtils::getInstance()->isFileExist(textureFileName)) + { + errorFilePath = textureFileName; + } + } + else + { + errorFilePath = plist; + } + fileExist = false; + } + break; + } + + default: + break; + } + if (fileExist) + { + loadingBar->loadTexture(imageFileName, (Widget::TextureResType)imageFileNameType); + } + else + { + auto label = Label::create(); + label->setString(__String::createWithFormat("%s missed", errorFilePath.c_str())->getCString()); + loadingBar->addChild(label); + } int direction = options->direction(); loadingBar->setDirection(LoadingBar::Direction(direction)); diff --git a/cocos/editor-support/cocostudio/WidgetReader/NodeReader/NodeReader.cpp b/cocos/editor-support/cocostudio/WidgetReader/NodeReader/NodeReader.cpp index 897d5dfa03..38d46b4a88 100644 --- a/cocos/editor-support/cocostudio/WidgetReader/NodeReader/NodeReader.cpp +++ b/cocos/editor-support/cocostudio/WidgetReader/NodeReader/NodeReader.cpp @@ -27,7 +27,7 @@ #include "cocostudio/CSParseBinary_generated.h" #include "cocostudio/ActionTimeline/CCActionTimeline.h" -#include "tinyxml2/tinyxml2.h" +#include "tinyxml2.h" #include "flatbuffers/flatbuffers.h" @@ -290,7 +290,7 @@ namespace cocostudio auto options = CreateWidgetOptions(*builder, builder->CreateString(name), - actionTag, + (int)actionTag, &f_rotationskew, zOrder, visible, diff --git a/cocos/editor-support/cocostudio/WidgetReader/PageViewReader/PageViewReader.cpp b/cocos/editor-support/cocostudio/WidgetReader/PageViewReader/PageViewReader.cpp index b31de5ec9d..0285bf55ff 100644 --- a/cocos/editor-support/cocostudio/WidgetReader/PageViewReader/PageViewReader.cpp +++ b/cocos/editor-support/cocostudio/WidgetReader/PageViewReader/PageViewReader.cpp @@ -8,7 +8,7 @@ #include "cocostudio/CSParseBinary_generated.h" #include "cocostudio/FlatBuffersSerialize.h" -#include "tinyxml2/tinyxml2.h" +#include "tinyxml2.h" #include "flatbuffers/flatbuffers.h" USING_NS_CC; @@ -272,10 +272,7 @@ namespace cocostudio if (resourceType == 1) { FlatBuffersSerialize* fbs = FlatBuffersSerialize::getInstance(); - fbs->_textures.push_back(builder->CreateString(texture)); - - texturePng = texture.substr(0, texture.find_last_of('.')).append(".png"); - fbs->_texturePngs.push_back(builder->CreateString(texturePng)); + fbs->_textures.push_back(builder->CreateString(texture)); } } @@ -342,21 +339,71 @@ namespace cocostudio pageView->setBackGroundColorOpacity(bgColorOpacity); + bool fileExist = false; + std::string errorFilePath = ""; auto imageFileNameDic = options->backGroundImageData(); int imageFileNameType = imageFileNameDic->resourceType(); - std::string imageFileName = imageFileNameDic->path()->c_str(); - pageView->setBackGroundImage(imageFileName, (Widget::TextureResType)imageFileNameType); - - - if (backGroundScale9Enabled) + std::string imageFileName = this->getResourcePath(imageFileNameDic->path()->c_str(), (Widget::TextureResType)imageFileNameType); + if (imageFileName != "") { - auto f_capInsets = options->capInsets(); - Rect capInsets(f_capInsets->x(), f_capInsets->y(), f_capInsets->width(), f_capInsets->height()); - pageView->setBackGroundImageCapInsets(capInsets); - - auto f_scale9Size = options->scale9Size(); - Size scale9Size(f_scale9Size->width(), f_scale9Size->height()); - pageView->setContentSize(scale9Size); + switch (imageFileNameType) + { + case 0: + { + if (FileUtils::getInstance()->isFileExist(imageFileName)) + { + fileExist = true; + } + else + { + errorFilePath = imageFileName; + fileExist = false; + } + break; + } + + case 1: + { + std::string plist = imageFileNameDic->plistFile()->c_str(); + SpriteFrame* spriteFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(imageFileName); + if (spriteFrame) + { + fileExist = true; + } + else + { + if (FileUtils::getInstance()->isFileExist(plist)) + { + ValueMap value = FileUtils::getInstance()->getValueMapFromFile(plist); + ValueMap metadata = value["metadata"].asValueMap(); + std::string textureFileName = metadata["textureFileName"].asString(); + if (!FileUtils::getInstance()->isFileExist(textureFileName)) + { + errorFilePath = textureFileName; + } + } + else + { + errorFilePath = plist; + } + fileExist = false; + } + break; + } + + default: + break; + } + if (fileExist) + { + pageView->setBackGroundImage(imageFileName, (Widget::TextureResType)imageFileNameType); + } + else + { + auto label = Label::create(); + label->setString(__String::createWithFormat("%s missed", errorFilePath.c_str())->getCString()); + pageView->addChild(label); + } } auto widgetOptions = options->widgetOptions(); @@ -371,6 +418,24 @@ namespace cocostudio auto widgetReader = WidgetReader::getInstance(); widgetReader->setPropsWithFlatBuffers(node, (Table*)options->widgetOptions()); + if (backGroundScale9Enabled) + { + auto f_capInsets = options->capInsets(); + Rect capInsets(f_capInsets->x(), f_capInsets->y(), f_capInsets->width(), f_capInsets->height()); + pageView->setBackGroundImageCapInsets(capInsets); + + auto f_scale9Size = options->scale9Size(); + Size scale9Size(f_scale9Size->width(), f_scale9Size->height()); + pageView->setContentSize(scale9Size); + } + else + { + if (!pageView->isIgnoreContentAdaptWithSize()) + { + Size contentSize(widgetOptions->size()->width(), widgetOptions->size()->height()); + pageView->setContentSize(contentSize); + } + } } Node* PageViewReader::createNodeWithFlatBuffers(const flatbuffers::Table *pageViewOptions) diff --git a/cocos/editor-support/cocostudio/WidgetReader/ParticleReader/ParticleReader.cpp b/cocos/editor-support/cocostudio/WidgetReader/ParticleReader/ParticleReader.cpp index ef2596c850..dc7f7a7d63 100644 --- a/cocos/editor-support/cocostudio/WidgetReader/ParticleReader/ParticleReader.cpp +++ b/cocos/editor-support/cocostudio/WidgetReader/ParticleReader/ParticleReader.cpp @@ -27,7 +27,7 @@ #include "cocostudio/CSParseBinary_generated.h" #include "cocostudio/WidgetReader/NodeReader/NodeReader.h" -#include "tinyxml2/tinyxml2.h" +#include "tinyxml2.h" #include "flatbuffers/flatbuffers.h" USING_NS_CC; @@ -134,15 +134,22 @@ namespace cocostudio auto options = (ParticleSystemOptions*)particleOptions; auto fileNameData = options->fileNameData(); + bool fileExist = false; + std::string errorFilePath = ""; + std::string path = fileNameData->path()->c_str(); int resourceType = fileNameData->resourceType(); switch (resourceType) { case 0: { - std::string path = fileNameData->path()->c_str(); - if (path != "") + if (FileUtils::getInstance()->isFileExist(path)) { - particle = ParticleSystemQuad::create(path); + fileExist = true; + } + else + { + errorFilePath = path; + fileExist = false; } break; } @@ -150,10 +157,22 @@ namespace cocostudio default: break; } - - if (particle) + if (fileExist) { - setPropsWithFlatBuffers(particle, (Table*)particleOptions); + particle = ParticleSystemQuad::create(path); + if (particle) + { + setPropsWithFlatBuffers(particle, (Table*)particleOptions); + } + } + else + { + Node* node = Node::create(); + setPropsWithFlatBuffers(node, (Table*)particleOptions); + auto label = Label::create(); + label->setString(__String::createWithFormat("%s missed", errorFilePath.c_str())->getCString()); + node->addChild(label); + return node; } return particle; diff --git a/cocos/editor-support/cocostudio/WidgetReader/ProjectNodeReader/ProjectNodeReader.cpp b/cocos/editor-support/cocostudio/WidgetReader/ProjectNodeReader/ProjectNodeReader.cpp index f01ea8575c..3b733b434e 100644 --- a/cocos/editor-support/cocostudio/WidgetReader/ProjectNodeReader/ProjectNodeReader.cpp +++ b/cocos/editor-support/cocostudio/WidgetReader/ProjectNodeReader/ProjectNodeReader.cpp @@ -27,7 +27,7 @@ #include "cocostudio/CSParseBinary_generated.h" #include "cocostudio/WidgetReader/NodeReader/NodeReader.h" -#include "tinyxml2/tinyxml2.h" +#include "tinyxml2.h" #include "flatbuffers/flatbuffers.h" USING_NS_CC; diff --git a/cocos/editor-support/cocostudio/WidgetReader/ScrollViewReader/ScrollViewReader.cpp b/cocos/editor-support/cocostudio/WidgetReader/ScrollViewReader/ScrollViewReader.cpp index c2c93d4263..9dd10412bf 100644 --- a/cocos/editor-support/cocostudio/WidgetReader/ScrollViewReader/ScrollViewReader.cpp +++ b/cocos/editor-support/cocostudio/WidgetReader/ScrollViewReader/ScrollViewReader.cpp @@ -7,7 +7,7 @@ #include "cocostudio/CSParseBinary_generated.h" #include "cocostudio/FlatBuffersSerialize.h" -#include "tinyxml2/tinyxml2.h" +#include "tinyxml2.h" #include "flatbuffers/flatbuffers.h" USING_NS_CC; @@ -354,10 +354,7 @@ namespace cocostudio if (resourceType == 1) { FlatBuffersSerialize* fbs = FlatBuffersSerialize::getInstance(); - fbs->_textures.push_back(builder->CreateString(texture)); - - texturePng = texture.substr(0, texture.find_last_of('.')).append(".png"); - fbs->_texturePngs.push_back(builder->CreateString(texturePng)); + fbs->_textures.push_back(builder->CreateString(texture)); } } @@ -428,21 +425,71 @@ namespace cocostudio scrollView->setBackGroundColorOpacity(bgColorOpacity); + bool fileExist = false; + std::string errorFilePath = ""; auto imageFileNameDic = options->backGroundImageData(); int imageFileNameType = imageFileNameDic->resourceType(); - std::string imageFileName = imageFileNameDic->path()->c_str(); - scrollView->setBackGroundImage(imageFileName, (Widget::TextureResType)imageFileNameType); - - - if (backGroundScale9Enabled) + std::string imageFileName = this->getResourcePath(imageFileNameDic->path()->c_str(), (Widget::TextureResType)imageFileNameType); + if (imageFileName != "") { - auto f_capInsets = options->capInsets(); - Rect capInsets(f_capInsets->x(), f_capInsets->y(), f_capInsets->width(), f_capInsets->height()); - scrollView->setBackGroundImageCapInsets(capInsets); - - auto f_scale9Size = options->scale9Size(); - Size scale9Size(f_scale9Size->width(), f_scale9Size->height()); - scrollView->setContentSize(scale9Size); + switch (imageFileNameType) + { + case 0: + { + if (FileUtils::getInstance()->isFileExist(imageFileName)) + { + fileExist = true; + } + else + { + errorFilePath = imageFileName; + fileExist = false; + } + break; + } + + case 1: + { + std::string plist = imageFileNameDic->plistFile()->c_str(); + SpriteFrame* spriteFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(imageFileName); + if (spriteFrame) + { + fileExist = true; + } + else + { + if (FileUtils::getInstance()->isFileExist(plist)) + { + ValueMap value = FileUtils::getInstance()->getValueMapFromFile(plist); + ValueMap metadata = value["metadata"].asValueMap(); + std::string textureFileName = metadata["textureFileName"].asString(); + if (!FileUtils::getInstance()->isFileExist(textureFileName)) + { + errorFilePath = textureFileName; + } + } + else + { + errorFilePath = plist; + } + fileExist = false; + } + break; + } + + default: + break; + } + if (fileExist) + { + scrollView->setBackGroundImage(imageFileName, (Widget::TextureResType)imageFileNameType); + } + else + { + auto label = Label::create(); + label->setString(__String::createWithFormat("%s missed", errorFilePath.c_str())->getCString()); + scrollView->addChild(label); + } } auto widgetOptions = options->widgetOptions(); @@ -465,6 +512,25 @@ namespace cocostudio auto widgetReader = WidgetReader::getInstance(); widgetReader->setPropsWithFlatBuffers(node, (Table*)options->widgetOptions()); + if (backGroundScale9Enabled) + { + auto f_capInsets = options->capInsets(); + Rect capInsets(f_capInsets->x(), f_capInsets->y(), f_capInsets->width(), f_capInsets->height()); + scrollView->setBackGroundImageCapInsets(capInsets); + + auto f_scale9Size = options->scale9Size(); + Size scale9Size(f_scale9Size->width(), f_scale9Size->height()); + scrollView->setContentSize(scale9Size); + } + else + { + if (!scrollView->isIgnoreContentAdaptWithSize()) + { + Size contentSize(widgetOptions->size()->width(), widgetOptions->size()->height()); + scrollView->setContentSize(contentSize); + } + } + } Node* ScrollViewReader::createNodeWithFlatBuffers(const flatbuffers::Table *scrollViewOptions) diff --git a/cocos/editor-support/cocostudio/WidgetReader/SingleNodeReader/SingleNodeReader.cpp b/cocos/editor-support/cocostudio/WidgetReader/SingleNodeReader/SingleNodeReader.cpp index bddd8855c6..9c26174ae4 100644 --- a/cocos/editor-support/cocostudio/WidgetReader/SingleNodeReader/SingleNodeReader.cpp +++ b/cocos/editor-support/cocostudio/WidgetReader/SingleNodeReader/SingleNodeReader.cpp @@ -28,7 +28,7 @@ #include "cocostudio/ActionTimeline/CCActionTimeline.h" #include "cocostudio/WidgetReader/NodeReader/NodeReader.h" -#include "tinyxml2/tinyxml2.h" +#include "tinyxml2.h" #include "flatbuffers/flatbuffers.h" diff --git a/cocos/editor-support/cocostudio/WidgetReader/SliderReader/SliderReader.cpp b/cocos/editor-support/cocostudio/WidgetReader/SliderReader/SliderReader.cpp index 69c3dd9124..4c45a2f1cc 100644 --- a/cocos/editor-support/cocostudio/WidgetReader/SliderReader/SliderReader.cpp +++ b/cocos/editor-support/cocostudio/WidgetReader/SliderReader/SliderReader.cpp @@ -7,7 +7,7 @@ #include "cocostudio/CSParseBinary_generated.h" #include "cocostudio/FlatBuffersSerialize.h" -#include "tinyxml2/tinyxml2.h" +#include "tinyxml2.h" #include "flatbuffers/flatbuffers.h" USING_NS_CC; @@ -281,9 +281,6 @@ namespace cocostudio { FlatBuffersSerialize* fbs = FlatBuffersSerialize::getInstance(); fbs->_textures.push_back(builder->CreateString(texture)); - - texturePng = texture.substr(0, texture.find_last_of('.')).append(".png"); - fbs->_texturePngs.push_back(builder->CreateString(texturePng)); } } else if (name == "BallNormalData") @@ -319,9 +316,6 @@ namespace cocostudio { FlatBuffersSerialize* fbs = FlatBuffersSerialize::getInstance(); fbs->_textures.push_back(builder->CreateString(texture)); - - texturePng = texture.substr(0, texture.find_last_of('.')).append(".png"); - fbs->_texturePngs.push_back(builder->CreateString(texturePng)); } } else if (name == "BallPressedData") @@ -357,9 +351,6 @@ namespace cocostudio { FlatBuffersSerialize* fbs = FlatBuffersSerialize::getInstance(); fbs->_textures.push_back(builder->CreateString(texture)); - - texturePng = texture.substr(0, texture.find_last_of('.')).append(".png"); - fbs->_texturePngs.push_back(builder->CreateString(texturePng)); } } else if (name == "BallDisabledData") @@ -385,6 +376,7 @@ namespace cocostudio else if (name == "Plist") { ballDisabledPlistFile = value; + texture = value; } attribute = attribute->Next(); @@ -394,9 +386,6 @@ namespace cocostudio { FlatBuffersSerialize* fbs = FlatBuffersSerialize::getInstance(); fbs->_textures.push_back(builder->CreateString(texture)); - - texturePng = texture.substr(0, texture.find_last_of('.')).append(".png"); - fbs->_texturePngs.push_back(builder->CreateString(texturePng)); } } else if (name == "ProgressBarData") @@ -422,6 +411,7 @@ namespace cocostudio else if (name == "Plist") { progressBarPlistFile = value; + texture = value; } attribute = attribute->Next(); @@ -430,10 +420,7 @@ namespace cocostudio if (progressBarResourceType == 1) { FlatBuffersSerialize* fbs = FlatBuffersSerialize::getInstance(); - fbs->_textures.push_back(builder->CreateString(texture)); - - texturePng = texture.substr(0, texture.find_last_of('.')).append(".png"); - fbs->_texturePngs.push_back(builder->CreateString(texturePng)); + fbs->_textures.push_back(builder->CreateString(texture)); } } @@ -476,34 +463,329 @@ namespace cocostudio int percent = options->percent(); slider->setPercent(percent); + bool imageFileExist = false; + std::string imageErrorFilePath = ""; auto imageFileNameDic = options->barFileNameData(); int imageFileNameType = imageFileNameDic->resourceType(); - std::string imageFileName = imageFileNameDic->path()->c_str(); - slider->loadBarTexture(imageFileName, (Widget::TextureResType)imageFileNameType); + std::string imageFileName = this->getResourcePath(imageFileNameDic->path()->c_str(), (Widget::TextureResType)imageFileNameType); + switch (imageFileNameType) + { + case 0: + { + if (FileUtils::getInstance()->isFileExist(imageFileName)) + { + imageFileExist = true; + } + else + { + imageErrorFilePath = imageFileName; + imageFileExist = false; + } + break; + } + + case 1: + { + std::string plist = imageFileNameDic->plistFile()->c_str(); + SpriteFrame* spriteFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(imageFileName); + if (spriteFrame) + { + imageFileExist = true; + } + else + { + if (FileUtils::getInstance()->isFileExist(plist)) + { + ValueMap value = FileUtils::getInstance()->getValueMapFromFile(plist); + ValueMap metadata = value["metadata"].asValueMap(); + std::string textureFileName = metadata["textureFileName"].asString(); + if (!FileUtils::getInstance()->isFileExist(textureFileName)) + { + imageErrorFilePath = textureFileName; + } + } + else + { + imageErrorFilePath = plist; + } + imageFileExist = false; + } + break; + } + + default: + break; + } + if (imageFileExist) + { + slider->loadBarTexture(imageFileName, (Widget::TextureResType)imageFileNameType); + } + else + { + auto label = Label::create(); + label->setString(__String::createWithFormat("%s missed", imageErrorFilePath.c_str())->getCString()); + slider->addChild(label); + } //loading normal slider ball texture + bool normalFileExist = false; + std::string normalErrorFilePath = ""; auto normalDic = options->ballNormalData(); int normalType = normalDic->resourceType(); - std::string normalFileName = normalDic->path()->c_str(); - slider->loadSlidBallTextureNormal(normalFileName, (Widget::TextureResType)normalType); + std::string normalFileName = this->getResourcePath(normalDic->path()->c_str(), (Widget::TextureResType)normalType); + switch (normalType) + { + case 0: + { + if (FileUtils::getInstance()->isFileExist(normalFileName)) + { + normalFileExist = true; + } + else + { + normalErrorFilePath = normalFileName; + normalFileExist = false; + } + break; + } + + case 1: + { + std::string plist = normalDic->plistFile()->c_str(); + SpriteFrame* spriteFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(normalFileName); + if (spriteFrame) + { + normalFileExist = true; + } + else + { + if (FileUtils::getInstance()->isFileExist(plist)) + { + ValueMap value = FileUtils::getInstance()->getValueMapFromFile(plist); + ValueMap metadata = value["metadata"].asValueMap(); + std::string textureFileName = metadata["textureFileName"].asString(); + if (!FileUtils::getInstance()->isFileExist(textureFileName)) + { + normalErrorFilePath = textureFileName; + } + } + else + { + normalErrorFilePath = plist; + } + normalFileExist = false; + } + break; + } + + default: + break; + } + if (normalFileExist) + { + slider->loadSlidBallTextureNormal(normalFileName, (Widget::TextureResType)normalType); + } + else + { + auto label = Label::create(); + label->setString(__String::createWithFormat("%s missed", normalErrorFilePath.c_str())->getCString()); + slider->addChild(label); + } //loading slider ball press texture + bool pressedFileExist = false; + std::string pressedErrorFilePath = ""; auto pressedDic = options->ballPressedData(); int pressedType = pressedDic->resourceType(); - std::string pressedFileName = pressedDic->path()->c_str(); - slider->loadSlidBallTexturePressed(pressedFileName, (Widget::TextureResType)pressedType); + std::string pressedFileName = this->getResourcePath(pressedDic->path()->c_str(), (Widget::TextureResType)pressedType); + switch (pressedType) + { + case 0: + { + if (FileUtils::getInstance()->isFileExist(pressedFileName)) + { + pressedFileExist = true; + } + else + { + pressedErrorFilePath = pressedFileName; + pressedFileExist = false; + } + break; + } + + case 1: + { + std::string plist = pressedDic->plistFile()->c_str(); + SpriteFrame* spriteFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(pressedFileName); + if (spriteFrame) + { + pressedFileExist = true; + } + else + { + if (FileUtils::getInstance()->isFileExist(plist)) + { + ValueMap value = FileUtils::getInstance()->getValueMapFromFile(plist); + ValueMap metadata = value["metadata"].asValueMap(); + std::string textureFileName = metadata["textureFileName"].asString(); + if (!FileUtils::getInstance()->isFileExist(textureFileName)) + { + pressedErrorFilePath = textureFileName; + } + } + else + { + pressedErrorFilePath = plist; + } + pressedFileExist = false; + } + break; + } + + default: + break; + } + if (pressedFileExist) + { + slider->loadSlidBallTexturePressed(pressedFileName, (Widget::TextureResType)pressedType); + } + else + { + auto label = Label::create(); + label->setString(__String::createWithFormat("%s missed", pressedErrorFilePath.c_str())->getCString()); + slider->addChild(label); + } //loading silder ball disable texture + bool disabledFileExist = false; + std::string disabledErrorFilePath = ""; auto disabledDic = options->ballDisabledData(); int disabledType = disabledDic->resourceType(); - std::string disabledFileName = disabledDic->path()->c_str(); - slider->loadSlidBallTextureDisabled(disabledFileName, (Widget::TextureResType)disabledType); + std::string disabledFileName = this->getResourcePath(disabledDic->path()->c_str(), (Widget::TextureResType)disabledType); + switch (disabledType) + { + case 0: + { + if (FileUtils::getInstance()->isFileExist(disabledFileName)) + { + disabledFileExist = true; + } + else + { + disabledErrorFilePath = disabledFileName; + disabledFileExist = false; + } + break; + } + + case 1: + { + std::string plist = disabledDic->plistFile()->c_str(); + SpriteFrame* spriteFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(disabledFileName); + if (spriteFrame) + { + disabledFileExist = true; + } + else + { + if (FileUtils::getInstance()->isFileExist(plist)) + { + ValueMap value = FileUtils::getInstance()->getValueMapFromFile(plist); + ValueMap metadata = value["metadata"].asValueMap(); + std::string textureFileName = metadata["textureFileName"].asString(); + if (!FileUtils::getInstance()->isFileExist(textureFileName)) + { + disabledErrorFilePath = textureFileName; + } + } + else + { + disabledErrorFilePath = plist; + } + disabledFileExist = false; + } + break; + } + + default: + break; + } + if (disabledFileExist) + { + slider->loadSlidBallTextureDisabled(disabledFileName, (Widget::TextureResType)disabledType); + } + else + { + auto label = Label::create(); + label->setString(__String::createWithFormat("%s missed", disabledErrorFilePath.c_str())->getCString()); + slider->addChild(label); + } //load slider progress texture + bool progressFileExist = false; + std::string progressErrorFilePath = ""; auto progressBarDic = options->progressBarData(); int progressBarType = progressBarDic->resourceType(); - std::string progressBarFileName = progressBarDic->path()->c_str(); - slider->loadProgressBarTexture(progressBarFileName, (Widget::TextureResType)progressBarType); + std::string progressBarFileName = this->getResourcePath(progressBarDic->path()->c_str(), (Widget::TextureResType)progressBarType); + switch (progressBarType) + { + case 0: + { + if (FileUtils::getInstance()->isFileExist(progressBarFileName)) + { + progressFileExist = true; + } + else + { + progressErrorFilePath = progressBarFileName; + progressFileExist = false; + } + break; + } + + case 1: + { + std::string plist = progressBarDic->plistFile()->c_str(); + SpriteFrame* spriteFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(progressBarFileName); + if (spriteFrame) + { + progressFileExist = true; + } + else + { + if (FileUtils::getInstance()->isFileExist(plist)) + { + ValueMap value = FileUtils::getInstance()->getValueMapFromFile(plist); + ValueMap metadata = value["metadata"].asValueMap(); + std::string textureFileName = metadata["textureFileName"].asString(); + if (!FileUtils::getInstance()->isFileExist(textureFileName)) + { + progressErrorFilePath = textureFileName; + } + } + else + { + progressErrorFilePath = plist; + } + progressFileExist = false; + } + break; + } + + default: + break; + } + if (progressFileExist) + { + slider->loadProgressBarTexture(progressBarFileName, (Widget::TextureResType)progressBarType); + } + else + { + auto label = Label::create(); + label->setString(__String::createWithFormat("%s missed", progressErrorFilePath.c_str())->getCString()); + slider->addChild(label); + } bool displaystate = options->displaystate(); slider->setBright(displaystate); diff --git a/cocos/editor-support/cocostudio/WidgetReader/SpriteReader/SpriteReader.cpp b/cocos/editor-support/cocostudio/WidgetReader/SpriteReader/SpriteReader.cpp index 67ee066142..645829263d 100644 --- a/cocos/editor-support/cocostudio/WidgetReader/SpriteReader/SpriteReader.cpp +++ b/cocos/editor-support/cocostudio/WidgetReader/SpriteReader/SpriteReader.cpp @@ -28,7 +28,7 @@ #include "cocostudio/FlatBuffersSerialize.h" #include "cocostudio/WidgetReader/NodeReader/NodeReader.h" -#include "tinyxml2/tinyxml2.h" +#include "tinyxml2.h" #include "flatbuffers/flatbuffers.h" USING_NS_CC; @@ -113,10 +113,7 @@ namespace cocostudio if (resourceType == 1) { FlatBuffersSerialize* fbs = FlatBuffersSerialize::getInstance(); - fbs->_textures.push_back(builder->CreateString(texture)); - - texturePng = texture.substr(0, texture.find_last_of('.')).append(".png"); - fbs->_texturePngs.push_back(builder->CreateString(texturePng)); + fbs->_textures.push_back(builder->CreateString(texture)); } } @@ -144,24 +141,54 @@ namespace cocostudio auto fileNameData = options->fileNameData(); int resourceType = fileNameData->resourceType(); + std::string path = fileNameData->path()->c_str(); + + bool fileExist = false; + std::string errorFilePath = ""; + switch (resourceType) { case 0: { - std::string path = fileNameData->path()->c_str(); - if (path != "") + if (FileUtils::getInstance()->isFileExist(path)) { sprite->setTexture(path); + fileExist = true; + } + else + { + errorFilePath = path; + fileExist = false; } break; } case 1: { - std::string path = fileNameData->path()->c_str(); - if (path != "") + std::string plist = fileNameData->plistFile()->c_str(); + SpriteFrame* spriteFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(path); + if (spriteFrame) { - sprite->setSpriteFrame(path); + sprite->setSpriteFrame(spriteFrame); + fileExist = true; + } + else + { + if (FileUtils::getInstance()->isFileExist(plist)) + { + ValueMap value = FileUtils::getInstance()->getValueMapFromFile(plist); + ValueMap metadata = value["metadata"].asValueMap(); + std::string textureFileName = metadata["textureFileName"].asString(); + if (!FileUtils::getInstance()->isFileExist(textureFileName)) + { + errorFilePath = textureFileName; + } + } + else + { + errorFilePath = plist; + } + fileExist = false; } break; } @@ -169,6 +196,12 @@ namespace cocostudio default: break; } + if (!fileExist) + { + auto label = Label::create(); + label->setString(__String::createWithFormat("%s missed", errorFilePath.c_str())->getCString()); + sprite->addChild(label); + } auto nodeReader = NodeReader::getInstance(); @@ -226,4 +259,4 @@ namespace cocostudio } return 1; } -} \ No newline at end of file +} diff --git a/cocos/editor-support/cocostudio/WidgetReader/TextAtlasReader/TextAtlasReader.cpp b/cocos/editor-support/cocostudio/WidgetReader/TextAtlasReader/TextAtlasReader.cpp index 7b2c739418..1f78ac201b 100644 --- a/cocos/editor-support/cocostudio/WidgetReader/TextAtlasReader/TextAtlasReader.cpp +++ b/cocos/editor-support/cocostudio/WidgetReader/TextAtlasReader/TextAtlasReader.cpp @@ -7,7 +7,7 @@ #include "cocostudio/CSParseBinary_generated.h" #include "cocostudio/FlatBuffersSerialize.h" -#include "tinyxml2/tinyxml2.h" +#include "tinyxml2.h" #include "flatbuffers/flatbuffers.h" USING_NS_CC; diff --git a/cocos/editor-support/cocostudio/WidgetReader/TextBMFontReader/TextBMFontReader.cpp b/cocos/editor-support/cocostudio/WidgetReader/TextBMFontReader/TextBMFontReader.cpp index cf3e716ce2..39502292ca 100644 --- a/cocos/editor-support/cocostudio/WidgetReader/TextBMFontReader/TextBMFontReader.cpp +++ b/cocos/editor-support/cocostudio/WidgetReader/TextBMFontReader/TextBMFontReader.cpp @@ -2,11 +2,12 @@ #include "TextBMFontReader.h" +#include "2d/CCFontAtlasCache.h" #include "ui/UITextBMFont.h" #include "cocostudio/CocoLoader.h" #include "cocostudio/CSParseBinary_generated.h" -#include "tinyxml2/tinyxml2.h" +#include "tinyxml2.h" #include "flatbuffers/flatbuffers.h" USING_NS_CC; @@ -190,23 +191,50 @@ namespace cocostudio auto options = (TextBMFontOptions*)textBMFontOptions; auto cmftDic = options->fileNameData(); + bool fileExist = false; + std::string errorFilePath = ""; + std::string errorContent = ""; + std::string path = cmftDic->path()->c_str(); int cmfType = cmftDic->resourceType(); switch (cmfType) { case 0: { - const char* cmfPath = cmftDic->path()->c_str(); - labelBMFont->setFntFile(cmfPath); + if (FileUtils::getInstance()->isFileExist(path)) + { + FontAtlas* newAtlas = FontAtlasCache::getFontAtlasFNT(path); + if (newAtlas) + { + fileExist = true; + } + else + { + errorContent = "has problem"; + fileExist = false; + } + } + else + { + errorContent = "missed"; + fileExist = false; + } break; } - case 1: - CCLOG("Wrong res type of LabelAtlas!"); - break; - default: break; } + if (fileExist) + { + labelBMFont->setFntFile(path); + } + else + { + errorFilePath = path; + auto label = Label::create(); + label->setString(__String::createWithFormat("%s %s", errorFilePath.c_str(), errorContent.c_str())->getCString()); + labelBMFont->addChild(label); + } std::string text = options->text()->c_str(); labelBMFont->setString(text); diff --git a/cocos/editor-support/cocostudio/WidgetReader/TextFieldReader/TextFieldReader.cpp b/cocos/editor-support/cocostudio/WidgetReader/TextFieldReader/TextFieldReader.cpp index 2958443e05..1bf4e66b8d 100644 --- a/cocos/editor-support/cocostudio/WidgetReader/TextFieldReader/TextFieldReader.cpp +++ b/cocos/editor-support/cocostudio/WidgetReader/TextFieldReader/TextFieldReader.cpp @@ -6,7 +6,7 @@ #include "cocostudio/CocoLoader.h" #include "cocostudio/CSParseBinary_generated.h" -#include "tinyxml2/tinyxml2.h" +#include "tinyxml2.h" #include "flatbuffers/flatbuffers.h" USING_NS_CC; @@ -107,7 +107,7 @@ namespace cocostudio textField->setFontSize(DICTOOL->getIntValue_json(options, P_FontSize,20)); - textField->setFontName(DICTOOL->getStringValue_json(options, P_FontName,"微软雅黑")); + textField->setFontName(DICTOOL->getStringValue_json(options, P_FontName, "")); bool tsw = DICTOOL->checkObjectExist_json(options, P_TouchSizeWidth); bool tsh = DICTOOL->checkObjectExist_json(options, P_TouchSizeHeight); @@ -274,9 +274,6 @@ namespace cocostudio TextField* textField = static_cast(node); auto options = (TextFieldOptions*)textFieldOptions; - textField->setUnifySizeEnabled(false); - textField->ignoreContentAdaptWithSize(false); - std::string placeholder = options->placeHolder()->c_str(); textField->setPlaceHolder(placeholder); @@ -306,22 +303,48 @@ namespace cocostudio } + bool fileExist = false; + std::string errorFilePath = ""; auto resourceData = options->fontResource(); std::string path = resourceData->path()->c_str(); if (path != "") { - textField->setFontName(path); + if (FileUtils::getInstance()->isFileExist(path)) + { + fileExist = true; + } + else + { + errorFilePath = path; + fileExist = false; + } + if (fileExist) + { + textField->setFontName(path); + } + else + { + auto label = Label::create(); + label->setString(__String::createWithFormat("%s missed", errorFilePath.c_str())->getCString()); + textField->addChild(label); + } } auto widgetReader = WidgetReader::getInstance(); widgetReader->setPropsWithFlatBuffers(node, (Table*)options->widgetOptions()); - const WidgetOptions* widgetOptions = options->widgetOptions(); + textField->setUnifySizeEnabled(false); + textField->ignoreContentAdaptWithSize(false); + + auto widgetOptions = options->widgetOptions(); if (!textField->isIgnoreContentAdaptWithSize()) { + ((Label*)(textField->getVirtualRenderer()))->setLineBreakWithoutSpace(true); Size contentSize(widgetOptions->size()->width(), widgetOptions->size()->height()); textField->setContentSize(contentSize); } + + } Node* TextFieldReader::createNodeWithFlatBuffers(const flatbuffers::Table *textFieldOptions) diff --git a/cocos/editor-support/cocostudio/WidgetReader/TextReader/TextReader.cpp b/cocos/editor-support/cocostudio/WidgetReader/TextReader/TextReader.cpp index 8e988cf752..f352e03821 100644 --- a/cocos/editor-support/cocostudio/WidgetReader/TextReader/TextReader.cpp +++ b/cocos/editor-support/cocostudio/WidgetReader/TextReader/TextReader.cpp @@ -6,7 +6,7 @@ #include "cocostudio/CocoLoader.h" #include "cocostudio/CSParseBinary_generated.h" -#include "tinyxml2/tinyxml2.h" +#include "tinyxml2.h" #include "flatbuffers/flatbuffers.h" USING_NS_CC; @@ -111,7 +111,7 @@ namespace cocostudio label->setFontSize(DICTOOL->getIntValue_json(options, P_FontSize,20)); - std::string fontName = DICTOOL->getStringValue_json(options, P_FontName, "微软雅黑"); + std::string fontName = DICTOOL->getStringValue_json(options, P_FontName, ""); std::string fontFilePath = jsonPath.append(fontName); if (FileUtils::getInstance()->isFileExist(fontFilePath)) @@ -292,13 +292,9 @@ namespace cocostudio Text* label = static_cast(node); auto options = (TextOptions*)textOptions; - bool IsCustomSize = options->isCustomSize(); - label->ignoreContentAdaptWithSize(!IsCustomSize); - - label->setUnifySizeEnabled(false); - bool touchScaleEnabled = options->touchScaleEnable(); label->setTouchScaleChangeEnabled(touchScaleEnabled); + std::string text = options->text()->c_str(); label->setString(text); @@ -320,22 +316,48 @@ namespace cocostudio TextVAlignment v_alignment = (TextVAlignment)options->vAlignment(); label->setTextVerticalAlignment((TextVAlignment)v_alignment); + bool fileExist = false; + std::string errorFilePath = ""; auto resourceData = options->fontResource(); std::string path = resourceData->path()->c_str(); if (path != "") { - label->setFontName(path); + if (FileUtils::getInstance()->isFileExist(path)) + { + fileExist = true; + } + else + { + errorFilePath = path; + fileExist = false; + } + if (fileExist) + { + label->setFontName(path); + } + else + { + auto alert = Label::create(); + alert->setString(__String::createWithFormat("%s missed", errorFilePath.c_str())->getCString()); + label->addChild(alert); + } } auto widgetReader = WidgetReader::getInstance(); widgetReader->setPropsWithFlatBuffers(node, (Table*)options->widgetOptions()); - const WidgetOptions* widgetOptions = options->widgetOptions(); + label->setUnifySizeEnabled(false); + + bool IsCustomSize = options->isCustomSize(); + label->ignoreContentAdaptWithSize(!IsCustomSize); + + auto widgetOptions = options->widgetOptions(); if (!label->isIgnoreContentAdaptWithSize()) { Size contentSize(widgetOptions->size()->width(), widgetOptions->size()->height()); label->setContentSize(contentSize); } + } Node* TextReader::createNodeWithFlatBuffers(const flatbuffers::Table *textOptions) diff --git a/cocos/editor-support/cocostudio/WidgetReader/WidgetReader.cpp b/cocos/editor-support/cocostudio/WidgetReader/WidgetReader.cpp index 0737f761ab..5e382580c3 100644 --- a/cocos/editor-support/cocostudio/WidgetReader/WidgetReader.cpp +++ b/cocos/editor-support/cocostudio/WidgetReader/WidgetReader.cpp @@ -7,7 +7,7 @@ #include "../ActionTimeline/CCActionTimeline.h" #include "cocostudio/CSParseBinary_generated.h" -#include "tinyxml2/tinyxml2.h" +#include "tinyxml2.h" #include "flatbuffers/flatbuffers.h" USING_NS_CC; diff --git a/cocos/platform/CCImage.cpp b/cocos/platform/CCImage.cpp index 6eab37e61d..d4adf40184 100644 --- a/cocos/platform/CCImage.cpp +++ b/cocos/platform/CCImage.cpp @@ -2042,6 +2042,9 @@ bool Image::initWithWebpData(const unsigned char * data, ssize_t dataLen) _width = config.input.width; _height = config.input.height; + //webp doesn't have premultipliedAlpha + _hasPremultipliedAlpha = false; + _dataLen = _width * _height * 4; _data = static_cast(malloc(_dataLen * sizeof(unsigned char))); diff --git a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxAccelerometer.java b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxAccelerometer.java index 1c10d9f1f3..abebbf4ff7 100644 --- a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxAccelerometer.java +++ b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxAccelerometer.java @@ -55,8 +55,8 @@ public class Cocos2dxAccelerometer implements SensorEventListener { // Constructors // =========================================================== - public Cocos2dxAccelerometer(final Context pContext) { - this.mContext = pContext; + public Cocos2dxAccelerometer(final Context context) { + this.mContext = context; this.mSensorManager = (SensorManager) this.mContext.getSystemService(Context.SENSOR_SERVICE); this.mAccelerometer = this.mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); @@ -92,14 +92,14 @@ public class Cocos2dxAccelerometer implements SensorEventListener { // =========================================================== @Override - public void onSensorChanged(final SensorEvent pSensorEvent) { - if (pSensorEvent.sensor.getType() != Sensor.TYPE_ACCELEROMETER) { + public void onSensorChanged(final SensorEvent sensorEvent) { + if (sensorEvent.sensor.getType() != Sensor.TYPE_ACCELEROMETER) { return; } - float x = pSensorEvent.values[0]; - float y = pSensorEvent.values[1]; - final float z = pSensorEvent.values[2]; + float x = sensorEvent.values[0]; + float y = sensorEvent.values[1]; + final float z = sensorEvent.values[2]; /* * Because the axes are not swapped when the device's screen orientation @@ -118,17 +118,17 @@ public class Cocos2dxAccelerometer implements SensorEventListener { y = -tmp; } - Cocos2dxGLSurfaceView.queueAccelerometer(x,y,z,pSensorEvent.timestamp); + Cocos2dxGLSurfaceView.queueAccelerometer(x,y,z,sensorEvent.timestamp); /* if(BuildConfig.DEBUG) { - Log.d(TAG, "x = " + pSensorEvent.values[0] + " y = " + pSensorEvent.values[1] + " z = " + pSensorEvent.values[2]); + Log.d(TAG, "x = " + sensorEvent.values[0] + " y = " + sensorEvent.values[1] + " z = " + pSensorEvent.values[2]); } */ } @Override - public void onAccuracyChanged(final Sensor pSensor, final int pAccuracy) { + public void onAccuracyChanged(final Sensor sensor, final int accuracy) { } // =========================================================== @@ -136,7 +136,7 @@ public class Cocos2dxAccelerometer implements SensorEventListener { // Native method called from Cocos2dxGLSurfaceView (To be in the same thread) // =========================================================== - public static native void onSensorChanged(final float pX, final float pY, final float pZ, final long pTimestamp); + public static native void onSensorChanged(final float x, final float y, final float z, final long timestamp); // =========================================================== // Inner and Anonymous Classes diff --git a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java index d4e5347880..32ae89876e 100644 --- a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java +++ b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java @@ -56,9 +56,9 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe // Fields // =========================================================== - private Cocos2dxGLSurfaceView mGLSurfaceView; - private int[] glContextAttrs; - private Cocos2dxHandler mHandler; + private Cocos2dxGLSurfaceView mGLSurfaceView = null; + private int[] mGLContextAttrs = null; + private Cocos2dxHandler mHandler = null; private static Cocos2dxActivity sContext = null; private Cocos2dxVideoHelper mVideoHelper = null; private Cocos2dxWebViewHelper mWebViewHelper = null; @@ -103,7 +103,7 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe Cocos2dxHelper.init(this); - this.glContextAttrs = getGLContextAttrs(); + this.mGLContextAttrs = getGLContextAttrs(); this.init(); if (mVideoHelper == null) { @@ -222,7 +222,7 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe public Cocos2dxGLSurfaceView onCreateView() { Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this); //this line is need on some device if we specify an alpha bits - if(this.glContextAttrs[3] > 0) glSurfaceView.getHolder().setFormat(PixelFormat.TRANSLUCENT); + if(this.mGLContextAttrs[3] > 0) glSurfaceView.getHolder().setFormat(PixelFormat.TRANSLUCENT); class cocos2dEGLConfigChooser implements GLSurfaceView.EGLConfigChooser { @@ -344,7 +344,7 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe } } - cocos2dEGLConfigChooser chooser = new cocos2dEGLConfigChooser(this.glContextAttrs); + cocos2dEGLConfigChooser chooser = new cocos2dEGLConfigChooser(this.mGLContextAttrs); glSurfaceView.setEGLConfigChooser(chooser); return glSurfaceView; diff --git a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxBitmap.java b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxBitmap.java index 2edbbf280b..7b01bc9942 100644 --- a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxBitmap.java +++ b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxBitmap.java @@ -58,7 +58,7 @@ public class Cocos2dxBitmap { // Fields // =========================================================== - private static Context _context; + private static Context sContext; // =========================================================== // Constructors @@ -69,7 +69,7 @@ public class Cocos2dxBitmap { // =========================================================== public static void setContext(final Context context) { - Cocos2dxBitmap._context = context; + Cocos2dxBitmap.sContext = context; } // =========================================================== @@ -84,20 +84,19 @@ public class Cocos2dxBitmap { final int height, final byte[] pixels); /** - * @param pWidth + * @param width * the width to draw, it can be 0 - * @param pHeight + * @param height * the height to draw, it can be 0 */ public static void createTextBitmap(String string, final String fontName, final int fontSize, final int alignment, final int width, final int height) { - // createTextBitmapShadowStroke( string, fontName, fontSize, 1.0f, 1.0f, 1.0f, // text font and color alignment, width, height, // alignment and size - false, 0.0f, 0.0f, 0.0f, 0.0f, // no shadow - false, 1.0f, 1.0f, 1.0f, 1.0f); // no stroke + false, 0.0f, 0.0f, 0.0f, 0.0f, // no shadow + false, 1.0f, 1.0f, 1.0f, 1.0f); // no stroke } @@ -113,13 +112,12 @@ public class Cocos2dxBitmap { string = Cocos2dxBitmap.refactorString(string); final Paint paint = Cocos2dxBitmap.newPaint(fontName, fontSize, horizontalAlignment); - /** - * if the first word width less than designed width,It means no words to show - */ + + // if the first word width less than designed width, it means no words to show if(0 != width) { final int firstWordWidth = (int) Math.ceil(paint.measureText(string, 0,1)); - if ( firstWordWidth > width) + if (firstWordWidth > width) { Log.w("createTextBitmapShadowStroke warning:","the input width is less than the width of the pString's first word\n"); return false; @@ -151,7 +149,7 @@ public class Cocos2dxBitmap { final Canvas canvas = new Canvas(bitmap); - /* Draw string. */ + // Draw string. final FontMetricsInt fontMetricsInt = paint.getFontMetricsInt(); // draw again with stroke on if needed @@ -204,17 +202,17 @@ public class Cocos2dxBitmap { paint.setTextSize(fontSize); paint.setAntiAlias(true); - /* Set type face for paint, now it support .ttf file. */ + // Set type face for paint, now it support .ttf file. if (fontName.endsWith(".ttf")) { try { final Typeface typeFace = Cocos2dxTypefaces.get( - Cocos2dxBitmap._context, fontName); + Cocos2dxBitmap.sContext, fontName); paint.setTypeface(typeFace); } catch (final Exception e) { Log.e("Cocos2dxBitmap", "error to create ttf type face: " + fontName); - /* The file may not find, use system font. */ + // The file may not find, use system font. paint.setTypeface(Typeface.create(fontName, Typeface.NORMAL)); } } else { @@ -249,7 +247,7 @@ public class Cocos2dxBitmap { if (width != 0) { maxContentWidth = width; } else { - /* Compute the max width. */ + // Compute the max width. int temp = 0; for (final String line : lines) { temp = (int) Math.ceil(paint.measureText(line, 0, @@ -335,13 +333,13 @@ public class Cocos2dxBitmap { strList.add(line); } - /* Should not exceed the max height. */ + // Should not exceed the max height. if (maxLines > 0 && strList.size() >= maxLines) { break; } } - /* Remove exceeding lines. */ + // Remove exceeding lines. if (maxLines > 0 && strList.size() > maxLines) { while (strList.size() > maxLines) { strList.removeLast(); @@ -366,13 +364,13 @@ public class Cocos2dxBitmap { } private static LinkedList divideStringWithMaxWidth( - final String string, final int maxWidth, final Paint paint) { + final String string, final int maxWidth, final Paint paint) { final int charLength = string.length(); int start = 0; int tempWidth = 0; final LinkedList strList = new LinkedList(); - /* Break a String into String[] by the width & should wrap the word. */ + // 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(string, start, i)); @@ -381,21 +379,21 @@ public class Cocos2dxBitmap { .lastIndexOf(" "); if (lastIndexOfSpace != -1 && lastIndexOfSpace > start) { - /* Should wrap the word. */ + // Should wrap the word. strList.add(string.substring(start, lastIndexOfSpace)); i = lastIndexOfSpace + 1; // skip space } else { - /* Should not exceed the width. */ + // Should not exceed the width. if (tempWidth > maxWidth) { strList.add(string.substring(start, i - 1)); - /* Compute from previous char. */ + // Compute from previous char. --i; } else { strList.add(string.substring(start, i)); } } - /* Remove spaces at the beginning of a new line. */ + // Remove spaces at the beginning of a new line. while (i < charLength && string.charAt(i) == ' ') { ++i; } @@ -404,7 +402,7 @@ public class Cocos2dxBitmap { } } - /* Add the last chars. */ + // Add the last chars. if (start < charLength) { strList.add(string.substring(start)); } @@ -413,7 +411,7 @@ public class Cocos2dxBitmap { } private static String refactorString(final String string) { - /* Avoid error when content is "". */ + // Avoid error when content is "". if (string.compareTo("") == 0) { return " "; } diff --git a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxDialog.java b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxDialog.java index 8333991cce..a54068c082 100644 --- a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxDialog.java +++ b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxDialog.java @@ -275,7 +275,7 @@ public class Cocos2dxEditBoxDialog extends Dialog { this.mInputEditText.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(final TextView v, final int actionId, final KeyEvent event) { - /* If user didn't set keyboard type, this callback will be invoked twice with 'KeyEvent.ACTION_DOWN' and 'KeyEvent.ACTION_UP'. */ + // 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)) { Cocos2dxHelper.setEditTextDialogResult(Cocos2dxEditBoxDialog.this.mInputEditText.getText().toString()); Cocos2dxEditBoxDialog.this.closeKeyboard(); diff --git a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditText.java b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditText.java index 391cf81802..5a195d9c3e 100644 --- a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditText.java +++ b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditText.java @@ -72,7 +72,7 @@ public class Cocos2dxEditText extends EditText { public boolean onKeyDown(final int pKeyCode, final KeyEvent pKeyEvent) { super.onKeyDown(pKeyCode, pKeyEvent); - /* Let GlSurfaceView get focus if back key is input. */ + // Let GlSurfaceView get focus if back key is input. if (pKeyCode == KeyEvent.KEYCODE_BACK) { this.mCocos2dxGLSurfaceView.requestFocus(); } diff --git a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxMusic.java b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxMusic.java index 5e2a73d9c8..4e9bdf5405 100644 --- a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxMusic.java +++ b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxMusic.java @@ -47,17 +47,17 @@ public class Cocos2dxMusic { private MediaPlayer mBackgroundMediaPlayer; private float mLeftVolume; private float mRightVolume; - private boolean mPaused;// whether music is paused state. + private boolean mPaused; // whether music is paused state. private boolean mIsLoop = false; - private boolean mManualPaused = false;// whether music is paused manually before the program is switched to the background. + private boolean mManualPaused = false; // whether music is paused manually before the program is switched to the background. private String mCurrentPath; // =========================================================== // Constructors // =========================================================== - public Cocos2dxMusic(final Context pContext) { - this.mContext = pContext; + public Cocos2dxMusic(final Context context) { + this.mContext = context; this.initData(); } @@ -74,8 +74,8 @@ public class Cocos2dxMusic { // Methods // =========================================================== - public void preloadBackgroundMusic(final String pPath) { - if ((this.mCurrentPath == null) || (!this.mCurrentPath.equals(pPath))) { + public void preloadBackgroundMusic(final String path) { + if ((this.mCurrentPath == null) || (!this.mCurrentPath.equals(path))) { // preload new background music // release old resource and create a new one @@ -83,10 +83,10 @@ public class Cocos2dxMusic { this.mBackgroundMediaPlayer.release(); } - this.mBackgroundMediaPlayer = this.createMediaplayer(pPath); + this.mBackgroundMediaPlayer = this.createMediaplayer(path); // record the path - this.mCurrentPath = pPath; + this.mCurrentPath = path; } } @@ -136,8 +136,11 @@ public class Cocos2dxMusic { if (this.mBackgroundMediaPlayer != null) { mBackgroundMediaPlayer.release(); mBackgroundMediaPlayer = createMediaplayer(mCurrentPath); - // should set the state, if not, the following sequence will be error - // play -> pause -> stop -> resume + + /** + * should set the state, if not, the following sequence will be error + * play -> pause -> stop -> resume + */ this.mPaused = false; } } @@ -192,16 +195,16 @@ public class Cocos2dxMusic { } } - public void setBackgroundVolume(float pVolume) { - if (pVolume < 0.0f) { - pVolume = 0.0f; + public void setBackgroundVolume(float volume) { + if (volume < 0.0f) { + volume = 0.0f; } - if (pVolume > 1.0f) { - pVolume = 1.0f; + if (volume > 1.0f) { + volume = 1.0f; } - this.mLeftVolume = this.mRightVolume = pVolume; + this.mLeftVolume = this.mRightVolume = volume; if (this.mBackgroundMediaPlayer != null) { this.mBackgroundMediaPlayer.setVolume(this.mLeftVolume, this.mRightVolume); } @@ -238,16 +241,16 @@ public class Cocos2dxMusic { * the pPath relative to assets * @return */ - private MediaPlayer createMediaplayer(final String pPath) { + private MediaPlayer createMediaplayer(final String path) { MediaPlayer mediaPlayer = new MediaPlayer(); try { - if (pPath.startsWith("/")) { - final FileInputStream fis = new FileInputStream(pPath); + if (path.startsWith("/")) { + final FileInputStream fis = new FileInputStream(path); mediaPlayer.setDataSource(fis.getFD()); fis.close(); } else { - final AssetFileDescriptor assetFileDescritor = this.mContext.getAssets().openFd(pPath); + final AssetFileDescriptor assetFileDescritor = this.mContext.getAssets().openFd(path); mediaPlayer.setDataSource(assetFileDescritor.getFileDescriptor(), assetFileDescritor.getStartOffset(), assetFileDescritor.getLength()); } diff --git a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxRenderer.java b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxRenderer.java index e4596476c3..7847b4c035 100644 --- a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxRenderer.java +++ b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxRenderer.java @@ -56,13 +56,13 @@ public class Cocos2dxRenderer implements GLSurfaceView.Renderer { // Getter & Setter // =========================================================== - public static void setAnimationInterval(final double pAnimationInterval) { - Cocos2dxRenderer.sAnimationInterval = (long) (pAnimationInterval * Cocos2dxRenderer.NANOSECONDSPERSECOND); + public static void setAnimationInterval(final double animationInterval) { + Cocos2dxRenderer.sAnimationInterval = (long) (animationInterval * Cocos2dxRenderer.NANOSECONDSPERSECOND); } - public void setScreenWidthAndHeight(final int pSurfaceWidth, final int pSurfaceHeight) { - this.mScreenWidth = pSurfaceWidth; - this.mScreenHeight = pSurfaceHeight; + public void setScreenWidthAndHeight(final int surfaceWidth, final int surfaceHeight) { + this.mScreenWidth = surfaceWidth; + this.mScreenHeight = surfaceHeight; } // =========================================================== @@ -70,15 +70,15 @@ public class Cocos2dxRenderer implements GLSurfaceView.Renderer { // =========================================================== @Override - public void onSurfaceCreated(final GL10 pGL10, final EGLConfig pEGLConfig) { + public void onSurfaceCreated(final GL10 GL10, final EGLConfig EGLConfig) { Cocos2dxRenderer.nativeInit(this.mScreenWidth, this.mScreenHeight); this.mLastTickInNanoSeconds = System.nanoTime(); mNativeInitCompleted = true; } @Override - public void onSurfaceChanged(final GL10 pGL10, final int pWidth, final int pHeight) { - Cocos2dxRenderer.nativeOnSurfaceChanged(pWidth, pHeight); + public void onSurfaceChanged(final GL10 GL10, final int width, final int height) { + Cocos2dxRenderer.nativeOnSurfaceChanged(width, height); } @Override @@ -111,42 +111,44 @@ public class Cocos2dxRenderer implements GLSurfaceView.Renderer { // Methods // =========================================================== - private static native void nativeTouchesBegin(final int pID, final float pX, final float pY); - private static native void nativeTouchesEnd(final int pID, final float pX, final float pY); - private static native void nativeTouchesMove(final int[] pIDs, final float[] pXs, final float[] pYs); - private static native void nativeTouchesCancel(final int[] pIDs, final float[] pXs, final float[] pYs); - private static native boolean nativeKeyDown(final int pKeyCode); + private static native void nativeTouchesBegin(final int id, final float x, final float y); + private static native void nativeTouchesEnd(final int id, final float x, final float y); + private static native void nativeTouchesMove(final int[] ids, final float[] xs, final float[] ys); + private static native void nativeTouchesCancel(final int[] ids, final float[] xs, final float[] ys); + private static native boolean nativeKeyDown(final int keyCode); private static native void nativeRender(); - private static native void nativeInit(final int pWidth, final int pHeight); - private static native void nativeOnSurfaceChanged(final int pWidth, final int pHeight); + private static native void nativeInit(final int width, final int height); + private static native void nativeOnSurfaceChanged(final int width, final int height); private static native void nativeOnPause(); private static native void nativeOnResume(); - public void handleActionDown(final int pID, final float pX, final float pY) { - Cocos2dxRenderer.nativeTouchesBegin(pID, pX, pY); + public void handleActionDown(final int id, final float x, final float y) { + Cocos2dxRenderer.nativeTouchesBegin(id, x, y); } - public void handleActionUp(final int pID, final float pX, final float pY) { - Cocos2dxRenderer.nativeTouchesEnd(pID, pX, pY); + public void handleActionUp(final int id, final float x, final float y) { + Cocos2dxRenderer.nativeTouchesEnd(id, x, y); } - public void handleActionCancel(final int[] pIDs, final float[] pXs, final float[] pYs) { - Cocos2dxRenderer.nativeTouchesCancel(pIDs, pXs, pYs); + public void handleActionCancel(final int[] ids, final float[] xs, final float[] ys) { + Cocos2dxRenderer.nativeTouchesCancel(ids, xs, ys); } - public void handleActionMove(final int[] pIDs, final float[] pXs, final float[] pYs) { - Cocos2dxRenderer.nativeTouchesMove(pIDs, pXs, pYs); + public void handleActionMove(final int[] ids, final float[] xs, final float[] ys) { + Cocos2dxRenderer.nativeTouchesMove(ids, xs, ys); } - public void handleKeyDown(final int pKeyCode) { - Cocos2dxRenderer.nativeKeyDown(pKeyCode); + public void handleKeyDown(final int keyCode) { + Cocos2dxRenderer.nativeKeyDown(keyCode); } public void handleOnPause() { - // onPause may be invoked before onSurfaceCreated - // and engine will be initialized correctly after - // onSurfaceCreated is invoked, can not invoke any - // native methed before onSurfaceCreated is invoked + /** + * onPause may be invoked before onSurfaceCreated, + * and engine will be initialized correctly after + * onSurfaceCreated is invoked. Can not invoke any + * native method before onSurfaceCreated is invoked + */ if (! mNativeInitCompleted) return; @@ -159,12 +161,12 @@ public class Cocos2dxRenderer implements GLSurfaceView.Renderer { Cocos2dxRenderer.nativeOnResume(); } - private static native void nativeInsertText(final String pText); + private static native void nativeInsertText(final String text); private static native void nativeDeleteBackward(); private static native String nativeGetContentText(); - public void handleInsertText(final String pText) { - Cocos2dxRenderer.nativeInsertText(pText); + public void handleInsertText(final String text) { + Cocos2dxRenderer.nativeInsertText(text); } public void handleDeleteBackward() { diff --git a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxSound.java b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxSound.java index 13c2c1d23b..9c08fe98ce 100644 --- a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxSound.java +++ b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxSound.java @@ -77,8 +77,8 @@ public class Cocos2dxSound { // Constructors // =========================================================== - public Cocos2dxSound(final Context pContext) { - this.mContext = pContext; + public Cocos2dxSound(final Context context) { + this.mContext = context; this.initData(); } @@ -111,50 +111,50 @@ public class Cocos2dxSound { // Methods // =========================================================== - public int preloadEffect(final String pPath) { - Integer soundID = this.mPathSoundIDMap.get(pPath); + public int preloadEffect(final String path) { + Integer soundID = this.mPathSoundIDMap.get(path); if (soundID == null) { - soundID = this.createSoundIDFromAsset(pPath); + soundID = this.createSoundIDFromAsset(path); // save value just in case if file is really loaded if (soundID != Cocos2dxSound.INVALID_SOUND_ID) { - this.mPathSoundIDMap.put(pPath, soundID); + this.mPathSoundIDMap.put(path, soundID); } } return soundID; } - public void unloadEffect(final String pPath) { + public void unloadEffect(final String path) { // stop effects - final ArrayList streamIDs = this.mPathStreamIDsMap.get(pPath); + final ArrayList streamIDs = this.mPathStreamIDsMap.get(path); if (streamIDs != null) { for (final Integer steamID : streamIDs) { this.mSoundPool.stop(steamID); } } - this.mPathStreamIDsMap.remove(pPath); + this.mPathStreamIDsMap.remove(path); // unload effect - final Integer soundID = this.mPathSoundIDMap.get(pPath); + final Integer soundID = this.mPathSoundIDMap.get(path); if(soundID != null){ this.mSoundPool.unload(soundID); - this.mPathSoundIDMap.remove(pPath); + this.mPathSoundIDMap.remove(path); } } - public int playEffect(final String pPath, final boolean pLoop, float pitch, float pan, float gain){ - Integer soundID = this.mPathSoundIDMap.get(pPath); + public int playEffect(final String path, final boolean loop, float pitch, float pan, float gain){ + Integer soundID = this.mPathSoundIDMap.get(path); int streamID = Cocos2dxSound.INVALID_STREAM_ID; if (soundID != null) { // parameters; pan = -1 for left channel, 1 for right channel, 0 for both channels // play sound - streamID = this.doPlayEffect(pPath, soundID.intValue(), pLoop, pitch, pan, gain); + streamID = this.doPlayEffect(path, soundID.intValue(), loop, pitch, pan, gain); } else { // the effect is not prepared - soundID = this.preloadEffect(pPath); + soundID = this.preloadEffect(path); if (soundID == Cocos2dxSound.INVALID_SOUND_ID) { // can not preload effect return Cocos2dxSound.INVALID_SOUND_ID; @@ -163,7 +163,7 @@ public class Cocos2dxSound { // only allow one playEffect at a time, or the semaphore will not work correctly synchronized(this.mSoundPool) { // add this effect into mEffecToPlayWhenLoadedArray, and it will be played when loaded completely - mEffecToPlayWhenLoadedArray.add(new SoundInfoForLoadedCompleted(pPath, soundID.intValue(), pLoop, + mEffecToPlayWhenLoadedArray.add(new SoundInfoForLoadedCompleted(path, soundID.intValue(), loop, pitch, pan, gain)); try { @@ -247,16 +247,16 @@ public class Cocos2dxSound { return (this.mLeftVolume + this.mRightVolume) / 2; } - public void setEffectsVolume(float pVolume) { - // pVolume should be in [0, 1.0] - if (pVolume < 0) { - pVolume = 0; + public void setEffectsVolume(float volume) { + // volume should be in [0, 1.0] + if (volume < 0) { + volume = 0; } - if (pVolume > 1) { - pVolume = 1; + if (volume > 1) { + volume = 1; } - this.mLeftVolume = this.mRightVolume = pVolume; + this.mLeftVolume = this.mRightVolume = volume; // change the volume of playing sounds if (!this.mPathStreamIDsMap.isEmpty()) { @@ -282,14 +282,14 @@ public class Cocos2dxSound { this.initData(); } - public int createSoundIDFromAsset(final String pPath) { + public int createSoundIDFromAsset(final String path) { int soundID = Cocos2dxSound.INVALID_SOUND_ID; try { - if (pPath.startsWith("/")) { - soundID = this.mSoundPool.load(pPath, 0); + if (path.startsWith("/")) { + soundID = this.mSoundPool.load(path, 0); } else { - soundID = this.mSoundPool.load(this.mContext.getAssets().openFd(pPath), 0); + soundID = this.mSoundPool.load(this.mContext.getAssets().openFd(path), 0); } } catch (final Exception e) { soundID = Cocos2dxSound.INVALID_SOUND_ID; @@ -308,19 +308,19 @@ public class Cocos2dxSound { return Math.max(min, (Math.min(value, max))); } - private int doPlayEffect(final String pPath, final int soundId, final boolean pLoop, float pitch, float pan, float gain) { + private int doPlayEffect(final String path, final int soundId, final boolean loop, float pitch, float pan, float gain) { float leftVolume = this.mLeftVolume * gain * (1.0f - this.clamp(pan, 0.0f, 1.0f)); float rightVolume = this.mRightVolume * gain * (1.0f - this.clamp(-pan, 0.0f, 1.0f)); float soundRate = this.clamp(SOUND_RATE * pitch, 0.5f, 2.0f); // play sound - int streamID = this.mSoundPool.play(soundId, this.clamp(leftVolume, 0.0f, 1.0f), this.clamp(rightVolume, 0.0f, 1.0f), Cocos2dxSound.SOUND_PRIORITY, pLoop ? -1 : 0, soundRate); + int streamID = this.mSoundPool.play(soundId, this.clamp(leftVolume, 0.0f, 1.0f), this.clamp(rightVolume, 0.0f, 1.0f), Cocos2dxSound.SOUND_PRIORITY, loop ? -1 : 0, soundRate); // record stream id - ArrayList streamIDs = this.mPathStreamIDsMap.get(pPath); + ArrayList streamIDs = this.mPathStreamIDsMap.get(path); if (streamIDs == null) { streamIDs = new ArrayList(); - this.mPathStreamIDsMap.put(pPath, streamIDs); + this.mPathStreamIDsMap.put(path, streamIDs); } streamIDs.add(streamID); @@ -370,8 +370,10 @@ public class Cocos2dxSound { // set the stream id which will be returned by playEffect() mStreamIdSyn = doPlayEffect(info.path, info.soundID, info.isLoop, info.pitch, info.pan, info.gain); - // remove it from array, because we will break here - // so it is safe to do + /* + * Remove it from array, because we will break here. + * So it is safe to do. + */ mEffecToPlayWhenLoadedArray.remove(info); break; diff --git a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxTypefaces.java b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxTypefaces.java index ed22487ea3..ead7074ddf 100644 --- a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxTypefaces.java +++ b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxTypefaces.java @@ -56,21 +56,21 @@ public class Cocos2dxTypefaces { // Methods // =========================================================== - public static synchronized Typeface get(final Context pContext, final String pAssetName) { - if (!Cocos2dxTypefaces.sTypefaceCache.containsKey(pAssetName)) { + public static synchronized Typeface get(final Context context, final String assetName) { + if (!Cocos2dxTypefaces.sTypefaceCache.containsKey(assetName)) { Typeface typeface = null; - if (pAssetName.startsWith("/")) + if (assetName.startsWith("/")) { - typeface = Typeface.createFromFile(pAssetName); + typeface = Typeface.createFromFile(assetName); } else { - typeface = Typeface.createFromAsset(pContext.getAssets(), pAssetName); + typeface = Typeface.createFromAsset(context.getAssets(), assetName); } - Cocos2dxTypefaces.sTypefaceCache.put(pAssetName, typeface); + Cocos2dxTypefaces.sTypefaceCache.put(assetName, typeface); } - return Cocos2dxTypefaces.sTypefaceCache.get(pAssetName); + return Cocos2dxTypefaces.sTypefaceCache.get(assetName); } // =========================================================== diff --git a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxVideoHelper.java b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxVideoHelper.java index 823b27c37d..46b005ea5a 100644 --- a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxVideoHelper.java +++ b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxVideoHelper.java @@ -232,7 +232,7 @@ public class Cocos2dxVideoHelper { } } - public static void setVideoUrl(int index,int videoSource,String videoUrl) { + public static void setVideoUrl(int index, int videoSource, String videoUrl) { Message msg = new Message(); msg.what = VideoTaskSetSource; msg.arg1 = index; @@ -241,7 +241,7 @@ public class Cocos2dxVideoHelper { mVideoHandler.sendMessage(msg); } - private void _setVideoURL(int index,int videoSource,String videoUrl) { + private void _setVideoURL(int index, int videoSource, String videoUrl) { Cocos2dxVideoView videoView = sVideoViews.get(index); if (videoView != null) { switch (videoSource) { @@ -257,7 +257,7 @@ public class Cocos2dxVideoHelper { } } - public static void setVideoRect(int index,int left,int top,int maxWidth,int maxHeight) { + public static void setVideoRect(int index, int left, int top, int maxWidth, int maxHeight) { Message msg = new Message(); msg.what = VideoTaskSetRect; msg.arg1 = index; @@ -265,14 +265,14 @@ public class Cocos2dxVideoHelper { mVideoHandler.sendMessage(msg); } - private void _setVideoRect(int index,int left,int top,int maxWidth,int maxHeight) { + private void _setVideoRect(int index, int left, int top, int maxWidth, int maxHeight) { Cocos2dxVideoView videoView = sVideoViews.get(index); if (videoView != null) { videoView.setVideoRect(left,top,maxWidth,maxHeight); } } - public static void setFullScreenEnabled(int index,boolean enabled, int width,int height) { + public static void setFullScreenEnabled(int index, boolean enabled, int width, int height) { Message msg = new Message(); msg.what = VideoTaskFullScreen; msg.arg1 = index; diff --git a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxVideoView.java b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxVideoView.java index c54fb0c8e6..e55f80ec31 100644 --- a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxVideoView.java +++ b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxVideoView.java @@ -52,11 +52,13 @@ public class Cocos2dxVideoView extends SurfaceView implements MediaPlayerControl private static final int STATE_PAUSED = 4; private static final int STATE_PLAYBACK_COMPLETED = 5; - // mCurrentState is a VideoView object's current state. - // mTargetState is the state that a method caller intends to reach. - // For instance, regardless the VideoView object's current state, - // calling pause() intends to bring the object to a target state - // of STATE_PAUSED. + /** + * mCurrentState is a VideoView object's current state. + * mTargetState is the state that a method caller intends to reach. + * For instance, regardless the VideoView object's current state, + * calling pause() intends to bring the object to a target state + * of STATE_PAUSED. + */ private int mCurrentState = STATE_IDLE; private int mTargetState = STATE_IDLE; @@ -113,7 +115,7 @@ public class Cocos2dxVideoView extends SurfaceView implements MediaPlayerControl } - public void setVideoRect(int left,int top,int maxWidth,int maxHeight) { + public void setVideoRect(int left, int top, int maxWidth, int maxHeight) { mViewLeft = left; mViewTop = top; mViewWidth = maxWidth; @@ -296,8 +298,10 @@ public class Cocos2dxVideoView extends SurfaceView implements MediaPlayerControl } mMediaPlayer.prepareAsync(); - // we don't set the target state here either, but preserve the - // target state that was there before. + + /** + * Don't set the target state here either, but preserve the target state that was there before. + */ mCurrentState = STATE_PREPARING; } catch (IOException ex) { Log.w(TAG, "Unable to open content: " + mUri, ex); @@ -329,7 +333,7 @@ public class Cocos2dxVideoView extends SurfaceView implements MediaPlayerControl } } - public void fixSize(int left,int top,int width,int height) { + public void fixSize(int left, int top, int width, int height) { if (width != 0 && height != 0) { if (mKeepRatio) { if ( mVideoWidth * height > width * mVideoHeight ) { @@ -389,7 +393,8 @@ public class Cocos2dxVideoView extends SurfaceView implements MediaPlayerControl mVideoWidth = mp.getVideoWidth(); mVideoHeight = mp.getVideoHeight(); - int seekToPosition = mSeekWhenPrepared; // mSeekWhenPrepared may be changed after seekTo() call + // mSeekWhenPrepared may be changed after seekTo() call + int seekToPosition = mSeekWhenPrepared; if (seekToPosition != 0) { seekTo(seekToPosition); } @@ -451,10 +456,10 @@ public class Cocos2dxVideoView extends SurfaceView implements MediaPlayerControl int messageId; if (framework_err == MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK) { - //messageId = com.android.internal.R.string.VideoView_error_text_invalid_progressive_playback; + // messageId = com.android.internal.R.string.VideoView_error_text_invalid_progressive_playback; messageId = r.getIdentifier("VideoView_error_text_invalid_progressive_playback", "string", "android"); } else { - //messageId = com.android.internal.R.string.VideoView_error_text_unknown; + // messageId = com.android.internal.R.string.VideoView_error_text_unknown; messageId = r.getIdentifier("VideoView_error_text_unknown", "string", "android"); } @@ -502,7 +507,7 @@ public class Cocos2dxVideoView extends SurfaceView implements MediaPlayerControl /** * Register a callback to be invoked when the end of a media file - * has been reached during playback. + * has been reached during play back. * * @param l The callback that will be run */ @@ -513,7 +518,7 @@ public class Cocos2dxVideoView extends SurfaceView implements MediaPlayerControl /** * Register a callback to be invoked when an error occurs - * during playback or setup. If no listener is specified, + * during play back or setup. If no listener is specified, * or if the listener returned false, VideoView will inform * the user of any errors. * diff --git a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxWebView.java b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxWebView.java index c58ad937e8..f4b1ad83aa 100755 --- a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxWebView.java +++ b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxWebView.java @@ -15,8 +15,8 @@ import android.widget.FrameLayout; public class Cocos2dxWebView extends WebView { private static final String TAG = Cocos2dxWebViewHelper.class.getSimpleName(); - private int viewTag; - private String jsScheme; + private int mViewTag; + private String mJSScheme; public Cocos2dxWebView(Context context) { this(context, -1); @@ -25,8 +25,8 @@ public class Cocos2dxWebView extends WebView { @SuppressLint("SetJavaScriptEnabled") public Cocos2dxWebView(Context context, int viewTag) { super(context); - this.viewTag = viewTag; - this.jsScheme = ""; + this.mViewTag = viewTag; + this.mJSScheme = ""; this.setFocusable(true); this.setFocusableInTouchMode(true); @@ -48,7 +48,7 @@ public class Cocos2dxWebView extends WebView { } public void setJavascriptInterfaceScheme(String scheme) { - this.jsScheme = scheme != null ? scheme : ""; + this.mJSScheme = scheme != null ? scheme : ""; } public void setScalesPageToFit(boolean scalesPageToFit) { @@ -59,23 +59,23 @@ public class Cocos2dxWebView extends WebView { @Override public boolean shouldOverrideUrlLoading(WebView view, String urlString) { URI uri = URI.create(urlString); - if (uri != null && uri.getScheme().equals(jsScheme)) { - Cocos2dxWebViewHelper._onJsCallback(viewTag, urlString); + if (uri != null && uri.getScheme().equals(mJSScheme)) { + Cocos2dxWebViewHelper._onJsCallback(mViewTag, urlString); return true; } - return Cocos2dxWebViewHelper._shouldStartLoading(viewTag, urlString); + return Cocos2dxWebViewHelper._shouldStartLoading(mViewTag, urlString); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); - Cocos2dxWebViewHelper._didFinishLoading(viewTag, url); + Cocos2dxWebViewHelper._didFinishLoading(mViewTag, url); } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); - Cocos2dxWebViewHelper._didFailLoading(viewTag, failingUrl); + Cocos2dxWebViewHelper._didFailLoading(mViewTag, failingUrl); } } diff --git a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxWebViewHelper.java b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxWebViewHelper.java index e8d45b787e..c8fc269a26 100755 --- a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxWebViewHelper.java +++ b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxWebViewHelper.java @@ -13,18 +13,18 @@ import java.util.concurrent.FutureTask; public class Cocos2dxWebViewHelper { private static final String TAG = Cocos2dxWebViewHelper.class.getSimpleName(); - private static Handler handler; - private static Cocos2dxActivity cocos2dxActivity; - private static FrameLayout layout; + private static Handler sHandler; + private static Cocos2dxActivity sCocos2dxActivity; + private static FrameLayout sLayout; private static SparseArray webViews; private static int viewTag = 0; public Cocos2dxWebViewHelper(FrameLayout layout) { - Cocos2dxWebViewHelper.layout = layout; - Cocos2dxWebViewHelper.handler = new Handler(Looper.myLooper()); + Cocos2dxWebViewHelper.sLayout = layout; + Cocos2dxWebViewHelper.sHandler = new Handler(Looper.myLooper()); - Cocos2dxWebViewHelper.cocos2dxActivity = (Cocos2dxActivity) Cocos2dxActivity.getContext(); + Cocos2dxWebViewHelper.sCocos2dxActivity = (Cocos2dxActivity) Cocos2dxActivity.getContext(); Cocos2dxWebViewHelper.webViews = new SparseArray(); } @@ -55,14 +55,14 @@ public class Cocos2dxWebViewHelper { @SuppressWarnings("unused") public static int createWebView() { final int index = viewTag; - cocos2dxActivity.runOnUiThread(new Runnable() { + sCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { - Cocos2dxWebView webView = new Cocos2dxWebView(cocos2dxActivity, index); + Cocos2dxWebView webView = new Cocos2dxWebView(sCocos2dxActivity, index); FrameLayout.LayoutParams lParams = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT); - layout.addView(webView, lParams); + sLayout.addView(webView, lParams); webViews.put(index, webView); } @@ -72,13 +72,13 @@ public class Cocos2dxWebViewHelper { @SuppressWarnings("unused") public static void removeWebView(final int index) { - cocos2dxActivity.runOnUiThread(new Runnable() { + sCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { Cocos2dxWebView webView = webViews.get(index); if (webView != null) { webViews.remove(index); - layout.removeView(webView); + sLayout.removeView(webView); } } }); @@ -86,7 +86,7 @@ public class Cocos2dxWebViewHelper { @SuppressWarnings("unused") public static void setVisible(final int index, final boolean visible) { - cocos2dxActivity.runOnUiThread(new Runnable() { + sCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { Cocos2dxWebView webView = webViews.get(index); @@ -99,7 +99,7 @@ public class Cocos2dxWebViewHelper { @SuppressWarnings("unused") public static void setWebViewRect(final int index, final int left, final int top, final int maxWidth, final int maxHeight) { - cocos2dxActivity.runOnUiThread(new Runnable() { + sCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { Cocos2dxWebView webView = webViews.get(index); @@ -112,7 +112,7 @@ public class Cocos2dxWebViewHelper { @SuppressWarnings("unused") public static void setJavascriptInterfaceScheme(final int index, final String scheme) { - cocos2dxActivity.runOnUiThread(new Runnable() { + sCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { Cocos2dxWebView webView = webViews.get(index); @@ -125,7 +125,7 @@ public class Cocos2dxWebViewHelper { @SuppressWarnings("unused") public static void loadData(final int index, final String data, final String mimeType, final String encoding, final String baseURL) { - cocos2dxActivity.runOnUiThread(new Runnable() { + sCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { Cocos2dxWebView webView = webViews.get(index); @@ -138,7 +138,7 @@ public class Cocos2dxWebViewHelper { @SuppressWarnings("unused") public static void loadHTMLString(final int index, final String htmlString, final String mimeType, final String encoding) { - cocos2dxActivity.runOnUiThread(new Runnable() { + sCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { Cocos2dxWebView webView = webViews.get(index); @@ -151,7 +151,7 @@ public class Cocos2dxWebViewHelper { @SuppressWarnings("unused") public static void loadUrl(final int index, final String url) { - cocos2dxActivity.runOnUiThread(new Runnable() { + sCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { Cocos2dxWebView webView = webViews.get(index); @@ -164,7 +164,7 @@ public class Cocos2dxWebViewHelper { @SuppressWarnings("unused") public static void loadFile(final int index, final String filePath) { - cocos2dxActivity.runOnUiThread(new Runnable() { + sCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { Cocos2dxWebView webView = webViews.get(index); @@ -176,7 +176,7 @@ public class Cocos2dxWebViewHelper { } public static void stopLoading(final int index) { - cocos2dxActivity.runOnUiThread(new Runnable() { + sCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { Cocos2dxWebView webView = webViews.get(index); @@ -189,7 +189,7 @@ public class Cocos2dxWebViewHelper { } public static void reload(final int index) { - cocos2dxActivity.runOnUiThread(new Runnable() { + sCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { Cocos2dxWebView webView = webViews.get(index); @@ -202,7 +202,7 @@ public class Cocos2dxWebViewHelper { public static T callInMainThread(Callable call) throws ExecutionException, InterruptedException { FutureTask task = new FutureTask(call); - handler.post(task); + sHandler.post(task); return task.get(); } @@ -244,7 +244,7 @@ public class Cocos2dxWebViewHelper { @SuppressWarnings("unused") public static void goBack(final int index) { - cocos2dxActivity.runOnUiThread(new Runnable() { + sCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { Cocos2dxWebView webView = webViews.get(index); @@ -257,7 +257,7 @@ public class Cocos2dxWebViewHelper { @SuppressWarnings("unused") public static void goForward(final int index) { - cocos2dxActivity.runOnUiThread(new Runnable() { + sCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { Cocos2dxWebView webView = webViews.get(index); @@ -270,7 +270,7 @@ public class Cocos2dxWebViewHelper { @SuppressWarnings("unused") public static void evaluateJS(final int index, final String js) { - cocos2dxActivity.runOnUiThread(new Runnable() { + sCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { Cocos2dxWebView webView = webViews.get(index); @@ -283,7 +283,7 @@ public class Cocos2dxWebViewHelper { @SuppressWarnings("unused") public static void setScalesPageToFit(final int index, final boolean scalesPageToFit) { - cocos2dxActivity.runOnUiThread(new Runnable() { + sCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { Cocos2dxWebView webView = webViews.get(index); diff --git a/cocos/platform/desktop/CCGLViewImpl-desktop.cpp b/cocos/platform/desktop/CCGLViewImpl-desktop.cpp index 6fdbb4c8de..5616b080e4 100644 --- a/cocos/platform/desktop/CCGLViewImpl-desktop.cpp +++ b/cocos/platform/desktop/CCGLViewImpl-desktop.cpp @@ -661,38 +661,11 @@ void GLViewImpl::onGLFWMouseScrollCallback(GLFWwindow* window, double x, double void GLViewImpl::onGLFWKeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) { - EventKeyboard::KeyCode additionalKeyCode = EventKeyboard::KeyCode::KEY_NONE; - - switch (key) - { - case GLFW_KEY_LEFT_ALT: - case GLFW_KEY_RIGHT_ALT: - additionalKeyCode = EventKeyboard::KeyCode::KEY_ALT; - break; - case GLFW_KEY_LEFT_CONTROL: - case GLFW_KEY_RIGHT_CONTROL: - additionalKeyCode = EventKeyboard::KeyCode::KEY_CTRL; - break; - case GLFW_KEY_LEFT_SHIFT: - case GLFW_KEY_RIGHT_SHIFT: - additionalKeyCode = EventKeyboard::KeyCode::KEY_SHIFT; - break; - default: - break; - } - if (GLFW_REPEAT != action) { EventKeyboard event(g_keyCodeMap[key], GLFW_PRESS == action); auto dispatcher = Director::getInstance()->getEventDispatcher(); dispatcher->dispatchEvent(&event); - - // Keep compatibility for the old keycodes like SHIFT, CTRL, ALT. - if (additionalKeyCode != EventKeyboard::KeyCode::KEY_NONE) - { - EventKeyboard additionalEvent(additionalKeyCode, GLFW_PRESS == action); - dispatcher->dispatchEvent(&additionalEvent); - } } if (GLFW_RELEASE != action && g_keyCodeMap[key] == EventKeyboard::KeyCode::KEY_BACKSPACE) diff --git a/cocos/platform/ios/CCEAGLView-ios.mm b/cocos/platform/ios/CCEAGLView-ios.mm index b3d5fc4100..44749c5838 100644 --- a/cocos/platform/ios/CCEAGLView-ios.mm +++ b/cocos/platform/ios/CCEAGLView-ios.mm @@ -778,13 +778,10 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. float scaleY = glview->getScaleY(); - if (self.contentScaleFactor == 2.0f) - { - // Convert to pixel coordinate - - begin = CGRectApplyAffineTransform(begin, CGAffineTransformScale(CGAffineTransformIdentity, 2.0f, 2.0f)); - end = CGRectApplyAffineTransform(end, CGAffineTransformScale(CGAffineTransformIdentity, 2.0f, 2.0f)); - } + + // Convert to pixel coordinate + begin = CGRectApplyAffineTransform(begin, CGAffineTransformScale(CGAffineTransformIdentity, self.contentScaleFactor, self.contentScaleFactor)); + end = CGRectApplyAffineTransform(end, CGAffineTransformScale(CGAffineTransformIdentity, self.contentScaleFactor, self.contentScaleFactor)); float offestY = glview->getViewPortRect().origin.y; CCLOG("offestY = %f", offestY); @@ -861,10 +858,7 @@ UIInterfaceOrientation getFixedOrientation(UIInterfaceOrientation statusBarOrien auto glview = cocos2d::Director::getInstance()->getOpenGLView(); dis *= glview->getScaleY(); - if (self.contentScaleFactor == 2.0f) - { - dis /= 2.0f; - } + dis /= self.contentScaleFactor; switch (getFixedOrientation([[UIApplication sharedApplication] statusBarOrientation])) { diff --git a/cocos/platform/win32/CCApplication-win32.cpp b/cocos/platform/win32/CCApplication-win32.cpp index 0bb95e6420..8910012563 100644 --- a/cocos/platform/win32/CCApplication-win32.cpp +++ b/cocos/platform/win32/CCApplication-win32.cpp @@ -63,11 +63,9 @@ int Application::run() PVRFrameEnableControlWindow(false); // Main message loop: - LARGE_INTEGER nFreq; LARGE_INTEGER nLast; LARGE_INTEGER nNow; - QueryPerformanceFrequency(&nFreq); QueryPerformanceCounter(&nLast); initGLContextAttrs(); diff --git a/cocos/renderer/CCGLProgramStateCache.cpp b/cocos/renderer/CCGLProgramStateCache.cpp index 81af4a1e29..13a06e59f4 100644 --- a/cocos/renderer/CCGLProgramStateCache.cpp +++ b/cocos/renderer/CCGLProgramStateCache.cpp @@ -80,7 +80,7 @@ void GLProgramStateCache::removeUnusedGLProgramState() if( value->getReferenceCount() == 1 ) { CCLOG("cocos2d: GLProgramStateCache: removing unused GLProgramState"); - value->release(); + //value->release(); _glProgramStates.erase(it++); } else { ++it; diff --git a/cocos/renderer/CCMeshCommand.cpp b/cocos/renderer/CCMeshCommand.cpp index 73e189c013..5747ef574c 100644 --- a/cocos/renderer/CCMeshCommand.cpp +++ b/cocos/renderer/CCMeshCommand.cpp @@ -164,13 +164,13 @@ void MeshCommand::applyRenderState() if (_cullFaceEnabled && !s_cullFaceEnabled) { glEnable(GL_CULL_FACE); - if (s_cullFace != _cullFace) - { - glCullFace(_cullFace); - s_cullFace = _cullFace; - } s_cullFaceEnabled = true; } + if (s_cullFace != _cullFace) + { + glCullFace(_cullFace); + s_cullFace = _cullFace; + } if (_depthTestEnabled && !s_depthTestEnabled) { glEnable(GL_DEPTH_TEST); diff --git a/cocos/scripting/lua-bindings/auto/api/ActionManagerEx.lua b/cocos/scripting/lua-bindings/auto/api/ActionManagerEx.lua index df0e25a32b..3bb33f85d4 100644 --- a/cocos/scripting/lua-bindings/auto/api/ActionManagerEx.lua +++ b/cocos/scripting/lua-bindings/auto/api/ActionManagerEx.lua @@ -5,15 +5,16 @@ -- @parent_module ccs -------------------------------- --- @overload self, char, char, cc.CallFunc --- @overload self, char, char --- @function [parent=#ActionManagerEx] playActionByName +-- Stop an Action with a name.
+-- param jsonName UI file name
+-- param actionName action name in teh UIfile.
+-- return ActionObject which named as the param name +-- @function [parent=#ActionManagerEx] stopActionByName -- @param self -- @param #char jsonName -- @param #char actionName --- @param #cc.CallFunc func -- @return ActionObject#ActionObject ret (return value: ccs.ActionObject) - + -------------------------------- -- Gets an ActionObject with a name.
-- param jsonName UI file name
@@ -25,6 +26,16 @@ -- @param #char actionName -- @return ActionObject#ActionObject ret (return value: ccs.ActionObject) +-------------------------------- +-- @overload self, char, char, cc.CallFunc +-- @overload self, char, char +-- @function [parent=#ActionManagerEx] playActionByName +-- @param self +-- @param #char jsonName +-- @param #char actionName +-- @param #cc.CallFunc func +-- @return ActionObject#ActionObject ret (return value: ccs.ActionObject) + -------------------------------- -- Release all actions. -- @function [parent=#ActionManagerEx] releaseActions diff --git a/cocos/scripting/lua-bindings/auto/api/ActionTimelineCache.lua b/cocos/scripting/lua-bindings/auto/api/ActionTimelineCache.lua index 7130f68880..9c92e9512a 100644 --- a/cocos/scripting/lua-bindings/auto/api/ActionTimelineCache.lua +++ b/cocos/scripting/lua-bindings/auto/api/ActionTimelineCache.lua @@ -55,6 +55,13 @@ -- @param self -- @param #string fileName +-------------------------------- +-- +-- @function [parent=#ActionTimelineCache] createActionWithFlatBuffersForSimulator +-- @param self +-- @param #string fileName +-- @return ActionTimeline#ActionTimeline ret (return value: ccs.ActionTimeline) + -------------------------------- -- Destroys the singleton -- @function [parent=#ActionTimelineCache] destroyInstance diff --git a/cocos/scripting/lua-bindings/auto/api/CSLoader.lua b/cocos/scripting/lua-bindings/auto/api/CSLoader.lua index 00b6035ef5..bd2a5d6945 100644 --- a/cocos/scripting/lua-bindings/auto/api/CSLoader.lua +++ b/cocos/scripting/lua-bindings/auto/api/CSLoader.lua @@ -75,6 +75,13 @@ -- @param self -- @param #bool record +-------------------------------- +-- +-- @function [parent=#CSLoader] createNodeWithFlatBuffersForSimulator +-- @param self +-- @param #string filename +-- @return Node#Node ret (return value: cc.Node) + -------------------------------- -- -- @function [parent=#CSLoader] destroyInstance diff --git a/cocos/scripting/lua-bindings/auto/api/EventFrame.lua b/cocos/scripting/lua-bindings/auto/api/EventFrame.lua index 1a9582afc2..2806d47b35 100644 --- a/cocos/scripting/lua-bindings/auto/api/EventFrame.lua +++ b/cocos/scripting/lua-bindings/auto/api/EventFrame.lua @@ -15,6 +15,12 @@ -- @function [parent=#EventFrame] init -- @param self +-------------------------------- +-- +-- @function [parent=#EventFrame] setNode +-- @param self +-- @param #cc.Node node + -------------------------------- -- -- @function [parent=#EventFrame] getEvent diff --git a/cocos/scripting/lua-bindings/auto/api/LoadingBar.lua b/cocos/scripting/lua-bindings/auto/api/LoadingBar.lua index 535a59cbb7..c75f0df75b 100644 --- a/cocos/scripting/lua-bindings/auto/api/LoadingBar.lua +++ b/cocos/scripting/lua-bindings/auto/api/LoadingBar.lua @@ -72,9 +72,11 @@ -------------------------------- -- @overload self, string, float -- @overload self +-- @overload self, string, int, float -- @function [parent=#LoadingBar] create -- @param self -- @param #string textureName +-- @param #int texType -- @param #float percentage -- @return LoadingBar#LoadingBar ret (return value: ccui.LoadingBar) diff --git a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_csloader_auto.cpp b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_csloader_auto.cpp index c2dc9b0c2f..524716110b 100644 --- a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_csloader_auto.cpp +++ b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_csloader_auto.cpp @@ -548,6 +548,56 @@ int lua_cocos2dx_csloader_CSLoader_setRecordJsonPath(lua_State* tolua_S) return 0; } +int lua_cocos2dx_csloader_CSLoader_createNodeWithFlatBuffersForSimulator(lua_State* tolua_S) +{ + int argc = 0; + cocos2d::CSLoader* cobj = nullptr; + bool ok = true; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; +#endif + + +#if COCOS2D_DEBUG >= 1 + if (!tolua_isusertype(tolua_S,1,"cc.CSLoader",0,&tolua_err)) goto tolua_lerror; +#endif + + cobj = (cocos2d::CSLoader*)tolua_tousertype(tolua_S,1,0); + +#if COCOS2D_DEBUG >= 1 + if (!cobj) + { + tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_csloader_CSLoader_createNodeWithFlatBuffersForSimulator'", nullptr); + return 0; + } +#endif + + argc = lua_gettop(tolua_S)-1; + if (argc == 1) + { + std::string arg0; + + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "cc.CSLoader:createNodeWithFlatBuffersForSimulator"); + if(!ok) + { + tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_csloader_CSLoader_createNodeWithFlatBuffersForSimulator'", nullptr); + return 0; + } + cocos2d::Node* ret = cobj->createNodeWithFlatBuffersForSimulator(arg0); + object_to_luaval(tolua_S, "cc.Node",(cocos2d::Node*)ret); + return 1; + } + luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.CSLoader:createNodeWithFlatBuffersForSimulator",argc, 1); + return 0; + +#if COCOS2D_DEBUG >= 1 + tolua_lerror: + tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_csloader_CSLoader_createNodeWithFlatBuffersForSimulator'.",&tolua_err); +#endif + + return 0; +} int lua_cocos2dx_csloader_CSLoader_destroyInstance(lua_State* tolua_S) { int argc = 0; @@ -710,6 +760,7 @@ int lua_register_cocos2dx_csloader_CSLoader(lua_State* tolua_S) tolua_function(tolua_S,"isRecordJsonPath",lua_cocos2dx_csloader_CSLoader_isRecordJsonPath); tolua_function(tolua_S,"getJsonPath",lua_cocos2dx_csloader_CSLoader_getJsonPath); tolua_function(tolua_S,"setRecordJsonPath",lua_cocos2dx_csloader_CSLoader_setRecordJsonPath); + tolua_function(tolua_S,"createNodeWithFlatBuffersForSimulator",lua_cocos2dx_csloader_CSLoader_createNodeWithFlatBuffersForSimulator); tolua_function(tolua_S,"destroyInstance", lua_cocos2dx_csloader_CSLoader_destroyInstance); tolua_function(tolua_S,"createNode", lua_cocos2dx_csloader_CSLoader_createNode); tolua_function(tolua_S,"getInstance", lua_cocos2dx_csloader_CSLoader_getInstance); diff --git a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_csloader_auto.hpp b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_csloader_auto.hpp index bdedab007e..4c4e5bc666 100644 --- a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_csloader_auto.hpp +++ b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_csloader_auto.hpp @@ -28,4 +28,5 @@ int register_all_cocos2dx_csloader(lua_State* tolua_S); + #endif // __cocos2dx_csloader_h__ diff --git a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.cpp b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.cpp index 5d6646a6e3..d92c0e0824 100644 --- a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.cpp +++ b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.cpp @@ -2590,6 +2590,112 @@ int lua_register_cocos2dx_studio_ActionObject(lua_State* tolua_S) return 1; } +int lua_cocos2dx_studio_ActionManagerEx_stopActionByName(lua_State* tolua_S) +{ + int argc = 0; + cocostudio::ActionManagerEx* cobj = nullptr; + bool ok = true; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; +#endif + + +#if COCOS2D_DEBUG >= 1 + if (!tolua_isusertype(tolua_S,1,"ccs.ActionManagerEx",0,&tolua_err)) goto tolua_lerror; +#endif + + cobj = (cocostudio::ActionManagerEx*)tolua_tousertype(tolua_S,1,0); + +#if COCOS2D_DEBUG >= 1 + if (!cobj) + { + tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_studio_ActionManagerEx_stopActionByName'", nullptr); + return 0; + } +#endif + + argc = lua_gettop(tolua_S)-1; + if (argc == 2) + { + const char* arg0; + const char* arg1; + + std::string arg0_tmp; ok &= luaval_to_std_string(tolua_S, 2, &arg0_tmp, "ccs.ActionManagerEx:stopActionByName"); arg0 = arg0_tmp.c_str(); + + std::string arg1_tmp; ok &= luaval_to_std_string(tolua_S, 3, &arg1_tmp, "ccs.ActionManagerEx:stopActionByName"); arg1 = arg1_tmp.c_str(); + if(!ok) + { + tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ActionManagerEx_stopActionByName'", nullptr); + return 0; + } + cocostudio::ActionObject* ret = cobj->stopActionByName(arg0, arg1); + object_to_luaval(tolua_S, "ccs.ActionObject",(cocostudio::ActionObject*)ret); + return 1; + } + luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccs.ActionManagerEx:stopActionByName",argc, 2); + return 0; + +#if COCOS2D_DEBUG >= 1 + tolua_lerror: + tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_studio_ActionManagerEx_stopActionByName'.",&tolua_err); +#endif + + return 0; +} +int lua_cocos2dx_studio_ActionManagerEx_getActionByName(lua_State* tolua_S) +{ + int argc = 0; + cocostudio::ActionManagerEx* cobj = nullptr; + bool ok = true; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; +#endif + + +#if COCOS2D_DEBUG >= 1 + if (!tolua_isusertype(tolua_S,1,"ccs.ActionManagerEx",0,&tolua_err)) goto tolua_lerror; +#endif + + cobj = (cocostudio::ActionManagerEx*)tolua_tousertype(tolua_S,1,0); + +#if COCOS2D_DEBUG >= 1 + if (!cobj) + { + tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_studio_ActionManagerEx_getActionByName'", nullptr); + return 0; + } +#endif + + argc = lua_gettop(tolua_S)-1; + if (argc == 2) + { + const char* arg0; + const char* arg1; + + std::string arg0_tmp; ok &= luaval_to_std_string(tolua_S, 2, &arg0_tmp, "ccs.ActionManagerEx:getActionByName"); arg0 = arg0_tmp.c_str(); + + std::string arg1_tmp; ok &= luaval_to_std_string(tolua_S, 3, &arg1_tmp, "ccs.ActionManagerEx:getActionByName"); arg1 = arg1_tmp.c_str(); + if(!ok) + { + tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ActionManagerEx_getActionByName'", nullptr); + return 0; + } + cocostudio::ActionObject* ret = cobj->getActionByName(arg0, arg1); + object_to_luaval(tolua_S, "ccs.ActionObject",(cocostudio::ActionObject*)ret); + return 1; + } + luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccs.ActionManagerEx:getActionByName",argc, 2); + return 0; + +#if COCOS2D_DEBUG >= 1 + tolua_lerror: + tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_studio_ActionManagerEx_getActionByName'.",&tolua_err); +#endif + + return 0; +} int lua_cocos2dx_studio_ActionManagerEx_playActionByName(lua_State* tolua_S) { int argc = 0; @@ -2657,59 +2763,6 @@ int lua_cocos2dx_studio_ActionManagerEx_playActionByName(lua_State* tolua_S) return 0; } -int lua_cocos2dx_studio_ActionManagerEx_getActionByName(lua_State* tolua_S) -{ - int argc = 0; - cocostudio::ActionManagerEx* cobj = nullptr; - bool ok = true; - -#if COCOS2D_DEBUG >= 1 - tolua_Error tolua_err; -#endif - - -#if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,1,"ccs.ActionManagerEx",0,&tolua_err)) goto tolua_lerror; -#endif - - cobj = (cocostudio::ActionManagerEx*)tolua_tousertype(tolua_S,1,0); - -#if COCOS2D_DEBUG >= 1 - if (!cobj) - { - tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_studio_ActionManagerEx_getActionByName'", nullptr); - return 0; - } -#endif - - argc = lua_gettop(tolua_S)-1; - if (argc == 2) - { - const char* arg0; - const char* arg1; - - std::string arg0_tmp; ok &= luaval_to_std_string(tolua_S, 2, &arg0_tmp, "ccs.ActionManagerEx:getActionByName"); arg0 = arg0_tmp.c_str(); - - std::string arg1_tmp; ok &= luaval_to_std_string(tolua_S, 3, &arg1_tmp, "ccs.ActionManagerEx:getActionByName"); arg1 = arg1_tmp.c_str(); - if(!ok) - { - tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ActionManagerEx_getActionByName'", nullptr); - return 0; - } - cocostudio::ActionObject* ret = cobj->getActionByName(arg0, arg1); - object_to_luaval(tolua_S, "ccs.ActionObject",(cocostudio::ActionObject*)ret); - return 1; - } - luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccs.ActionManagerEx:getActionByName",argc, 2); - return 0; - -#if COCOS2D_DEBUG >= 1 - tolua_lerror: - tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_studio_ActionManagerEx_getActionByName'.",&tolua_err); -#endif - - return 0; -} int lua_cocos2dx_studio_ActionManagerEx_releaseActions(lua_State* tolua_S) { int argc = 0; @@ -2835,8 +2888,9 @@ int lua_register_cocos2dx_studio_ActionManagerEx(lua_State* tolua_S) tolua_cclass(tolua_S,"ActionManagerEx","ccs.ActionManagerEx","cc.Ref",nullptr); tolua_beginmodule(tolua_S,"ActionManagerEx"); - tolua_function(tolua_S,"playActionByName",lua_cocos2dx_studio_ActionManagerEx_playActionByName); + tolua_function(tolua_S,"stopActionByName",lua_cocos2dx_studio_ActionManagerEx_stopActionByName); tolua_function(tolua_S,"getActionByName",lua_cocos2dx_studio_ActionManagerEx_getActionByName); + tolua_function(tolua_S,"playActionByName",lua_cocos2dx_studio_ActionManagerEx_playActionByName); tolua_function(tolua_S,"releaseActions",lua_cocos2dx_studio_ActionManagerEx_releaseActions); tolua_function(tolua_S,"destroyInstance", lua_cocos2dx_studio_ActionManagerEx_destroyInstance); tolua_function(tolua_S,"getInstance", lua_cocos2dx_studio_ActionManagerEx_getInstance); @@ -15554,6 +15608,56 @@ int lua_cocos2dx_studio_ActionTimelineCache_removeAction(lua_State* tolua_S) return 0; } +int lua_cocos2dx_studio_ActionTimelineCache_createActionWithFlatBuffersForSimulator(lua_State* tolua_S) +{ + int argc = 0; + cocostudio::timeline::ActionTimelineCache* cobj = nullptr; + bool ok = true; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; +#endif + + +#if COCOS2D_DEBUG >= 1 + if (!tolua_isusertype(tolua_S,1,"ccs.ActionTimelineCache",0,&tolua_err)) goto tolua_lerror; +#endif + + cobj = (cocostudio::timeline::ActionTimelineCache*)tolua_tousertype(tolua_S,1,0); + +#if COCOS2D_DEBUG >= 1 + if (!cobj) + { + tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_studio_ActionTimelineCache_createActionWithFlatBuffersForSimulator'", nullptr); + return 0; + } +#endif + + argc = lua_gettop(tolua_S)-1; + if (argc == 1) + { + std::string arg0; + + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccs.ActionTimelineCache:createActionWithFlatBuffersForSimulator"); + if(!ok) + { + tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_ActionTimelineCache_createActionWithFlatBuffersForSimulator'", nullptr); + return 0; + } + cocostudio::timeline::ActionTimeline* ret = cobj->createActionWithFlatBuffersForSimulator(arg0); + object_to_luaval(tolua_S, "ccs.ActionTimeline",(cocostudio::timeline::ActionTimeline*)ret); + return 1; + } + luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccs.ActionTimelineCache:createActionWithFlatBuffersForSimulator",argc, 1); + return 0; + +#if COCOS2D_DEBUG >= 1 + tolua_lerror: + tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_studio_ActionTimelineCache_createActionWithFlatBuffersForSimulator'.",&tolua_err); +#endif + + return 0; +} int lua_cocos2dx_studio_ActionTimelineCache_destroyInstance(lua_State* tolua_S) { int argc = 0; @@ -15643,6 +15747,7 @@ int lua_register_cocos2dx_studio_ActionTimelineCache(lua_State* tolua_S) tolua_function(tolua_S,"loadAnimationActionWithFile",lua_cocos2dx_studio_ActionTimelineCache_loadAnimationActionWithFile); tolua_function(tolua_S,"loadAnimationActionWithContent",lua_cocos2dx_studio_ActionTimelineCache_loadAnimationActionWithContent); tolua_function(tolua_S,"removeAction",lua_cocos2dx_studio_ActionTimelineCache_removeAction); + tolua_function(tolua_S,"createActionWithFlatBuffersForSimulator",lua_cocos2dx_studio_ActionTimelineCache_createActionWithFlatBuffersForSimulator); tolua_function(tolua_S,"destroyInstance", lua_cocos2dx_studio_ActionTimelineCache_destroyInstance); tolua_function(tolua_S,"createAction", lua_cocos2dx_studio_ActionTimelineCache_createAction); tolua_endmodule(tolua_S); @@ -18794,6 +18899,55 @@ int lua_cocos2dx_studio_EventFrame_init(lua_State* tolua_S) return 0; } +int lua_cocos2dx_studio_EventFrame_setNode(lua_State* tolua_S) +{ + int argc = 0; + cocostudio::timeline::EventFrame* cobj = nullptr; + bool ok = true; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; +#endif + + +#if COCOS2D_DEBUG >= 1 + if (!tolua_isusertype(tolua_S,1,"ccs.EventFrame",0,&tolua_err)) goto tolua_lerror; +#endif + + cobj = (cocostudio::timeline::EventFrame*)tolua_tousertype(tolua_S,1,0); + +#if COCOS2D_DEBUG >= 1 + if (!cobj) + { + tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_studio_EventFrame_setNode'", nullptr); + return 0; + } +#endif + + argc = lua_gettop(tolua_S)-1; + if (argc == 1) + { + cocos2d::Node* arg0; + + ok &= luaval_to_object(tolua_S, 2, "cc.Node",&arg0); + if(!ok) + { + tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_EventFrame_setNode'", nullptr); + return 0; + } + cobj->setNode(arg0); + return 0; + } + luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccs.EventFrame:setNode",argc, 1); + return 0; + +#if COCOS2D_DEBUG >= 1 + tolua_lerror: + tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_studio_EventFrame_setNode'.",&tolua_err); +#endif + + return 0; +} int lua_cocos2dx_studio_EventFrame_getEvent(lua_State* tolua_S) { int argc = 0; @@ -18927,6 +19081,7 @@ int lua_register_cocos2dx_studio_EventFrame(lua_State* tolua_S) tolua_function(tolua_S,"new",lua_cocos2dx_studio_EventFrame_constructor); tolua_function(tolua_S,"setEvent",lua_cocos2dx_studio_EventFrame_setEvent); tolua_function(tolua_S,"init",lua_cocos2dx_studio_EventFrame_init); + tolua_function(tolua_S,"setNode",lua_cocos2dx_studio_EventFrame_setNode); tolua_function(tolua_S,"getEvent",lua_cocos2dx_studio_EventFrame_getEvent); tolua_function(tolua_S,"create", lua_cocos2dx_studio_EventFrame_create); tolua_endmodule(tolua_S); diff --git a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.hpp b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.hpp index 1f5778d277..4d6cac2de3 100644 --- a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.hpp +++ b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.hpp @@ -483,6 +483,9 @@ int register_all_cocos2dx_studio(lua_State* tolua_S); + + + diff --git a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.cpp b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.cpp index c91c046408..070dbf613e 100644 --- a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.cpp +++ b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.cpp @@ -10774,7 +10774,42 @@ int lua_cocos2dx_ui_LoadingBar_create(lua_State* tolua_S) } } while (0); ok = true; - luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d", "ccui.LoadingBar:create",argc, 0); + do + { + if (argc == 2) + { + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.LoadingBar:create"); + if (!ok) { break; } + cocos2d::ui::Widget::TextureResType arg1; + ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.LoadingBar:create"); + if (!ok) { break; } + cocos2d::ui::LoadingBar* ret = cocos2d::ui::LoadingBar::create(arg0, arg1); + object_to_luaval(tolua_S, "ccui.LoadingBar",(cocos2d::ui::LoadingBar*)ret); + return 1; + } + } while (0); + ok = true; + do + { + if (argc == 3) + { + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccui.LoadingBar:create"); + if (!ok) { break; } + cocos2d::ui::Widget::TextureResType arg1; + ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "ccui.LoadingBar:create"); + if (!ok) { break; } + double arg2; + ok &= luaval_to_number(tolua_S, 4,&arg2, "ccui.LoadingBar:create"); + if (!ok) { break; } + cocos2d::ui::LoadingBar* ret = cocos2d::ui::LoadingBar::create(arg0, arg1, arg2); + object_to_luaval(tolua_S, "ccui.LoadingBar",(cocos2d::ui::LoadingBar*)ret); + return 1; + } + } while (0); + ok = true; + luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d", "ccui.LoadingBar:create",argc, 2); return 0; #if COCOS2D_DEBUG >= 1 tolua_lerror: diff --git a/cocos/scripting/lua-bindings/manual/network/lua_cocos2dx_network_manual.cpp b/cocos/scripting/lua-bindings/manual/network/lua_cocos2dx_network_manual.cpp index 8a79fefe0b..d8da25c163 100644 --- a/cocos/scripting/lua-bindings/manual/network/lua_cocos2dx_network_manual.cpp +++ b/cocos/scripting/lua-bindings/manual/network/lua_cocos2dx_network_manual.cpp @@ -44,7 +44,7 @@ int register_network_module(lua_State* L) luaopen_lua_extensions(L); #endif -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 || CC_TARGET_PLATFORM == CC_PLATFORM_MAC) tolua_web_socket_open(L); register_web_socket_manual(L); #endif diff --git a/cocos/scripting/lua-bindings/script/cocos2d/Cocos2dConstants.lua b/cocos/scripting/lua-bindings/script/cocos2d/Cocos2dConstants.lua index 641ac22a0d..defb4a51b8 100644 --- a/cocos/scripting/lua-bindings/script/cocos2d/Cocos2dConstants.lua +++ b/cocos/scripting/lua-bindings/script/cocos2d/Cocos2dConstants.lua @@ -327,8 +327,11 @@ cc.KeyCodeKey = "KEY_RETURN", "KEY_CAPS_LOCK", "KEY_SHIFT", + "KEY_RIGHT_SHIFT", "KEY_CTRL", + "KEY_RIGHT_CTRL", "KEY_ALT", + "KEY_RIGHT_ALT", "KEY_MENU", "KEY_HYPER", "KEY_INSERT", @@ -488,6 +491,9 @@ for k,v in ipairs(cc.KeyCodeKey) do end cc.KeyCode.KEY_BACK = cc.KeyCode.KEY_ESCAPE +cc.KeyCode.KEY_LEFT_SHIFT = cc.KeyCode.KEY_SHIFT +cc.KeyCode.KEY_LEFT_CTRL = cc.KeyCode.KEY_CTRL +cc.KeyCode.KEY_LEFT_ALT = cc.KeyCode.KEY_ALT cc.EventAssetsManagerEx = { diff --git a/cocos/ui/UIButton.cpp b/cocos/ui/UIButton.cpp index 1d4a45fafb..5b08712d60 100644 --- a/cocos/ui/UIButton.cpp +++ b/cocos/ui/UIButton.cpp @@ -24,6 +24,7 @@ THE SOFTWARE. #include "ui/UIButton.h" #include "ui/UIScale9Sprite.h" +#include "ui/UIHelper.h" #include "2d/CCLabel.h" #include "2d/CCSprite.h" #include "2d/CCActionInterval.h" @@ -101,7 +102,8 @@ Button* Button::create(const std::string &normalImage, TextureResType texType) { Button *btn = new (std::nothrow) Button; - if (btn && btn->init(normalImage,selectedImage,disableImage,texType)) { + if (btn && btn->init(normalImage,selectedImage,disableImage,texType)) + { btn->autorelease(); return btn; } @@ -115,8 +117,10 @@ bool Button::init(const std::string &normalImage, TextureResType texType) { bool ret = true; - do { - if (!Widget::init()) { + do + { + if (!Widget::init()) + { ret = false; break; } @@ -197,6 +201,7 @@ void Button::ignoreContentAdaptWithSize(bool ignore) this->updateContentSize(); return; } + if (!_scale9Enabled || (_scale9Enabled && !ignore)) { Widget::ignoreContentAdaptWithSize(ignore); @@ -319,97 +324,54 @@ void Button::setCapInsets(const Rect &capInsets) setCapInsetsDisabledRenderer(capInsets); } + + void Button::setCapInsetsNormalRenderer(const Rect &capInsets) { - float x = capInsets.origin.x; - float y = capInsets.origin.y; - float width = capInsets.size.width; - float height = capInsets.size.height; + _capInsetsNormal = Helper::restrictCapInsetRect(capInsets, this->_normalTextureSize); - if (_normalTextureSize.width < width) - { - x = 0.0f; - width = 0.0f; - } - if (_normalTextureSize.height < height) - { - y = 0.0f; - height = 0.0f; - } - Rect rect(x, y, width, height); - - _capInsetsNormal = rect; + //for performance issue if (!_scale9Enabled) { return; } - _buttonNormalRenderer->setCapInsets(rect); + _buttonNormalRenderer->setCapInsets(_capInsetsNormal); +} + +void Button::setCapInsetsPressedRenderer(const Rect &capInsets) +{ + _capInsetsPressed = Helper::restrictCapInsetRect(capInsets, this->_pressedTextureSize); + + //for performance issue + if (!_scale9Enabled) + { + return; + } + _buttonClickedRenderer->setCapInsets(_capInsetsPressed); +} + +void Button::setCapInsetsDisabledRenderer(const Rect &capInsets) +{ + _capInsetsDisabled = Helper::restrictCapInsetRect(capInsets, this->_disabledTextureSize); + + //for performance issue + if (!_scale9Enabled) + { + return; + } + _buttonDisableRenderer->setCapInsets(_capInsetsDisabled); } const Rect& Button::getCapInsetsNormalRenderer()const { return _capInsetsNormal; } - -void Button::setCapInsetsPressedRenderer(const Rect &capInsets) -{ - float x = capInsets.origin.x; - float y = capInsets.origin.y; - float width = capInsets.size.width; - float height = capInsets.size.height; - if (_pressedTextureSize.width < width) - { - x = 0.0f; - width = 0.0f; - } - if (_pressedTextureSize.height < height) - { - y = 0.0f; - height = 0.0f; - } - Rect rect(x, y, width, height); - - _capInsetsPressed = rect; - if (!_scale9Enabled) - { - return; - } - _buttonClickedRenderer->setCapInsets(rect); -} - const Rect& Button::getCapInsetsPressedRenderer()const { return _capInsetsPressed; } - -void Button::setCapInsetsDisabledRenderer(const Rect &capInsets) -{ - float x = capInsets.origin.x; - float y = capInsets.origin.y; - float width = capInsets.size.width; - float height = capInsets.size.height; - if (_disabledTextureSize.width < width) - { - x = 0.0f; - width = 0.0f; - } - if (_disabledTextureSize.height < height) - { - y = 0.0f; - height = 0.0f; - } - Rect rect(x, y, width, height); - - _capInsetsDisabled = rect; - if (!_scale9Enabled) - { - return; - } - _buttonDisableRenderer->setCapInsets(rect); -} - const Rect& Button::getCapInsetsDisabledRenderer()const { return _capInsetsDisabled; @@ -557,7 +519,9 @@ void Button::updateContentSize() onSizeChanged(); return; } - if (_ignoreSize) { + + if (_ignoreSize) + { this->setContentSize(getVirtualRendererSize()); } } @@ -578,11 +542,13 @@ void Button::adaptRenderers() normalTextureScaleChangedWithSize(); _normalTextureAdaptDirty = false; } + if (_pressedTextureAdaptDirty) { pressedTextureScaleChangedWithSize(); _pressedTextureAdaptDirty = false; } + if (_disabledTextureAdaptDirty) { disabledTextureScaleChangedWithSize(); @@ -596,8 +562,10 @@ Size Button::getVirtualRendererSize() const { return this->getNormalSize(); } + Size titleSize = _titleRenderer->getContentSize(); - if (!_normalTextureLoaded && _titleRenderer->getString().size() > 0) { + if (!_normalTextureLoaded && _titleRenderer->getString().size() > 0) + { return titleSize; } return _normalTextureSize; @@ -766,10 +734,12 @@ const Color3B& Button::getTitleColor() const void Button::setTitleFontSize(float size) { - if (_type == FontType::SYSTEM) { + if (_type == FontType::SYSTEM) + { _titleRenderer->setSystemFontSize(size); } - else{ + else + { TTFConfig config = _titleRenderer->getTTFConfig(); config.fontSize = size; _titleRenderer->setTTFConfig(config); @@ -802,7 +772,9 @@ void Button::setTitleFontName(const std::string& fontName) config.fontSize = _fontSize; _titleRenderer->setTTFConfig(config); _type = FontType::TTF; - } else{ + } + else + { _titleRenderer->setSystemFontName(fontName); if (_type == FontType::TTF) { @@ -864,6 +836,7 @@ Size Button::getNormalSize() const { titleSize = _titleRenderer->getContentSize(); } + Size imageSize; if (_buttonNormalRenderer != nullptr) { diff --git a/cocos/ui/UICheckBox.cpp b/cocos/ui/UICheckBox.cpp index a2dc739b43..9f13684cc8 100644 --- a/cocos/ui/UICheckBox.cpp +++ b/cocos/ui/UICheckBox.cpp @@ -112,8 +112,10 @@ bool CheckBox::init(const std::string& backGround, TextureResType texType) { bool ret = true; - do { - if (!Widget::init()) { + do + { + if (!Widget::init()) + { ret = false; break; } @@ -191,10 +193,12 @@ void CheckBox::loadTextureBackGround(const std::string& backGround,TextureResTyp void CheckBox::loadTextureBackGroundSelected(const std::string& backGroundSelected,TextureResType texType) { - if (backGroundSelected.empty() || (_backGroundSelectedFileName == backGroundSelected && _backGroundSelectedTexType == texType)) + if (backGroundSelected.empty() || + (_backGroundSelectedFileName == backGroundSelected && _backGroundSelectedTexType == texType)) { return; } + _backGroundSelectedFileName = backGroundSelected; _backGroundSelectedTexType = texType; switch (_backGroundSelectedTexType) @@ -241,7 +245,8 @@ void CheckBox::loadTextureFrontCross(const std::string& cross,TextureResType tex void CheckBox::loadTextureBackGroundDisabled(const std::string& backGroundDisabled,TextureResType texType) { - if (backGroundDisabled.empty() || (_backGroundDisabledFileName == backGroundDisabled && _backGroundDisabledTexType == texType)) + if (backGroundDisabled.empty() || + (_backGroundDisabledFileName == backGroundDisabled && _backGroundDisabledTexType == texType)) { return; } @@ -266,7 +271,8 @@ void CheckBox::loadTextureBackGroundDisabled(const std::string& backGroundDisabl void CheckBox::loadTextureFrontCrossDisabled(const std::string& frontCrossDisabled,TextureResType texType) { - if (frontCrossDisabled.empty() || (_frontCrossDisabledFileName == frontCrossDisabled && _frontCrossDisabledTexType == texType)) + if (frontCrossDisabled.empty() || + (_frontCrossDisabledFileName == frontCrossDisabled && _frontCrossDisabledTexType == texType)) { return; } @@ -294,7 +300,8 @@ void CheckBox::releaseUpEvent() { Widget::releaseUpEvent(); - if (_isSelected){ + if (_isSelected) + { setSelected(false); unSelectedEvent(); } @@ -312,6 +319,7 @@ void CheckBox::onPressStateChangedToNormal() _backGroundSelectedBoxRenderer->setVisible(false); _backGroundBoxDisabledRenderer->setVisible(false); _frontCrossDisabledRenderer->setVisible(false); + if (_isSelected) { _frontCrossRenderer->setVisible(true); @@ -375,7 +383,8 @@ void CheckBox::selectedEvent() void CheckBox::unSelectedEvent() { this->retain(); - if (_checkBoxEventCallback) { + if (_checkBoxEventCallback) + { _checkBoxEventCallback(this, EventType::UNSELECTED); } if (_ccEventCallback) diff --git a/cocos/ui/UIEditBox/UIEditBoxImpl-ios.h b/cocos/ui/UIEditBox/UIEditBoxImpl-ios.h index 20a3636481..5ac51bdd65 100644 --- a/cocos/ui/UIEditBox/UIEditBoxImpl-ios.h +++ b/cocos/ui/UIEditBox/UIEditBoxImpl-ios.h @@ -132,7 +132,6 @@ private: Vec2 _anchorPoint; UIEditBoxImplIOS_objc* _systemControl; int _maxTextLength; - bool _inRetinaMode; }; diff --git a/cocos/ui/UIEditBox/UIEditBoxImpl-ios.mm b/cocos/ui/UIEditBox/UIEditBoxImpl-ios.mm index 600ed3ee0e..cddb47be36 100644 --- a/cocos/ui/UIEditBox/UIEditBoxImpl-ios.mm +++ b/cocos/ui/UIEditBox/UIEditBoxImpl-ios.mm @@ -279,9 +279,6 @@ EditBoxImplIOS::EditBoxImplIOS(EditBox* pEditText) , _systemControl(nullptr) , _maxTextLength(-1) { - auto view = cocos2d::Director::getInstance()->getOpenGLView(); - - _inRetinaMode = view->isRetinaDisplay(); } EditBoxImplIOS::~EditBoxImplIOS() @@ -305,11 +302,10 @@ bool EditBoxImplIOS::initWithSize(const Size& size) CGRect rect = CGRectMake(0, 0, size.width * glview->getScaleX(),size.height * glview->getScaleY()); - if (_inRetinaMode) - { - rect.size.width /= 2.0f; - rect.size.height /= 2.0f; - } + CCEAGLView *eaglview = static_cast(glview->getEAGLView()); + float factor = eaglview.contentScaleFactor; + rect.size.width /= factor; + rect.size.height /= factor; _systemControl = [[UIEditBoxImplIOS_objc alloc] initWithFrame:rect editBox:this]; if (!_systemControl) break; @@ -376,7 +372,8 @@ void EditBoxImplIOS::setFont(const char* pFontName, int fontSize) isValidFontName = false; } - float retinaFactor = _inRetinaMode ? 2.0f : 1.0f; + CCEAGLView *eaglview = static_cast(cocos2d::Director::getInstance()->getOpenGLView()->getEAGLView()); + float retinaFactor = eaglview.contentScaleFactor; NSString * fntName = [NSString stringWithUTF8String:pFontName]; auto glview = cocos2d::Director::getInstance()->getOpenGLView(); @@ -554,7 +551,7 @@ void EditBoxImplIOS::setPlaceHolder(const char* pText) _labelPlaceHolder->setString(pText); } -static CGPoint convertDesignCoordToScreenCoord(const Vec2& designCoord, bool bInRetinaMode) +static CGPoint convertDesignCoordToScreenCoord(const Vec2& designCoord) { auto glview = cocos2d::Director::getInstance()->getOpenGLView(); CCEAGLView *eaglview = (CCEAGLView *) glview->getEAGLView(); @@ -566,11 +563,10 @@ static CGPoint convertDesignCoordToScreenCoord(const Vec2& designCoord, bool bIn CGPoint screenPos = CGPointMake(screenGLPos.x, viewH - screenGLPos.y); - if (bInRetinaMode) - { - screenPos.x = screenPos.x / 2.0f; - screenPos.y = screenPos.y / 2.0f; - } + float factor = eaglview.contentScaleFactor; + screenPos.x = screenPos.x / factor; + screenPos.y = screenPos.y / factor; + CCLOGINFO("[EditBox] pos x = %f, y = %f", screenGLPos.x, screenGLPos.y); return screenPos; } @@ -594,11 +590,11 @@ void EditBoxImplIOS::setContentSize(const Size& size) auto glview = cocos2d::Director::getInstance()->getOpenGLView(); CGSize controlSize = CGSizeMake(size.width * glview->getScaleX(),size.height * glview->getScaleY()); - if (_inRetinaMode) - { - controlSize.width /= 2.0f; - controlSize.height /= 2.0f; - } + CCEAGLView *eaglview = static_cast(glview->getEAGLView()); + float factor = eaglview.contentScaleFactor; + controlSize.width /= factor; + controlSize.height /= factor; + [_systemControl setContentSize:controlSize]; } @@ -638,7 +634,7 @@ void EditBoxImplIOS::adjustTextFieldPosition() rect = RectApplyAffineTransform(rect, _editBox->nodeToWorldTransform()); Vec2 designCoord = Vec2(rect.origin.x, rect.origin.y + rect.size.height); - [_systemControl setPosition:convertDesignCoordToScreenCoord(designCoord, _inRetinaMode)]; + [_systemControl setPosition:convertDesignCoordToScreenCoord(designCoord)]; } void EditBoxImplIOS::openKeyboard() diff --git a/cocos/ui/UIHelper.cpp b/cocos/ui/UIHelper.cpp index 67eba0490c..8335944b55 100644 --- a/cocos/ui/UIHelper.cpp +++ b/cocos/ui/UIHelper.cpp @@ -183,6 +183,26 @@ void Helper::doLayout(cocos2d::Node *rootNode) } } } + +Rect Helper::restrictCapInsetRect(const cocos2d::Rect &capInsets, const Size& textureSize ) +{ + float x = capInsets.origin.x; + float y = capInsets.origin.y; + float width = capInsets.size.width; + float height = capInsets.size.height; + + if (textureSize.width < width) + { + x = 0.0f; + width = 0.0f; + } + if (textureSize.height < height) + { + y = 0.0f; + height = 0.0f; + } + return Rect(x, y, width, height); +} } NS_CC_END diff --git a/cocos/ui/UIHelper.h b/cocos/ui/UIHelper.h index 072fcc79e8..5f86288960 100644 --- a/cocos/ui/UIHelper.h +++ b/cocos/ui/UIHelper.h @@ -82,6 +82,10 @@ public: static void doLayout(Node *rootNode); static void changeLayoutSystemActiveState(bool bActive); + +private: + static Rect restrictCapInsetRect(const Rect& capInsets, const Size& textureSize); + friend class Button; }; } diff --git a/cocos/ui/UIImageView.cpp b/cocos/ui/UIImageView.cpp index c9e0590182..36f0d222eb 100644 --- a/cocos/ui/UIImageView.cpp +++ b/cocos/ui/UIImageView.cpp @@ -55,7 +55,8 @@ ImageView::~ImageView() ImageView* ImageView::create(const std::string &imageFileName, TextureResType texType) { ImageView *widget = new (std::nothrow) ImageView; - if (widget && widget->init(imageFileName, texType)) { + if (widget && widget->init(imageFileName, texType)) + { widget->autorelease(); return widget; } @@ -78,8 +79,10 @@ ImageView* ImageView::create() bool ImageView::init() { bool ret = true; - do { - if (!Widget::init()) { + do + { + if (!Widget::init()) + { ret = false; break; } @@ -91,8 +94,10 @@ bool ImageView::init() bool ImageView::init(const std::string &imageFileName, TextureResType texType) { bool bRet = true; - do { - if (!Widget::init()) { + do + { + if (!Widget::init()) + { bRet = false; break; } diff --git a/cocos/ui/UILayout.cpp b/cocos/ui/UILayout.cpp index 9b75316cbf..6274d514d0 100644 --- a/cocos/ui/UILayout.cpp +++ b/cocos/ui/UILayout.cpp @@ -359,7 +359,8 @@ void Layout::drawFullScreenQuadClearStencil() director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION); director->loadIdentityMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION); - Vec2 vertices[] = { + Vec2 vertices[] = + { Vec2(-1, -1), Vec2(1, -1), Vec2(1, 1), @@ -1128,25 +1129,30 @@ float Layout::calculateNearestDistance(Widget* baseWidget) Vec2 widgetPosition = this->getWorldCenterPoint(baseWidget); - for (Node* node : _children) { + for (Node* node : _children) + { Layout *layout = dynamic_cast(node); int length; - if (layout) { + if (layout) + { length = layout->calculateNearestDistance(baseWidget); } else { Widget* w = dynamic_cast(node); - if (w && w->isFocusEnabled()) { + if (w && w->isFocusEnabled()) + { Vec2 wPosition = this->getWorldCenterPoint(w); length = (wPosition - widgetPosition).length(); } - else { + else + { continue; } } - if (length < distance) { + if (length < distance) + { distance = length; } @@ -1161,10 +1167,12 @@ float Layout::calculateFarthestDistance(cocos2d::ui::Widget *baseWidget) Vec2 widgetPosition = this->getWorldCenterPoint(baseWidget); - for (Node* node : _children) { + for (Node* node : _children) + { Layout *layout = dynamic_cast(node); int length; - if (layout) { + if (layout) + { length = layout->calculateFarthestDistance(baseWidget); } else @@ -1174,12 +1182,14 @@ float Layout::calculateFarthestDistance(cocos2d::ui::Widget *baseWidget) Vec2 wPosition = this->getWorldCenterPoint(w); length = (wPosition - widgetPosition).length(); } - else { + else + { continue; } } - if (length > distance) { + if (length > distance) + { distance = length; } } @@ -1190,9 +1200,11 @@ int Layout::findFirstFocusEnabledWidgetIndex() { ssize_t index = 0; ssize_t count = this->getChildren().size(); - while (index < count) { + while (index < count) + { Widget* w = dynamic_cast(_children.at(index)); - if (w && w->isFocusEnabled()) { + if (w && w->isFocusEnabled()) + { return (int)index; } index++; @@ -1321,15 +1333,19 @@ Widget *Layout::findFirstNonLayoutWidget() for(Node *node : _children) { Layout* layout = dynamic_cast(node); - if (layout) { + if (layout) + { widget = layout->findFirstNonLayoutWidget(); - if (widget != nullptr) { + if (widget != nullptr) + { return widget; } } - else{ + else + { Widget *w = dynamic_cast(node); - if (w) { + if (w) + { widget = w; break; } @@ -1342,7 +1358,8 @@ Widget *Layout::findFirstNonLayoutWidget() void Layout::findProperSearchingFunctor(FocusDirection dir, Widget* baseWidget) { - if (baseWidget == nullptr) { + if (baseWidget == nullptr) + { return; } @@ -1350,33 +1367,52 @@ void Layout::findProperSearchingFunctor(FocusDirection dir, Widget* baseWidget) Vec2 widgetPosition = this->getWorldCenterPoint(this->findFirstNonLayoutWidget()); - if (dir == FocusDirection::LEFT) { - if (previousWidgetPosition.x > widgetPosition.x) { + if (dir == FocusDirection::LEFT) + { + if (previousWidgetPosition.x > widgetPosition.x) + { onPassFocusToChild = CC_CALLBACK_2(Layout::findNearestChildWidgetIndex, this); } - else{ + else + { onPassFocusToChild = CC_CALLBACK_2(Layout::findFarthestChildWidgetIndex, this); } - }else if(dir == FocusDirection::RIGHT){ - if (previousWidgetPosition.x > widgetPosition.x) { + } + else if(dir == FocusDirection::RIGHT) + { + if (previousWidgetPosition.x > widgetPosition.x) + { onPassFocusToChild = CC_CALLBACK_2(Layout::findFarthestChildWidgetIndex, this); } - else{ + else + { onPassFocusToChild = CC_CALLBACK_2(Layout::findNearestChildWidgetIndex, this); } - }else if(dir == FocusDirection::DOWN){ - if (previousWidgetPosition.y > widgetPosition.y) { + } + else if(dir == FocusDirection::DOWN) + { + if (previousWidgetPosition.y > widgetPosition.y) + { onPassFocusToChild = CC_CALLBACK_2(Layout::findNearestChildWidgetIndex, this); - }else{ + } + else + { onPassFocusToChild = CC_CALLBACK_2(Layout::findFarthestChildWidgetIndex, this); } - }else if(dir == FocusDirection::UP){ - if (previousWidgetPosition.y < widgetPosition.y) { + } + else if(dir == FocusDirection::UP) + { + if (previousWidgetPosition.y < widgetPosition.y) + { onPassFocusToChild = CC_CALLBACK_2(Layout::findNearestChildWidgetIndex, this); - }else{ + } + else + { onPassFocusToChild = CC_CALLBACK_2(Layout::findFarthestChildWidgetIndex, this); } - }else{ + } + else + { CCASSERT(0, "invalid direction!"); } @@ -1476,8 +1512,6 @@ Widget* Layout::getPreviousFocusedWidget(FocusDirection direction, Widget *curre nextWidget = this->getChildWidgetByIndex(previousWidgetPos); if (nextWidget->isFocusEnabled()) { - - Layout* layout = dynamic_cast(nextWidget); if (layout) { @@ -1492,7 +1526,8 @@ Widget* Layout::getPreviousFocusedWidget(FocusDirection direction, Widget *curre //handling the disabled widget, there is no actual focus lose or get, so we don't need any envet return this->getPreviousFocusedWidget(direction, nextWidget); } - }else + } + else { if (_loopFocus) { @@ -1521,7 +1556,8 @@ Widget* Layout::getPreviousFocusedWidget(FocusDirection direction, Widget *curre } else { - if (dynamic_cast(current)) { + if (dynamic_cast(current)) + { return current; } else @@ -1538,7 +1574,8 @@ Widget* Layout::getPreviousFocusedWidget(FocusDirection direction, Widget *curre { return Widget::findNextFocusedWidget(direction, this); } - if (dynamic_cast(current)) { + if (dynamic_cast(current)) + { return current; } else @@ -1567,7 +1604,6 @@ Widget* Layout::getNextFocusedWidget(FocusDirection direction, Widget *current) { if (nextWidget->isFocusEnabled()) { - Layout* layout = dynamic_cast(nextWidget); if (layout) { @@ -1589,7 +1625,8 @@ Widget* Layout::getNextFocusedWidget(FocusDirection direction, Widget *current) { return current; } - }else + } + else { if (_loopFocus) { @@ -1599,7 +1636,6 @@ Widget* Layout::getNextFocusedWidget(FocusDirection direction, Widget *current) nextWidget = this->getChildWidgetByIndex(previousWidgetPos); if (nextWidget->isFocusEnabled()) { - Layout* layout = dynamic_cast(nextWidget); if (layout) { @@ -1628,7 +1664,8 @@ Widget* Layout::getNextFocusedWidget(FocusDirection direction, Widget *current) } } } - else{ + else + { if (isLastWidgetInContainer(current, direction)) { if (isWidgetAncestorSupportLoopFocus(this, direction)) @@ -1663,7 +1700,8 @@ bool Layout::isLastWidgetInContainer(Widget* widget, FocusDirection direction)c ssize_t index = container.getIndex(widget); if (parent->getLayoutType() == Type::HORIZONTAL) { - if (direction == FocusDirection::LEFT) { + if (direction == FocusDirection::LEFT) + { if (index == 0) { return isLastWidgetInContainer(parent, direction); @@ -1673,7 +1711,8 @@ bool Layout::isLastWidgetInContainer(Widget* widget, FocusDirection direction)c return false; } } - if (direction == FocusDirection::RIGHT) { + if (direction == FocusDirection::RIGHT) + { if (index == container.size()-1) { return isLastWidgetInContainer(parent, direction); @@ -1791,8 +1830,10 @@ Widget* Layout::findNextFocusedWidget(FocusDirection direction, Widget* current) if (_passFocusToChild) { Widget * w = this->passFocusToChild(direction, current); - if (dynamic_cast(w)) { - if (parent) { + if (dynamic_cast(w)) + { + if (parent) + { parent->_isFocusPassing = true; return parent->findNextFocusedWidget(direction, this); } @@ -1800,7 +1841,8 @@ Widget* Layout::findNextFocusedWidget(FocusDirection direction, Widget* current) return w; } - if (nullptr == parent) { + if (nullptr == parent) + { return this; } parent->_isFocusPassing = true; @@ -1832,7 +1874,8 @@ Widget* Layout::findNextFocusedWidget(FocusDirection direction, Widget* current) } return current; } - else{ + else + { return Widget::findNextFocusedWidget(direction, this); } }break; diff --git a/cocos/ui/UIListView.cpp b/cocos/ui/UIListView.cpp index 0b8615eafc..23e7d9a610 100644 --- a/cocos/ui/UIListView.cpp +++ b/cocos/ui/UIListView.cpp @@ -126,14 +126,16 @@ void ListView::remedyLayoutParameter(Widget *item) { return; } - switch (_direction) { + switch (_direction) + { case Direction::VERTICAL: { LinearLayoutParameter* llp = (LinearLayoutParameter*)(item->getLayoutParameter()); if (!llp) { LinearLayoutParameter* defaultLp = LinearLayoutParameter::create(); - switch (_gravity) { + switch (_gravity) + { case Gravity::LEFT: defaultLp->setGravity(LinearLayoutParameter::LinearGravity::LEFT); break; @@ -166,7 +168,8 @@ void ListView::remedyLayoutParameter(Widget *item) { llp->setMargin(Margin(0.0f, _itemsMargin, 0.0f, 0.0f)); } - switch (_gravity) { + switch (_gravity) + { case Gravity::LEFT: llp->setGravity(LinearLayoutParameter::LinearGravity::LEFT); break; @@ -188,7 +191,8 @@ void ListView::remedyLayoutParameter(Widget *item) if (!llp) { LinearLayoutParameter* defaultLp = LinearLayoutParameter::create(); - switch (_gravity) { + switch (_gravity) + { case Gravity::TOP: defaultLp->setGravity(LinearLayoutParameter::LinearGravity::TOP); break; @@ -221,7 +225,8 @@ void ListView::remedyLayoutParameter(Widget *item) { llp->setMargin(Margin(_itemsMargin, 0.0f, 0.0f, 0.0f)); } - switch (_gravity) { + switch (_gravity) + { case Gravity::TOP: llp->setGravity(LinearLayoutParameter::LinearGravity::TOP); break; @@ -314,7 +319,8 @@ void ListView::addChild(Node* child, int zOrder, const std::string &name) void ListView::removeChild(cocos2d::Node *child, bool cleaup) { Widget* widget = dynamic_cast(child); - if (widget) { + if (widget) + { _items.eraseObject(widget); } @@ -484,6 +490,10 @@ void ListView::selectedItemEvent(TouchEventType event) if (_eventCallback) { _eventCallback(this,EventType::ON_SELECTED_ITEM_START); } + if (_ccEventCallback) + { + _ccEventCallback(this, static_cast(EventType::ON_SELECTED_ITEM_START)); + } } break; default: @@ -495,6 +505,10 @@ void ListView::selectedItemEvent(TouchEventType event) if (_eventCallback) { _eventCallback(this, EventType::ON_SELECTED_ITEM_END); } + if (_ccEventCallback) + { + _ccEventCallback(this, static_cast(EventType::ON_SELECTED_ITEM_END)); + } } break; } diff --git a/cocos/ui/UILoadingBar.cpp b/cocos/ui/UILoadingBar.cpp index 3b61062231..42a2eb7eaf 100644 --- a/cocos/ui/UILoadingBar.cpp +++ b/cocos/ui/UILoadingBar.cpp @@ -67,11 +67,19 @@ LoadingBar* LoadingBar::create() } LoadingBar* LoadingBar::create(const std::string &textureName, float percentage) +{ + return LoadingBar::create(textureName, TextureResType::LOCAL, percentage); +} + +LoadingBar* LoadingBar::create(const std::string &textureName, + TextureResType texType, + float percentage) { LoadingBar* widget = new (std::nothrow) LoadingBar; - if (widget && widget->init()) { + if (widget && widget->init()) + { widget->autorelease(); - widget->loadTexture(textureName); + widget->loadTexture(textureName,texType); widget->setPercent(percentage); return widget; } diff --git a/cocos/ui/UILoadingBar.h b/cocos/ui/UILoadingBar.h index 8e8f8317ea..058ce793ac 100644 --- a/cocos/ui/UILoadingBar.h +++ b/cocos/ui/UILoadingBar.h @@ -67,6 +67,10 @@ public: **/ static LoadingBar* create(const std::string& textureName, float percentage = 0); + static LoadingBar* create(const std::string& textureName, + TextureResType texType, + float percentage = 0); + /** * Changes the progress direction of loadingbar. * diff --git a/cocos/ui/UIPageView.cpp b/cocos/ui/UIPageView.cpp index 11b6c3a0a4..477c10e661 100644 --- a/cocos/ui/UIPageView.cpp +++ b/cocos/ui/UIPageView.cpp @@ -570,7 +570,8 @@ void PageView::pageTurningEvent() { (_pageViewEventListener->*_pageViewEventSelector)(this, PAGEVIEW_EVENT_TURNING); } - if (_eventCallback) { + if (_eventCallback) + { _eventCallback(this,EventType::TURNING); } if (_ccEventCallback) diff --git a/cocos/ui/UIScrollView.cpp b/cocos/ui/UIScrollView.cpp index 0f4ce415de..423a0baa8a 100644 --- a/cocos/ui/UIScrollView.cpp +++ b/cocos/ui/UIScrollView.cpp @@ -703,7 +703,7 @@ bool ScrollView::checkCustomScrollDestination(float* touchOffsetX, float* touchO bool scrollenabled = true; switch (_direction) { - case Direction::VERTICAL: // vertical + case Direction::VERTICAL: { if (_autoScrollDir.y > 0) { @@ -725,7 +725,7 @@ bool ScrollView::checkCustomScrollDestination(float* touchOffsetX, float* touchO } break; } - case Direction::HORIZONTAL: // horizontal + case Direction::HORIZONTAL: { if (_autoScrollDir.x > 0) { @@ -1612,7 +1612,8 @@ void ScrollView::scrollToTopEvent() { (_scrollViewEventListener->*_scrollViewEventSelector)(this, SCROLLVIEW_EVENT_SCROLL_TO_TOP); } - if (_eventCallback) { + if (_eventCallback) + { _eventCallback(this,EventType::SCROLL_TO_TOP); } if (_ccEventCallback) @@ -1629,7 +1630,8 @@ void ScrollView::scrollToBottomEvent() { (_scrollViewEventListener->*_scrollViewEventSelector)(this, SCROLLVIEW_EVENT_SCROLL_TO_BOTTOM); } - if (_eventCallback) { + if (_eventCallback) + { _eventCallback(this,EventType::SCROLL_TO_BOTTOM); } if (_ccEventCallback) @@ -1646,7 +1648,8 @@ void ScrollView::scrollToLeftEvent() { (_scrollViewEventListener->*_scrollViewEventSelector)(this, SCROLLVIEW_EVENT_SCROLL_TO_LEFT); } - if (_eventCallback) { + if (_eventCallback) + { _eventCallback(this,EventType::SCROLL_TO_LEFT); } if (_ccEventCallback) @@ -1663,7 +1666,8 @@ void ScrollView::scrollToRightEvent() { (_scrollViewEventListener->*_scrollViewEventSelector)(this, SCROLLVIEW_EVENT_SCROLL_TO_RIGHT); } - if (_eventCallback) { + if (_eventCallback) + { _eventCallback(this,EventType::SCROLL_TO_RIGHT); } if (_ccEventCallback) @@ -1680,7 +1684,8 @@ void ScrollView::scrollingEvent() { (_scrollViewEventListener->*_scrollViewEventSelector)(this, SCROLLVIEW_EVENT_SCROLLING); } - if (_eventCallback) { + if (_eventCallback) + { _eventCallback(this,EventType::SCROLLING); } if (_ccEventCallback) @@ -1697,7 +1702,8 @@ void ScrollView::bounceTopEvent() { (_scrollViewEventListener->*_scrollViewEventSelector)(this, SCROLLVIEW_EVENT_BOUNCE_TOP); } - if (_eventCallback) { + if (_eventCallback) + { _eventCallback(this,EventType::BOUNCE_TOP); } if (_ccEventCallback) @@ -1714,7 +1720,8 @@ void ScrollView::bounceBottomEvent() { (_scrollViewEventListener->*_scrollViewEventSelector)(this, SCROLLVIEW_EVENT_BOUNCE_BOTTOM); } - if (_eventCallback) { + if (_eventCallback) + { _eventCallback(this,EventType::BOUNCE_BOTTOM); } if (_ccEventCallback) @@ -1731,7 +1738,8 @@ void ScrollView::bounceLeftEvent() { (_scrollViewEventListener->*_scrollViewEventSelector)(this, SCROLLVIEW_EVENT_BOUNCE_LEFT); } - if (_eventCallback) { + if (_eventCallback) + { _eventCallback(this,EventType::BOUNCE_LEFT); } if (_ccEventCallback) @@ -1748,7 +1756,8 @@ void ScrollView::bounceRightEvent() { (_scrollViewEventListener->*_scrollViewEventSelector)(this, SCROLLVIEW_EVENT_BOUNCE_RIGHT); } - if (_eventCallback) { + if (_eventCallback) + { _eventCallback(this,EventType::BOUNCE_RIGHT); } if (_ccEventCallback) @@ -1858,7 +1867,8 @@ void ScrollView::copySpecialProperties(Widget *widget) Widget* ScrollView::findNextFocusedWidget(cocos2d::ui::Widget::FocusDirection direction, cocos2d::ui::Widget *current) { if (this->getLayoutType() == Layout::Type::VERTICAL - || this->getLayoutType() == Layout::Type::HORIZONTAL) { + || this->getLayoutType() == Layout::Type::HORIZONTAL) + { return _innerContainer->findNextFocusedWidget(direction, current); } else diff --git a/cocos/ui/UISlider.cpp b/cocos/ui/UISlider.cpp index d949f524ea..a23bde5e62 100644 --- a/cocos/ui/UISlider.cpp +++ b/cocos/ui/UISlider.cpp @@ -250,7 +250,10 @@ const Rect& Slider::getCapInsetsProgressBarRebderer()const return _capInsetsProgressBarRenderer; } - void Slider::loadSlidBallTextures(const std::string& normal,const std::string& pressed,const std::string& disabled,TextureResType texType) +void Slider::loadSlidBallTextures(const std::string& normal, + const std::string& pressed, + const std::string& disabled, + TextureResType texType) { loadSlidBallTextureNormal(normal, texType); loadSlidBallTexturePressed(pressed,texType); @@ -358,7 +361,8 @@ bool Slider::hitTest(const cocos2d::Vec2 &pt) Vec2 nsp = this->_slidBallNormalRenderer->convertToNodeSpace(pt); Size ballSize = this->_slidBallNormalRenderer->getContentSize(); Rect ballRect = Rect(0,0, ballSize.width, ballSize.height); - if (ballRect.containsPoint(nsp)) { + if (ballRect.containsPoint(nsp)) + { return true; } return false; @@ -417,7 +421,8 @@ void Slider::percentChangedEvent() { (_sliderEventListener->*_sliderEventSelector)(this,SLIDER_PERCENTCHANGED); } - if (_eventCallback) { + if (_eventCallback) + { _eventCallback(this, EventType::ON_PERCENTAGE_CHANGED); } if (_ccEventCallback) diff --git a/cocos/ui/UIText.cpp b/cocos/ui/UIText.cpp index dfdb6b84de..86434cbbdd 100644 --- a/cocos/ui/UIText.cpp +++ b/cocos/ui/UIText.cpp @@ -324,22 +324,24 @@ std::string Text::getDescription() const return "Label"; } - - -void Text::enableShadow(const Color4B& shadowColor,const Size &offset, int blurRadius) { +void Text::enableShadow(const Color4B& shadowColor,const Size &offset, int blurRadius) +{ _labelRenderer->enableShadow(shadowColor, offset, blurRadius); } -void Text::enableOutline(const Color4B& outlineColor,int outlineSize) { +void Text::enableOutline(const Color4B& outlineColor,int outlineSize) +{ _labelRenderer->enableOutline(outlineColor, outlineSize); } -void Text::enableGlow(const Color4B& glowColor) { +void Text::enableGlow(const Color4B& glowColor) +{ if (_type == Type::TTF) _labelRenderer->enableGlow(glowColor); } -void Text::disableEffect() { +void Text::disableEffect() +{ _labelRenderer->disableEffect(); } @@ -360,6 +362,7 @@ void Text::copySpecialProperties(Widget *widget) setTextHorizontalAlignment(label->_labelRenderer->getHorizontalAlignment()); setTextVerticalAlignment(label->_labelRenderer->getVerticalAlignment()); setTextAreaSize(label->_labelRenderer->getDimensions()); + setContentSize(label->getContentSize()); } } diff --git a/cocos/ui/UITextField.cpp b/cocos/ui/UITextField.cpp index 260b99c549..a4bb810d07 100644 --- a/cocos/ui/UITextField.cpp +++ b/cocos/ui/UITextField.cpp @@ -386,7 +386,8 @@ bool TextField::hitTest(const Vec2 &pt) { Vec2 nsp = convertToNodeSpace(pt); Rect bb = Rect(-_touchWidth * _anchorPoint.x, -_touchHeight * _anchorPoint.y, _touchWidth, _touchHeight); - if (nsp.x >= bb.origin.x && nsp.x <= bb.origin.x + bb.size.width && nsp.y >= bb.origin.y && nsp.y <= bb.origin.y + bb.size.height) + if (nsp.x >= bb.origin.x && nsp.x <= bb.origin.x + bb.size.width + && nsp.y >= bb.origin.y && nsp.y <= bb.origin.y + bb.size.height) { return true; } @@ -468,9 +469,12 @@ void TextField::setTextColor(const cocos2d::Color4B &textColor) void TextField::setFontSize(int size) { - if (_fontType == FontType::SYSTEM) { + if (_fontType == FontType::SYSTEM) + { _textFieldRenderer->setSystemFontSize(size); - } else { + } + else + { TTFConfig config = _textFieldRenderer->getTTFConfig(); config.fontSize = size; _textFieldRenderer->setTTFConfig(config); @@ -494,7 +498,9 @@ void TextField::setFontName(const std::string& name) config.fontSize = _fontSize; _textFieldRenderer->setTTFConfig(config); _fontType = FontType::TTF; - } else { + } + else + { _textFieldRenderer->setSystemFontName(name); if (_fontType == FontType::TTF) { @@ -533,7 +539,9 @@ bool TextField::onTouchBegan(Touch *touch, Event *unusedEvent) if (_hitted) { _textFieldRenderer->attachWithIME(); - } else { + } + else + { this->didNotSelectSelf(); } return pass; @@ -678,7 +686,8 @@ void TextField::detachWithIMEEvent() { (_textFieldEventListener->*_textFieldEventSelector)(this, TEXTFIELD_EVENT_DETACH_WITH_IME); } - if (_eventCallback) { + if (_eventCallback) + { _eventCallback(this, EventType::DETACH_WITH_IME); } if (_ccEventCallback) @@ -695,7 +704,8 @@ void TextField::insertTextEvent() { (_textFieldEventListener->*_textFieldEventSelector)(this, TEXTFIELD_EVENT_INSERT_TEXT); } - if (_eventCallback) { + if (_eventCallback) + { _eventCallback(this, EventType::INSERT_TEXT); } if (_ccEventCallback) @@ -712,7 +722,8 @@ void TextField::deleteBackwardEvent() { (_textFieldEventListener->*_textFieldEventSelector)(this, TEXTFIELD_EVENT_DELETE_BACKWARD); } - if (_eventCallback) { + if (_eventCallback) + { _eventCallback(this, EventType::DELETE_BACKWARD); } if (_ccEventCallback) diff --git a/docs/RELEASE_NOTES.md b/docs/RELEASE_NOTES.md index 0fc72cf398..10f57de840 100644 --- a/docs/RELEASE_NOTES.md +++ b/docs/RELEASE_NOTES.md @@ -1,54 +1,60 @@ -# cocos2d-x v3.3rc2 Release Notes # +# cocos2d-x v3.3 Release Notes # **Table of Contents** *generated with [DocToc](http://doctoc.herokuapp.com/)* -- [cocos2d-x v3.3rc2 Release Notes](#cocos2d-x-v33rc2-release-notes) -- [Misc Information](#misc-information) -- [Requirements](#requirements) - - [Runtime Requirements](#runtime-requirements) - - [Compiler Requirements](#compiler-requirements) - - [How to run tests](#how-to-run-tests) - - [Mac OSX & iOS](#mac-osx-&-ios) - - [Android](#android) - - [Windows](#windows) - - [Linux](#linux) - - [How to start a new game](#how-to-start-a-new-game) -- [Highlights of v3.3rc2](#highlights-of-v33rc2) -- [Notes of v3.3rc1](#notes-of-v33rc1) -- [Highlights of v3.3rc1](#highlights-of-v33rc1) -- [Notes of v3.3rc0](#notes-of-v33rc0) -- [Highlights of v3.3rc0](#highlights-of-v33rc0) -- [Features in detail](#features-in-detail) - - [Light](#light) - - [Spine runtime](#spine-runtime) - - [AssetsManagerEx](#assetsmanagerex) - - [Application::openURL](#applicationopenurl) - - [ClippingRectangleNode](#clippingrectanglenode) - - [Facebook platform support](#facebook-platform-support) -- [Highlights of v3.3beta0](#highlights-of-v33beta0) -- [Features in detail](#features-in-detail-1) - - [BillBoard](#billboard) - - [Triangles command](#triangles-command) - - [WebView](#webview) - - [New audio](#new-audio) -- [Highlights of v3.3alpha0](#highlights-of-v33alpha0) -- [Features in detail](#features-in-detail-2) - - [Camera](#camera) - - [Reskin](#reskin) - - [Attachment](#attachment) - - [Better support for FBX](#better-support-for-fbx) - - [New fbx-conv](#new-fbx-conv) - - [AABB, OBB and Ray](#aabb-obb-and-ray) - - [ui::Scale9Sprite](#uiscale9sprite) - - [c++11 random support](#c11-random-support) - - [RenderTexture save function](#rendertexture-save-function) - - [Primitive](#primitive) - - [Consistent way to set GL context attributes](#consistent-way-to-set-gl-context-attributes) - - [Only two libraries left](#only-two-libraries-left) +- [cocos2d-x v3.3 Release Notes](#) +- [Misc Information](#) +- [Requirements](#) + - [Runtime Requirements](#) + - [Compiler Requirements](#) + - [How to run tests](#) + - [Mac OSX & iOS](#) + - [Android](#) + - [Windows](#) + - [Linux](#) + - [How to start a new game](#) +- [v3.3](#) +- [v3.3rc2](#) + - [Highlights of v3.3rc2](#) + - [Notes of v3.3rc1](#) +- [v3.3rc1](#) + - [Highlights of v3.3rc1](#) + - [Notes of v3.3rc0](#) +- [v3.3rc0](#) + - [Highlights of v3.3rc0](#) + - [Features in detail](#) + - [Light](#) + - [Spine runtime](#) + - [AssetsManagerEx](#) + - [Application::openURL](#) + - [ClippingRectangleNode](#) + - [Facebook platform support](#) +- [v3.3beta0](#) + - [Highlights of v3.3beta0](#) + - [Features in detail](#) + - [BillBoard](#) + - [Triangles command](#) + - [WebView](#) + - [New audio](#) +- [v3.3alpha0](#) + - [Highlights of v3.3alpha0](#) + - [Features in detail](#) + - [Camera](#) + - [Reskin](#) + - [Attachment](#) + - [Better support for FBX](#) + - [New fbx-conv](#) + - [AABB, OBB and Ray](#) + - [ui::Scale9Sprite](#) + - [c++11 random support](#) + - [RenderTexture save function](#) + - [Primitive](#) + - [Consistent way to set GL context attributes](#) + - [Only two libraries left](#) # Misc Information -* Full Changelog: https://github.com/cocos2d/cocos2d-x/blob/cocos2d-x-3.3rc2/CHANGELOG +* Full Changelog: https://github.com/cocos2d/cocos2d-x/blob/cocos2d-x-3.3/CHANGELOG * v3.0 Release Notes can be found here: [v3.0 Release Notes](https://github.com/cocos2d/cocos2d-x/blob/cocos2d-x-3.0/docs/RELEASE_NOTES.md) # Requirements @@ -134,23 +140,31 @@ Run Please refer to this document: [ReadMe](../README.md) -# Highlights of v3.3rc2 +# v3.3 + +It just fixed some bugs since v3.3rc2. + +# v3.3rc2 + +## Highlights of v3.3rc2 * Support for android arm64 architecture, all test cases run on Nexus 9 * Cocos Studio Reader: Replace [Protobuffer](https://github.com/google/protobuf) by [FlatBuffer](https://github.com/google/flatbuffers) -# Notes of v3.3rc1 +## Notes of v3.3rc1 **android** Android NDK-r10c is needed. Here is the detailed link for this: http://discuss.cocos2d-x.org/t/build-android-base-on-ndk-r10c/18543. -# Highlights of v3.3rc1 +# v3.3rc1 + +## Highlights of v3.3rc1 * WP8: add Win8.1 universal app support * Many other bugfix. -# Notes of v3.3rc0 +## Notes of v3.3rc0 **wp8** @@ -203,7 +217,9 @@ require "cocos.init" * registerSpineEventHandler(fucntion) -> registerSpineEventHandler(funtion, eventType) -# Highlights of v3.3rc0 +# v3.3rc0 + +## Highlights of v3.3rc0 * 3d: added light support: including directional light, point light, spot light and ambient light * New audio: more platfroms supported(Mac OS X and Windows) @@ -215,9 +231,9 @@ require "cocos.init" * Node: schedule/unschedule lambda functions * Facebook platform support in `plugin` on iOS and Android, all features has been added, but the API needs to be polished with Facebook guys -# Features in detail +## Features in detail -## Light +### Light To make 3d objects looks realistic, we add lights to this version. cocos2d-x supports four types of lights, directional light, point light, spot light and ambient light. @@ -261,7 +277,7 @@ Note that we use forward render method, the number of lights can effect the perf 1 ``` -## Spine runtime +### Spine runtime Spine runtime is updated to latest version `v2.0.18`. This version supports `Free-Form-Deformation(FFD)`, which allows meshes to stretch, squash, blend and bounce in ways that aren't possible using rectangle images. @@ -269,7 +285,7 @@ Spine runtime is updated to latest version `v2.0.18`. This version supports `Fre Please refer to `tests/cpp-tests/Classes/SpineTest/SpineTest.cpp` for usage. -## AssetsManagerEx +### AssetsManagerEx `AssetsMangerEx` is an enhancement version of `AssetsManager`. Compared to `AssetsManager`, there are some pros using `AssetsManagerEx`: @@ -279,7 +295,7 @@ Please refer to `tests/cpp-tests/Classes/SpineTest/SpineTest.cpp` for usage. Please refer to [this document](http://cocos2d-x.org/wiki/Assets_manager) for detail information. -## Application::openURL +### Application::openURL Because in iOS, there is an function named `openURL` in `UIApplication`, so we added this function in Application too. You can use this function to open a url. @@ -287,7 +303,7 @@ Because in iOS, there is an function named `openURL` in `UIApplication`, so we a Application::getInstance()->openURL("http://www.cocos2d-x.org/"); ``` -## ClippingRectangleNode +### ClippingRectangleNode `ClippingRectangleNode` is a lite version of `ClippingNode`. Compared to `ClippingNode`, there re some pros and cons: @@ -308,7 +324,7 @@ auto content = Sprite::create("MyPicture.png"); clipper->addChild(content); ``` -## Facebook platform support +### Facebook platform support All features has been added, but the API needs to be polished with Facebook guys. There is a test case in `plugin` for it. Steps to run test case @@ -318,7 +334,9 @@ All features has been added, but the API needs to be polished with Facebook guys You can refer to [this document](http://www.cocos2d-x.org/wiki/Integrate_the_Facebook_SDK_for_Cocos2d-x) for detail information. -# Highlights of v3.3beta0 +# v3.3beta0 + +## Highlights of v3.3beta0 * 3d: `BillBoard` * audio: new audio is added on iOS and Android @@ -327,9 +345,9 @@ You can refer to [this document](http://www.cocos2d-x.org/wiki/Integrate_the_Fac * UI: added `WebView` on iOS and Android * Many other small features added and many bugs fixed -# Features in detail +## Features in detail -## BillBoard +### BillBoard `BillBoard` is a rectangle always faces to the camera. It is useful in the 3D world. People use BillBoard to create trees in some racing games. It looks real, but the cost is much lower than 3d tree. @@ -349,7 +367,7 @@ addChild(camera); //add this camera billboard->setCameraMask((unsigned short)CameraFlag::CAMERA_USER1); ``` -## Triangles command +### Triangles command We have enhanced auto batching feature by introduce `TrianglesCommand`, the rendering of the `Triangles` can be auto batched. Now if we have anything which can be rendered by `Triangles`, we can use `TrianglesCommand` or inherit from `TrianglesCommand` to take use of auto batching feature and gain rendering improvements. The `QuadCommand`, which is used for `Quad` rendering, is a good example of inheriting from `TrianglesCommand`. @@ -362,7 +380,7 @@ The step to use Triangle Command is very simple. ``` To improve performance, `Triangles` will hold a weak reference to the vertices and indices data to be rendered, which is the same like `QuadCommand`. The userer should not release any rendered data before the `Command` is executed by `Renderer`. -## WebView +### WebView WebView is an new widget type which allows you to display web content inside Cocos2D-X. We only provide iOS and Android implementation currently, more platform might be added in the future. @@ -397,7 +415,7 @@ We could also set some callback to the WebView: For full test case, please refer to [WebViewTest](https://github.com/cocos2d/cocos2d-x/blob/v3/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIWebViewTest/UIWebViewTest.cpp) -## New audio +### New audio New audio is more powerful than old one, and it is not compatible with old one. We will deprecated old one when new audio is ready on all supported platforms. Now it only supports iOS and Android. We plan to finish it on v3.4. @@ -419,8 +437,9 @@ The difference compared to old audio engine Full test case please refer to `tests/cpp-tests/Classes/NewAudioEngineTest/NewAudioEngineTest.cpp`. +# v3.3alpha0 -# Highlights of v3.3alpha0 +## Highlights of v3.3alpha0 * 3d: `Camera`, `Reskin`, `Attachment`, `Better support for FBX`, `New fbx-conv`, `AABB`, `OBB` and `Ray` * ui: added `Scale9Sprite` @@ -434,9 +453,9 @@ Full test case please refer to `tests/cpp-tests/Classes/NewAudioEngineTest/NewAu * Only two libraries in cocos2d-x, one for c++ codes, another one for lua-binding codes * Many other small features added and many bugs fixed -# Features in detail +## Features in detail -## Camera +### Camera This version of camera is powerful than previous one. And you can add it as a child anywhere. If you want to let a Node to be visited by a camera, Node's camera mask should include Camera's flag: @@ -467,7 +486,7 @@ scene->addChild(camera); Full test case please refer to `tests/cpp-tests/res/Camera3DTest/Camera3DTest.cpp`. -## Reskin +### Reskin It is a powerful feature, all the user change the appearance of character. @@ -490,7 +509,7 @@ mesh1->setVisible(false); Full test case please refer to 'tests/cpp-tests/Classes/Spret3DTest/Sprite3DTest.cpp' -## Attachment +### Attachment Allows to attach a node to a bone @@ -505,17 +524,17 @@ attachNode->addChild(weapon); Full test case please refer to 'tests/cpp-tests/Classes/Spret3DTest/Sprite3DTest.cpp' -## Better support for FBX +### Better support for FBX support multiple mesh support multiple material bones bind to each mesh limited to 40. But the FBX model can contain more meshes. So the model can contain much more bones. -## New fbx-conv +### New fbx-conv It can export more complex model, which contains multiple meshes and multiple materials. -## AABB, OBB and Ray +### AABB, OBB and Ray AABB means Axis Aligned Bounding Box OBB means Oriented Bounding Box @@ -539,7 +558,7 @@ ray.intersects(sprite3d->getAABB( ) ); Full test case please refer to 'tests/cpp-tests/Classes/Spret3DTest/Sprite3DTest.cpp' -## ui::Scale9Sprite +### ui::Scale9Sprite Now we have implemented a new Scale9Sprite class under ui module. Its internal implementation is concise than the previous one plus more features. The main reason of reimplementing this class is that the Scale9Sprite is heavily used in ui module. Now the ui module is not dependent from extension module. @@ -566,7 +585,7 @@ you could call `sprite->getSprite()` to access it. Full test case please refer to `tests/cpp-tests/Classes/UITests/CocostudioGUITest/UIScale9SpriteTest.cpp`. -## c++11 random support +### c++11 random support Since `rand()` is not good(refer to [this document](http://c-faq.com/lib/randrange.html)), we use c++11 random library to do generate random number, and provide a function to easily using: @@ -575,7 +594,7 @@ int randInt = cocos2d::random(1, 10); float randFloat = cocos2d::random(1.f, 10.f); ``` -## RenderTexture save function +### RenderTexture save function `RenderTexture::saveToFile()` will not save rendertexture when the function returns, because it just send render command to renderer. The file will be saved after render command is executed. It is not convenient if you want to use the saved file to do some work. So we added a parameter in `RenderTexture::saveToFile()` to set a call back function when the file is saved. @@ -588,7 +607,7 @@ renderTexture->saveToFile("myFile.png", true, callback); ``` -## Primitive +### Primitive `Primitive` is added to support `Points`,`Lines`,`Triangles` rendering. Previously, if we want to draw a custom geometry(sphere, line), we can only do this by using `CustomCommand`. Now, what is need is to create a Primitive, set datas, and use the corresponding `PrimitiveCommand` to draw the Primitive. @@ -635,7 +654,7 @@ Primitive supports three typs of primitives (POINTS, LINES, TRIANGLES), vertex a 1. The size of vertex and index Buffer is fixed, which means data must be pre allocated. 2. Batching is not supported. -## Consistent way to set GL context attributes +### Consistent way to set GL context attributes Now you can set GL context attributes by override `Application::initGLContextAttrs()`, then set GL context attributes there. @@ -650,7 +669,7 @@ void AppDelegate::initGLContextAttrs() Now can only support setting bits of `r`, `g`, `b`, `a`, `depth buffer` and `stencil buffer`. We will support other attributes if needed. -## Only two libraries left +### Only two libraries left Now there are two libraries left: one for all c++ codes and another one for lua-bindings codes. diff --git a/external/config.json b/external/config.json index 8cb6c7a1b4..19e8fee3e5 100644 --- a/external/config.json +++ b/external/config.json @@ -1,5 +1,5 @@ { - "version":"v3-deps-28", + "version":"v3-deps-29", "zip_file_size":"87419231", "repo_name":"cocos2d-x-3rd-party-libs-bin", "repo_parent":"https://github.com/cocos2d/", diff --git a/setup.py b/setup.py index 952c41500b..c3c33d490e 100755 --- a/setup.py +++ b/setup.py @@ -483,28 +483,6 @@ class SetEnvVar(object): self._force_update_env(COCOS_CONSOLE_ROOT, cocos_consle_root) - def set_cocos_x_root(self): - print("->Check environment variable %s" % COCOS_X_ROOT) - cocos_x_root = self.current_absolute_path - old_dir = self._find_environment_variable(COCOS_X_ROOT) - if old_dir is None: - # add environment variable - if self._isWindows(): - self.set_windows_path(cocos_x_root) - - self._set_environment_variable(COCOS_X_ROOT, cocos_x_root) - else: - if old_dir == cocos_x_root: - # is same with before, nothing to do - return - - # update the environment variable - if self._isWindows(): - self.remove_dir_from_win_path(old_dir) - self.set_windows_path(cocos_x_root) - - self._force_update_env(COCOS_X_ROOT, cocos_x_root) - def set_templates_root(self): print("->Check environment variable %s" % COCOS_TEMPLATES_ROOT) cocos_templates_root = os.path.join(self.current_absolute_path, 'templates') @@ -685,7 +663,6 @@ class SetEnvVar(object): self.file_used_for_setup = self._get_filepath_for_setup() self.set_console_root() - self.set_cocos_x_root() self.set_templates_root() if self._isWindows(): diff --git a/templates/lua-template-default/frameworks/runtime-src/proj.android/build-cfg.json b/templates/lua-template-default/frameworks/runtime-src/proj.android/build-cfg.json index e63488b974..6fada4f617 100644 --- a/templates/lua-template-default/frameworks/runtime-src/proj.android/build-cfg.json +++ b/templates/lua-template-default/frameworks/runtime-src/proj.android/build-cfg.json @@ -13,13 +13,6 @@ { "from": "../../../res", "to": "res" - }, - { - "from": "../../cocos2d-x/external/lua/luasocket", - "to": "src", - "include": [ - "*.lua" - ] } ] } diff --git a/templates/lua-template-runtime/frameworks/runtime-src/Classes/runtime/Runtime.cpp b/templates/lua-template-runtime/frameworks/runtime-src/Classes/runtime/Runtime.cpp index 8c7e49ab69..c2088d222d 100644 --- a/templates/lua-template-runtime/frameworks/runtime-src/Classes/runtime/Runtime.cpp +++ b/templates/lua-template-runtime/frameworks/runtime-src/Classes/runtime/Runtime.cpp @@ -98,7 +98,7 @@ std::string& replaceAll(std::string& str, const std::string& old_value, const st const char* getRuntimeVersion() { - return "1.6"; + return "1.7"; } int lua_cocos2dx_runtime_addSearchPath(lua_State* tolua_S) @@ -212,10 +212,9 @@ int lua_cocos2dx_runtime_setSearchPaths(lua_State* tolua_S) { originPath.push_back(vecPaths[i]); // for IOS platform. projPath.push_back(g_projectPath + vecPaths[i]); //for Desktop platform. - writePaths[i] = FileServer::getShareInstance()->getWritePath() + vecPaths[i]; + writePaths.push_back(FileServer::getShareInstance()->getWritePath() + vecPaths[i]); } } - vecPaths.clear(); #if(CC_TARGET_PLATFORM == CC_PLATFORM_MAC || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) vecPaths.insert(vecPaths.end(), projPath.begin(), projPath.end()); diff --git a/templates/lua-template-runtime/runtime/config.json b/templates/lua-template-runtime/runtime/config.json index ed0868f924..b64a3dbbfa 100644 --- a/templates/lua-template-runtime/runtime/config.json +++ b/templates/lua-template-runtime/runtime/config.json @@ -1,5 +1,5 @@ { - "version":"v3-lua-runtime-1.6", + "version":"v3-lua-runtime-1.7", "zip_file_size":"39063553", "repo_name":"cocos-runtime-bin", "repo_parent":"https://github.com/chukong/" diff --git a/tests/cpp-tests/CMakeLists.txt b/tests/cpp-tests/CMakeLists.txt index b80057dc94..253ceac2bb 100644 --- a/tests/cpp-tests/CMakeLists.txt +++ b/tests/cpp-tests/CMakeLists.txt @@ -22,6 +22,7 @@ set(TESTS_SRC Classes/ActionsEaseTest/ActionsEaseTest.cpp Classes/ActionsProgressTest/ActionsProgressTest.cpp Classes/ActionsTest/ActionsTest.cpp + Classes/AllocatorTest/AllocatorTest.cpp Classes/BillBoardTest/BillBoardTest.cpp Classes/BugsTest/Bug-1159.cpp Classes/BugsTest/Bug-1174.cpp diff --git a/tests/cpp-tests/Classes/AllocatorTest/AllocatorTest.cpp b/tests/cpp-tests/Classes/AllocatorTest/AllocatorTest.cpp new file mode 100644 index 0000000000..c273df0628 --- /dev/null +++ b/tests/cpp-tests/Classes/AllocatorTest/AllocatorTest.cpp @@ -0,0 +1,214 @@ + +/**************************************************************************** + Copyright (c) 2014 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 INAN 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 "AllocatorTest.h" +#include "cocos2d.h" +#include + +namespace AllocatorTestNS +{ + +#if CC_ENABLE_ALLOCATOR + Test1::tAllocator Test1::_allocator("Test1", kNumberOfInstances); +#endif // CC_ENABLE_ALLOCATOR + + static int sceneIdx = -1; + + static std::function createFunctions[] = + { + CL(AllocatorTest) + }; + +#define MAX_LAYER (sizeof(createFunctions) / sizeof(createFunctions[0])) + + static Layer* nextAllocatorTestAction() + { + sceneIdx++; + sceneIdx = sceneIdx % MAX_LAYER; + + auto layer = (createFunctions[sceneIdx])(); + return layer; + } + + static Layer* backAllocatorTestAction() + { + sceneIdx--; + int total = MAX_LAYER; + if( sceneIdx < 0 ) + sceneIdx += total; + + auto layer = (createFunctions[sceneIdx])(); + return layer; + } + + static Layer* restartAllocatorTestAction() + { + auto layer = (createFunctions[sceneIdx])(); + return layer; + } + + // + // AllocatorTest + // + + AllocatorTest::AllocatorTest() + { + typedef std::vector tTest1Container; + typedef std::vector tTest2Container; + + tTest1Container test1Container; + test1Container.reserve(kNumberOfInstances); + + tTest2Container test2Container; + test2Container.reserve(kNumberOfInstances); + + std::chrono::time_point alloc1Start, alloc1End, alloc2Start, alloc2End; + std::chrono::time_point free1Start, free1End, free2Start, free2End; + + alloc1Start = std::chrono::high_resolution_clock::now(); + for (int i = 0; i < kNumberOfInstances; ++i) + test1Container.push_back(new Test1); + alloc1End = std::chrono::high_resolution_clock::now(); + + alloc2Start = std::chrono::high_resolution_clock::now(); + for (int i = 0; i < kNumberOfInstances; ++i) + test2Container.push_back(new Test2); + alloc2End = std::chrono::high_resolution_clock::now(); + + free1Start = std::chrono::high_resolution_clock::now(); + for (int i = 0; i < kNumberOfInstances; ++i) + delete test1Container[i]; + free1End = std::chrono::high_resolution_clock::now(); + + free2Start = std::chrono::high_resolution_clock::now(); + for (int i = 0; i < kNumberOfInstances; ++i) + delete test2Container[i]; + free2End = std::chrono::high_resolution_clock::now(); + + test1Container.clear(); + test2Container.clear(); + + std::chrono::duration elapsed_seconds_alloc1 = alloc1End - alloc1Start; + std::chrono::duration elapsed_seconds_alloc2 = alloc2End - alloc2Start; + std::chrono::duration elapsed_seconds_free1 = free1End - free1Start; + std::chrono::duration elapsed_seconds_free2 = free2End - free2Start; + + char buf[1000]; + + const float x_start = 240; + const float y_start = 100; + const float y_delta = 20; + float y = 0; + + sprintf(buf, "alloc1 %f", elapsed_seconds_alloc1.count()); + auto alloc1 = Label::createWithSystemFont(buf, "Helvetica", 12); + alloc1->setPosition(x_start, y++ * y_delta + y_start); + addChild(alloc1); + + sprintf(buf, "alloc2 %f", elapsed_seconds_alloc2.count()); + auto alloc2 = Label::createWithSystemFont(buf, "Helvetica", 12); + alloc2->setPosition(x_start, y++ * y_delta + y_start); + addChild(alloc2); + + sprintf(buf, "free1 %f", elapsed_seconds_free1.count()); + auto free1 = Label::createWithSystemFont(buf, "Helvetica", 12); + free1->setPosition(x_start, y++ * y_delta + y_start); + addChild(free1); + + sprintf(buf, "free2 %f", elapsed_seconds_free2.count()); + auto free2 = Label::createWithSystemFont(buf, "Helvetica", 12); + free2->setPosition(x_start, y++ * y_delta + y_start); + addChild(free2); + } + + AllocatorTest::~AllocatorTest() + { + } + + std::string AllocatorTest::title() const + { + return "Allocator Test"; + } + + std::string AllocatorTest::subtitle() const + { + return ""; + } + + void AllocatorTest::restartCallback( Ref* sender ) + { + auto s = new AllocatorTestScene(); + s->addChild(restartAllocatorTestAction()); + Director::getInstance()->replaceScene(s); + s->release(); + } + + void AllocatorTest::nextCallback( Ref* sender ) + { + auto s = new AllocatorTestScene(); + s->addChild( nextAllocatorTestAction() ); + Director::getInstance()->replaceScene(s); + s->release(); + } + + void AllocatorTest::backCallback( Ref* sender ) + { + auto s = new AllocatorTestScene(); + s->addChild( backAllocatorTestAction() ); + Director::getInstance()->replaceScene(s); + s->release(); + } + + void AllocatorTest::onEnter() + { + BaseTest::onEnter(); + } + + void AllocatorTest::onExit() + { + BaseTest::onExit(); + } + + void AllocatorTest::update(float delta) + { + } + + // + // AllocatorTestScene + // + + AllocatorTestScene::AllocatorTestScene() + { + } + + void AllocatorTestScene::runThisTest() + { + auto layer = nextAllocatorTestAction(); + addChild(layer); + Director::getInstance()->replaceScene(this); + } + +} // AllocatorTestNS + diff --git a/tests/cpp-tests/Classes/AllocatorTest/AllocatorTest.h b/tests/cpp-tests/Classes/AllocatorTest/AllocatorTest.h new file mode 100644 index 0000000000..40cf283c1c --- /dev/null +++ b/tests/cpp-tests/Classes/AllocatorTest/AllocatorTest.h @@ -0,0 +1,99 @@ + +#pragma once + +/**************************************************************************** + Copyright (c) 2014 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "../testBasic.h" +#include "../BaseTest.h" +#include "base/allocator/CCAllocatorStrategyPool.h" + +namespace AllocatorTestNS +{ + + // + // Test Classes + // + +#define kNumberOfInstances 100000 +#define kObjectSize 952 // sizeof(Sprite) + + class Test1; + + class Test1 + { + public: + + Test1() + { + memset(bytes, 0, sizeof(bytes)); + } + uint8_t bytes[kObjectSize]; + +#if CC_ENABLE_ALLOCATOR + typedef cocos2d::allocator::AllocatorStrategyPool tAllocator; + static tAllocator _allocator; +#endif // CC_ENABLE_ALLOCATOR + CC_USE_ALLOCATOR_POOL(Test1, _allocator); + }; + + class Test2 + { + public: + + Test2() + { + memset(bytes, 0, sizeof(bytes)); + } + uint8_t bytes[kObjectSize]; + }; + + class AllocatorTest : public BaseTest + { + public: + CREATE_FUNC(AllocatorTest); + AllocatorTest(); + virtual ~AllocatorTest(); + + virtual std::string title() const; + virtual std::string subtitle() const; + + virtual void restartCallback(Ref* sender); + virtual void nextCallback(Ref* sender); + virtual void backCallback(Ref* sender); + + virtual void onEnter() override; + virtual void onExit() override; + + virtual void update(float delta); + }; + + class AllocatorTestScene : public TestScene + { + public: + AllocatorTestScene(); + virtual void runThisTest(); + }; + +} // AllocatorTestNS diff --git a/tests/cpp-tests/Classes/AppDelegate.cpp b/tests/cpp-tests/Classes/AppDelegate.cpp index 8e34f05066..66a9bbbd6e 100644 --- a/tests/cpp-tests/Classes/AppDelegate.cpp +++ b/tests/cpp-tests/Classes/AppDelegate.cpp @@ -118,6 +118,7 @@ bool AppDelegate::applicationDidFinishLaunching() searchPaths.push_back("ccs-res/hd/cocosui/UIEditorTest/UISlider"); searchPaths.push_back("ccs-res/hd/cocosui/UIEditorTest/UITextField"); searchPaths.push_back("ccs-res/hd/cocosui/UIEditorTest/UIWidgetAddNode"); + searchPaths.push_back("ccs-res/hd/cocosui/UIEditorTest/UIListView/New"); searchPaths.push_back("ccs-res/hd/cocosui/CustomTest/CustomWidgetCallbackBindTest"); searchPaths.push_back("hd/ActionTimeline"); @@ -156,9 +157,9 @@ bool AppDelegate::applicationDidFinishLaunching() searchPaths.push_back("ccs-res/cocosui/UIEditorTest/UISlider"); searchPaths.push_back("ccs-res/cocosui/UIEditorTest/UITextField"); searchPaths.push_back("ccs-res/cocosui/UIEditorTest/UIWidgetAddNode"); + searchPaths.push_back("ccs-res/cocosui/UIEditorTest/UIListView/New"); searchPaths.push_back("ccs-res/cocosui/CustomTest/CustomWidgetCallbackBindTest"); - searchPaths.push_back("ActionTimeline"); } diff --git a/tests/cpp-tests/Classes/Sprite3DTest/Sprite3DTest.cpp b/tests/cpp-tests/Classes/Sprite3DTest/Sprite3DTest.cpp index bc99e117b1..900a140b0a 100644 --- a/tests/cpp-tests/Classes/Sprite3DTest/Sprite3DTest.cpp +++ b/tests/cpp-tests/Classes/Sprite3DTest/Sprite3DTest.cpp @@ -270,8 +270,8 @@ Sprite3DUVAnimationTest::Sprite3DUVAnimationTest() //create the second texture for cylinder auto shining_texture = Director::getInstance()->getTextureCache()->addImage("Sprite3DTest/caustics.png"); Texture2D::TexParams tRepeatParams;//set texture parameters - tRepeatParams.magFilter = GL_LINEAR_MIPMAP_LINEAR; - tRepeatParams.minFilter = GL_LINEAR; + tRepeatParams.magFilter = GL_NEAREST; + tRepeatParams.minFilter = GL_NEAREST; tRepeatParams.wrapS = GL_REPEAT; tRepeatParams.wrapT = GL_REPEAT; shining_texture->setTexParameters(tRepeatParams); diff --git a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/GUIEditorTest.cpp b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/GUIEditorTest.cpp index 4e71ecba43..f59843dbe5 100644 --- a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/GUIEditorTest.cpp +++ b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/GUIEditorTest.cpp @@ -207,7 +207,6 @@ g_guisTests[] = Director::getInstance()->replaceScene(pScene); } }, - /* { "gui ListView Editor Test", [](Ref* sender) @@ -220,7 +219,6 @@ g_guisTests[] = Director::getInstance()->replaceScene(pScene); } }, - */ /* { "gui GridViewTest", diff --git a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIListViewTest/UIListViewTest_Editor.cpp b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIListViewTest/UIListViewTest_Editor.cpp index 15c0f466c9..7afe1b1b92 100644 --- a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIListViewTest/UIListViewTest_Editor.cpp +++ b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIListViewTest/UIListViewTest_Editor.cpp @@ -124,14 +124,19 @@ bool UIListViewTest_Vertical_Editor::init() { if (UIScene_Editor::init()) { - _layout = static_cast(cocostudio::GUIReader::getInstance()->widgetFromJsonFile("cocosui/UIEditorTest/UIListView/Vertical/windows_ui_listview_editor_1.json")); + Node* node = CSLoader::createNode("cocosui/UIEditorTest/UIListView/New/crossplatform_UIListView_Editor_Vertical.csb"); + Node* child = node->getChildByTag(5); + child->removeFromParent(); + _layout = dynamic_cast(child); _touchGroup->addChild(_layout); + this->configureGUIScene(); - - Menu* menu = static_cast(getChildByTag(1)); - MenuItemToggle* menuItemToggle = static_cast(menu->getChildByTag(1)); - MenuItem* selectedItem = menuItemToggle->getSelectedItem(); - menuItemToggle->setPosition(Vec2(VisibleRect::center().x, VisibleRect::center().y + selectedItem->getContentSize().height * 4.25f)); + auto listView1 = dynamic_cast(Helper::seekWidgetByName(_layout, "ListView1")); + auto listView2 = dynamic_cast(Helper::seekWidgetByName(_layout, "ListView2")); + auto listView3 = dynamic_cast(Helper::seekWidgetByName(_layout, "ListView3")); + setupListView(listView1); + setupListView(listView2); + setupListView(listView3); return true; } @@ -139,6 +144,60 @@ bool UIListViewTest_Vertical_Editor::init() return false; } +void UIListViewTest_Vertical_Editor::setupListView(ListView* listView) +{ + float scale = 0.5f; + float itemMargin = listView->getItemsMargin(); + + auto item0 = Text::create(); + item0->setString(String::createWithFormat("Item margin: %d", static_cast(itemMargin))->getCString()); + listView->addChild(item0); + + auto item1 = Layout::create(); + auto checkbox = CheckBox::create("selected01.png", "selected01.png", "selected02.png", "selected01.png", "selected01.png"); + checkbox->setPosition(Vec2(checkbox->getCustomSize().width / 2, checkbox->getCustomSize().height / 2)); + item1->addChild(checkbox); + auto checkboxText = Text::create(); + checkboxText->setString("CheckBox"); + checkboxText->setFontSize(checkbox->getCustomSize().width * .8f); + checkboxText->setPosition(Vec2(checkbox->getCustomSize().width + checkboxText->getCustomSize().width / 2, checkbox->getCustomSize().height / 2)); + item1->addChild(checkboxText); + float item1Width = scale * (checkbox->getCustomSize().width + checkboxText->getCustomSize().width); + float item1Height = scale * checkbox->getCustomSize().height; + item1->setContentSize(Size(item1Width, item1Height)); + item1->setScale(scale); + listView->addChild(item1); + + auto item2 = Text::create(); + item2->setString("Text2"); + item2->setFontSize(checkbox->getCustomSize().width * .4f); + item2->setTextColor(Color4B(0, 255, 0, 255)); + listView->addChild(item2); + + auto item3 = Layout::create(); + auto imageview0 = ImageView::create("image.png"); + auto imageview1 = ImageView::create("image.png"); + imageview1->setPositionX(imageview1->getCustomSize().width * 2); + imageview0->setAnchorPoint(Vec2(0, 0)); + imageview1->setAnchorPoint(Vec2(0, 0)); + item3->setContentSize(Size(imageview0->getCustomSize().width * 3 * scale, imageview0->getCustomSize().height * scale)); + item3->addChild(imageview0); + item3->addChild(imageview1); + item3->setScale(scale); + listView->addChild(item3); + + auto item4 = Button::create("button.png", "button_p.png"); + item4->setTitleText("Button"); + listView->pushBackCustomItem(item4); + + auto itemModel = Text::create(); + itemModel->setTextColor(Color4B(255, 0, 0, 125)); + itemModel->setString("List item model"); + listView->setItemModel(itemModel); + listView->pushBackDefaultItem(); + listView->pushBackDefaultItem(); +} + // UIListViewTest_Horizontal_Editor @@ -256,16 +315,20 @@ bool UIListViewTest_Horizontal_Editor::init() { if (UIScene_Editor::init()) { - _layout = static_cast(cocostudio::GUIReader::getInstance()->widgetFromJsonFile("cocosui/UIEditorTest/UIListView/Horizontal/windows_ui_listview_horizontal_editor_1.json")); + Node* node = CSLoader::createNode("cocosui/UIEditorTest/UIListView/New/crossplatform_UIListView_Editor_Horizontal.csb"); + Node* child = node->getChildByTag(5); + child->removeFromParent(); + _layout = dynamic_cast(child); _touchGroup->addChild(_layout); - + this->configureGUIScene(); - - Menu* menu = static_cast(getChildByTag(1)); - MenuItemToggle* menuItemToggle = static_cast(menu->getChildByTag(1)); - MenuItem* selectedItem = menuItemToggle->getSelectedItem(); - menuItemToggle->setPosition(Vec2(VisibleRect::center().x, VisibleRect::center().y + selectedItem->getContentSize().height * 4.25f)); - + auto listView1 = dynamic_cast(Helper::seekWidgetByName(_layout, "ListView1")); + auto listView2 = dynamic_cast(Helper::seekWidgetByName(_layout, "ListView2")); + auto listView3 = dynamic_cast(Helper::seekWidgetByName(_layout, "ListView3")); + UIListViewTest_Vertical_Editor::setupListView(listView1); + UIListViewTest_Vertical_Editor::setupListView(listView2); + UIListViewTest_Vertical_Editor::setupListView(listView3); + return true; } diff --git a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIListViewTest/UIListViewTest_Editor.h b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIListViewTest/UIListViewTest_Editor.h index f8d1efe3e8..d6761b3566 100644 --- a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIListViewTest/UIListViewTest_Editor.h +++ b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIListViewTest/UIListViewTest_Editor.h @@ -30,6 +30,7 @@ class UIListViewTest_Vertical_Editor : public UIScene_Editor { public: + static void setupListView(ListView* listView); UIListViewTest_Vertical_Editor(); ~UIListViewTest_Vertical_Editor(); bool init(); diff --git a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UISceneManager_Editor.cpp b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UISceneManager_Editor.cpp index ec531c72eb..2e9346bfed 100644 --- a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UISceneManager_Editor.cpp +++ b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UISceneManager_Editor.cpp @@ -41,9 +41,9 @@ static const char* s_testArray[] = "UILayoutTest_Layout_Linear_Horizontal_Editor", "UILayoutTest_Layout_Relative_Align_Parent_Editor", "UILayoutTest_Layout_Relative_Location_Editor", + */ "UIListViewTest_Vertical_Editor", "UIListViewTest_Horizontal_Editor", - */ "UIPageViewTest_Editor", "UIScrollViewTest_Vertical_Editor", "UIScrollViewTest_Horizontal_Editor", @@ -161,13 +161,12 @@ Scene* UISceneManager_Editor::currentUIScene() case kUILayoutTest_Layout_Relative_Location_Editor: return UILayoutTest_Layout_Relative_Location_Editor::sceneWithTitle(s_testArray[_currentUISceneId]); - + */ case kUIListViewTest_Vertical_Editor: return UIListViewTest_Vertical_Editor::sceneWithTitle(s_testArray[_currentUISceneId]); case kUIListViewTest_Horizontal_Editor: return UIListViewTest_Horizontal_Editor::sceneWithTitle(s_testArray[_currentUISceneId]); - */ case kUIPageViewTest_Editor: return UIPageViewTest_Editor::sceneWithTitle(s_testArray[_currentUISceneId]); diff --git a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UISceneManager_Editor.h b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UISceneManager_Editor.h index f721cb941d..c932da5dec 100644 --- a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UISceneManager_Editor.h +++ b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UISceneManager_Editor.h @@ -51,9 +51,9 @@ enum kUILayoutTest_Layout_Linear_Horizontal_Editor, kUILayoutTest_Layout_Relative_Align_Parent_Editor, kUILayoutTest_Layout_Relative_Location_Editor, + */ kUIListViewTest_Vertical_Editor, kUIListViewTest_Horizontal_Editor, - */ kUIPageViewTest_Editor, kUIScrollViewTest_Vertical_Editor, kUIScrollViewTest_Horizontal_Editor, diff --git a/tests/cpp-tests/Classes/controller.cpp b/tests/cpp-tests/Classes/controller.cpp index f05c2b44e6..5f5d910da4 100644 --- a/tests/cpp-tests/Classes/controller.cpp +++ b/tests/cpp-tests/Classes/controller.cpp @@ -38,7 +38,8 @@ Controller g_aTestNames[] = { { "Actions - Basic", [](){ return new ActionsTestScene(); } }, { "Actions - Ease", [](){return new ActionsEaseTestScene();} }, { "Actions - Progress", [](){return new ProgressActionsTestScene(); } }, - { "Audio - CocosDenshion", []() { return new CocosDenshionTestScene(); } }, + { "Allocator - Basic", [](){return new AllocatorTestNS::AllocatorTestScene(); } }, + { "Audio - CocosDenshion", []() { return new CocosDenshionTestScene(); } }, #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) { "Audio - NewAudioEngine", []() { return new AudioEngineTestScene(); } }, #endif diff --git a/tests/cpp-tests/Classes/tests.h b/tests/cpp-tests/Classes/tests.h index 78db79616e..0b3b997209 100644 --- a/tests/cpp-tests/Classes/tests.h +++ b/tests/cpp-tests/Classes/tests.h @@ -79,5 +79,6 @@ #include "LightTest/LightTest.h" #include "OpenURLTest/OpenURLTest.h" +#include "AllocatorTest/AllocatorTest.h" #endif diff --git a/tests/cpp-tests/proj.android/.classpath b/tests/cpp-tests/proj.android/.classpath index 51769745b2..5cc5eb909c 100644 --- a/tests/cpp-tests/proj.android/.classpath +++ b/tests/cpp-tests/proj.android/.classpath @@ -2,7 +2,7 @@ - + diff --git a/tests/cpp-tests/proj.android/jni/Android.mk b/tests/cpp-tests/proj.android/jni/Android.mk index 40eb1c33ed..c15139a2ec 100644 --- a/tests/cpp-tests/proj.android/jni/Android.mk +++ b/tests/cpp-tests/proj.android/jni/Android.mk @@ -16,6 +16,7 @@ LOCAL_SRC_FILES := main.cpp \ ../../Classes/ActionsEaseTest/ActionsEaseTest.cpp \ ../../Classes/ActionsProgressTest/ActionsProgressTest.cpp \ ../../Classes/ActionsTest/ActionsTest.cpp \ +../../Classes/AllocatorTest/AllocatorTest.cpp \ ../../Classes/BillBoardTest/BillBoardTest.cpp \ ../../Classes/Box2DTest/Box2dTest.cpp \ ../../Classes/Box2DTestBed/Box2dView.cpp \ diff --git a/tests/cpp-tests/proj.win32/cpp-tests.vcxproj b/tests/cpp-tests/proj.win32/cpp-tests.vcxproj index dcc42405d0..c5fe62f7e0 100644 --- a/tests/cpp-tests/proj.win32/cpp-tests.vcxproj +++ b/tests/cpp-tests/proj.win32/cpp-tests.vcxproj @@ -136,6 +136,7 @@ + @@ -324,6 +325,7 @@ + diff --git a/tests/cpp-tests/proj.win32/cpp-tests.vcxproj.filters b/tests/cpp-tests/proj.win32/cpp-tests.vcxproj.filters index a82a990b9b..437e37739e 100644 --- a/tests/cpp-tests/proj.win32/cpp-tests.vcxproj.filters +++ b/tests/cpp-tests/proj.win32/cpp-tests.vcxproj.filters @@ -343,6 +343,9 @@ {65be3b70-58d6-47f4-bc67-fac9ee134c42} + + {eed1887a-757e-4625-b21c-bbfcfaa5200f} + @@ -903,6 +906,9 @@ Classes\UITest\CocostudioGUISceneTest\CustomTest\CustomWidgetCallbackBindTest + + Classes\AllocatorTest + @@ -1661,5 +1667,8 @@ Classes\UITest\CocostudioGUISceneTest\CustomTest\CustomWidgetCallbackBindTest + + Classes\AllocatorTest + \ No newline at end of file diff --git a/tests/lua-empty-test/project/proj.android/build-cfg.json b/tests/lua-empty-test/project/proj.android/build-cfg.json index 497120df2f..92b544334b 100644 --- a/tests/lua-empty-test/project/proj.android/build-cfg.json +++ b/tests/lua-empty-test/project/proj.android/build-cfg.json @@ -16,13 +16,6 @@ { "from": "../../../../cocos/scripting/lua-bindings/script/", "to": "src/cocos" - }, - { - "from": "../../../../external/lua/luasocket", - "to": "", - "include": [ - "*.lua" - ] } ] } diff --git a/tests/lua-tests/project/proj.android/build-cfg.json b/tests/lua-tests/project/proj.android/build-cfg.json index 4f18ce29ab..41ae5ae199 100644 --- a/tests/lua-tests/project/proj.android/build-cfg.json +++ b/tests/lua-tests/project/proj.android/build-cfg.json @@ -23,14 +23,6 @@ { "from": "../../../../cocos/scripting/lua-bindings/script/", "to": "src/cocos" - }, - - { - "from": "../../../../external/lua/luasocket", - "to": "", - "include": [ - "*.lua" - ] } ] } diff --git a/tests/lua-tests/src/ExtensionTest/ExtensionTest.lua b/tests/lua-tests/src/ExtensionTest/ExtensionTest.lua index 91fb9db48a..e62cb39f23 100644 --- a/tests/lua-tests/src/ExtensionTest/ExtensionTest.lua +++ b/tests/lua-tests/src/ExtensionTest/ExtensionTest.lua @@ -1215,7 +1215,7 @@ local function ExtensionsMainLayer() cc.MenuItemFont:setFontSize(24) local targetPlatform = cc.Application:getInstance():getTargetPlatform() local bSupportWebSocket = false - if (cc.PLATFORM_OS_IPHONE == targetPlatform) or (cc.PLATFORM_OS_IPAD == targetPlatform) or (cc.PLATFORM_OS_ANDROID == targetPlatform) or (cc.PLATFORM_OS_WINDOWS == targetPlatform) then + if (cc.PLATFORM_OS_IPHONE == targetPlatform) or (cc.PLATFORM_OS_IPAD == targetPlatform) or (cc.PLATFORM_OS_ANDROID == targetPlatform) or (cc.PLATFORM_OS_WINDOWS == targetPlatform) or (cc.PLATFORM_OS_MAC == targetPlatform) then bSupportWebSocket = true end local bSupportEdit = false