Conflicts:
	cocos/2d/libcocos2d.vcxproj.filters
	tests/cpp-tests/Classes/ExtensionsTest/CocoStudioActionTimelineTest/ActionTimelineTestScene.cpp
This commit is contained in:
kaile.yin 2014-12-22 11:14:31 +08:00
commit b924dafe83
132 changed files with 5105 additions and 1359 deletions

View File

@ -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

View File

@ -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

View File

@ -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 = "<group>"; };
B67C624419D4186F00F11FC6 /* ccShader_3D_ColorNormalTex.frag */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.glsl; path = ccShader_3D_ColorNormalTex.frag; sourceTree = "<group>"; };
B67C624519D4186F00F11FC6 /* ccShader_3D_PositionNormalTex.vert */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.glsl; path = ccShader_3D_PositionNormalTex.vert; sourceTree = "<group>"; };
D0FD033B1A3B51AA00825BB5 /* CCAllocatorBase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCAllocatorBase.h; sourceTree = "<group>"; };
D0FD033C1A3B51AA00825BB5 /* CCAllocatorDiagnostics.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCAllocatorDiagnostics.cpp; sourceTree = "<group>"; };
D0FD033D1A3B51AA00825BB5 /* CCAllocatorDiagnostics.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCAllocatorDiagnostics.h; sourceTree = "<group>"; };
D0FD033E1A3B51AA00825BB5 /* CCAllocatorGlobal.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCAllocatorGlobal.cpp; sourceTree = "<group>"; };
D0FD033F1A3B51AA00825BB5 /* CCAllocatorGlobal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCAllocatorGlobal.h; sourceTree = "<group>"; };
D0FD03401A3B51AA00825BB5 /* CCAllocatorGlobalNewDelete.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCAllocatorGlobalNewDelete.cpp; sourceTree = "<group>"; };
D0FD03411A3B51AA00825BB5 /* CCAllocatorMacros.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCAllocatorMacros.h; sourceTree = "<group>"; };
D0FD03421A3B51AA00825BB5 /* CCAllocatorMutex.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCAllocatorMutex.h; sourceTree = "<group>"; };
D0FD03431A3B51AA00825BB5 /* CCAllocatorStrategyDefault.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCAllocatorStrategyDefault.h; sourceTree = "<group>"; };
D0FD03441A3B51AA00825BB5 /* CCAllocatorStrategyFixedBlock.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCAllocatorStrategyFixedBlock.h; sourceTree = "<group>"; };
D0FD03451A3B51AA00825BB5 /* CCAllocatorStrategyGlobalSmallBlock.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCAllocatorStrategyGlobalSmallBlock.h; sourceTree = "<group>"; };
D0FD03461A3B51AA00825BB5 /* CCAllocatorStrategyPool.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCAllocatorStrategyPool.h; sourceTree = "<group>"; };
DA8C62A019E52C6400000516 /* ioapi_mem.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ioapi_mem.cpp; sourceTree = "<group>"; };
DA8C62A119E52C6400000516 /* ioapi_mem.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ioapi_mem.h; sourceTree = "<group>"; };
DABC9FA719E7DFA900FA252C /* CCClippingRectangleNode.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCClippingRectangleNode.cpp; sourceTree = "<group>"; };
@ -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 = "<group>";
};
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 = "<group>";
};
/* 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 */,

View File

@ -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 = "<group>"; };
C04F93591941B05400E9FEAB /* TileMapTest2.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TileMapTest2.h; sourceTree = "<group>"; };
C08689C018D370C90093E810 /* background.caf */ = {isa = PBXFileReference; lastKnownFileType = file; name = background.caf; path = "../tests/cpp-tests/Resources/background.caf"; sourceTree = "<group>"; };
D0FD03621A3B546400825BB5 /* AllocatorTest.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = AllocatorTest.cpp; path = AllocatorTest/AllocatorTest.cpp; sourceTree = "<group>"; };
D0FD03631A3B546400825BB5 /* AllocatorTest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AllocatorTest.h; path = AllocatorTest/AllocatorTest.h; sourceTree = "<group>"; };
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 = "<group>";
};
D0FD03611A3B543700825BB5 /* AllocatorTest */ = {
isa = PBXGroup;
children = (
D0FD03621A3B546400825BB5 /* AllocatorTest.cpp */,
D0FD03631A3B546400825BB5 /* AllocatorTest.h */,
);
name = AllocatorTest;
sourceTree = "<group>";
};
/* 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 */,

View File

@ -583,6 +583,7 @@ void Label::alignText()
{
if (_fontAtlas == nullptr || _currentUTF16String.empty())
{
setContentSize(Size::ZERO);
return;
}

View File

@ -93,6 +93,7 @@ Node::Node(void)
, _anchorPointInPoints(Vec2::ZERO)
, _anchorPoint(Vec2::ZERO)
, _contentSize(Size::ZERO)
, _contentSizeDirty(true)
, _transformDirty(true)
, _inverseDirty(true)
, _useAdditionalTransform(false)

View File

@ -243,6 +243,9 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\chipmunk\prebuilt\win32\release-lib\*.*
<ClCompile Include="..\audio\win32\AudioPlayer.cpp" />
<ClCompile Include="..\audio\win32\MciPlayer.cpp" />
<ClCompile Include="..\audio\win32\SimpleAudioEngine.cpp" />
<ClCompile Include="..\base\allocator\CCAllocatorDiagnostics.cpp" />
<ClCompile Include="..\base\allocator\CCAllocatorGlobal.cpp" />
<ClCompile Include="..\base\allocator\CCAllocatorGlobalNewDelete.cpp" />
<ClCompile Include="..\base\atitc.cpp" />
<ClCompile Include="..\base\base64.cpp" />
<ClCompile Include="..\base\CCAutoreleasePool.cpp" />
@ -611,6 +614,15 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\chipmunk\prebuilt\win32\release-lib\*.*
<ClInclude Include="..\audio\win32\AudioEngine-win32.h" />
<ClInclude Include="..\audio\win32\AudioPlayer.h" />
<ClInclude Include="..\audio\win32\MciPlayer.h" />
<ClInclude Include="..\base\allocator\CCAllocatorBase.h" />
<ClInclude Include="..\base\allocator\CCAllocatorDiagnostics.h" />
<ClInclude Include="..\base\allocator\CCAllocatorGlobal.h" />
<ClInclude Include="..\base\allocator\CCAllocatorMacros.h" />
<ClInclude Include="..\base\allocator\CCAllocatorMutex.h" />
<ClInclude Include="..\base\allocator\CCAllocatorStrategyDefault.h" />
<ClInclude Include="..\base\allocator\CCAllocatorStrategyFixedBlock.h" />
<ClInclude Include="..\base\allocator\CCAllocatorStrategyGlobalSmallBlock.h" />
<ClInclude Include="..\base\allocator\CCAllocatorStrategyPool.h" />
<ClInclude Include="..\base\atitc.h" />
<ClInclude Include="..\base\base64.h" />
<ClInclude Include="..\base\CCAutoreleasePool.h" />

View File

@ -238,6 +238,9 @@
<Filter Include="cocostudio\reader\WidgetReader\SpriteReader">
<UniqueIdentifier>{9aee531c-f935-4836-bf84-be42e78e38bb}</UniqueIdentifier>
</Filter>
<Filter Include="base\allocator">
<UniqueIdentifier>{92ff4e66-3943-47da-a439-c8f182bb871a}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\physics\CCPhysicsBody.cpp">
@ -1292,6 +1295,15 @@
<ClCompile Include="..\editor-support\cocostudio\ActionTimeline\CCActionTimelineNode.cpp">
<Filter>cocostudio\TimelineAction</Filter>
</ClCompile>
<ClCompile Include="..\base\allocator\CCAllocatorDiagnostics.cpp">
<Filter>base\allocator</Filter>
</ClCompile>
<ClCompile Include="..\base\allocator\CCAllocatorGlobal.cpp">
<Filter>base\allocator</Filter>
</ClCompile>
<ClCompile Include="..\base\allocator\CCAllocatorGlobalNewDelete.cpp">
<Filter>base\allocator</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\physics\CCPhysicsBody.h">
@ -2511,6 +2523,33 @@
<ClInclude Include="..\editor-support\cocostudio\ActionTimeline\CCActionTimelineNode.h">
<Filter>cocostudio\TimelineAction</Filter>
</ClInclude>
<ClInclude Include="..\base\allocator\CCAllocatorGlobal.h">
<Filter>base\allocator</Filter>
</ClInclude>
<ClInclude Include="..\base\allocator\CCAllocatorBase.h">
<Filter>base\allocator</Filter>
</ClInclude>
<ClInclude Include="..\base\allocator\CCAllocatorDiagnostics.h">
<Filter>base\allocator</Filter>
</ClInclude>
<ClInclude Include="..\base\allocator\CCAllocatorMacros.h">
<Filter>base\allocator</Filter>
</ClInclude>
<ClInclude Include="..\base\allocator\CCAllocatorMutex.h">
<Filter>base\allocator</Filter>
</ClInclude>
<ClInclude Include="..\base\allocator\CCAllocatorStrategyDefault.h">
<Filter>base\allocator</Filter>
</ClInclude>
<ClInclude Include="..\base\allocator\CCAllocatorStrategyFixedBlock.h">
<Filter>base\allocator</Filter>
</ClInclude>
<ClInclude Include="..\base\allocator\CCAllocatorStrategyGlobalSmallBlock.h">
<Filter>base\allocator</Filter>
</ClInclude>
<ClInclude Include="..\base\allocator\CCAllocatorStrategyPool.h">
<Filter>base\allocator</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<None Include="..\math\Mat4.inl">

View File

@ -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 \

View File

@ -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)

View File

@ -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;

View File

@ -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);

View File

@ -36,6 +36,7 @@ EventMouse::EventMouse(MouseEventType mouseEventCode)
, _y(0.0f)
, _scrollX(0.0f)
, _scrollY(0.0f)
, _startPointCaptured(false)
{
};

View File

@ -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

View File

@ -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 <string>
#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

View File

@ -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

View File

@ -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 <unordered_set>
#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

View File

@ -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

View File

@ -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

View File

@ -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 <new>
#include <exception>
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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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 <stdint.h>
#include <vector>
#include <typeinfo>
#include <sstream>
#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 <size_t _block_size, size_t _alignment = 16, typename lock_traits = locking_semantics>
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

View File

@ -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<size>
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

View File

@ -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 <vector>
#include <typeinfo>
#include <sstream>
#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 <typename T, size_t _alignment = sizeof(uint32_t)>
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 T, typename O = ObjectTraits<T>, typename locking_traits = lockless_semantics>
class AllocatorStrategyPool
: public AllocatorStrategyFixedBlock<sizeof(T), O::alignment, locking_traits>
, 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<sizeof(T), O::alignment, locking_traits> 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

View File

@ -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__

View File

@ -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

View File

@ -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();

View File

@ -34,7 +34,7 @@ THE SOFTWARE.
namespace flatbuffers
{
struct FlatBufferBuilder;
class FlatBufferBuilder;
struct NodeAction;
struct TimeLine;

View File

@ -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();
}

View File

@ -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

View File

@ -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());

View File

@ -32,7 +32,7 @@
namespace flatbuffers
{
struct FlatBufferBuilder;
class FlatBufferBuilder;
struct NodeTree;

View File

@ -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()
{

View File

@ -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);

View File

@ -1447,8 +1447,10 @@ struct ListViewOptions : private flatbuffers::Table {
const FlatSize *innerSize() const { return GetStruct<const FlatSize *>(28); }
int32_t direction() const { return GetField<int32_t>(30, 0); }
uint8_t bounceEnabled() const { return GetField<uint8_t>(32, 0); }
int32_t gravity() const { return GetField<int32_t>(34, 0); }
int32_t itemMargin() const { return GetField<int32_t>(36, 0); }
int32_t itemMargin() const { return GetField<int32_t>(34, 0); }
const flatbuffers::String *directionType() const { return GetPointer<const flatbuffers::String *>(36); }
const flatbuffers::String *horizontalType() const { return GetPointer<const flatbuffers::String *>(38); }
const flatbuffers::String *verticalType() const { return GetPointer<const flatbuffers::String *>(40); }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyField<flatbuffers::uoffset_t>(verifier, 4 /* widgetOptions */) &&
@ -1468,8 +1470,13 @@ struct ListViewOptions : private flatbuffers::Table {
VerifyField<FlatSize>(verifier, 28 /* innerSize */) &&
VerifyField<int32_t>(verifier, 30 /* direction */) &&
VerifyField<uint8_t>(verifier, 32 /* bounceEnabled */) &&
VerifyField<int32_t>(verifier, 34 /* gravity */) &&
VerifyField<int32_t>(verifier, 36 /* itemMargin */) &&
VerifyField<int32_t>(verifier, 34 /* itemMargin */) &&
VerifyField<flatbuffers::uoffset_t>(verifier, 36 /* directionType */) &&
verifier.Verify(directionType()) &&
VerifyField<flatbuffers::uoffset_t>(verifier, 38 /* horizontalType */) &&
verifier.Verify(horizontalType()) &&
VerifyField<flatbuffers::uoffset_t>(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<int32_t>(30, direction, 0); }
void add_bounceEnabled(uint8_t bounceEnabled) { fbb_.AddElement<uint8_t>(32, bounceEnabled, 0); }
void add_gravity(int32_t gravity) { fbb_.AddElement<int32_t>(34, gravity, 0); }
void add_itemMargin(int32_t itemMargin) { fbb_.AddElement<int32_t>(36, itemMargin, 0); }
void add_itemMargin(int32_t itemMargin) { fbb_.AddElement<int32_t>(34, itemMargin, 0); }
void add_directionType(flatbuffers::Offset<flatbuffers::String> directionType) { fbb_.AddOffset(36, directionType); }
void add_horizontalType(flatbuffers::Offset<flatbuffers::String> horizontalType) { fbb_.AddOffset(38, horizontalType); }
void add_verticalType(flatbuffers::Offset<flatbuffers::String> verticalType) { fbb_.AddOffset(40, verticalType); }
ListViewOptionsBuilder(flatbuffers::FlatBufferBuilder &_fbb) : fbb_(_fbb) { start_ = fbb_.StartTable(); }
ListViewOptionsBuilder &operator=(const ListViewOptionsBuilder &);
flatbuffers::Offset<ListViewOptions> Finish() {
auto o = flatbuffers::Offset<ListViewOptions>(fbb_.EndTable(start_, 17));
auto o = flatbuffers::Offset<ListViewOptions>(fbb_.EndTable(start_, 19));
return o;
}
};
@ -1518,11 +1527,15 @@ inline flatbuffers::Offset<ListViewOptions> 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<flatbuffers::String> directionType = 0,
flatbuffers::Offset<flatbuffers::String> horizontalType = 0,
flatbuffers::Offset<flatbuffers::String> 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<TimeLineColorFrame> CreateTimeLineColorFrame(flatbuff
struct TimeLineTextureFrame : private flatbuffers::Table {
int32_t frameIndex() const { return GetField<int32_t>(4, 0); }
uint8_t tween() const { return GetField<uint8_t>(6, 1); }
const flatbuffers::String *path() const { return GetPointer<const flatbuffers::String *>(8); }
const ResourceData *fileNameData() const { return GetPointer<const ResourceData *>(8); }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyField<int32_t>(verifier, 4 /* frameIndex */) &&
VerifyField<uint8_t>(verifier, 6 /* tween */) &&
VerifyField<flatbuffers::uoffset_t>(verifier, 8 /* path */) &&
verifier.Verify(path()) &&
VerifyField<flatbuffers::uoffset_t>(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<int32_t>(4, frameIndex, 0); }
void add_tween(uint8_t tween) { fbb_.AddElement<uint8_t>(6, tween, 1); }
void add_path(flatbuffers::Offset<flatbuffers::String> path) { fbb_.AddOffset(8, path); }
void add_fileNameData(flatbuffers::Offset<ResourceData> fileNameData) { fbb_.AddOffset(8, fileNameData); }
TimeLineTextureFrameBuilder(flatbuffers::FlatBufferBuilder &_fbb) : fbb_(_fbb) { start_ = fbb_.StartTable(); }
TimeLineTextureFrameBuilder &operator=(const TimeLineTextureFrameBuilder &);
flatbuffers::Offset<TimeLineTextureFrame> Finish() {
@ -2053,9 +2066,9 @@ struct TimeLineTextureFrameBuilder {
inline flatbuffers::Offset<TimeLineTextureFrame> CreateTimeLineTextureFrame(flatbuffers::FlatBufferBuilder &_fbb,
int32_t frameIndex = 0,
uint8_t tween = 1,
flatbuffers::Offset<flatbuffers::String> path = 0) {
flatbuffers::Offset<ResourceData> fileNameData = 0) {
TimeLineTextureFrameBuilder builder_(_fbb);
builder_.add_path(path);
builder_.add_fileNameData(fileNameData);
builder_.add_frameIndex(frameIndex);
builder_.add_tween(tween);
return builder_.Finish();

View File

@ -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> nodeTree;
Offset<NodeAction> 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<const char *>(builder.GetBufferPointer()),
builder.GetSize(),
reinterpret_cast<const char *>(_builder->GetBufferPointer()),
_builder->GetSize(),
true);
if (!save)
{
return "couldn't save files!";
}
deleteFlatBufferBuilder();
}
return "";
@ -268,7 +280,7 @@ Offset<NodeTree> 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<NodeTree> 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<NodeTree> 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<NodeTree> 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> nodeTree;
Offset<NodeAction> 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<NodeTree> 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> options;
std::vector<Offset<NodeTree>> children;
if (classname == "ProjectNode")
{
auto projectNodeOptions = createProjectNodeOptionsForSimulator(objectData);
options = CreateOptions(*_builder, *(Offset<Table>*)(&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<NodeReaderProtocol*>(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<ProjectNodeOptions> FlatBuffersSerialize::createProjectNodeOptionsForSimulator(const tinyxml2::XMLElement *objectData)
{
auto temp = NodeReader::getInstance()->createOptionsWithFlatBuffers(objectData, _builder);
auto nodeOptions = *(Offset<WidgetOptions>*)(&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<NodeAction> 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<TimeLine> 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<TimeLine> FlatBuffersSerialize::createTimeLine(const tinyxml2::XMLElement
0, // VisibleFrame
0, // ZOrderFrame
rotationSkewFrame);
frames.push_back(frame);
}
else if (frameType == FrameType_EventFrame)
{
@ -852,8 +607,6 @@ Offset<TimeLine> FlatBuffersSerialize::createTimeLine(const tinyxml2::XMLElement
0, // ZOrderFrame
0, // RotationSkewFrame
eventFrame);
frames.push_back(frame);
}
else if (frameType == FrameType_AnchorFrame)
{
@ -864,8 +617,6 @@ Offset<TimeLine> FlatBuffersSerialize::createTimeLine(const tinyxml2::XMLElement
0, // RotationSkewFrame
0, // EventFrame
anchorPointFrame);
frames.push_back(frame);
}
else if (frameType == FrameType_PositionFrame)
{
@ -877,12 +628,10 @@ Offset<TimeLine> 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<TimeLine> 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<TimeLine> 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<TimeLine> FlatBuffersSerialize::createTimeLine(const tinyxml2::XMLElement
0, // ColorFrame
textureFrame);
}
frames.push_back(frame);
frameElement = frameElement->NextSiblingElement();
}
@ -1136,83 +886,323 @@ Offset<TimeLineColorFrame> FlatBuffersSerialize::createTimeLineColorFrame(const
&f_color);
}
Offset<TimeLineTextureFrame> FlatBuffersSerialize::createTimeLineTextureFrame(const tinyxml2::XMLElement *objectData)
Offset<TimeLineTextureFrame> 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> nodeTree;
Offset<NodeAction> 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<NodeTree> 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> options;
std::vector<Offset<NodeTree>> children;
if (classname == "ProjectNode")
{
auto projectNodeOptions = createProjectNodeOptionsForSimulator(objectData);
options = CreateOptions(*_builder, *(Offset<Table>*)(&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<NodeReaderProtocol*>(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<ProjectNodeOptions> FlatBuffersSerialize::createProjectNodeOptionsForSimulator(const tinyxml2::XMLElement *objectData)
{
auto temp = NodeReader::getInstance()->createOptionsWithFlatBuffers(objectData, _builder);
auto nodeOptions = *(Offset<WidgetOptions>*)(&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));
}
}
/**/
/**/

View File

@ -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<flatbuffers::NodeTree> createNodeTree(const tinyxml2::XMLElement* objectData,
std::string classType);
std::string classType);
// NodeAction
flatbuffers::Offset<flatbuffers::NodeAction> createNodeAction(const tinyxml2::XMLElement* objectData);
@ -110,17 +118,17 @@ public:
flatbuffers::Offset<flatbuffers::TimeLineTextureFrame> createTimeLineTextureFrame(const tinyxml2::XMLElement* objectData);
/**/
flatbuffers::FlatBufferBuilder* createFlatBuffersWithXMLFileForSimulator(const std::string& xmlFileName);
flatbuffers::Offset<flatbuffers::NodeTree> createNodeTreeForSimulator(const tinyxml2::XMLElement* objectData,
std::string classType);
flatbuffers::Offset<flatbuffers::ProjectNodeOptions> 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<flatbuffers::NodeTree> createNodeTreeForSimulator(const tinyxml2::XMLElement* objectData,
std::string classType);
flatbuffers::Offset<flatbuffers::ProjectNodeOptions> createProjectNodeOptionsForSimulator(const tinyxml2::XMLElement* objectData);
/**/
public:
std::vector<flatbuffers::Offset<flatbuffers::String>> _textures;
std::vector<flatbuffers::Offset<flatbuffers::String>> _texturePngs;
@ -131,7 +139,6 @@ private:
flatbuffers::Offset<flatbuffers::CSParseBinary>* _csparsebinary;
};
}
#endif /* defined(__cocos2d_libs__FlatBuffersSerialize__) */

View File

@ -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);
}
}

View File

@ -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<WidgetOptions>*)(&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<CheckBox*>(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);

View File

@ -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;
}
}
}

View File

@ -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;

View File

@ -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)

View File

@ -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)

View File

@ -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<WidgetOptions>*)(&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<Table>*)(&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)

View File

@ -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<LoadingBar*>(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));

View File

@ -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,

View File

@ -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)

View File

@ -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;

View File

@ -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;

View File

@ -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)

View File

@ -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"

View File

@ -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);

View File

@ -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;
}
}
}

View File

@ -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;

View File

@ -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);

View File

@ -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<TextField*>(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)

View File

@ -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<Text*>(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)

View File

@ -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;

View File

@ -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<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));

View File

@ -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

View File

@ -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;

View File

@ -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<String> 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<String> strList = new LinkedList<String>();
/* 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 " ";
}

View File

@ -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();

View File

@ -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();
}

View File

@ -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());
}

View File

@ -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() {

View File

@ -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<Integer> streamIDs = this.mPathStreamIDsMap.get(pPath);
final ArrayList<Integer> 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<Integer> streamIDs = this.mPathStreamIDsMap.get(pPath);
ArrayList<Integer> streamIDs = this.mPathStreamIDsMap.get(path);
if (streamIDs == null) {
streamIDs = new ArrayList<Integer>();
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;

View File

@ -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);
}
// ===========================================================

View File

@ -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;

View File

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

View File

@ -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);
}
}

View File

@ -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<Cocos2dxWebView> 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<Cocos2dxWebView>();
}
@ -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> T callInMainThread(Callable<T> call) throws ExecutionException, InterruptedException {
FutureTask<T> task = new FutureTask<T>(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);

View File

@ -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)

View File

@ -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]))
{

View File

@ -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();

View File

@ -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;

View File

@ -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);

View File

@ -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.<br>
-- param jsonName UI file name<br>
-- param actionName action name in teh UIfile.<br>
-- 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.<br>
-- param jsonName UI file name<br>
@ -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

View File

@ -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

View File

@ -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

View File

@ -15,6 +15,12 @@
-- @function [parent=#EventFrame] init
-- @param self
--------------------------------
--
-- @function [parent=#EventFrame] setNode
-- @param self
-- @param #cc.Node node
--------------------------------
--
-- @function [parent=#EventFrame] getEvent

View File

@ -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)

View File

@ -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<cocos2d::Node>(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);

View File

@ -28,4 +28,5 @@ int register_all_cocos2dx_csloader(lua_State* tolua_S);
#endif // __cocos2dx_csloader_h__

View File

@ -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<cocostudio::ActionObject>(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<cocostudio::ActionObject>(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<cocostudio::ActionObject>(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<cocostudio::timeline::ActionTimeline>(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<cocos2d::Node>(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);

View File

@ -483,6 +483,9 @@ int register_all_cocos2dx_studio(lua_State* tolua_S);

View File

@ -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<cocos2d::ui::LoadingBar>(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<cocos2d::ui::LoadingBar>(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:

View File

@ -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

View File

@ -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 =
{

View File

@ -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)
{

View File

@ -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)

View File

@ -132,7 +132,6 @@ private:
Vec2 _anchorPoint;
UIEditBoxImplIOS_objc* _systemControl;
int _maxTextLength;
bool _inRetinaMode;
};

View File

@ -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<CCEAGLView *>(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<CCEAGLView *>(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<CCEAGLView *>(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()

View File

@ -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

View File

@ -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;
};
}

View File

@ -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;
}

View File

@ -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<Layout*>(node);
int length;
if (layout) {
if (layout)
{
length = layout->calculateNearestDistance(baseWidget);
}
else
{
Widget* w = dynamic_cast<Widget*>(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<Layout*>(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<Widget*>(_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<Layout*>(node);
if (layout) {
if (layout)
{
widget = layout->findFirstNonLayoutWidget();
if (widget != nullptr) {
if (widget != nullptr)
{
return widget;
}
}
else{
else
{
Widget *w = dynamic_cast<Widget*>(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<Layout*>(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<Layout*>(current)) {
if (dynamic_cast<Layout*>(current))
{
return current;
}
else
@ -1538,7 +1574,8 @@ Widget* Layout::getPreviousFocusedWidget(FocusDirection direction, Widget *curre
{
return Widget::findNextFocusedWidget(direction, this);
}
if (dynamic_cast<Layout*>(current)) {
if (dynamic_cast<Layout*>(current))
{
return current;
}
else
@ -1567,7 +1604,6 @@ Widget* Layout::getNextFocusedWidget(FocusDirection direction, Widget *current)
{
if (nextWidget->isFocusEnabled())
{
Layout* layout = dynamic_cast<Layout*>(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<Layout*>(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<Layout*>(w)) {
if (parent) {
if (dynamic_cast<Layout*>(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;

View File

@ -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<Widget*>(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<int>(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<int>(EventType::ON_SELECTED_ITEM_END));
}
}
break;
}

Some files were not shown because too many files have changed in this diff Show More