# By chuanweizhang2013 (30) and others
# Via chuanweizhang2013 (19) and others
* 'v3' of https://github.com/cocos2d/cocos2d-x: (78 commits)
  fix ui::Helper::seekWigetByName can not find pages in pageview
  [AUTO][ci skip]: updating cocos2dx_files.json
  add const for getter. fixed redefinition of 'registerListeners'
  Update CCController-android.cpp
  fixed missing function
  issue #4689: Refactoring game controller API[ios]
  Add resources
  version1.2
  Remove useless codes
  Refactoring game controller API
  should not include android cpp files in win/wp project
  Remove useless codes
  Remove useless codes
  Add Lua bindings for utils and CaptureScreen test case
  revert Android.mk
  issue #4689: Refactor controller API.
  add setXXTEAKeyAndSign
  fix indent problems
  initialize member variable
  fix windows compile and running error
  ...
This commit is contained in:
mannewalis 2014-07-05 12:26:44 -07:00
commit f238593bfb
206 changed files with 41112 additions and 6343 deletions

View File

@ -1,4 +1,4 @@
cocos2d-x-3.2beta0 Jul.2 2014
cocos2d-x-3.2rc0 ??
[NEW] FastTMXTiledMap: added fast tmx, which is much more faster for static tiled map
[NEW] GLProgramState: can use uniform location to get/set uniform values
[NEW] HttpClient: added sendImmediate()

View File

@ -53,23 +53,7 @@ def check_environment_variables_sdk():
return SDK_ROOT
def select_toolchain_version():
'''Because ndk-r8e uses gcc4.6 as default. gcc4.6 doesn't support c++11. So we should select gcc4.7 when
using ndk-r8e. But gcc4.7 is removed in ndk-r9, so we should determine whether gcc4.7 exist.
Conclution:
ndk-r8e -> use gcc4.7
ndk-r9 -> use gcc4.8
'''
ndk_root = check_environment_variables()
if os.path.isdir(os.path.join(ndk_root,"toolchains/arm-linux-androideabi-4.8")):
os.environ['NDK_TOOLCHAIN_VERSION'] = '4.8'
print "The Selected NDK toolchain version was 4.8 !"
elif os.path.isdir(os.path.join(ndk_root,"toolchains/arm-linux-androideabi-4.7")):
os.environ['NDK_TOOLCHAIN_VERSION'] = '4.7'
print "The Selected NDK toolchain version was 4.7 !"
else:
print "Couldn't find the gcc toolchain."
exit(1)
pass
def caculate_built_samples(args):
''' Compute the sampels to be built

View File

@ -1025,23 +1025,12 @@
373B912A187891FB00198F86 /* CCComBase.h in Headers */ = {isa = PBXBuildFile; fileRef = 373B910718787C0B00198F86 /* CCComBase.h */; };
3E6176681960F89B00DE83F5 /* CCController-iOS.mm in Sources */ = {isa = PBXBuildFile; fileRef = 3E6176551960F89B00DE83F5 /* CCController-iOS.mm */; };
3E6176691960F89B00DE83F5 /* CCController.h in Headers */ = {isa = PBXBuildFile; fileRef = 3E6176561960F89B00DE83F5 /* CCController.h */; };
3E61766A1960F89B00DE83F5 /* CCControllerAxisInput.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3E6176571960F89B00DE83F5 /* CCControllerAxisInput.cpp */; };
3E61766B1960F89B00DE83F5 /* CCControllerAxisInput.h in Headers */ = {isa = PBXBuildFile; fileRef = 3E6176581960F89B00DE83F5 /* CCControllerAxisInput.h */; };
3E61766C1960F89B00DE83F5 /* CCControllerButtonInput.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3E6176591960F89B00DE83F5 /* CCControllerButtonInput.cpp */; };
3E61766D1960F89B00DE83F5 /* CCControllerButtonInput.h in Headers */ = {isa = PBXBuildFile; fileRef = 3E61765A1960F89B00DE83F5 /* CCControllerButtonInput.h */; };
3E61766E1960F89B00DE83F5 /* CCControllerDirectionPad.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3E61765B1960F89B00DE83F5 /* CCControllerDirectionPad.cpp */; };
3E61766F1960F89B00DE83F5 /* CCControllerDirectionPad.h in Headers */ = {isa = PBXBuildFile; fileRef = 3E61765C1960F89B00DE83F5 /* CCControllerDirectionPad.h */; };
3E6176701960F89B00DE83F5 /* CCControllerElement.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3E61765D1960F89B00DE83F5 /* CCControllerElement.cpp */; };
3E6176711960F89B00DE83F5 /* CCControllerElement.h in Headers */ = {isa = PBXBuildFile; fileRef = 3E61765E1960F89B00DE83F5 /* CCControllerElement.h */; };
3E6176721960F89B00DE83F5 /* CCControllerThumbstick.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3E61765F1960F89B00DE83F5 /* CCControllerThumbstick.cpp */; };
3E6176731960F89B00DE83F5 /* CCControllerThumbstick.h in Headers */ = {isa = PBXBuildFile; fileRef = 3E6176601960F89B00DE83F5 /* CCControllerThumbstick.h */; };
3E6176741960F89B00DE83F5 /* CCEventController.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3E6176611960F89B00DE83F5 /* CCEventController.cpp */; };
3E6176751960F89B00DE83F5 /* CCEventController.h in Headers */ = {isa = PBXBuildFile; fileRef = 3E6176621960F89B00DE83F5 /* CCEventController.h */; };
3E6176761960F89B00DE83F5 /* CCEventListenerController.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3E6176631960F89B00DE83F5 /* CCEventListenerController.cpp */; };
3E6176771960F89B00DE83F5 /* CCEventListenerController.h in Headers */ = {isa = PBXBuildFile; fileRef = 3E6176641960F89B00DE83F5 /* CCEventListenerController.h */; };
3E6176781960F89B00DE83F5 /* CCGameController.h in Headers */ = {isa = PBXBuildFile; fileRef = 3E6176651960F89B00DE83F5 /* CCGameController.h */; };
3E6176791960F89B00DE83F5 /* CCGamepad.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3E6176661960F89B00DE83F5 /* CCGamepad.cpp */; };
3E61767A1960F89B00DE83F5 /* CCGamepad.h in Headers */ = {isa = PBXBuildFile; fileRef = 3E6176671960F89B00DE83F5 /* CCGamepad.h */; };
3E61781D1966A5A300DE83F5 /* CCController.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3E61781C1966A5A300DE83F5 /* CCController.cpp */; };
3EA0FB6B191C841D00B170C8 /* UIVideoPlayer.h in Headers */ = {isa = PBXBuildFile; fileRef = 3EA0FB69191C841D00B170C8 /* UIVideoPlayer.h */; };
3EA0FB6C191C841D00B170C8 /* UIVideoPlayerIOS.mm in Sources */ = {isa = PBXBuildFile; fileRef = 3EA0FB6A191C841D00B170C8 /* UIVideoPlayerIOS.mm */; };
3EA47870195478E00068D9D1 /* CCBundleReader.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3EA4786E195478E00068D9D1 /* CCBundleReader.cpp */; };
@ -2370,23 +2359,12 @@
37936A3E1869B76800E974DD /* writer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = writer.h; sourceTree = "<group>"; };
3E6176551960F89B00DE83F5 /* CCController-iOS.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = "CCController-iOS.mm"; path = "../base/CCController-iOS.mm"; sourceTree = "<group>"; };
3E6176561960F89B00DE83F5 /* CCController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CCController.h; path = ../base/CCController.h; sourceTree = "<group>"; };
3E6176571960F89B00DE83F5 /* CCControllerAxisInput.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = CCControllerAxisInput.cpp; path = ../base/CCControllerAxisInput.cpp; sourceTree = "<group>"; };
3E6176581960F89B00DE83F5 /* CCControllerAxisInput.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CCControllerAxisInput.h; path = ../base/CCControllerAxisInput.h; sourceTree = "<group>"; };
3E6176591960F89B00DE83F5 /* CCControllerButtonInput.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = CCControllerButtonInput.cpp; path = ../base/CCControllerButtonInput.cpp; sourceTree = "<group>"; };
3E61765A1960F89B00DE83F5 /* CCControllerButtonInput.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CCControllerButtonInput.h; path = ../base/CCControllerButtonInput.h; sourceTree = "<group>"; };
3E61765B1960F89B00DE83F5 /* CCControllerDirectionPad.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = CCControllerDirectionPad.cpp; path = ../base/CCControllerDirectionPad.cpp; sourceTree = "<group>"; };
3E61765C1960F89B00DE83F5 /* CCControllerDirectionPad.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CCControllerDirectionPad.h; path = ../base/CCControllerDirectionPad.h; sourceTree = "<group>"; };
3E61765D1960F89B00DE83F5 /* CCControllerElement.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = CCControllerElement.cpp; path = ../base/CCControllerElement.cpp; sourceTree = "<group>"; };
3E61765E1960F89B00DE83F5 /* CCControllerElement.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CCControllerElement.h; path = ../base/CCControllerElement.h; sourceTree = "<group>"; };
3E61765F1960F89B00DE83F5 /* CCControllerThumbstick.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = CCControllerThumbstick.cpp; path = ../base/CCControllerThumbstick.cpp; sourceTree = "<group>"; };
3E6176601960F89B00DE83F5 /* CCControllerThumbstick.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CCControllerThumbstick.h; path = ../base/CCControllerThumbstick.h; sourceTree = "<group>"; };
3E6176611960F89B00DE83F5 /* CCEventController.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = CCEventController.cpp; path = ../base/CCEventController.cpp; sourceTree = "<group>"; };
3E6176621960F89B00DE83F5 /* CCEventController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CCEventController.h; path = ../base/CCEventController.h; sourceTree = "<group>"; };
3E6176631960F89B00DE83F5 /* CCEventListenerController.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = CCEventListenerController.cpp; path = ../base/CCEventListenerController.cpp; sourceTree = "<group>"; };
3E6176641960F89B00DE83F5 /* CCEventListenerController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CCEventListenerController.h; path = ../base/CCEventListenerController.h; sourceTree = "<group>"; };
3E6176651960F89B00DE83F5 /* CCGameController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CCGameController.h; path = ../base/CCGameController.h; sourceTree = "<group>"; };
3E6176661960F89B00DE83F5 /* CCGamepad.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = CCGamepad.cpp; path = ../base/CCGamepad.cpp; sourceTree = "<group>"; };
3E6176671960F89B00DE83F5 /* CCGamepad.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CCGamepad.h; path = ../base/CCGamepad.h; sourceTree = "<group>"; };
3E61781C1966A5A300DE83F5 /* CCController.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = CCController.cpp; path = ../base/CCController.cpp; sourceTree = "<group>"; };
3EA0FB69191C841D00B170C8 /* UIVideoPlayer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = UIVideoPlayer.h; sourceTree = "<group>"; };
3EA0FB6A191C841D00B170C8 /* UIVideoPlayerIOS.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = UIVideoPlayerIOS.mm; sourceTree = "<group>"; };
3EA4786E195478E00068D9D1 /* CCBundleReader.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCBundleReader.cpp; sourceTree = "<group>"; };
@ -3187,25 +3165,14 @@
1A5700A2180BC5E60088DEC7 /* base */ = {
isa = PBXGroup;
children = (
3E61781C1966A5A300DE83F5 /* CCController.cpp */,
3E6176551960F89B00DE83F5 /* CCController-iOS.mm */,
3E6176561960F89B00DE83F5 /* CCController.h */,
3E6176571960F89B00DE83F5 /* CCControllerAxisInput.cpp */,
3E6176581960F89B00DE83F5 /* CCControllerAxisInput.h */,
3E6176591960F89B00DE83F5 /* CCControllerButtonInput.cpp */,
3E61765A1960F89B00DE83F5 /* CCControllerButtonInput.h */,
3E61765B1960F89B00DE83F5 /* CCControllerDirectionPad.cpp */,
3E61765C1960F89B00DE83F5 /* CCControllerDirectionPad.h */,
3E61765D1960F89B00DE83F5 /* CCControllerElement.cpp */,
3E61765E1960F89B00DE83F5 /* CCControllerElement.h */,
3E61765F1960F89B00DE83F5 /* CCControllerThumbstick.cpp */,
3E6176601960F89B00DE83F5 /* CCControllerThumbstick.h */,
3E6176611960F89B00DE83F5 /* CCEventController.cpp */,
3E6176621960F89B00DE83F5 /* CCEventController.h */,
3E6176631960F89B00DE83F5 /* CCEventListenerController.cpp */,
3E6176641960F89B00DE83F5 /* CCEventListenerController.h */,
3E6176651960F89B00DE83F5 /* CCGameController.h */,
3E6176661960F89B00DE83F5 /* CCGamepad.cpp */,
3E6176671960F89B00DE83F5 /* CCGamepad.h */,
299754F2193EC95400A54AC3 /* ObjectFactory.cpp */,
299754F3193EC95400A54AC3 /* ObjectFactory.h */,
50ABBDC11925AB6E00A911A9 /* atitc.cpp */,
@ -5571,7 +5538,6 @@
1A570068180BC5A10088DEC7 /* CCActionCamera.h in Headers */,
1A57006C180BC5A10088DEC7 /* CCActionCatmullRom.h in Headers */,
5034CA3A191D591100CE6051 /* ccShader_PositionColorLengthTexture.frag in Headers */,
3E61766B1960F89B00DE83F5 /* CCControllerAxisInput.h in Headers */,
50ABBEC41925AB6F00A911A9 /* CCVector.h in Headers */,
50ABBE501925AB6F00A911A9 /* CCEventCustom.h in Headers */,
1A570070180BC5A10088DEC7 /* CCActionEase.h in Headers */,
@ -5608,7 +5574,6 @@
50ABC0101926664800A911A9 /* CCFileUtils.h in Headers */,
2905FA4318CF08D100240AA3 /* CocosGUI.h in Headers */,
5034CA30191D591100CE6051 /* ccShader_PositionTexture.vert in Headers */,
3E6176711960F89B00DE83F5 /* CCControllerElement.h in Headers */,
50E6D33718E174130051CA34 /* UIHBox.h in Headers */,
1A570111180BC8EE0088DEC7 /* CCDrawingPrimitives.h in Headers */,
50E6D33F18E174130051CA34 /* UIVBox.h in Headers */,
@ -5676,7 +5641,6 @@
5034CA2C191D591100CE6051 /* ccShader_PositionTextureA8Color.vert in Headers */,
50ABBE981925AB6F00A911A9 /* CCProtocols.h in Headers */,
2905FA8B18CF08D100240AA3 /* UITextField.h in Headers */,
3E6176731960F89B00DE83F5 /* CCControllerThumbstick.h in Headers */,
50FCEBA618C72017004AD434 /* ListViewReader.h in Headers */,
50ABBD431925AB0000A911A9 /* CCMathBase.h in Headers */,
50ABBE441925AB6F00A911A9 /* CCDirector.h in Headers */,
@ -5695,7 +5659,6 @@
50ABBE741925AB6F00A911A9 /* CCEventListenerMouse.h in Headers */,
2905FA8F18CF08D100240AA3 /* UIWidget.h in Headers */,
50FCEB9A18C72017004AD434 /* CheckBoxReader.h in Headers */,
3E61766D1960F89B00DE83F5 /* CCControllerButtonInput.h in Headers */,
1A5702CB180BCE370088DEC7 /* CCTextFieldTTF.h in Headers */,
2905FA7F18CF08D100240AA3 /* UIText.h in Headers */,
1A5702ED180BCE750088DEC7 /* CCTileMapAtlas.h in Headers */,
@ -5708,7 +5671,6 @@
1A570303180BCE890088DEC7 /* CCParallaxNode.h in Headers */,
50ABBE2A1925AB6F00A911A9 /* CCAutoreleasePool.h in Headers */,
1A57030F180BCF190088DEC7 /* CCComponent.h in Headers */,
3E61766F1960F89B00DE83F5 /* CCControllerDirectionPad.h in Headers */,
1A570313180BCF190088DEC7 /* CCComponentContainer.h in Headers */,
0634A4DF194B19E400E608AF /* CCNodeReader.h in Headers */,
1A087AEB1860400400196EF5 /* edtaa3func.h in Headers */,
@ -5815,7 +5777,6 @@
1AD71ED0180E26E600808F54 /* Skeleton.h in Headers */,
50ABBE541925AB6F00A911A9 /* CCEventDispatcher.h in Headers */,
1AD71ED4180E26E600808F54 /* SkeletonData.h in Headers */,
3E61767A1960F89B00DE83F5 /* CCGamepad.h in Headers */,
1AD71ED8180E26E600808F54 /* SkeletonJson.h in Headers */,
1A12775A18DFCC4F0005F345 /* CCTweenFunction.h in Headers */,
1AD71EDC180E26E600808F54 /* Skin.h in Headers */,
@ -6752,7 +6713,6 @@
3E6176681960F89B00DE83F5 /* CCController-iOS.mm in Sources */,
2905FA8D18CF08D100240AA3 /* UIWidget.cpp in Sources */,
29E99D1F1957BA7000046604 /* CocoLoader.cpp in Sources */,
3E61766C1960F89B00DE83F5 /* CCControllerButtonInput.cpp in Sources */,
B29594B51926D5EC003EEF37 /* CCMeshCommand.cpp in Sources */,
0634A4D5194B19E400E608AF /* CCActionTimelineCache.cpp in Sources */,
50ABBE7E1925AB6F00A911A9 /* CCEventTouch.cpp in Sources */,
@ -6792,6 +6752,7 @@
1A57019E180BCB590088DEC7 /* CCFont.cpp in Sources */,
503DD8E21926736A00CD74DD /* CCCommon.mm in Sources */,
1A5701A2180BCB590088DEC7 /* CCFontAtlas.cpp in Sources */,
3E61781D1966A5A300DE83F5 /* CCController.cpp in Sources */,
50ABC00E1926664800A911A9 /* CCFileUtils.cpp in Sources */,
50ABBE241925AB6F00A911A9 /* base64.cpp in Sources */,
1A5701A6180BCB590088DEC7 /* CCFontAtlasCache.cpp in Sources */,
@ -6831,13 +6792,11 @@
1A570215180BCBF40088DEC7 /* CCRenderTexture.cpp in Sources */,
1A570222180BCC1A0088DEC7 /* CCParticleBatchNode.cpp in Sources */,
1A570226180BCC1A0088DEC7 /* CCParticleExamples.cpp in Sources */,
3E6176791960F89B00DE83F5 /* CCGamepad.cpp in Sources */,
1A57022A180BCC1A0088DEC7 /* CCParticleSystem.cpp in Sources */,
B24AA98A195A675C007B4522 /* CCFastTMXTiledMap.cpp in Sources */,
B24AA986195A675C007B4522 /* CCFastTMXLayer.cpp in Sources */,
1A57022E180BCC1A0088DEC7 /* CCParticleSystemQuad.cpp in Sources */,
50ABBD901925AB4100A911A9 /* CCGLProgramCache.cpp in Sources */,
3E6176701960F89B00DE83F5 /* CCControllerElement.cpp in Sources */,
2905FA5718CF08D100240AA3 /* UILayout.cpp in Sources */,
2905FA7D18CF08D100240AA3 /* UIText.cpp in Sources */,
50E6D33D18E174130051CA34 /* UIVBox.cpp in Sources */,
@ -6853,7 +6812,6 @@
1A5702C9180BCE370088DEC7 /* CCTextFieldTTF.cpp in Sources */,
1A5702EB180BCE750088DEC7 /* CCTileMapAtlas.cpp in Sources */,
1A5702EF180BCE750088DEC7 /* CCTMXLayer.cpp in Sources */,
3E61766A1960F89B00DE83F5 /* CCControllerAxisInput.cpp in Sources */,
1A5702F3180BCE750088DEC7 /* CCTMXObjectGroup.cpp in Sources */,
50ABBD3D1925AB0000A911A9 /* CCGeometry.cpp in Sources */,
50ABBECC1925AB6F00A911A9 /* s3tc.cpp in Sources */,
@ -6966,7 +6924,6 @@
50ABBE9A1925AB6F00A911A9 /* CCRef.cpp in Sources */,
3E6176741960F89B00DE83F5 /* CCEventController.cpp in Sources */,
50ABBE361925AB6F00A911A9 /* CCConsole.cpp in Sources */,
3E61766E1960F89B00DE83F5 /* CCControllerDirectionPad.cpp in Sources */,
503DD8E51926736A00CD74DD /* CCDirectorCaller.mm in Sources */,
50ABBD5D1925AB0000A911A9 /* Vec3.cpp in Sources */,
50ABC0121926664800A911A9 /* CCGLViewProtocol.cpp in Sources */,
@ -7005,7 +6962,6 @@
1A8C59D4180E930E00EF57C3 /* CCDecorativeDisplay.cpp in Sources */,
1A8C59D8180E930E00EF57C3 /* CCDisplayFactory.cpp in Sources */,
46C02E0818E91123004B7456 /* xxhash.c in Sources */,
3E6176721960F89B00DE83F5 /* CCControllerThumbstick.cpp in Sources */,
50ABBED01925AB6F00A911A9 /* TGAlib.cpp in Sources */,
2905FA4118CF08D100240AA3 /* CocosGUI.cpp in Sources */,
1A01C68518F57BE800EFE3A6 /* CCArray.cpp in Sources */,

View File

@ -827,8 +827,6 @@
3E6177351960FB4000DE83F5 /* AppController.mm in Sources */ = {isa = PBXBuildFile; fileRef = 3E6176DE1960FA6300DE83F5 /* AppController.mm */; };
3E6177361960FB5A00DE83F5 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 3E6176EE1960FA6300DE83F5 /* main.m */; };
3E6177371960FB5E00DE83F5 /* RootViewController.mm in Sources */ = {isa = PBXBuildFile; fileRef = 3E6176F01960FA6300DE83F5 /* RootViewController.mm */; };
3E6177391960FBB800DE83F5 /* SystemConfiguration.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3E6177381960FBB800DE83F5 /* SystemConfiguration.framework */; };
3E61773B1960FBC300DE83F5 /* CFNetwork.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3E61773A1960FBC300DE83F5 /* CFNetwork.framework */; };
3E61773D1960FBD200DE83F5 /* GameController.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3E61773C1960FBD100DE83F5 /* GameController.framework */; };
3E6177F41960FEFE00DE83F5 /* fonts in Resources */ = {isa = PBXBuildFile; fileRef = 3E6177F01960FEFE00DE83F5 /* fonts */; };
3E6177F51960FEFE00DE83F5 /* ipad in Resources */ = {isa = PBXBuildFile; fileRef = 3E6177F11960FEFE00DE83F5 /* ipad */; };
@ -2132,8 +2130,6 @@
buildActionMask = 2147483647;
files = (
3E61773D1960FBD200DE83F5 /* GameController.framework in Frameworks */,
3E61773B1960FBC300DE83F5 /* CFNetwork.framework in Frameworks */,
3E6177391960FBB800DE83F5 /* SystemConfiguration.framework in Frameworks */,
3E6177211960FAED00DE83F5 /* libchipmunk iOS.a in Frameworks */,
3E6177221960FAED00DE83F5 /* libcocos2dx iOS.a in Frameworks */,
3E6177231960FAED00DE83F5 /* libCocosDenshion iOS.a in Frameworks */,
@ -5728,6 +5724,7 @@
"$(inherited)",
CC_TARGET_OS_IPHONE,
);
GCC_PREPROCESSOR_DEFINITIONS_NOT_USED_IN_PRECOMPS = "";
INFOPLIST_FILE = "$(SRCROOT)/../tests/game-controller-test/proj.ios/Info.plist";
IPHONEOS_DEPLOYMENT_TARGET = 5.1.1;
PRODUCT_NAME = "game-controller-test IOS";
@ -5745,6 +5742,7 @@
"$(inherited)",
CC_TARGET_OS_IPHONE,
);
GCC_PREPROCESSOR_DEFINITIONS_NOT_USED_IN_PRECOMPS = "";
INFOPLIST_FILE = "$(SRCROOT)/../tests/game-controller-test/proj.ios/Info.plist";
IPHONEOS_DEPLOYMENT_TARGET = 5.1.1;
PRODUCT_NAME = "game-controller-test IOS";

View File

@ -237,7 +237,7 @@ void FastTMXLayer::updateTiles(const Rect& culledRect)
else
{
//do nothing, do not support
CCASSERT(0, "TMX invalid value");
//CCASSERT(0, "TMX invalid value");
}
_indicesVertexZNumber.clear();
@ -264,9 +264,8 @@ void FastTMXLayer::updateTiles(const Rect& culledRect)
int offset = iter->second;
iter->second++;
//CC_ASSERT(_tileToQuadIndex.find(tileIndex) != _tileToQuadIndex.end() && _tileToQuadIndex[tileIndex] <= _totalQuads.size()-1);
int quadIndex = (int)_tileToQuadIndex[tileIndex];
int quadIndex = _tileToQuadIndex[tileIndex];
CC_ASSERT(-1 != quadIndex);
_indices[6 * offset + 0] = quadIndex * 4 + 0;
_indices[6 * offset + 1] = quadIndex * 4 + 1;
_indices[6 * offset + 2] = quadIndex * 4 + 2;
@ -387,7 +386,13 @@ Mat4 FastTMXLayer::tileToNodeTransform()
}
case FAST_TMX_ORIENTATION_HEX:
{
_tileToNodeTransform = Mat4::IDENTITY;
_tileToNodeTransform = Mat4
(
h * sqrtf(0.75), 0, 0, 0,
-h/2, -h, 0, offY,
0, 0, 1, 0,
0, 0, 0, 1
);
return _tileToNodeTransform;
}
default:
@ -408,6 +413,7 @@ void FastTMXLayer::updateTotalQuads()
_tileToQuadIndex.clear();
_totalQuads.resize(int(_layerSize.width * _layerSize.height));
_indices.resize(6 * int(_layerSize.width * _layerSize.height));
_tileToQuadIndex.resize(int(_layerSize.width * _layerSize.height),-1);
_indicesVertexZOffsets.clear();
int quadIndex = 0;
@ -617,7 +623,7 @@ int FastTMXLayer::getVertexZForPos(const Vec2& pos)
ret = static_cast<int>(-(_layerSize.height-pos.y));
break;
case FAST_TMX_ORIENTATION_HEX:
CCASSERT(0, "TMX Hexa zOrder not supported");
CCASSERT(0, "TMX Hexa vertexZ not supported");
break;
default:
CCASSERT(0, "TMX invalid value");

View File

@ -239,7 +239,7 @@ protected:
Mat4 _tileToNodeTransform;
/** data for rendering */
bool _quadsDirty;
std::unordered_map<ssize_t, ssize_t> _tileToQuadIndex;
std::vector<int> _tileToQuadIndex;
std::vector<V3F_C4B_T2F_Quad> _totalQuads;
std::vector<int> _indices;
std::map<int/*vertexZ*/, int/*offset to _indices by quads*/> _indicesVertexZOffsets;

View File

@ -861,25 +861,24 @@ void Node::enumerateChildren(const std::string &name, std::function<bool (Node *
}
}
// TODO: support ends with '/..'
// End with '/..'?
// bool searchFromParent = false;
// if (length > 3 &&
// name[length-3] == '/' &&
// name[length-2] == '.' &&
// name[length-1] == '.')
// {
// searchFromParent = true;
// subStrlength -= 3;
// }
bool searchFromParent = false;
if (length > 3 &&
name[length-3] == '/' &&
name[length-2] == '.' &&
name[length-1] == '.')
{
searchFromParent = true;
subStrlength -= 3;
}
// Remove '/', '//' if exist
// Remove '/', '//', '/..' if exist
std::string newName = name.substr(subStrStartPos, subStrlength);
// If search from parent, then add * at first to make it match its children, which will do make
// if (searchFromParent)
// {
// newName.insert(0, "[[:alnum:]]+/");
// }
if (searchFromParent)
{
newName.insert(0, "[[:alnum:]]+/");
}
if (searchFromRoot)
{
@ -944,14 +943,10 @@ bool Node::doEnumerate(std::string name, std::function<bool (Node *)> callback)
needRecursive = true;
}
std::hash<std::string> h;
size_t hashOfName = h(searchName);
bool ret = false;
for (const auto& child : _children)
{
// TODO: regular expression support
// Android doesn't support c++ 11 regular expression well, may use external lib
if (hashOfName == child->_hashOfName && searchName.compare(child->_name) == 0)
if (std::regex_match(child->_name, std::regex(searchName)))
{
if (!needRecursive)
{

View File

@ -714,17 +714,20 @@ public:
virtual Node* getChildByName(const std::string& name) const;
/** Search the children of the receiving node to perform processing for nodes which share a name.
*
* @param name The name to search for
* @param name The name to search for, supports c++11 regular expression
* Search syntax options:
* `/` : When placed at the start of the search string, this indicates that the search should be performed on the tree's node.
* `//`: Can only be placed at the begin of the search string. This indicates that the search should be performed on the tree's node
* and be performed recursively across the entire node tree.
* `..`: The search should move up to the node's parent. Can only be placed at the end of string
* `/` : When placed anywhere but the start of the search string, this indicates that the search should move to the node's children
*
* @code
* enumerateChildren("/MyName", ...): This searches the root's children and matches any node with the name `MyName`.
* enumerateChildren("//MyName", ...): This searches the root's children recursively and matches any node with the name `MyName`.
* enumerateChildren("[[:alnum:]]+", ...): This search string matches every node of its children.
* enumerateChildren("/MyName", ...): This searches the node tree and matches the parent node of every node named `MyName`.
* enumerateChildren("A[[:digit:]]", ...): This searches the node's children and returns any child named `A0`, `A1`, ..., `A9`
* enumerateChildren("Abby/Normal", ...): This searches the node's grandchildren and returns any node whose name is `Normal`
* and whose parent is named `Abby`.
* enumerateChildren("//Abby/Normal", ...): This searches the node tree and returns any node whose name is `Normal` and whose

View File

@ -222,7 +222,6 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<ClCompile Include="..\base\CCTouch.cpp" />
<ClCompile Include="..\base\ccTypes.cpp" />
<ClCompile Include="..\base\CCUserDefault.cpp" />
<ClCompile Include="..\base\CCUserDefaultAndroid.cpp" />
<ClCompile Include="..\base\ccUTF8.cpp" />
<ClCompile Include="..\base\ccUtils.cpp" />
<ClCompile Include="..\base\CCValue.cpp" />

View File

@ -353,7 +353,6 @@
<ClCompile Include="..\base\CCTouch.cpp" />
<ClCompile Include="..\base\ccTypes.cpp" />
<ClCompile Include="..\base\CCUserDefault.cpp" />
<ClCompile Include="..\base\CCUserDefaultAndroid.cpp" />
<ClCompile Include="..\base\ccUTF8.cpp" />
<ClCompile Include="..\base\ccUtils.cpp" />
<ClCompile Include="..\base\CCValue.cpp" />

View File

@ -280,7 +280,6 @@
<ClCompile Include="..\base\CCTouch.cpp" />
<ClCompile Include="..\base\ccTypes.cpp" />
<ClCompile Include="..\base\CCUserDefault.cpp" />
<ClCompile Include="..\base\CCUserDefaultAndroid.cpp" />
<ClCompile Include="..\base\ccUTF8.cpp" />
<ClCompile Include="..\base\ccUtils.cpp" />
<ClCompile Include="..\base\CCValue.cpp" />

View File

@ -141,13 +141,8 @@ base/ccUTF8.cpp \
base/ccUtils.cpp \
base/etc1.cpp \
base/s3tc.cpp \
base/CCController.cpp \
base/CCController-android.cpp \
base/CCControllerAxisInput.cpp \
base/CCControllerButtonInput.cpp \
base/CCControllerDirectionPad.cpp \
base/CCControllerElement.cpp \
base/CCControllerThumbstick.cpp \
base/CCGamepad.cpp \
base/ObjectFactory.cpp \
renderer/CCBatchCommand.cpp \
renderer/CCCustomCommand.cpp \
@ -227,10 +222,10 @@ LOCAL_WHOLE_STATIC_LIBRARIES += chipmunk_static
LOCAL_WHOLE_STATIC_LIBRARIES += cocos2dxandroid_static
# define the macro to compile through support/zip_support/ioapi.c
LOCAL_CFLAGS := -Wno-psabi -DUSE_FILE32API
LOCAL_CPPFLAGS := -Wno-literal-suffix -Wno-deprecated-declarations
LOCAL_EXPORT_CFLAGS := -Wno-psabi -DUSE_FILE32API
LOCAL_EXPORT_CPPFLAGS := -Wno-literal-suffix -Wno-deprecated-declarations
LOCAL_CFLAGS := -DUSE_FILE32API
LOCAL_CPPFLAGS := -Wno-deprecated-declarations
LOCAL_EXPORT_CFLAGS := -DUSE_FILE32API
LOCAL_EXPORT_CPPFLAGS := -Wno-deprecated-declarations
include $(BUILD_STATIC_LIBRARY)

View File

@ -15,7 +15,4 @@ LOCAL_C_INCLUDES := $(LOCAL_PATH)/../include \
$(LOCAL_PATH)/../.. \
$(LOCAL_PATH)/../../platform/android
LOCAL_CFLAGS += -Wno-psabi
LOCAL_EXPORT_CFLAGS += -Wno-psabi
include $(BUILD_STATIC_LIBRARY)

View File

@ -26,258 +26,93 @@
#include "CCController.h"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include "CCGamepad.h"
#include "CCControllerDirectionPad.h"
#include "CCControllerButtonInput.h"
#include "CCControllerAxisInput.h"
#include "CCControllerThumbstick.h"
#include <functional>
#include "ccMacros.h"
#include "CCEventDispatcher.h"
#include "CCEventController.h"
#include "CCEventListenerController.h"
#include "CCDirector.h"
#include "jni/JniHelper.h"
NS_CC_BEGIN
enum class AndroidControllerCode
{
THUMBSTICK_LEFT_X = 100,
THUMBSTICK_LEFT_Y = 101,
THUMBSTICK_RIGHT_X = 102,
THUMBSTICK_RIGHT_Y = 103,
BUTTON_A = 110,
BUTTON_B = 111,
BUTTON_C = 112,
BUTTON_X = 113,
BUTTON_Y = 114,
BUTTON_Z = 115,
BUTTON_LEFT_SHOULDER = 120,
BUTTON_RIGHT_SHOULDER = 121,
BUTTON_LEFT_TRIGGER = 122,
BUTTON_RIGHT_TRIGGER = 123,
BUTTON_DPAD_UP = 130,
BUTTON_DPAD_DOWN = 131,
BUTTON_DPAD_LEFT = 132,
BUTTON_DPAD_RIGHT = 133,
BUTTON_DPAD_CENTER = 134,
BUTTON_LEFT_THUMBSTICK = 140,
BUTTON_RIGHT_THUMBSTICK = 141,
BUTTON_START = 150,
BUTTON_SELECT = 151,
};
class ControllerImpl
{
public:
ControllerImpl(Controller* controller)
: _controller(controller)
, _controllerID(-1)
{
}
static std::vector<Controller*>::iterator findController(const std::string& vendorName, int controllerID)
static std::vector<Controller*>::iterator findController(const std::string& deviceName, int deviceId)
{
auto iter = std::find_if(Controller::_controllers.begin(), Controller::_controllers.end(), [&](Controller* controller){
return (vendorName == controller->getVendorName()) && (controllerID == controller->_impl->_controllerID);
auto iter = std::find_if(Controller::s_allController.begin(), Controller::s_allController.end(), [&](Controller* controller){
return (deviceName == controller->_deviceName) && (deviceId == controller->_deviceId);
});
}
static void onConnected(const std::string& vendorName, int controllerID)
static void onConnected(const std::string& deviceName, int deviceId)
{
// Check whether the controller is already connected.
auto iter = findController(vendorName, controllerID);
if (iter != Controller::_controllers.end())
log("onConnected %s,%d", deviceName.c_str(),deviceId);
auto iter = findController(deviceName, deviceId);
if (iter != Controller::s_allController.end())
return;
log("onConnected new device");
// It's a new controller being connected.
auto controller = new cocos2d::Controller();
controller->_vendorName = vendorName;
Controller::_controllers.push_back(controller);
controller->_impl->_controllerID = controllerID;
EventController evt(EventController::ControllerEventType::CONNECTION, controller, true);
Director::getInstance()->getEventDispatcher()->dispatchEvent(&evt);
controller->_deviceId = deviceId;
controller->_deviceName = deviceName;
Controller::s_allController.push_back(controller);
controller->onConnected();
}
static void onDisconnected(const std::string& vendorName, int controllerID)
static void onDisconnected(const std::string& deviceName, int deviceId)
{
auto iter = findController(vendorName, controllerID);
if (iter == Controller::_controllers.end())
log("onDisconnected %s,%d", deviceName.c_str(),deviceId);
auto iter = findController(deviceName, deviceId);
if (iter == Controller::s_allController.end())
{
log("Could not find the controller!");
CCLOGERROR("Could not find the controller!");
return;
}
EventController evt(EventController::ControllerEventType::CONNECTION, *iter, false);
Director::getInstance()->getEventDispatcher()->dispatchEvent(&evt);
Controller::_controllers.erase(iter);
(*iter)->onDisconnected();
Controller::s_allController.erase(iter);
}
void sendEventButton(ControllerButtonInput* button, bool isPressed, float value, bool isAnalog)
static void onButtonEvent(const std::string& deviceName, int deviceId, int keyCode, bool isPressed, float value, bool isAnalog)
{
button->setPressed(isPressed);
button->setValue(value);
button->setAnalog(isAnalog);
EventController evt(EventController::ControllerEventType::BUTTON_STATUS_CHANGED, _controller, button);
Director::getInstance()->getEventDispatcher()->dispatchEvent(&evt);
log("onButtonEvent %s,%d", deviceName.c_str(),deviceId);
auto iter = findController(deviceName, deviceId);
if (iter == Controller::s_allController.end())
{
log("onButtonEvent new connect");
onConnected(deviceName, deviceId);
iter = findController(deviceName, deviceId);
}
(*iter)->onButtonEvent(keyCode, isPressed, value, isAnalog);
}
void sendEventAxis(ControllerAxisInput* axis, float value, bool isAnalog)
static void onAxisEvent(const std::string& deviceName, int deviceId, int axisCode, float value, bool isAnalog)
{
axis->setValue(value);
axis->setAnalog(isAnalog);
EventController evt(EventController::ControllerEventType::AXIS_STATUS_CHANGED, _controller, axis);
Director::getInstance()->getEventDispatcher()->dispatchEvent(&evt);
}
static void onButtonEvent(const std::string& vendorName, int controllerID, AndroidControllerCode btnCode, bool isPressed, float value, bool isAnalog)
{
auto iter = findController(vendorName, controllerID);
if (iter == Controller::_controllers.end())
auto iter = findController(deviceName, deviceId);
if (iter == Controller::s_allController.end())
{
onConnected(vendorName, controllerID);
iter = findController(vendorName, controllerID);
onConnected(deviceName, deviceId);
iter = findController(deviceName, deviceId);
}
auto gamepad = (*iter)->getGamepad();
auto thiz = (*iter)->getImpl();
switch(btnCode)
{
case AndroidControllerCode::BUTTON_A:
{
thiz->sendEventButton(gamepad->getButtonA(), isPressed, value, isAnalog);
}
break;
case AndroidControllerCode::BUTTON_B:
{
thiz->sendEventButton(gamepad->getButtonB(), isPressed, value, isAnalog);
}
break;
case AndroidControllerCode::BUTTON_X:
{
thiz->sendEventButton(gamepad->getButtonX(), isPressed, value, isAnalog);
}
break;
case AndroidControllerCode::BUTTON_Y:
{
thiz->sendEventButton(gamepad->getButtonY(), isPressed, value, isAnalog);
}
break;
case AndroidControllerCode::BUTTON_LEFT_SHOULDER:
{
thiz->sendEventButton(gamepad->getLeftShoulder(), isPressed, value, isAnalog);
}
break;
case AndroidControllerCode::BUTTON_RIGHT_SHOULDER:
{
thiz->sendEventButton(gamepad->getRightShoulder(), isPressed, value, isAnalog);
}
break;
case AndroidControllerCode::BUTTON_LEFT_TRIGGER:
{
thiz->sendEventButton(gamepad->getLeftTrigger(), isPressed, value, isAnalog);
}
break;
case AndroidControllerCode::BUTTON_RIGHT_TRIGGER:
{
thiz->sendEventButton(gamepad->getRightTrigger(), isPressed, value, isAnalog);
}
break;
case AndroidControllerCode::BUTTON_DPAD_UP:
{
thiz->sendEventButton(gamepad->getDirectionPad()->getUp(), isPressed, value, isAnalog);
}
break;
case AndroidControllerCode::BUTTON_DPAD_DOWN:
{
thiz->sendEventButton(gamepad->getDirectionPad()->getDown(), isPressed, value, isAnalog);
}
break;
case AndroidControllerCode::BUTTON_DPAD_LEFT:
{
thiz->sendEventButton(gamepad->getDirectionPad()->getLeft(), isPressed, value, isAnalog);
}
break;
case AndroidControllerCode::BUTTON_DPAD_RIGHT:
{
thiz->sendEventButton(gamepad->getDirectionPad()->getRight(), isPressed, value, isAnalog);
}
break;
case AndroidControllerCode::BUTTON_START:
{
thiz->sendEventButton(gamepad->getButtonStart(), isPressed, value, isAnalog);
}
break;
case AndroidControllerCode::BUTTON_SELECT:
{
thiz->sendEventButton(gamepad->getButtonSelect(), isPressed, value, isAnalog);
}
break;
case AndroidControllerCode::BUTTON_LEFT_THUMBSTICK:
{
thiz->sendEventButton(gamepad->getLeftThumbstick()->getButton(), isPressed, value, isAnalog);
}
break;
case AndroidControllerCode::BUTTON_RIGHT_THUMBSTICK:
{
thiz->sendEventButton(gamepad->getRightThumbstick()->getButton(), isPressed, value, isAnalog);
}
break;
default:
// CCASSERT(false, "Invalid controller button code!");
break;
}
}
static void onAxisEvent(const std::string& vendorName, int controllerID, AndroidControllerCode axisCode, float value, bool isAnalog)
{
// log("vendorName: %s, controller id: %d, axis: %d, value: %f", vendorName.c_str(), controllerID, axisCode, value);
auto iter = findController(vendorName, controllerID);
if (iter == Controller::_controllers.end())
{
onConnected(vendorName, controllerID);
iter = findController(vendorName, controllerID);
}
auto gamepad = (*iter)->getGamepad();
auto thiz = (*iter)->getImpl();
switch (axisCode)
{
case AndroidControllerCode::THUMBSTICK_LEFT_X:
thiz->sendEventAxis(gamepad->getLeftThumbstick()->getAxisX(), value, isAnalog);
break;
case AndroidControllerCode::THUMBSTICK_LEFT_Y:
thiz->sendEventAxis(gamepad->getLeftThumbstick()->getAxisY(), value, isAnalog);
break;
case AndroidControllerCode::THUMBSTICK_RIGHT_X:
thiz->sendEventAxis(gamepad->getRightThumbstick()->getAxisX(), value, isAnalog);
break;
case AndroidControllerCode::THUMBSTICK_RIGHT_Y:
thiz->sendEventAxis(gamepad->getRightThumbstick()->getAxisY(), value, isAnalog);
break;
default:
CCASSERT(false, "Invalid controller axis code!");
break;
}
(*iter)->onAxisEvent(axisCode, value, isAnalog);
}
private:
Controller* _controller;
int _controllerID;
};
std::vector<Controller*> Controller::_controllers;
const std::vector<Controller*>& Controller::getControllers()
{
return _controllers;
}
void Controller::startDiscoveryController()
{
// Empty implementation on Android
@ -288,9 +123,17 @@ void Controller::stopDiscoveryController()
// Empty implementation on Android
}
const std::string& Controller::getVendorName()
Controller::~Controller()
{
delete _impl;
delete _connectEvent;
delete _keyEvent;
delete _axisEvent;
}
void Controller::registerListeners()
{
return _vendorName;
}
bool Controller::isConnected() const
@ -301,61 +144,40 @@ bool Controller::isConnected() const
return true;
}
int Controller::getPlayerIndex() const
{
return _playerIndex;
}
void Controller::setPlayerIndex(int playerIndex)
{
_playerIndex = playerIndex;
}
Gamepad* Controller::getGamepad() const
{
return _gamepad;
}
Controller::Controller()
: _playerIndex(PLAYER_INDEX_UNSET)
, _gamepad(new Gamepad)
: _controllerTag(TAG_UNSET)
, _impl(new ControllerImpl(this))
, _connectEvent(nullptr)
, _keyEvent(nullptr)
, _axisEvent(nullptr)
{
_gamepad->_controller = this;
}
Controller::~Controller()
{
CC_SAFE_DELETE(_impl);
CC_SAFE_DELETE(_gamepad);
init();
}
NS_CC_END
extern "C" {
JNIEXPORT void JNICALL Java_org_cocos2dx_lib_GameControllerAdapter_nativeControllerConnected(JNIEnv* env, jobject thiz, jstring vendorName, jint controllerID)
void Java_org_cocos2dx_lib_GameControllerAdapter_nativeControllerConnected(JNIEnv* env, jobject thiz, jstring deviceName, jint controllerID)
{
CCLOG("controller id: %d connected!", controllerID);
cocos2d::ControllerImpl::onConnected(cocos2d::JniHelper::jstring2string(vendorName), controllerID);
cocos2d::ControllerImpl::onConnected(cocos2d::JniHelper::jstring2string(deviceName), controllerID);
}
JNIEXPORT void JNICALL Java_org_cocos2dx_lib_GameControllerAdapter_nativeControllerDisconnected(JNIEnv* env, jobject thiz, jstring vendorName, jint controllerID)
void Java_org_cocos2dx_lib_GameControllerAdapter_nativeControllerDisconnected(JNIEnv* env, jobject thiz, jstring deviceName, jint controllerID)
{
CCLOG("controller id: %d disconnected!", controllerID);
cocos2d::ControllerImpl::onDisconnected(cocos2d::JniHelper::jstring2string(vendorName), controllerID);
cocos2d::ControllerImpl::onDisconnected(cocos2d::JniHelper::jstring2string(deviceName), controllerID);
}
JNIEXPORT void JNICALL Java_org_cocos2dx_lib_GameControllerAdapter_nativeControllerButtonEvent(JNIEnv* env, jobject thiz, jstring vendorName, jint controllerID, jint button, jboolean isPressed, jfloat value, jboolean isAnalog)
void Java_org_cocos2dx_lib_GameControllerAdapter_nativeControllerButtonEvent(JNIEnv* env, jobject thiz, jstring deviceName, jint controllerID, jint button, jboolean isPressed, jfloat value, jboolean isAnalog)
{
CCLOG("controller id: %d, btn code: %d, isPressed: %d, value: %f, isAnalog:%d", controllerID, button, (int)isPressed, value, (int)isAnalog);
cocos2d::ControllerImpl::onButtonEvent(cocos2d::JniHelper::jstring2string(vendorName), controllerID, static_cast<cocos2d::AndroidControllerCode>(button), isPressed, value, isAnalog);
cocos2d::ControllerImpl::onButtonEvent(cocos2d::JniHelper::jstring2string(deviceName), controllerID, button, isPressed, value, isAnalog);
}
JNIEXPORT void JNICALL Java_org_cocos2dx_lib_GameControllerAdapter_nativeControllerAxisEvent(JNIEnv* env, jobject thiz, jstring vendorName, jint controllerID, jint axis, jfloat value, jboolean isAnalog)
void Java_org_cocos2dx_lib_GameControllerAdapter_nativeControllerAxisEvent(JNIEnv* env, jobject thiz, jstring deviceName, jint controllerID, jint axis, jfloat value, jboolean isAnalog)
{
// CCLOG("controller id: %d, axis code: %d, value: %f, isAnalog:%d", controllerID, axis, value, (int)isAnalog);
cocos2d::ControllerImpl::onAxisEvent(cocos2d::JniHelper::jstring2string(vendorName), controllerID, static_cast<cocos2d::AndroidControllerCode>(axis), value, isAnalog);
cocos2d::ControllerImpl::onAxisEvent(cocos2d::JniHelper::jstring2string(deviceName), controllerID, axis, value, isAnalog);
}
} // extern "C" {

View File

@ -27,17 +27,12 @@
#include "base/CCPlatformConfig.h"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
#include "CCGamepad.h"
#include "CCControllerDirectionPad.h"
#include "CCControllerButtonInput.h"
#include "CCControllerAxisInput.h"
#include "CCControllerThumbstick.h"
#include "ccMacros.h"
#include "CCEventDispatcher.h"
#include "CCEventController.h"
#include "CCEventListenerController.h"
#include "CCDirector.h"
#include "CCLabel.h"
#import <GameController/GameController.h>
@ -105,90 +100,51 @@ static GCControllerConnectionEventHandler* __instance = nil;
NS_CC_BEGIN
#define sendEventButton(dstID, srcID) \
dstID->setPressed(srcID.isPressed); \
dstID->setValue(srcID.value); \
dstID->setAnalog(srcID.isAnalog); \
EventController evt(EventController::ControllerEventType::BUTTON_STATUS_CHANGED, _gamepad->_controller, dstID); \
Director::getInstance()->getEventDispatcher()->dispatchEvent(&evt);
#define sendEventAxis(dstID, srcID) \
\
dstID->setValue(srcID.value); \
dstID->setAnalog(srcID.isAnalog); \
\
EventController evt(EventController::ControllerEventType::AXIS_STATUS_CHANGED, _gamepad->_controller, dstID); \
Director::getInstance()->getEventDispatcher()->dispatchEvent(&evt);
class ControllerImpl
{
public:
ControllerImpl(Controller* controller)
: _controller(controller)
, _gcController(nil)
, _lazyRegisterListener(true)
{
}
~ControllerImpl()
{
}
Controller* _controller;
GCController* _gcController;
bool _lazyRegisterListener;
};
std::vector<Controller*> Controller::_controllers;
const std::vector<Controller*>& Controller::getControllers()
{
return _controllers;
}
std::vector<Controller*> Controller::s_allController;
void Controller::startDiscoveryController()
{
[GCController startWirelessControllerDiscoveryWithCompletionHandler: nil];
[[GCControllerConnectionEventHandler getInstance] observerConnection: ^(GCController* gcController) {
auto controller = new Controller();
controller->_impl->_gcController = gcController;
controller->_deviceName = [gcController.vendorName UTF8String];
gcController.controllerPausedHandler = ^(GCController* gcCon){
auto iter = std::find_if(_controllers.begin(), _controllers.end(), [gcCon](Controller* c){ return c->_impl->_gcController == gcCon; });
CCASSERT(iter != _controllers.end(), "Could not find the controller");
auto button = (*iter)->getGamepad()->getButtonPause();
button->setPressed(true);
EventController evt(EventController::ControllerEventType::BUTTON_STATUS_CHANGED, (*iter), button);
Director::getInstance()->getEventDispatcher()->dispatchEvent(&evt);
// Reset the pause button status to unpressed.
button->setPressed(false);
};
s_allController.push_back(controller);
_controllers.push_back(controller);
controller->registerListeners();
controller->getDeviceName();
EventController evt(EventController::ControllerEventType::CONNECTION, controller, true);
Director::getInstance()->getEventDispatcher()->dispatchEvent(&evt);
controller->onConnected();
} disconnection: ^(GCController* gcController) {
auto iter = std::find_if(s_allController.begin(), s_allController.end(), [gcController](Controller* c){ return c->_impl->_gcController == gcController; });
auto iter = std::find_if(_controllers.begin(), _controllers.end(), [gcController](Controller* c){ return c->_impl->_gcController == gcController; });
if(iter == s_allController.end())
{
log("disconnect:Could not find the controller");
return;
}
CCASSERT(iter != _controllers.end(), "Could not find the controller");
(*iter)->onDisconnected();
s_allController.erase(iter);
EventController evt(EventController::ControllerEventType::CONNECTION, *iter, false);
Director::getInstance()->getEventDispatcher()->dispatchEvent(&evt);
delete (*iter);
_controllers.erase(iter);
}];
}
@ -198,26 +154,156 @@ void Controller::stopDiscoveryController()
}
Controller::Controller()
: _controllerTag(TAG_UNSET)
, _impl(new ControllerImpl(this))
, _connectEvent(nullptr)
, _keyEvent(nullptr)
, _axisEvent(nullptr)
, _deviceId(0)
{
_playerIndex = PLAYER_INDEX_UNSET;
_gamepad = new Gamepad();
_gamepad->_controller = this;
_impl = new ControllerImpl(this);
init();
}
Controller::~Controller()
{
CC_SAFE_DELETE(_impl);
CC_SAFE_DELETE(_gamepad);
delete _impl;
delete _connectEvent;
delete _keyEvent;
delete _axisEvent;
}
const std::string& Controller::getVendorName()
void Controller::registerListeners()
{
if (_vendorName.empty())
if (_impl->_gcController.extendedGamepad != nil)
{
_vendorName = [_impl->_gcController.vendorName UTF8String];
_impl->_gcController.extendedGamepad.dpad.up.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){
onButtonEvent(Key::BUTTON_DPAD_UP, pressed, value, button.isAnalog);
};
_impl->_gcController.extendedGamepad.dpad.down.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){
onButtonEvent(Key::BUTTON_DPAD_DOWN, pressed, value, button.isAnalog);
};
_impl->_gcController.extendedGamepad.dpad.left.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){
onButtonEvent(Key::BUTTON_DPAD_LEFT, pressed, value, button.isAnalog);
};
_impl->_gcController.extendedGamepad.dpad.right.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){
onButtonEvent(Key::BUTTON_DPAD_RIGHT, pressed, value, button.isAnalog);
};
_impl->_gcController.extendedGamepad.leftThumbstick.xAxis.valueChangedHandler = ^(GCControllerAxisInput *axis, float value){
onAxisEvent(Key::JOYSTICK_LEFT_X, value, axis.isAnalog);
};
_impl->_gcController.extendedGamepad.leftThumbstick.yAxis.valueChangedHandler = ^(GCControllerAxisInput *axis, float value){
onAxisEvent(Key::JOYSTICK_LEFT_Y, value, axis.isAnalog);
};
_impl->_gcController.extendedGamepad.rightThumbstick.xAxis.valueChangedHandler = ^(GCControllerAxisInput *axis, float value){
onAxisEvent(Key::JOYSTICK_RIGHT_X, value, axis.isAnalog);
};
_impl->_gcController.extendedGamepad.rightThumbstick.yAxis.valueChangedHandler = ^(GCControllerAxisInput *axis, float value){
onAxisEvent(Key::JOYSTICK_RIGHT_Y, value, axis.isAnalog);
};
_impl->_gcController.extendedGamepad.valueChangedHandler = ^(GCExtendedGamepad *gamepad, GCControllerElement *element){
if (element == gamepad.buttonA)
{
onButtonEvent(Key::BUTTON_A, gamepad.buttonA.isPressed, gamepad.buttonA.value, gamepad.buttonA.isAnalog);
}
else if (element == gamepad.buttonB)
{
onButtonEvent(Key::BUTTON_B, gamepad.buttonB.isPressed, gamepad.buttonB.value, gamepad.buttonB.isAnalog);
}
else if (element == gamepad.buttonX)
{
onButtonEvent(Key::BUTTON_X, gamepad.buttonX.isPressed, gamepad.buttonX.value, gamepad.buttonX.isAnalog);
}
else if (element == gamepad.buttonY)
{
onButtonEvent(Key::BUTTON_Y, gamepad.buttonY.isPressed, gamepad.buttonY.value, gamepad.buttonY.isAnalog);
}
else if (element == gamepad.leftShoulder)
{
onButtonEvent(Key::BUTTON_LEFT_SHOULDER, gamepad.leftShoulder.isPressed, gamepad.leftShoulder.value, gamepad.leftShoulder.isAnalog);
}
else if (element == gamepad.rightShoulder)
{
onButtonEvent(Key::BUTTON_RIGHT_SHOULDER, gamepad.rightShoulder.isPressed, gamepad.rightShoulder.value, gamepad.rightShoulder.isAnalog);
}
else if (element == gamepad.leftTrigger)
{
onAxisEvent(Key::AXIS_LEFT_TRIGGER, gamepad.leftTrigger.value, gamepad.leftTrigger.isAnalog);
}
else if (element == gamepad.rightTrigger)
{
onAxisEvent(Key::AXIS_RIGHT_TRIGGER, gamepad.rightTrigger.value, gamepad.rightTrigger.isAnalog);
}
};
}
return _vendorName;
else
{
_impl->_gcController.gamepad.dpad.up.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){
onButtonEvent(Key::BUTTON_DPAD_UP, pressed, value, button.isAnalog);
};
_impl->_gcController.gamepad.dpad.down.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){
onButtonEvent(Key::BUTTON_DPAD_DOWN, pressed, value, button.isAnalog);
};
_impl->_gcController.gamepad.dpad.left.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){
onButtonEvent(Key::BUTTON_DPAD_LEFT, pressed, value, button.isAnalog);
};
_impl->_gcController.gamepad.dpad.right.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){
onButtonEvent(Key::BUTTON_DPAD_RIGHT, pressed, value, button.isAnalog);
};
_impl->_gcController.gamepad.valueChangedHandler = ^(GCGamepad *gamepad, GCControllerElement *element){
if (element == gamepad.buttonA)
{
onButtonEvent(Key::BUTTON_A, gamepad.buttonA.isPressed, gamepad.buttonA.value, gamepad.buttonA.isAnalog);
}
else if (element == gamepad.buttonB)
{
onButtonEvent(Key::BUTTON_B, gamepad.buttonB.isPressed, gamepad.buttonB.value, gamepad.buttonB.isAnalog);
}
else if (element == gamepad.buttonX)
{
onButtonEvent(Key::BUTTON_X, gamepad.buttonX.isPressed, gamepad.buttonX.value, gamepad.buttonX.isAnalog);
}
else if (element == gamepad.buttonY)
{
onButtonEvent(Key::BUTTON_Y, gamepad.buttonY.isPressed, gamepad.buttonY.value, gamepad.buttonY.isAnalog);
}
else if (element == gamepad.leftShoulder)
{
onButtonEvent(Key::BUTTON_LEFT_SHOULDER, gamepad.leftShoulder.isPressed, gamepad.leftShoulder.value, gamepad.leftShoulder.isAnalog);
}
else if (element == gamepad.rightShoulder)
{
onButtonEvent(Key::BUTTON_RIGHT_SHOULDER, gamepad.rightShoulder.isPressed, gamepad.rightShoulder.value, gamepad.rightShoulder.isAnalog);
}
};
}
_impl->_gcController.controllerPausedHandler = ^(GCController* gcCon){
auto iter = std::find_if(s_allController.begin(), s_allController.end(), [gcCon](Controller* c){ return c->_impl->_gcController == gcCon; });
if(iter == s_allController.end())
{
log("Could not find the controller");
return;
}
onButtonEvent(Key::BUTTON_PAUSE, true, 1.0f, false);
onButtonEvent(Key::BUTTON_PAUSE, false, 0.0f, false);
};
}
bool Controller::isConnected() const
@ -225,147 +311,6 @@ bool Controller::isConnected() const
return _impl->_gcController.isAttachedToDevice == YES;
}
int Controller::getPlayerIndex() const
{
return _playerIndex;
}
void Controller::setPlayerIndex(int playerIndex)
{
_playerIndex = playerIndex;
}
Gamepad* Controller::getGamepad() const
{
if (_impl->_gcController == nil)
return nullptr;
if(_impl->_gcController.gamepad == nil && _impl->_gcController.extendedGamepad == nil)
{
CCASSERT(false, "No gamepad was found!");
}
else if (_impl->_lazyRegisterListener)
{
_impl->_lazyRegisterListener = false;
if (_impl->_gcController.extendedGamepad != nil)
{
_impl->_gcController.extendedGamepad.dpad.up.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){
sendEventButton(_gamepad->getDirectionPad()->getUp(), button);
};
_impl->_gcController.extendedGamepad.dpad.down.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){
sendEventButton(_gamepad->getDirectionPad()->getDown(), button);
};
_impl->_gcController.extendedGamepad.dpad.left.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){
sendEventButton(_gamepad->getDirectionPad()->getLeft(), button);
};
_impl->_gcController.extendedGamepad.dpad.right.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){
sendEventButton(_gamepad->getDirectionPad()->getRight(), button);
};
_impl->_gcController.extendedGamepad.leftThumbstick.xAxis.valueChangedHandler = ^(GCControllerAxisInput *axis, float value){
sendEventAxis(_gamepad->getLeftThumbstick()->getAxisX(), axis);
};
_impl->_gcController.extendedGamepad.leftThumbstick.yAxis.valueChangedHandler = ^(GCControllerAxisInput *axis, float value){
sendEventAxis(_gamepad->getLeftThumbstick()->getAxisY(), axis);
};
_impl->_gcController.extendedGamepad.rightThumbstick.xAxis.valueChangedHandler = ^(GCControllerAxisInput *axis, float value){
sendEventAxis(_gamepad->getRightThumbstick()->getAxisX(), axis);
};
_impl->_gcController.extendedGamepad.rightThumbstick.yAxis.valueChangedHandler = ^(GCControllerAxisInput *axis, float value){
sendEventAxis(_gamepad->getRightThumbstick()->getAxisY(), axis);
};
_impl->_gcController.extendedGamepad.valueChangedHandler = ^(GCExtendedGamepad *gamepad, GCControllerElement *element){
if (element == gamepad.buttonA)
{
sendEventButton(_gamepad->getButtonA(), gamepad.buttonA);
}
else if (element == gamepad.buttonB)
{
sendEventButton(_gamepad->getButtonB(), gamepad.buttonB);
}
else if (element == gamepad.buttonX)
{
sendEventButton(_gamepad->getButtonX(), gamepad.buttonX);
}
else if (element == gamepad.buttonY)
{
sendEventButton(_gamepad->getButtonY(), gamepad.buttonY);
}
else if (element == gamepad.leftShoulder)
{
sendEventButton(_gamepad->getLeftShoulder(), gamepad.leftShoulder);
}
else if (element == gamepad.rightShoulder)
{
sendEventButton(_gamepad->getRightShoulder(), gamepad.rightShoulder);
}
else if (element == gamepad.leftTrigger)
{
sendEventButton(_gamepad->getLeftTrigger(), gamepad.leftTrigger);
}
else if (element == gamepad.rightTrigger)
{
sendEventButton(_gamepad->getRightTrigger(), gamepad.rightTrigger);
}
};
}
else
{
_impl->_gcController.gamepad.dpad.up.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){
sendEventButton(_gamepad->getDirectionPad()->getUp(), button);
};
_impl->_gcController.gamepad.dpad.down.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){
sendEventButton(_gamepad->getDirectionPad()->getDown(), button);
};
_impl->_gcController.gamepad.dpad.left.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){
sendEventButton(_gamepad->getDirectionPad()->getLeft(), button);
};
_impl->_gcController.gamepad.dpad.right.valueChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed){
sendEventButton(_gamepad->getDirectionPad()->getRight(), button);
};
_impl->_gcController.gamepad.valueChangedHandler = ^(GCGamepad *gamepad, GCControllerElement *element){
if (element == gamepad.buttonA)
{
sendEventButton(_gamepad->getButtonA(), gamepad.buttonA);
}
else if (element == gamepad.buttonB)
{
sendEventButton(_gamepad->getButtonB(), gamepad.buttonB);
}
else if (element == gamepad.buttonX)
{
sendEventButton(_gamepad->getButtonX(), gamepad.buttonX);
}
else if (element == gamepad.buttonY)
{
sendEventButton(_gamepad->getButtonY(), gamepad.buttonY);
}
else if (element == gamepad.leftShoulder)
{
sendEventButton(_gamepad->getLeftShoulder(), gamepad.leftShoulder);
}
else if (element == gamepad.rightShoulder)
{
sendEventButton(_gamepad->getRightShoulder(), gamepad.rightShoulder);
}
};
}
}
return _gamepad;
}
NS_CC_END
#endif // #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)

117
cocos/base/CCController.cpp Normal file
View File

@ -0,0 +1,117 @@
/****************************************************************************
Copyright (c) 2014 cocos2d-x.org
Copyright (c) 2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCController.h"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
#include "ccMacros.h"
#include "CCEventDispatcher.h"
#include "CCEventController.h"
#include "CCEventListenerController.h"
#include "CCDirector.h"
NS_CC_BEGIN
std::vector<Controller*> Controller::s_allController;
Controller* Controller::getControllerByTag(int tag)
{
for (auto controller:Controller::s_allController)
{
if (controller->_controllerTag == tag)
{
return controller;
}
}
return nullptr;
}
void Controller::init()
{
for (int key = Key::JOYSTICK_LEFT_X; key < Key::KEY_MAX; ++key)
{
_allKeyStatus[key].isPressed = false;
_allKeyStatus[key].value = 0.0f;
_allKeyPrevStatus[key].isPressed = false;
_allKeyPrevStatus[key].value = 0.0f;
}
_eventDispatcher = Director::getInstance()->getEventDispatcher();
_connectEvent = new EventController(EventController::ControllerEventType::CONNECTION, this, false);
_keyEvent = new EventController(EventController::ControllerEventType::BUTTON_STATUS_CHANGED, this, 0);
_axisEvent = new EventController(EventController::ControllerEventType::AXIS_STATUS_CHANGED, this, 0);
}
const Controller::KeyStatus& Controller::getKeyStatus(int keyCode)
{
if (_allKeyStatus.find(keyCode) == _allKeyStatus.end())
{
_allKeyStatus[keyCode].isPressed = false;
_allKeyStatus[keyCode].value = 0.0f;
}
return _allKeyStatus[keyCode];
}
void Controller::onConnected()
{
_connectEvent->setConnectStatus(true);
_eventDispatcher->dispatchEvent(_connectEvent);
}
void Controller::onDisconnected()
{
_connectEvent->setConnectStatus(false);
_eventDispatcher->dispatchEvent(_connectEvent);
delete this;
}
void Controller::onButtonEvent(int keyCode, bool isPressed, float value, bool isAnalog)
{
_allKeyPrevStatus[keyCode] = _allKeyStatus[keyCode];
_allKeyStatus[keyCode].isPressed = isPressed;
_allKeyStatus[keyCode].value = value;
_allKeyStatus[keyCode].isAnalog = isAnalog;
_keyEvent->setKeyCode(keyCode);
_eventDispatcher->dispatchEvent(_keyEvent);
}
void Controller::onAxisEvent(int axisCode, float value, bool isAnalog)
{
_allKeyPrevStatus[axisCode] = _allKeyStatus[axisCode];
_allKeyStatus[axisCode].value = value;
_allKeyStatus[axisCode].isAnalog = isAnalog;
_axisEvent->setKeyCode(axisCode);
_eventDispatcher->dispatchEvent(_axisEvent);
}
NS_CC_END
#endif // #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)

View File

@ -27,50 +27,112 @@
#define __cocos2d_libs__CCController__
#include "CCPlatformMacros.h"
#include <string>
#include <vector>
#include <functional>
#include <unordered_map>
NS_CC_BEGIN
class Gamepad;
class ControllerImpl;
class EventListenerController;
class EventController;
class EventDispatcher;
class Controller
{
public:
static const std::vector<Controller*>& getControllers();
enum Key
{
JOYSTICK_LEFT_X = 1000,
JOYSTICK_LEFT_Y,
JOYSTICK_RIGHT_X,
JOYSTICK_RIGHT_Y,
BUTTON_A,
BUTTON_B,
BUTTON_C,
BUTTON_X,
BUTTON_Y,
BUTTON_Z,
BUTTON_DPAD_UP,
BUTTON_DPAD_DOWN,
BUTTON_DPAD_LEFT,
BUTTON_DPAD_RIGHT,
BUTTON_DPAD_CENTER,
BUTTON_LEFT_SHOULDER,
BUTTON_RIGHT_SHOULDER,
AXIS_LEFT_TRIGGER,
AXIS_RIGHT_TRIGGER,
BUTTON_LEFT_THUMBSTICK,
BUTTON_RIGHT_THUMBSTICK,
BUTTON_START,
BUTTON_SELECT,
BUTTON_PAUSE,
KEY_MAX
};
typedef struct _keyStatus
{
bool isPressed;
float value;
bool isAnalog;
}KeyStatus;
static const int TAG_UNSET = -1;
static const std::vector<Controller*>& getAllController(){ return s_allController;}
static Controller* getControllerByTag(int tag);
static void startDiscoveryController();
static void stopDiscoveryController();
const std::string& getVendorName();
const std::string& getDeviceName() const { return _deviceName;}
int getDeviceId() const { return _deviceId;}
bool isConnected() const;
static const int PLAYER_INDEX_UNSET = -1;
const KeyStatus& getKeyStatus(int keyCode);
void setTag(int tag) { _controllerTag = tag;}
int getTag() const { return _controllerTag;}
int getPlayerIndex() const;
void setPlayerIndex(int playerIndex);
Gamepad* getGamepad() const;
// For internal use only
inline ControllerImpl* getImpl() const { return _impl; };
private:
static std::vector<Controller*> s_allController;
Controller();
virtual ~Controller();
private:
static std::vector<Controller*> _controllers;
void init();
std::string _vendorName;
int _playerIndex;
Gamepad* _gamepad;
void onConnected();
void onDisconnected();
void onButtonEvent(int keyCode, bool isPressed, float value, bool isAnalog);
void onAxisEvent(int axisCode, float value, bool isAnalog);
void registerListeners();
std::unordered_map<int, KeyStatus> _allKeyStatus;
std::unordered_map<int, KeyStatus> _allKeyPrevStatus;
std::string _deviceName;
int _deviceId;
int _controllerTag;
ControllerImpl* _impl;
EventDispatcher* _eventDispatcher;
EventController *_connectEvent;
EventController *_keyEvent;
EventController *_axisEvent;
friend class ControllerImpl;
ControllerImpl* _impl;
friend class EventListenerController;
};

View File

@ -1,52 +0,0 @@
/****************************************************************************
Copyright (c) 2014 cocos2d-x.org
Copyright (c) 2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCControllerAxisInput.h"
NS_CC_BEGIN
ControllerAxisInput::ControllerAxisInput()
: _value(0.0f)
{
}
ControllerAxisInput::~ControllerAxisInput()
{
}
float ControllerAxisInput::getValue() const
{
return _value;
}
void ControllerAxisInput::setValue(float value)
{
_value = value;
}
NS_CC_END

View File

@ -1,55 +0,0 @@
/****************************************************************************
Copyright (c) 2014 cocos2d-x.org
Copyright (c) 2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __cocos2d_libs__CCControllerAxisInput__
#define __cocos2d_libs__CCControllerAxisInput__
#include "CCPlatformMacros.h"
#include "CCControllerElement.h"
NS_CC_BEGIN
class ControllerAxisInput : public ControllerElement
{
public:
float getValue() const;
protected:
ControllerAxisInput();
virtual ~ControllerAxisInput();
void setValue(float value);
float _value;
friend class Controller;
friend class ControllerImpl;
friend class ControllerDirectionPad;
friend class ControllerThumbstick;
};
NS_CC_END
#endif /* defined(__cocos2d_libs__CCControllerAxisInput__) */

View File

@ -1,69 +0,0 @@
/****************************************************************************
Copyright (c) 2014 cocos2d-x.org
Copyright (c) 2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCControllerButtonInput.h"
NS_CC_BEGIN
ControllerButtonInput::ControllerButtonInput()
: _value(0.0f)
, _isPressed(false)
, _isPrevStatusPressed(false)
{
}
ControllerButtonInput::~ControllerButtonInput()
{
}
float ControllerButtonInput::getValue() const
{
return _value;
}
bool ControllerButtonInput::isPressed() const
{
return _isPressed;
}
bool ControllerButtonInput::isPrevStatusPressed() const
{
return _isPrevStatusPressed;
}
void ControllerButtonInput::setValue(float value)
{
_value = value;
}
void ControllerButtonInput::setPressed(bool isPressed)
{
_isPrevStatusPressed = _isPressed;
_isPressed = isPressed;
}
NS_CC_END

View File

@ -1,63 +0,0 @@
/****************************************************************************
Copyright (c) 2014 cocos2d-x.org
Copyright (c) 2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __cocos2d_libs__CCControllerButtonInput__
#define __cocos2d_libs__CCControllerButtonInput__
#include "CCPlatformMacros.h"
#include "CCControllerElement.h"
NS_CC_BEGIN
class ControllerButtonInput : public ControllerElement
{
public:
float getValue() const;
bool isPressed() const;
bool isPrevStatusPressed() const;
protected:
ControllerButtonInput();
virtual ~ControllerButtonInput();
void setValue(float value);
void setPressed(bool isPressed);
float _value;
bool _isPressed;
bool _isPrevStatusPressed; // Whether previous status is pressed
friend class Controller;
friend class ControllerImpl;
friend class ControllerDirectionPad;
friend class ControllerThumbstick;
friend class Gamepad;
};
NS_CC_END
#endif /* defined(__cocos2d_libs__CCControllerButtonInput__) */

View File

@ -1,74 +0,0 @@
/****************************************************************************
Copyright (c) 2014 cocos2d-x.org
Copyright (c) 2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCControllerDirectionPad.h"
#include "CCControllerAxisInput.h"
#include "CCControllerButtonInput.h"
NS_CC_BEGIN
ControllerDirectionPad::ControllerDirectionPad()
: _up(new ControllerButtonInput())
, _down(new ControllerButtonInput())
, _left(new ControllerButtonInput())
, _right(new ControllerButtonInput())
{
_up->setCollection(this);
_down->setCollection(this);
_left->setCollection(this);
_right->setCollection(this);
}
ControllerDirectionPad::~ControllerDirectionPad()
{
CC_SAFE_DELETE(_up);
CC_SAFE_DELETE(_down);
CC_SAFE_DELETE(_left);
CC_SAFE_DELETE(_right);
}
ControllerButtonInput* ControllerDirectionPad::getUp() const
{
return _up;
}
ControllerButtonInput* ControllerDirectionPad::getDown() const
{
return _down;
}
ControllerButtonInput* ControllerDirectionPad::getLeft() const
{
return _left;
}
ControllerButtonInput* ControllerDirectionPad::getRight() const
{
return _right;
}
NS_CC_END

View File

@ -1,61 +0,0 @@
/****************************************************************************
Copyright (c) 2014 cocos2d-x.org
Copyright (c) 2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __cocos2d_libs__CCControllerDirectionPad__
#define __cocos2d_libs__CCControllerDirectionPad__
#include "CCPlatformMacros.h"
#include "CCControllerElement.h"
NS_CC_BEGIN
class ControllerAxisInput;
class ControllerButtonInput;
class ControllerDirectionPad : public ControllerElement
{
public:
ControllerButtonInput* getUp() const;
ControllerButtonInput* getDown() const;
ControllerButtonInput* getLeft() const;
ControllerButtonInput* getRight() const;
protected:
friend class Controller;
friend class Gamepad;
ControllerDirectionPad();
virtual ~ControllerDirectionPad();
ControllerButtonInput* _up;
ControllerButtonInput* _down;
ControllerButtonInput* _left;
ControllerButtonInput* _right;
};
NS_CC_END
#endif /* defined(__cocos2d_libs__CCControllerDirectionPad__) */

View File

@ -1,63 +0,0 @@
/****************************************************************************
Copyright (c) 2014 cocos2d-x.org
Copyright (c) 2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCControllerElement.h"
NS_CC_BEGIN
ControllerElement::ControllerElement()
: _isAnalog(false)
, _collection(nullptr)
{
}
ControllerElement::~ControllerElement()
{
}
bool ControllerElement::isAnalog() const
{
return _isAnalog;
}
void ControllerElement::setAnalog(bool isAnalog)
{
_isAnalog = isAnalog;
}
ControllerElement* ControllerElement::getCollection()
{
return _collection;
}
void ControllerElement::setCollection(ControllerElement* collection)
{
_collection = collection;
}
NS_CC_END

View File

@ -1,64 +0,0 @@
/****************************************************************************
Copyright (c) 2014 cocos2d-x.org
Copyright (c) 2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __cocos2d_libs__CCControllerElement__
#define __cocos2d_libs__CCControllerElement__
#include "CCPlatformMacros.h"
NS_CC_BEGIN
/**
Every controller element knows which collection it belongs to and whether its input value is analog or digital.
*/
class ControllerElement
{
public:
/**
Each element can be part of a wider collection of inputs that map to a single logical element. A directional pad (dpad)
is a logical collection of two axis inputs and thus each axis belongs to the same collection element - the dpad.
*/
ControllerElement * getCollection();
/**
Check if the element can support more than just digital values, such as decimal ranges between 0 and 1.
*/
bool isAnalog() const;
protected:
ControllerElement();
virtual ~ControllerElement();
void setAnalog(bool isAnalog);
void setCollection(ControllerElement* collection);
bool _isAnalog;
ControllerElement* _collection;
};
NS_CC_END
#endif /* defined(__cocos2d_libs__CCControllerElement__) */

View File

@ -1,66 +0,0 @@
/****************************************************************************
Copyright (c) 2014 cocos2d-x.org
Copyright (c) 2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCControllerThumbstick.h"
#include "CCControllerAxisInput.h"
#include "CCControllerButtonInput.h"
NS_CC_BEGIN
ControllerThumbstick::ControllerThumbstick()
: _axisX(new ControllerAxisInput())
, _axisY(new ControllerAxisInput())
, _button(new ControllerButtonInput())
{
_axisX->setCollection(this);
_axisY->setCollection(this);
_button->setCollection(this);
}
ControllerThumbstick::~ControllerThumbstick()
{
CC_SAFE_DELETE(_axisX);
CC_SAFE_DELETE(_axisY);
CC_SAFE_DELETE(_button);
}
ControllerAxisInput* ControllerThumbstick::getAxisX() const
{
return _axisX;
}
ControllerAxisInput* ControllerThumbstick::getAxisY() const
{
return _axisY;
}
ControllerButtonInput* ControllerThumbstick::getButton() const
{
return _button;
}
NS_CC_END

View File

@ -1,61 +0,0 @@
/****************************************************************************
Copyright (c) 2014 cocos2d-x.org
Copyright (c) 2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __cocos2d_libs__CCControllerThumbStick__
#define __cocos2d_libs__CCControllerThumbStick__
#include "CCPlatformMacros.h"
#include "CCControllerElement.h"
NS_CC_BEGIN
class ControllerAxisInput;
class ControllerButtonInput;
class ControllerThumbstick : public ControllerElement
{
public:
ControllerAxisInput* getAxisX() const;
ControllerAxisInput* getAxisY() const;
ControllerButtonInput* getButton() const;
protected:
friend class Controller;
friend class Gamepad;
ControllerThumbstick();
virtual ~ControllerThumbstick();
ControllerAxisInput* _axisX;
ControllerAxisInput* _axisY;
ControllerButtonInput* _button;
};
NS_CC_END
#endif /* defined(__cocos2d_libs__CCControllerThumbStick__) */

View File

@ -27,10 +27,10 @@
NS_CC_BEGIN
EventController::EventController(ControllerEventType type, Controller* controller, ControllerElement* element)
EventController::EventController(ControllerEventType type, Controller* controller, int keyCode)
: Event(Type::GAME_CONTROLLER)
, _controllerEventType(type)
, _element(element)
, _keyCode(keyCode)
, _controller(controller)
, _isConnected(true)
{
@ -40,31 +40,11 @@ EventController::EventController(ControllerEventType type, Controller* controlle
EventController::EventController(ControllerEventType type, Controller* controller, bool isConnected)
: Event(Type::GAME_CONTROLLER)
, _controllerEventType(type)
, _element(nullptr)
, _controller(controller)
, _isConnected(isConnected)
, _keyCode(0)
{
}
EventController::ControllerEventType EventController::getControllerEventType() const
{
return _controllerEventType;
}
Controller* EventController::getController() const
{
return _controller;
}
ControllerElement* EventController::getControllerElement() const
{
return _element;
}
bool EventController::isConnected() const
{
return _isConnected;
}
NS_CC_END

View File

@ -31,10 +31,8 @@
NS_CC_BEGIN
class ControllerButtonInput;
class ControllerAxisInput;
class ControllerElement;
class Controller;
class EventListenerController;
class EventController : public Event
{
@ -46,19 +44,25 @@ public:
AXIS_STATUS_CHANGED,
};
EventController(ControllerEventType type, Controller* controller, ControllerElement* element);
EventController(ControllerEventType type, Controller* controller, int keyCode);
EventController(ControllerEventType type, Controller* controller, bool isConnected);
ControllerEventType getControllerEventType() const;
Controller* getController() const;
ControllerElement* getControllerElement() const;
bool isConnected() const;
ControllerEventType getControllerEventType() const { return _controllerEventType; }
Controller* getController() const { return _controller; }
int getKeyCode() const{ return _keyCode; }
void setKeyCode(int keyCode) { _keyCode = keyCode;}
void setConnectStatus(bool isConnected) {_isConnected = isConnected;}
bool isConnected() const { return _isConnected; }
protected:
ControllerEventType _controllerEventType;
ControllerElement* _element;
Controller* _controller;
int _keyCode;
bool _isConnected;
friend class EventListenerController;
};
NS_CC_END

View File

@ -25,9 +25,8 @@
#include "CCEventListenerController.h"
#include "CCEventController.h"
#include "CCControllerButtonInput.h"
#include "CCControllerAxisInput.h"
#include "ccMacros.h"
#include "base/CCController.h"
NS_CC_BEGIN
@ -51,8 +50,9 @@ bool EventListenerController::init()
{
auto listener = [this](Event* event){
auto evtController = static_cast<EventController*>(event);
if (evtController->getControllerEventType() == EventController::ControllerEventType::CONNECTION)
switch (evtController->getControllerEventType())
{
case EventController::ControllerEventType::CONNECTION:
if (evtController->isConnected())
{
if (this->onConnected)
@ -63,45 +63,40 @@ bool EventListenerController::init()
if (this->onDisconnected)
this->onDisconnected(evtController->getController(), event);
}
}
else
{
switch (evtController->getControllerEventType()) {
case EventController::ControllerEventType::BUTTON_STATUS_CHANGED:
{
auto button = static_cast<ControllerButtonInput*>(evtController->getControllerElement());
break;
case EventController::ControllerEventType::BUTTON_STATUS_CHANGED:
{
const auto& keyStatus = evtController->_controller->_allKeyStatus[evtController->_keyCode];
const auto& keyPrevStatus = evtController->_controller->_allKeyPrevStatus[evtController->_keyCode];
if (this->onButtonPressed && button->isPressed() && !button->isPrevStatusPressed())
{
this->onButtonPressed(evtController->getController(), button, event);
}
else if (this->onButtonReleased && !button->isPressed() && button->isPrevStatusPressed())
{
this->onButtonReleased(evtController->getController(), button, event);
}
if (this->onButtonValueChanged)
{
this->onButtonValueChanged(evtController->getController(), button, event);
}
}
break;
case EventController::ControllerEventType::AXIS_STATUS_CHANGED:
{
if (this->onAxisValueChanged)
{
auto axis = static_cast<ControllerAxisInput*>(evtController->getControllerElement());
this->onAxisValueChanged(evtController->getController(), axis, event);
}
}
break;
default:
CCASSERT(false, "Invalid EventController type");
break;
if (this->onKeyDown && keyStatus.isPressed && !keyPrevStatus.isPressed)
{
this->onKeyDown(evtController->_controller, evtController->_keyCode, event);
}
else if (this->onKeyUp && !keyStatus.isPressed && keyPrevStatus.isPressed)
{
this->onKeyUp(evtController->_controller, evtController->_keyCode, event);
}
else if (this->onKeyRepeat && keyStatus.isPressed && keyPrevStatus.isPressed)
{
this->onKeyRepeat(evtController->_controller, evtController->_keyCode, event);
}
}
break;
case EventController::ControllerEventType::AXIS_STATUS_CHANGED:
{
if (this->onAxisEvent)
{
this->onAxisEvent(evtController->_controller, evtController->_keyCode, event);
}
}
break;
default:
CCASSERT(false, "Invalid EventController type");
break;
}
};
if (EventListener::init(EventListener::Type::GAME_CONTROLLER, LISTENER_ID, listener))
{
return true;

View File

@ -33,8 +33,6 @@ NS_CC_BEGIN
class Event;
class Controller;
class ControllerButtonInput;
class ControllerAxisInput;
class EventListenerController : public EventListener
{
@ -50,11 +48,11 @@ public:
std::function<void(Controller*, Event*)> onConnected;
std::function<void(Controller*, Event*)> onDisconnected;
std::function<void(Controller*, ControllerButtonInput*, Event*)> onButtonPressed;
std::function<void(Controller*, ControllerButtonInput*, Event*)> onButtonReleased;
std::function<void(Controller*, ControllerButtonInput*, Event*)> onButtonValueChanged;
std::function<void(Controller*, int, Event*)> onKeyDown;
std::function<void(Controller*, int, Event*)> onKeyUp;
std::function<void(Controller*, int, Event*)> onKeyRepeat;
std::function<void(Controller*, ControllerAxisInput*, Event*)> onAxisValueChanged;
std::function<void(Controller*, int, Event*)> onAxisEvent;
protected:
bool init();

View File

@ -26,12 +26,6 @@
#ifndef __cocos2d_libs__CCGameController__
#define __cocos2d_libs__CCGameController__
#include "CCControllerElement.h"
#include "CCControllerButtonInput.h"
#include "CCControllerAxisInput.h"
#include "CCControllerDirectionPad.h"
#include "CCControllerThumbstick.h"
#include "CCGamepad.h"
#include "CCController.h"
#include "CCEventController.h"
#include "CCEventListenerController.h"

View File

@ -1,146 +0,0 @@
/****************************************************************************
Copyright (c) 2014 cocos2d-x.org
Copyright (c) 2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCGamepad.h"
#include "CCControllerDirectionPad.h"
#include "CCControllerButtonInput.h"
#include "CCControllerThumbstick.h"
NS_CC_BEGIN
Gamepad::Gamepad()
: _controller(nullptr)
, _directionPad(new ControllerDirectionPad())
, _buttonA(new ControllerButtonInput())
, _buttonB(new ControllerButtonInput())
, _buttonX(new ControllerButtonInput())
, _buttonY(new ControllerButtonInput())
, _buttonSelect(new ControllerButtonInput())
, _buttonStart(new ControllerButtonInput())
, _buttonPause(new ControllerButtonInput())
, _leftShoulder(new ControllerButtonInput())
, _rightShoulder(new ControllerButtonInput())
, _leftThumbstick(new ControllerThumbstick())
, _rightThumbstick(new ControllerThumbstick())
, _leftTrigger(new ControllerButtonInput())
, _rightTrigger(new ControllerButtonInput())
{
}
Gamepad::~Gamepad()
{
CC_SAFE_DELETE(_directionPad);
CC_SAFE_DELETE(_buttonA);
CC_SAFE_DELETE(_buttonB);
CC_SAFE_DELETE(_buttonX);
CC_SAFE_DELETE(_buttonY);
CC_SAFE_DELETE(_buttonSelect);
CC_SAFE_DELETE(_buttonStart);
CC_SAFE_DELETE(_buttonPause);
CC_SAFE_DELETE(_leftShoulder);
CC_SAFE_DELETE(_rightShoulder);
CC_SAFE_DELETE(_leftThumbstick);
CC_SAFE_DELETE(_rightThumbstick);
CC_SAFE_DELETE(_leftTrigger);
CC_SAFE_DELETE(_rightTrigger);
}
Controller* Gamepad::getController()
{
return _controller;
}
ControllerDirectionPad* Gamepad::getDirectionPad() const
{
return _directionPad;
}
ControllerButtonInput* Gamepad::getButtonA() const
{
return _buttonA;
}
ControllerButtonInput* Gamepad::getButtonB() const
{
return _buttonB;
}
ControllerButtonInput* Gamepad::getButtonX() const
{
return _buttonX;
}
ControllerButtonInput* Gamepad::getButtonY() const
{
return _buttonY;
}
ControllerButtonInput* Gamepad::getButtonPause() const
{
return _buttonPause;
}
ControllerButtonInput* Gamepad::getButtonSelect() const
{
return _buttonSelect;
}
ControllerButtonInput* Gamepad::getButtonStart() const
{
return _buttonStart;
}
ControllerButtonInput* Gamepad::getLeftShoulder() const
{
return _leftShoulder;
}
ControllerButtonInput* Gamepad::getRightShoulder() const
{
return _rightShoulder;
}
ControllerThumbstick* Gamepad::getLeftThumbstick() const
{
return _leftThumbstick;
}
ControllerThumbstick* Gamepad::getRightThumbstick() const
{
return _rightThumbstick;
}
ControllerButtonInput* Gamepad::getLeftTrigger() const
{
return _leftTrigger;
}
ControllerButtonInput* Gamepad::getRightTrigger() const
{
return _rightTrigger;
}
NS_CC_END

View File

@ -1,122 +0,0 @@
/****************************************************************************
Copyright (c) 2014 cocos2d-x.org
Copyright (c) 2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __cocos2d_libs__CCGamepad__
#define __cocos2d_libs__CCGamepad__
#include "CCPlatformMacros.h"
NS_CC_BEGIN
class ControllerButtonInput;
class ControllerDirectionPad;
class ControllerThumbstick;
class Controller;
class Gamepad
{
public:
/**
A profile keeps a reference to the controller that this profile is mapping input from.
*/
Controller* getController();
// API for Standard / Extended Gamepad
ControllerDirectionPad* getDirectionPad() const;
/**
All face buttons are required to be analog in the Extended profile. These must be arranged
in the diamond pattern given below:
Y
/ \
X B
\ /
A
*/
ControllerButtonInput* getButtonA() const;
ControllerButtonInput* getButtonB() const;
ControllerButtonInput* getButtonX() const;
ControllerButtonInput* getButtonY() const;
// Select button
ControllerButtonInput* getButtonSelect() const;
// Start button
ControllerButtonInput* getButtonStart() const;
// Pause button
ControllerButtonInput* getButtonPause() const;
// Shoulder buttons
ControllerButtonInput* getLeftShoulder() const;
ControllerButtonInput* getRightShoulder() const;
// API for Extended Gamepad only
/**
A thumbstick is a 2-axis control that is physically required to be analog. All the elements of this directional input are thus analog.
*/
ControllerThumbstick* getLeftThumbstick() const;
ControllerThumbstick* getRightThumbstick() const;
/**
If Trigger button supports analog inputs, it could be used as acceleration and decelleration in a driving game for example.
*/
ControllerButtonInput* getLeftTrigger() const;
ControllerButtonInput* getRightTrigger() const;
protected:
Gamepad();
virtual ~Gamepad();
friend class Controller;
Controller* _controller;
ControllerDirectionPad* _directionPad;
ControllerButtonInput* _buttonA;
ControllerButtonInput* _buttonB;
ControllerButtonInput* _buttonX;
ControllerButtonInput* _buttonY;
ControllerButtonInput* _buttonSelect;
ControllerButtonInput* _buttonStart;
ControllerButtonInput* _buttonPause;
ControllerButtonInput* _leftShoulder;
ControllerButtonInput* _rightShoulder;
ControllerThumbstick* _leftThumbstick;
ControllerThumbstick* _rightThumbstick;
ControllerButtonInput* _leftTrigger;
ControllerButtonInput* _rightTrigger;
};
NS_CC_END
#endif /* defined(__cocos2d_libs__CCGamepad__) */

View File

@ -35,8 +35,6 @@ LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../2d \
$(LOCAL_PATH) \
$(LOCAL_PATH)/../../..
LOCAL_CFLAGS += -Wno-psabi
LOCAL_EXPORT_CFLAGS += -Wno-psabi
LOCAL_WHOLE_STATIC_LIBRARIES := cocos_extension_static

View File

@ -45,6 +45,8 @@ static const char* ClassName_Button = "Button";
static const char* ClassName_CheckBox = "CheckBox";
static const char* ClassName_ImageView = "ImageView";
static const char* ClassName_TextAtlas = "TextAtlas";
static const char* ClassName_LabelAtlas = "LabelAtlas";
static const char* ClassName_LabelBMFont= "LabelBMFont";
static const char* ClassName_TextBMFont = "TextBMFont";
static const char* ClassName_Text = "Text";
static const char* ClassName_LoadingBar = "LoadingBar";
@ -132,7 +134,8 @@ void NodeReader::init()
_funcs.insert(Pair(ClassName_SubGraph, std::bind(&NodeReader::loadSubGraph, this, _1)));
_funcs.insert(Pair(ClassName_Sprite, std::bind(&NodeReader::loadSprite, this, _1)));
_funcs.insert(Pair(ClassName_Particle, std::bind(&NodeReader::loadParticle, this, _1)));
_funcs.insert(Pair(ClassName_LabelAtlas,std::bind(&NodeReader::loadWidget, this, _1)));
_funcs.insert(Pair(ClassName_LabelBMFont,std::bind(&NodeReader::loadWidget, this, _1)));
_funcs.insert(Pair(ClassName_Panel, std::bind(&NodeReader::loadWidget, this, _1)));
_funcs.insert(Pair(ClassName_Button, std::bind(&NodeReader::loadWidget, this, _1)));
_funcs.insert(Pair(ClassName_CheckBox, std::bind(&NodeReader::loadWidget, this, _1)));

View File

@ -68,8 +68,8 @@ $(LOCAL_PATH)/../../../external \
$(LOCAL_PATH)/.. \
$(LOCAL_PATH)/../..
LOCAL_CFLAGS += -Wno-psabi -fexceptions
LOCAL_EXPORT_CFLAGS += -Wno-psabi
LOCAL_CFLAGS += -fexceptions
LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static
LOCAL_WHOLE_STATIC_LIBRARIES += cocosdenshion_static

View File

@ -83,7 +83,7 @@ void ActionManagerEx::initWithDictionary(const char* jsonName,const rapidjson::V
CCLOG("filename == %s",fileName.c_str());
cocos2d::Vector<ActionObject*> actionList;
stExpCocoNode *stChildArray = pCocoNode->GetChildArray();
stExpCocoNode *stChildArray = pCocoNode->GetChildArray(cocoLoader);
stExpCocoNode *actionNode = nullptr;
for (int i=0; i < pCocoNode->GetChildNum(); ++i) {
std::string key = stChildArray[i].GetName(cocoLoader);
@ -99,7 +99,7 @@ void ActionManagerEx::initWithDictionary(const char* jsonName,const rapidjson::V
ActionObject* action = new ActionObject();
action->autorelease();
action->initWithBinary(cocoLoader, actionNode->GetChildArray(), root);
action->initWithBinary(cocoLoader, actionNode->GetChildArray(cocoLoader), root);
actionList.pushBack(action);
}

View File

@ -195,11 +195,11 @@ void ActionNode::initWithDictionary(const rapidjson::Value& dic, Ref* root)
stExpCocoNode *stChildNode = cocoNode;
int actionNodeCount = stChildNode->GetChildNum();
stChildNode = stChildNode[0].GetChildArray();
stChildNode = stChildNode[0].GetChildArray(cocoLoader);
stExpCocoNode *frameListNode = nullptr;
for (int i = 0; i < actionNodeCount; ++i) {
std::string key = stChildNode[i].GetName(cocoLoader);
std::string value = stChildNode[i].GetValue();
std::string value = stChildNode[i].GetValue(cocoLoader);
if (key == "ActionTag") {
setActionTag(valueToInt(value));
}else if (key == "actionframelist"){
@ -208,7 +208,7 @@ void ActionNode::initWithDictionary(const rapidjson::Value& dic, Ref* root)
}
int actionFrameCount = frameListNode->GetChildNum();
stExpCocoNode *stFrameChildNode = frameListNode->GetChildArray();
stExpCocoNode *stFrameChildNode = frameListNode->GetChildArray(cocoLoader);
for (int i=0; i<actionFrameCount; i++) {
int frameIndex;
@ -225,10 +225,10 @@ void ActionNode::initWithDictionary(const rapidjson::Value& dic, Ref* root)
std::vector<float> frameTweenParameter;
int framesCount = stFrameChildNode[i].GetChildNum();
stExpCocoNode *innerFrameNode = stFrameChildNode[i].GetChildArray();
stExpCocoNode *innerFrameNode = stFrameChildNode[i].GetChildArray(cocoLoader);
for (int j = 0; j < framesCount; j++) {
std::string key = innerFrameNode[j].GetName(cocoLoader);
std::string value = innerFrameNode[j].GetValue();
std::string value = innerFrameNode[j].GetValue(cocoLoader);
if (key == "frameid") {
frameIndex = valueToInt(value);
@ -237,10 +237,10 @@ void ActionNode::initWithDictionary(const rapidjson::Value& dic, Ref* root)
}else if (key == "tweenParameter"){
// There are no tweenParameter args in the json file
int tweenParameterCount = innerFrameNode[j].GetChildNum();
stExpCocoNode *tweenParameterArray = innerFrameNode[j].GetChildArray();
stExpCocoNode *tweenParameterArray = innerFrameNode[j].GetChildArray(cocoLoader);
for (int k = 0; k < tweenParameterCount; ++k) {
std::string t_key = tweenParameterArray[j].GetName(cocoLoader);
std::string t_value = tweenParameterArray[j].GetValue();
std::string t_value = tweenParameterArray[j].GetValue(cocoLoader);
frameTweenParameter.push_back(valueToFloat(t_value));
}
}else if (key == "positionx"){

View File

@ -132,12 +132,12 @@ void ActionObject::initWithBinary(CocoLoader *cocoLoader,
stExpCocoNode *cocoNode,
cocos2d::Ref *root)
{
stExpCocoNode *stChildNode = cocoNode->GetChildArray();
stExpCocoNode *stChildNode = cocoNode->GetChildArray(cocoLoader);
stExpCocoNode *actionNodeList = nullptr;
int count = cocoNode->GetChildNum();
for (int i = 0; i < count; ++i) {
std::string key = stChildNode[i].GetName(cocoLoader);
std::string value = stChildNode[i].GetValue();
std::string value = stChildNode[i].GetValue(cocoLoader);
if (key == "name") {
setName(value.c_str());
}else if (key == "loop"){
@ -152,7 +152,7 @@ void ActionObject::initWithBinary(CocoLoader *cocoLoader,
if(nullptr != actionNodeList)
{
int actionNodeCount = actionNodeList->GetChildNum();
stExpCocoNode *actionNodeArray = actionNodeList->GetChildArray();
stExpCocoNode *actionNodeArray = actionNodeList->GetChildArray(cocoLoader);
int maxLength = 0;
for (int i=0; i<actionNodeCount; i++) {
ActionNode* actionNode = new ActionNode();

View File

@ -151,6 +151,7 @@ bool ComAttribute::serialize(void* r)
SerData *serData = (SerData *)(r);
const rapidjson::Value *v = serData->_rData;
stExpCocoNode *cocoNode = serData->_cocoNode;
CocoLoader *cocoLoader = serData->_cocoLoader;
const char *className = nullptr;
const char *comName = nullptr;
const char *file = nullptr;
@ -170,14 +171,14 @@ bool ComAttribute::serialize(void* r)
}
else if (cocoNode != nullptr)
{
className = cocoNode[1].GetValue();
className = cocoNode[1].GetValue(cocoLoader);
CC_BREAK_IF(className == nullptr);
comName = cocoNode[2].GetValue();
stExpCocoNode *fileData = cocoNode[3].GetChildArray();
comName = cocoNode[2].GetValue(cocoLoader);
stExpCocoNode *fileData = cocoNode[3].GetChildArray(cocoLoader);
CC_BREAK_IF(!fileData);
file = fileData[0].GetValue();
file = fileData[0].GetValue(cocoLoader);
CC_BREAK_IF(file == nullptr);
resType = atoi(fileData[2].GetValue());
resType = atoi(fileData[2].GetValue(cocoLoader));
CC_BREAK_IF(resType != 0);
}
if (comName != nullptr)

View File

@ -76,6 +76,7 @@ bool ComAudio::serialize(void* r)
SerData *serData = (SerData *)(r);
const rapidjson::Value *v = serData->_rData;
stExpCocoNode *cocoNode = serData->_cocoNode;
CocoLoader *cocoLoader = serData->_cocoLoader;
const char *className = nullptr;
const char *comName = nullptr;
const char *file = nullptr;
@ -97,16 +98,16 @@ bool ComAudio::serialize(void* r)
}
else if (cocoNode != nullptr)
{
className = cocoNode[1].GetValue();
className = cocoNode[1].GetValue(cocoLoader);
CC_BREAK_IF(className == nullptr);
comName = cocoNode[2].GetValue();
stExpCocoNode *pfileData = cocoNode[4].GetChildArray();
comName = cocoNode[2].GetValue(cocoLoader);
stExpCocoNode *pfileData = cocoNode[4].GetChildArray(cocoLoader);
CC_BREAK_IF(!pfileData);
file = pfileData[0].GetValue();
file = pfileData[0].GetValue(cocoLoader);
CC_BREAK_IF(file == nullptr);
resType = atoi(pfileData[2].GetValue());
resType = atoi(pfileData[2].GetValue(cocoLoader));
CC_BREAK_IF(resType != 0);
loop = atoi(cocoNode[5].GetValue()) != 0? true:false;
loop = atoi(cocoNode[5].GetValue(cocoLoader)) != 0? true:false;
ret = true;
}
if (comName != nullptr)

View File

@ -50,10 +50,12 @@ struct SerData
{
const rapidjson::Value *_rData;
cocostudio::stExpCocoNode *_cocoNode;
cocostudio::CocoLoader *_cocoLoader;
SerData()
{
_rData = NULL;
_cocoNode = NULL;
_cocoLoader = NULL;
}
};

View File

@ -97,6 +97,7 @@ bool ComRender::serialize(void* r)
SerData *serData = (SerData *)(r);
const rapidjson::Value *v = serData->_rData;
stExpCocoNode *cocoNode = serData->_cocoNode;
CocoLoader *cocoLoader = serData->_cocoLoader;
const char *className = nullptr;
const char *comName = nullptr;
const char *file = nullptr;
@ -118,15 +119,15 @@ bool ComRender::serialize(void* r)
}
else if(cocoNode != nullptr)
{
className = cocoNode[1].GetValue();
className = cocoNode[1].GetValue(cocoLoader);
CC_BREAK_IF(className == nullptr);
comName = cocoNode[2].GetValue();
stExpCocoNode *pfileData = cocoNode[4].GetChildArray();
comName = cocoNode[2].GetValue(cocoLoader);
stExpCocoNode *pfileData = cocoNode[4].GetChildArray(cocoLoader);
CC_BREAK_IF(!pfileData);
file = pfileData[0].GetValue();
plist = pfileData[1].GetValue();
file = pfileData[0].GetValue(cocoLoader);
plist = pfileData[1].GetValue(cocoLoader);
CC_BREAK_IF(file == nullptr && plist == nullptr);
resType = atoi(pfileData[2].GetValue());
resType = atoi(pfileData[2].GetValue(cocoLoader));
}
if (comName != nullptr)
{
@ -195,7 +196,7 @@ bool ComRender::serialize(void* r)
const char *actionName = nullptr;
if (cocoNode != nullptr)
{
actionName = cocoNode[6].GetValue();//DICTOOL->getStringValue_json(*v, "selectedactionname");
actionName = cocoNode[6].GetValue(cocoLoader);//DICTOOL->getStringValue_json(*v, "selectedactionname");
}
else
{
@ -222,25 +223,25 @@ bool ComRender::serialize(void* r)
if (rapidjson::kObjectType == tType)
{
int count = tpRootCocoNode->GetChildNum();
stExpCocoNode *tpChildArray = tpRootCocoNode->GetChildArray();
stExpCocoNode *tpChildArray = tpRootCocoNode->GetChildArray(&tCocoLoader);
for (int i = 0; i < count; ++i)
{
std::string key = tpChildArray[i].GetName(&tCocoLoader);
if (key.compare("armature_data") == 0)
{
int length = tpChildArray[i].GetChildNum();
stExpCocoNode *armature_dataArray = tpChildArray[i].GetChildArray();
stExpCocoNode *armature_dataArray = tpChildArray[i].GetChildArray(&tCocoLoader);
if (length < 1)
{
continue;
}
length = armature_dataArray[0].GetChildNum();
stExpCocoNode *armature_data = armature_dataArray[0].GetChildArray();
stExpCocoNode *armature_data = armature_dataArray[0].GetChildArray(&tCocoLoader);
for (int j = 0; j < length; ++j)
{
std::string key1 = armature_data[j].GetName(&tCocoLoader);
const char *str1 = armature_data[j].GetValue();
const char *str1 = armature_data[j].GetValue(&tCocoLoader);
if (key.compare("name") == 0)
{
if (str1 != nullptr)
@ -252,7 +253,7 @@ bool ComRender::serialize(void* r)
const char *actionName = nullptr;
if (cocoNode != nullptr)
{
actionName = cocoNode[6].GetValue();
actionName = cocoNode[6].GetValue(&tCocoLoader);
}
else
{

View File

@ -301,9 +301,9 @@ void DataReaderHelper::addDataFromFile(const std::string& filePath)
// Read content from file
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
bool isbinarysrc = str==".csb";
bool isbinaryfilesrc = str==".csb";
std::string filemode("r");
if(isbinarysrc)
if(isbinaryfilesrc)
filemode += "b";
ssize_t filesize;
@ -324,7 +324,7 @@ void DataReaderHelper::addDataFromFile(const std::string& filePath)
{
DataReaderHelper::addDataFromJsonCache(contentStr, &dataInfo);
}
else if(str == ".csb")
else if(isbinaryfilesrc)
{
DataReaderHelper::addDataFromBinaryCache(contentStr.c_str(),&dataInfo);
}
@ -438,7 +438,7 @@ void DataReaderHelper::addDataFromFileAsync(const std::string& imagePath, const
{
data->configType = CocoStudio_JSON;
}
else if(str == ".csb")
else if(isbinaryfilesrc)
{
data->configType = CocoStudio_Binary;
}
@ -474,7 +474,7 @@ void DataReaderHelper::addDataAsyncCallBack(float dt)
if (pAsyncStruct->imagePath != "" && pAsyncStruct->plistPath != "")
{
_getFileMutex.lock();
ArmatureDataManager::getInstance()->addSpriteFrameFromFile(pAsyncStruct->plistPath.c_str(), pAsyncStruct->imagePath.c_str());
ArmatureDataManager::getInstance()->addSpriteFrameFromFile(pAsyncStruct->plistPath.c_str(), pAsyncStruct->imagePath.c_str(), pDataInfo->filename.c_str());
_getFileMutex.unlock();
}
@ -482,7 +482,7 @@ void DataReaderHelper::addDataAsyncCallBack(float dt)
{
std::string configPath = pDataInfo->configFileQueue.front();
_getFileMutex.lock();
ArmatureDataManager::getInstance()->addSpriteFrameFromFile((pAsyncStruct->baseFilePath + configPath + ".plist").c_str(), (pAsyncStruct->baseFilePath + configPath + ".png").c_str());
ArmatureDataManager::getInstance()->addSpriteFrameFromFile((pAsyncStruct->baseFilePath + configPath + ".plist").c_str(), (pAsyncStruct->baseFilePath + configPath + ".png").c_str(),pDataInfo->filename.c_str());
_getFileMutex.unlock();
pDataInfo->configFileQueue.pop();
}
@ -1258,7 +1258,7 @@ void DataReaderHelper::addDataFromJsonCache(const std::string& fileContent, Data
{
_dataReaderHelper->_addDataMutex.lock();
}
ArmatureDataManager::getInstance()->addArmatureData(armatureData->name.c_str(), armatureData);
ArmatureDataManager::getInstance()->addArmatureData(armatureData->name.c_str(), armatureData, dataInfo->filename.c_str());
armatureData->release();
if (dataInfo->asyncStruct)
{
@ -1277,7 +1277,7 @@ void DataReaderHelper::addDataFromJsonCache(const std::string& fileContent, Data
{
_dataReaderHelper->_addDataMutex.lock();
}
ArmatureDataManager::getInstance()->addAnimationData(animationData->name.c_str(), animationData);
ArmatureDataManager::getInstance()->addAnimationData(animationData->name.c_str(), animationData, dataInfo->filename.c_str());
animationData->release();
if (dataInfo->asyncStruct)
{
@ -1296,7 +1296,7 @@ void DataReaderHelper::addDataFromJsonCache(const std::string& fileContent, Data
{
_dataReaderHelper->_addDataMutex.lock();
}
ArmatureDataManager::getInstance()->addTextureData(textureData->name.c_str(), textureData);
ArmatureDataManager::getInstance()->addTextureData(textureData->name.c_str(), textureData, dataInfo->filename.c_str());
textureData->release();
if (dataInfo->asyncStruct)
{
@ -1330,7 +1330,7 @@ void DataReaderHelper::addDataFromJsonCache(const std::string& fileContent, Data
std::string plistPath = filePath + ".plist";
std::string pngPath = filePath + ".png";
ArmatureDataManager::getInstance()->addSpriteFrameFromFile((dataInfo->baseFilePath + plistPath).c_str(), (dataInfo->baseFilePath + pngPath).c_str());
ArmatureDataManager::getInstance()->addSpriteFrameFromFile((dataInfo->baseFilePath + plistPath).c_str(), (dataInfo->baseFilePath + pngPath).c_str(), dataInfo->filename.c_str());
}
}
}
@ -1750,7 +1750,7 @@ void DataReaderHelper::decodeNode(BaseData *node, const rapidjson::Value& json,
rapidjson::Type tType = tpRootCocoNode->GetType(&tCocoLoader);
if (rapidjson::kObjectType == tType)
{
stExpCocoNode *tpChildArray = tpRootCocoNode->GetChildArray();
stExpCocoNode *tpChildArray = tpRootCocoNode->GetChildArray(&tCocoLoader);
int nCount = tpRootCocoNode->GetChildNum();
dataInfo->contentScale = 1.0f;
@ -1762,12 +1762,12 @@ void DataReaderHelper::decodeNode(BaseData *node, const rapidjson::Value& json,
key = tpChildArray[i].GetName(&tCocoLoader);
if (key.compare(CONTENT_SCALE) == 0)
{
std::string value = tpChildArray[i].GetValue();
std::string value = tpChildArray[i].GetValue(&tCocoLoader);
dataInfo->contentScale = atof(value.c_str());
}
else if ( 0 == key.compare(ARMATURE_DATA))
{
pDataArray = tpChildArray[i].GetChildArray();
pDataArray = tpChildArray[i].GetChildArray(&tCocoLoader);
length = tpChildArray[i].GetChildNum();
ArmatureData * armatureData;
for (int ii = 0; ii < length; ++ii)
@ -1787,7 +1787,7 @@ void DataReaderHelper::decodeNode(BaseData *node, const rapidjson::Value& json,
}
else if ( 0 == key.compare(ANIMATION_DATA))
{
pDataArray = tpChildArray[i].GetChildArray();
pDataArray = tpChildArray[i].GetChildArray(&tCocoLoader);
length = tpChildArray[i].GetChildNum();
AnimationData *animationData;
for (int ii = 0; ii < length; ++ii)
@ -1807,7 +1807,7 @@ void DataReaderHelper::decodeNode(BaseData *node, const rapidjson::Value& json,
}
else if (key.compare(TEXTURE_DATA) == 0)
{
pDataArray = tpChildArray[i].GetChildArray();
pDataArray = tpChildArray[i].GetChildArray(&tCocoLoader);
length = tpChildArray[i].GetChildNum();
for (int ii = 0; ii < length; ++ii)
{
@ -1837,10 +1837,10 @@ void DataReaderHelper::decodeNode(BaseData *node, const rapidjson::Value& json,
continue;
}
length = tpChildArray[i].GetChildNum();
stExpCocoNode *pConfigFilePath = tpChildArray[i].GetChildArray();
stExpCocoNode *pConfigFilePath = tpChildArray[i].GetChildArray(&tCocoLoader);
for (int ii = 0; ii < length; ii++)
{
const char *path = pConfigFilePath[ii].GetValue();
const char *path = pConfigFilePath[ii].GetValue(&tCocoLoader);
if (path == nullptr)
{
CCLOG("load CONFIG_FILE_PATH error.");
@ -1872,18 +1872,18 @@ void DataReaderHelper::decodeNode(BaseData *node, const rapidjson::Value& json,
{
ArmatureData *armatureData = new ArmatureData();
armatureData->init();
stExpCocoNode *pAramtureDataArray = cocoNode->GetChildArray();
const char *name = pAramtureDataArray[2].GetValue(); //DICTOOL->getStringValue_json(json, A_NAME);
stExpCocoNode *pAramtureDataArray = cocoNode->GetChildArray(cocoLoader);
const char *name = pAramtureDataArray[2].GetValue(cocoLoader); //DICTOOL->getStringValue_json(json, A_NAME);
if(name != nullptr)
{
armatureData->name = name;
}
float version = atof(pAramtureDataArray[1].GetValue());
float version = atof(pAramtureDataArray[1].GetValue(cocoLoader));
dataInfo->cocoStudioVersion = armatureData->dataVersion = version; //DICTOOL->getFloatValue_json(json, VERSION, 0.1f);
int length = pAramtureDataArray[3].GetChildNum(); //DICTOOL->getArrayCount_json(json, BONE_DATA, 0);
stExpCocoNode *pBoneChildren = pAramtureDataArray[3].GetChildArray();
stExpCocoNode *pBoneChildren = pAramtureDataArray[3].GetChildArray(cocoLoader);
stExpCocoNode* child;
for (int i = 0; i < length; i++)
{
@ -1905,7 +1905,7 @@ void DataReaderHelper::decodeNode(BaseData *node, const rapidjson::Value& json,
decodeNode(boneData, cocoLoader, cocoNode, dataInfo);
int length = cocoNode->GetChildNum();
stExpCocoNode *pBoneChildren = cocoNode->GetChildArray();
stExpCocoNode *pBoneChildren = cocoNode->GetChildArray(cocoLoader);
stExpCocoNode* child;
const char *str = nullptr;
std::string key;
@ -1913,7 +1913,7 @@ void DataReaderHelper::decodeNode(BaseData *node, const rapidjson::Value& json,
{
child = &pBoneChildren[i];
key = child->GetName(cocoLoader);
str = child->GetValue();
str = child->GetValue(cocoLoader);
if (key.compare(A_NAME) == 0)
{
//DICTOOL->getStringValue_json(json, A_NAME);
@ -1933,7 +1933,7 @@ void DataReaderHelper::decodeNode(BaseData *node, const rapidjson::Value& json,
else if (key.compare(DISPLAY_DATA) == 0)
{
int count = child->GetChildNum();
stExpCocoNode *pDisplayData = child->GetChildArray();
stExpCocoNode *pDisplayData = child->GetChildArray(cocoLoader);
for (int ii = 0; ii < count; ++ii)
{
DisplayData *displayData = decodeBoneDisplay(cocoLoader, &pDisplayData[ii], dataInfo);
@ -1950,16 +1950,16 @@ void DataReaderHelper::decodeNode(BaseData *node, const rapidjson::Value& json,
DisplayData* DataReaderHelper::decodeBoneDisplay(CocoLoader *cocoLoader, stExpCocoNode *cocoNode, DataInfo *dataInfo)
{
stExpCocoNode* children = cocoNode->GetChildArray();
stExpCocoNode* children = cocoNode->GetChildArray(cocoLoader);
stExpCocoNode* child = &children[1];
const char *str = nullptr;
std::string key = child->GetName(cocoLoader);
str = child->GetValue();
str = child->GetValue(cocoLoader);
DisplayData *displayData = nullptr;
if (key.compare(A_DISPLAY_TYPE) == 0)
{
str = child->GetValue();
str = child->GetValue(cocoLoader);
DisplayType displayType = (DisplayType)(atoi(str));
int length = 0;
@ -1969,12 +1969,12 @@ void DataReaderHelper::decodeNode(BaseData *node, const rapidjson::Value& json,
{
displayData = new SpriteDisplayData();
const char *name = children[0].GetValue();
const char *name = children[0].GetValue(cocoLoader);
if(name != nullptr)
{
((SpriteDisplayData *)displayData)->displayName = name;
}
stExpCocoNode *pSkinDataArray = children[2].GetChildArray();
stExpCocoNode *pSkinDataArray = children[2].GetChildArray(cocoLoader);
if (pSkinDataArray != nullptr)
{
stExpCocoNode *pSkinData = &pSkinDataArray[0];
@ -1982,11 +1982,11 @@ void DataReaderHelper::decodeNode(BaseData *node, const rapidjson::Value& json,
{
SpriteDisplayData *sdd = (SpriteDisplayData *)displayData;
length = pSkinData->GetChildNum();
stExpCocoNode *SkinDataValue = pSkinData->GetChildArray();
stExpCocoNode *SkinDataValue = pSkinData->GetChildArray(cocoLoader);
for (int i = 0; i < length; ++i)
{
key = SkinDataValue[i].GetName(cocoLoader);
str = SkinDataValue[i].GetValue();
str = SkinDataValue[i].GetValue(cocoLoader);
if (key.compare(A_X) == 0)
{
sdd->skinData.x = atof(str) * s_PositionReadScale;
@ -2024,7 +2024,7 @@ void DataReaderHelper::decodeNode(BaseData *node, const rapidjson::Value& json,
{
displayData = new ArmatureDisplayData();
const char *name = cocoNode[0].GetValue();
const char *name = cocoNode[0].GetValue(cocoLoader);
if(name != nullptr)
{
((ArmatureDisplayData *)displayData)->displayName = name;
@ -2035,11 +2035,11 @@ void DataReaderHelper::decodeNode(BaseData *node, const rapidjson::Value& json,
{
displayData = new ParticleDisplayData();
length = cocoNode->GetChildNum();
stExpCocoNode *pDisplayData = cocoNode->GetChildArray();
stExpCocoNode *pDisplayData = cocoNode->GetChildArray(cocoLoader);
for (int i = 0; i < length; ++i)
{
key = pDisplayData[i].GetName(cocoLoader);
str = pDisplayData[i].GetValue();
str = pDisplayData[i].GetValue(cocoLoader);
if (key.compare(A_PLIST) == 0)
{
const char *plist = str;
@ -2073,7 +2073,7 @@ void DataReaderHelper::decodeNode(BaseData *node, const rapidjson::Value& json,
AnimationData *aniData = new AnimationData();
int length = cocoNode->GetChildNum();
stExpCocoNode *pAnimationData = cocoNode->GetChildArray();
stExpCocoNode *pAnimationData = cocoNode->GetChildArray(cocoLoader);
const char *str = nullptr;
std::string key;
stExpCocoNode* child;
@ -2082,7 +2082,7 @@ void DataReaderHelper::decodeNode(BaseData *node, const rapidjson::Value& json,
{
child = &pAnimationData[i];
key = child->GetName(cocoLoader);
str = child->GetValue();
str = child->GetValue(cocoLoader);
if (key.compare(A_NAME) == 0)
{
if(str != nullptr)
@ -2093,7 +2093,7 @@ void DataReaderHelper::decodeNode(BaseData *node, const rapidjson::Value& json,
else if (key.compare(MOVEMENT_DATA) == 0)
{
int movcount = child->GetChildNum();
stExpCocoNode* movArray = child->GetChildArray();
stExpCocoNode* movArray = child->GetChildArray(cocoLoader);
for( int movnum =0; movnum <movcount; movnum++)
{
movementData = decodeMovement(cocoLoader, &movArray[movnum], dataInfo);
@ -2111,7 +2111,7 @@ void DataReaderHelper::decodeNode(BaseData *node, const rapidjson::Value& json,
movementData->scale = 1.0f;
int length = cocoNode->GetChildNum();
stExpCocoNode *pMoveDataArray = cocoNode->GetChildArray();
stExpCocoNode *pMoveDataArray = cocoNode->GetChildArray(cocoLoader);
const char *str = nullptr;
std::string key;
@ -2120,7 +2120,7 @@ void DataReaderHelper::decodeNode(BaseData *node, const rapidjson::Value& json,
{
child = &pMoveDataArray[i];
key = child->GetName(cocoLoader);
str = child->GetValue();
str = child->GetValue(cocoLoader);
if (key.compare(A_NAME) == 0)
{
if(str != nullptr)
@ -2182,7 +2182,7 @@ void DataReaderHelper::decodeNode(BaseData *node, const rapidjson::Value& json,
else if (key.compare(MOVEMENT_BONE_DATA) == 0)
{
int count = child->GetChildNum();
stExpCocoNode *pMoveBoneData = child->GetChildArray();
stExpCocoNode *pMoveBoneData = child->GetChildArray(cocoLoader);
MovementBoneData *movementBoneData;
for (int ii = 0; ii < count; ++ii)
{
@ -2201,14 +2201,14 @@ void DataReaderHelper::decodeNode(BaseData *node, const rapidjson::Value& json,
movementBoneData->init();
int length = cocoNode->GetChildNum();
stExpCocoNode *pMovementBoneDataArray = cocoNode->GetChildArray();
stExpCocoNode *pMovementBoneDataArray = cocoNode->GetChildArray(cocoLoader);
stExpCocoNode* movebonechild;
const char *str = nullptr;
for (int i = 0; i < length; ++i)
{
movebonechild = &pMovementBoneDataArray[i];
std::string key = movebonechild->GetName(cocoLoader);
str = movebonechild->GetValue();
str = movebonechild->GetValue(cocoLoader);
if (key.compare(A_NAME) == 0)
{
if(str != nullptr)
@ -2226,7 +2226,7 @@ void DataReaderHelper::decodeNode(BaseData *node, const rapidjson::Value& json,
else if (key.compare(FRAME_DATA) == 0)
{
int count =movebonechild->GetChildNum();
stExpCocoNode *pFrameDataArray = movebonechild->GetChildArray();
stExpCocoNode *pFrameDataArray = movebonechild->GetChildArray(cocoLoader);
for (int ii = 0; ii < count; ++ii)
{
FrameData *frameData = decodeFrame(cocoLoader, &pFrameDataArray[ii], dataInfo);
@ -2296,12 +2296,12 @@ void DataReaderHelper::decodeNode(BaseData *node, const rapidjson::Value& json,
decodeNode(frameData, cocoLoader, cocoNode, dataInfo);
int length = cocoNode->GetChildNum();
stExpCocoNode *pFrameDataArray = cocoNode->GetChildArray();
stExpCocoNode *pFrameDataArray = cocoNode->GetChildArray(cocoLoader);
const char *str = nullptr;
for (int i = 0; i < length; ++i)
{
std::string key = pFrameDataArray[i].GetName(cocoLoader);
str = pFrameDataArray[i].GetValue();
str = pFrameDataArray[i].GetValue(cocoLoader);
if (key.compare(A_TWEEN_EASING) == 0)
{
frameData->tweenEasing = cocos2d::tweenfunc::Linear;
@ -2376,10 +2376,10 @@ void DataReaderHelper::decodeNode(BaseData *node, const rapidjson::Value& json,
if (count != 0 )
{
frameData->easingParams = new float[count];
stExpCocoNode *pFrameData = pFrameDataArray[i].GetChildArray();
stExpCocoNode *pFrameData = pFrameDataArray[i].GetChildArray(cocoLoader);
for (int ii = 0; ii < count; ++ii)
{
str = pFrameData[ii].GetValue();
str = pFrameData[ii].GetValue(cocoLoader);
if (str != nullptr)
{
frameData->easingParams[ii] = atof(str);
@ -2404,12 +2404,12 @@ void DataReaderHelper::decodeNode(BaseData *node, const rapidjson::Value& json,
}
int length = cocoNode->GetChildNum();
stExpCocoNode *pTextureDataArray = cocoNode->GetChildArray();
stExpCocoNode *pTextureDataArray = cocoNode->GetChildArray(cocoLoader);
const char *str = nullptr;
for (int i = 0; i < length; ++i)
{
std::string key = pTextureDataArray[i].GetName(cocoLoader);
str = pTextureDataArray[i].GetValue();
str = pTextureDataArray[i].GetValue(cocoLoader);
if (key.compare(A_NAME) == 0)
{
if(str != nullptr)
@ -2448,7 +2448,7 @@ void DataReaderHelper::decodeNode(BaseData *node, const rapidjson::Value& json,
else if (key.compare(CONTOUR_DATA) == 0)
{
int count = pTextureDataArray[i].GetChildNum();
stExpCocoNode *pContourArray = pTextureDataArray[i].GetChildArray();
stExpCocoNode *pContourArray = pTextureDataArray[i].GetChildArray(cocoLoader);
for (int ii = 0; ii < count; ++ii)
{
ContourData *contourData = decodeContour(cocoLoader, &pContourArray[ii]);
@ -2466,23 +2466,23 @@ void DataReaderHelper::decodeNode(BaseData *node, const rapidjson::Value& json,
contourData->init();
int length = cocoNode->GetChildNum();
stExpCocoNode *verTexPointArray = cocoNode->GetChildArray();
stExpCocoNode *verTexPointArray = cocoNode->GetChildArray(cocoLoader);
const char *str = nullptr;
for (int i = 0; i < length; ++i)
{
std::string key = verTexPointArray[i].GetName(cocoLoader);
str = verTexPointArray[i].GetValue();
str = verTexPointArray[i].GetValue(cocoLoader);
if (key.compare(VERTEX_POINT) == 0)
{
int count = verTexPointArray[i].GetChildNum();
stExpCocoNode *pVerTexPointArray = verTexPointArray[i].GetChildArray();
stExpCocoNode *pVerTexPointArray = verTexPointArray[i].GetChildArray(cocoLoader);
stExpCocoNode *pVerTexPoint;
for (int ii = count - 1; ii >= 0; --ii)
{
pVerTexPoint = pVerTexPointArray[ii].GetChildArray();
pVerTexPoint = pVerTexPointArray[ii].GetChildArray(cocoLoader);
Vec2 vertex;
vertex.x = atof(pVerTexPoint[0].GetValue());
vertex.y = atof(pVerTexPoint[1].GetValue());
vertex.x = atof(pVerTexPoint[0].GetValue(cocoLoader));
vertex.y = atof(pVerTexPoint[1].GetValue(cocoLoader));
contourData->vertexList.push_back(vertex); }
break;
}
@ -2493,7 +2493,7 @@ void DataReaderHelper::decodeNode(BaseData *node, const rapidjson::Value& json,
void DataReaderHelper::decodeNode(BaseData *node, CocoLoader *cocoLoader, stExpCocoNode* cocoNode, DataInfo *dataInfo)
{
int length = cocoNode->GetChildNum();
stExpCocoNode *NodeArray = cocoNode->GetChildArray();
stExpCocoNode *NodeArray = cocoNode->GetChildArray(cocoLoader);
const char *str = nullptr;
bool isVersionL = dataInfo->cocoStudioVersion < VERSION_COLOR_READING;
@ -2502,7 +2502,7 @@ void DataReaderHelper::decodeNode(BaseData *node, const rapidjson::Value& json,
{
child = &NodeArray[i];
std::string key = child->GetName(cocoLoader);
str = child->GetValue();
str = child->GetValue(cocoLoader);
if (key.compare(A_X) == 0)
{
node->x = atof(str) * dataInfo->contentScale;
@ -2539,12 +2539,12 @@ void DataReaderHelper::decodeNode(BaseData *node, const rapidjson::Value& json,
{
if(child->GetChildNum() == 4)
{
stExpCocoNode *ChildArray = child->GetChildArray();
stExpCocoNode *ChildArray = child->GetChildArray(cocoLoader);
node->a = atoi(ChildArray[0].GetValue());
node->r = atoi(ChildArray[1].GetValue());
node->g = atoi(ChildArray[2].GetValue());
node->b = atoi(ChildArray[3].GetValue());
node->a = atoi(ChildArray[0].GetValue(cocoLoader));
node->r = atoi(ChildArray[1].GetValue(cocoLoader));
node->g = atoi(ChildArray[2].GetValue(cocoLoader));
node->b = atoi(ChildArray[3].GetValue(cocoLoader));
}
}
@ -2566,12 +2566,12 @@ void DataReaderHelper::decodeNode(BaseData *node, const rapidjson::Value& json,
{
if(NodeArray[0].GetChildNum() == 4)
{
stExpCocoNode *ChildArray = NodeArray[0].GetChildArray();
stExpCocoNode *ChildArray = NodeArray[0].GetChildArray(cocoLoader);
node->a = atoi(ChildArray[0].GetValue());
node->r = atoi(ChildArray[1].GetValue());
node->g = atoi(ChildArray[2].GetValue());
node->b = atoi(ChildArray[3].GetValue());
node->a = atoi(ChildArray[0].GetValue(cocoLoader));
node->r = atoi(ChildArray[1].GetValue(cocoLoader));
node->g = atoi(ChildArray[2].GetValue(cocoLoader));
node->b = atoi(ChildArray[3].GetValue(cocoLoader));
}
}

View File

@ -361,13 +361,13 @@ Widget* GUIReader::widgetFromBinaryFile(const char *fileName)
rapidjson::Type tType = tpRootCocoNode->GetType(&tCocoLoader);
if (rapidjson::kObjectType == tType || rapidjson::kArrayType == tType)
{
stExpCocoNode *tpChildArray = tpRootCocoNode->GetChildArray();
stExpCocoNode *tpChildArray = tpRootCocoNode->GetChildArray(&tCocoLoader);
for (int i = 0; i < tpRootCocoNode->GetChildNum(); ++i) {
std::string key = tpChildArray[i].GetName(&tCocoLoader);
if (key == "version") {
fileVersion = tpChildArray[i].GetValue();
fileVersion = tpChildArray[i].GetValue(&tCocoLoader);
break;
}
}
@ -1222,7 +1222,7 @@ Widget* WidgetPropertiesReader0300::createWidget(const rapidjson::Value& data, c
cocos2d::ui::Widget* WidgetPropertiesReader0300::createWidgetFromBinary(CocoLoader* cocoLoader,stExpCocoNode* cocoNode, const char* fileName)
{
stExpCocoNode *tpChildArray = cocoNode->GetChildArray();
stExpCocoNode *tpChildArray = cocoNode->GetChildArray(cocoLoader);
float fileDesignWidth;
float fileDesignHeight;
@ -1236,14 +1236,14 @@ Widget* WidgetPropertiesReader0300::createWidget(const rapidjson::Value& data, c
for (int j=0; j<texturesCount; j++)
{
std::string file;
stExpCocoNode *textureCountsArray = tpChildArray[i].GetChildArray();
file = textureCountsArray[j].GetValue();
stExpCocoNode *textureCountsArray = tpChildArray[i].GetChildArray(cocoLoader);
file = textureCountsArray[j].GetValue(cocoLoader);
SpriteFrameCache::getInstance()->addSpriteFramesWithFile(file);
}
}else if (key == "designWidth"){
fileDesignWidth = atof(tpChildArray[i].GetValue());
fileDesignWidth = atof(tpChildArray[i].GetValue(cocoLoader));
}else if (key == "designHeight"){
fileDesignHeight = atof(tpChildArray[i].GetValue());
fileDesignHeight = atof(tpChildArray[i].GetValue(cocoLoader));
}else if (key == "widgetTree"){
if (fileDesignWidth <= 0 || fileDesignHeight <= 0) {
@ -1275,7 +1275,7 @@ Widget* WidgetPropertiesReader0300::createWidget(const rapidjson::Value& data, c
/* ********************** */
/* ********************** */
stExpCocoNode *optionChildNode = cocoNode->GetChildArray();
stExpCocoNode *optionChildNode = cocoNode->GetChildArray(cocoLoader);
for (int k = 0; k < cocoNode->GetChildNum(); ++k) {
std::string key = optionChildNode[k].GetName(cocoLoader);
if (key == "animation") {
@ -1291,7 +1291,7 @@ Widget* WidgetPropertiesReader0300::createWidget(const rapidjson::Value& data, c
Widget* WidgetPropertiesReader0300::widgetFromBinary(CocoLoader* cocoLoader, stExpCocoNode* cocoNode)
{
Widget* widget = nullptr;
stExpCocoNode *stChildArray = cocoNode->GetChildArray();
stExpCocoNode *stChildArray = cocoNode->GetChildArray(cocoLoader);
stExpCocoNode *optionsNode = nullptr;
stExpCocoNode *childrenNode = nullptr;
int elementCount = cocoNode->GetChildNum();
@ -1299,7 +1299,7 @@ Widget* WidgetPropertiesReader0300::widgetFromBinary(CocoLoader* cocoLoader, st
for (int i = 0; i < elementCount; ++i) {
std::string key = stChildArray[i].GetName(cocoLoader);
std::string value = stChildArray[i].GetValue();
std::string value = stChildArray[i].GetValue(cocoLoader);
if (key == "classname" )
{
@ -1341,11 +1341,11 @@ Widget* WidgetPropertiesReader0300::widgetFromBinary(CocoLoader* cocoLoader, st
// 2nd., custom widget parse with custom reader
//2nd. parse custom property
const char* customProperty = NULL;
stExpCocoNode *optionChildNode = optionsNode->GetChildArray();
stExpCocoNode *optionChildNode = optionsNode->GetChildArray(cocoLoader);
for (int k = 0; k < optionsNode->GetChildNum(); ++k) {
std::string key = optionChildNode[k].GetName(cocoLoader);
if (key == "customProperty") {
customProperty = optionChildNode[k].GetValue();
customProperty = optionChildNode[k].GetValue(cocoLoader);
break;
}
}
@ -1369,7 +1369,7 @@ Widget* WidgetPropertiesReader0300::widgetFromBinary(CocoLoader* cocoLoader, st
if (tType22 == rapidjson::kArrayType) {
int childrenCount = childrenNode->GetChildNum();
stExpCocoNode* innerChildArray = childrenNode->GetChildArray();
stExpCocoNode* innerChildArray = childrenNode->GetChildArray(cocoLoader);
for (int i=0; i < childrenCount; ++i) {
rapidjson::Type tType = innerChildArray[i].GetType(cocoLoader);

View File

@ -91,7 +91,7 @@ cocos2d::Node* SceneReader::createNodeWithSceneFile(const std::string &fileName,
rapidjson::Type tType = tpRootCocoNode->GetType(&tCocoLoader);
if (rapidjson::kObjectType == tType)
{
stExpCocoNode *tpChildArray = tpRootCocoNode->GetChildArray();
stExpCocoNode *tpChildArray = tpRootCocoNode->GetChildArray(&tCocoLoader);
CC_BREAK_IF(tpRootCocoNode->GetChildNum() == 0);
_node = Node::create();
int nCount = 0;
@ -102,17 +102,17 @@ cocos2d::Node* SceneReader::createNodeWithSceneFile(const std::string &fileName,
{
nCount = tpChildArray[15].GetChildNum();
}
stExpCocoNode *pComponents = tpChildArray[15].GetChildArray();
stExpCocoNode *pComponents = tpChildArray[15].GetChildArray(&tCocoLoader);
SerData *data = new SerData();
for (int i = 0; i < nCount; i++)
{
stExpCocoNode *subDict = pComponents[i].GetChildArray();
stExpCocoNode *subDict = pComponents[i].GetChildArray(&tCocoLoader);
if (subDict == nullptr)
{
continue;
}
std::string key1 = subDict[1].GetName(&tCocoLoader);
const char *comName = subDict[1].GetValue();
const char *comName = subDict[1].GetValue(&tCocoLoader);
Component *pCom = nullptr;
if (key1 == "classname" && comName != nullptr)
{
@ -123,6 +123,7 @@ cocos2d::Node* SceneReader::createNodeWithSceneFile(const std::string &fileName,
{
data->_rData = nullptr;
data->_cocoNode = subDict;
data->_cocoLoader = &tCocoLoader;
if (pCom->serialize(data))
{
ComRender *pTRender = dynamic_cast<ComRender*>(pCom);
@ -152,7 +153,7 @@ cocos2d::Node* SceneReader::createNodeWithSceneFile(const std::string &fileName,
_node->addComponent(*iter);
}
stExpCocoNode *pGameObjects = tpChildArray[11].GetChildArray();
stExpCocoNode *pGameObjects = tpChildArray[11].GetChildArray(&tCocoLoader);
int length = tpChildArray[11].GetChildNum();
for (int i = 0; i < length; ++i)
{
@ -283,6 +284,7 @@ Node* SceneReader::createObject(const rapidjson::Value &dict, cocos2d::Node* par
{
data->_rData = &subDict;
data->_cocoNode = nullptr;
data->_cocoLoader = nullptr;
if (com->serialize(data))
{
ComRender *tRender = dynamic_cast<ComRender*>(com);
@ -349,11 +351,11 @@ Node* SceneReader::createObject(const rapidjson::Value &dict, cocos2d::Node* par
cocos2d::Node* SceneReader::createObject(CocoLoader *cocoLoader, stExpCocoNode *cocoNode, cocos2d::Node* parent, AttachComponentType attachComponent)
{
const char *className = nullptr;
stExpCocoNode *pNodeArray = cocoNode->GetChildArray();
stExpCocoNode *pNodeArray = cocoNode->GetChildArray(cocoLoader);
std::string Key = pNodeArray[1].GetName(cocoLoader);
if (Key == "classname")
{
className = pNodeArray[1].GetValue();
className = pNodeArray[1].GetValue(cocoLoader);
}
if(strcmp(className, "CCNode") == 0)
{
@ -366,17 +368,17 @@ cocos2d::Node* SceneReader::createObject(CocoLoader *cocoLoader, stExpCocoNode *
{
count = pNodeArray[13].GetChildNum();
}
stExpCocoNode *pComponents = pNodeArray[13].GetChildArray();
stExpCocoNode *pComponents = pNodeArray[13].GetChildArray(cocoLoader);
SerData *data = new SerData();
for (int i = 0; i < count; ++i)
{
stExpCocoNode *subDict = pComponents[i].GetChildArray();
stExpCocoNode *subDict = pComponents[i].GetChildArray(cocoLoader);
if (subDict == nullptr)
{
continue;
}
std::string key1 = subDict[1].GetName(cocoLoader);
const char *comName = subDict[1].GetValue();
const char *comName = subDict[1].GetValue(cocoLoader);
Component *pCom = nullptr;
if (key1 == "classname" && comName != nullptr)
{
@ -387,6 +389,7 @@ cocos2d::Node* SceneReader::createObject(CocoLoader *cocoLoader, stExpCocoNode *
{
data->_rData = nullptr;
data->_cocoNode = subDict;
data->_cocoLoader = cocoLoader;
if (pCom->serialize(data))
{
ComRender *pTRender = dynamic_cast<ComRender*>(pCom);
@ -436,7 +439,7 @@ cocos2d::Node* SceneReader::createObject(CocoLoader *cocoLoader, stExpCocoNode *
gb->addComponent(*iter);
}
stExpCocoNode *pGameObjects = pNodeArray[12].GetChildArray();
stExpCocoNode *pGameObjects = pNodeArray[12].GetChildArray(cocoLoader);
if (pGameObjects != nullptr)
{
int length = pNodeArray[12].GetChildNum();
@ -495,7 +498,7 @@ void SceneReader::setPropertyFromJsonDict(const rapidjson::Value &root, cocos2d:
void SceneReader::setPropertyFromJsonDict(CocoLoader *cocoLoader, stExpCocoNode *cocoNode, cocos2d::Node *node)
{
stExpCocoNode *stChildArray = cocoNode->GetChildArray();
stExpCocoNode *stChildArray = cocoNode->GetChildArray(cocoLoader);
float x = 0.0f, y = 0.0f, fScaleX = 1.0f, fScaleY = 1.0f, fRotationZ = 1.0f;
bool bVisible = false;
int nTag = 0, nZorder = -1;
@ -503,7 +506,7 @@ void SceneReader::setPropertyFromJsonDict(CocoLoader *cocoLoader, stExpCocoNode
for (int i = 0; i < cocoNode->GetChildNum(); ++i)
{
std::string key = stChildArray[i].GetName(cocoLoader);
std::string value = stChildArray[i].GetValue();
std::string value = stChildArray[i].GetValue(cocoLoader);
if (key == "x")
{

View File

@ -1,5 +1,5 @@
#include "CocoLoader.h"
#include "zlib.h"
using namespace std;
using namespace rapidjson;
@ -7,190 +7,222 @@ using namespace rapidjson;
namespace cocostudio{
char cTypeName[] = {'N','F','T','O','A','S','V'};
const char* kTypeNames[] = { "Null", "False", "True", "Object", "Array", "String", "Number" };
const char* kObjKeyName[] = { "__type" , "classname" };
char g_Buff[2048];
Type stExpCocoNode::GetType(CocoLoader* pCoco)
char* stExpCocoAttribDesc::GetName(CocoLoader* pCoco)
{
Type tType = kObjectType;
if(m_ObjIndex >= 0)
{
stExpCocoObjectDesc* tpCocoObjectDesc = pCoco->GetCocoObjectDescArray();
if( m_AttribIndex >= 0 )
{
stExpCocoAttribDesc* tpAttribDescArray = (stExpCocoAttribDesc*) tpCocoObjectDesc[m_ObjIndex].m_pAttribDescArray;
tType = tpAttribDescArray[m_AttribIndex].m_Type;
if(kFalseType == tType || kTrueType == tType)
{
char* szValue = (char*)m_szValue;
if(szValue[0] == '0')
{
return kFalseType;
}
else
{
return kTrueType;
}
}
return ( pCoco->GetMemoryAddr_String() + m_szName );
}
}
else
{
tType = kObjectType;
}
}
else
{
if(m_AttribIndex >= 0)
{
tType = (Type)m_ChildNum;
char* stExpCocoObjectDesc::GetName(CocoLoader* pCoco)
{
return ( pCoco->GetMemoryAddr_String() + m_szName );
}
if(kFalseType == tType || kTrueType == tType)
{
char* szValue = (char*)m_szValue;
if(szValue[0] == '0')
{
return kFalseType;
}
else
{
return kTrueType;
}
}
}
else
{
tType = kArrayType;
}
}
return tType;
int stExpCocoObjectDesc::GetAttribNum()
{
return m_cAttribNum;
}
stExpCocoAttribDesc* stExpCocoObjectDesc::GetAttribDescArray(CocoLoader* pCoco)
{
return (stExpCocoAttribDesc*)( pCoco->GetMemoryAddr_AttribDesc() + m_pAttribDescArray );
}
Type stExpCocoNode::GetType(CocoLoader* pCoco)
{
Type tType = kObjectType;
if(m_ObjIndex >= 0)
{
stExpCocoObjectDesc* tpCocoObjectDesc = pCoco->GetCocoObjectDescArray() ;
if( m_AttribIndex >= 0 )
{
stExpCocoAttribDesc* tpAttribDescArray = (stExpCocoAttribDesc*) tpCocoObjectDesc[m_ObjIndex].GetAttribDescArray(pCoco);
tType = Type(tpAttribDescArray[m_AttribIndex].m_cTypeName - 'N' + kNullType);
if(kFalseType == tType || kTrueType == tType)
{
char* szValue = (char*)GetValue(pCoco);
if(szValue[0] == '0')
{
return kFalseType;
}
else
{
return kTrueType;
}
}
}
else
{
tType = kObjectType;
}
}
else
{
if(m_AttribIndex >= 0)
{
tType = (Type)m_ChildNum;
if(kFalseType == tType || kTrueType == tType)
{
char* szValue = (char*)GetValue(pCoco);
if(szValue[0] == '0')
{
return kFalseType;
}
else
{
return kTrueType;
}
}
}
else
{
tType = kArrayType;
}
}
return tType;
}
char* stExpCocoNode::GetName(CocoLoader* pCoco)
{
char* szName = NULL ;
if(m_ObjIndex >= 0)
{
stExpCocoObjectDesc* tpCocoObjectDesc = pCoco->GetCocoObjectDescArray();
if( m_AttribIndex >= 0 )
{
stExpCocoAttribDesc* tpAttribDescArray = (stExpCocoAttribDesc*) tpCocoObjectDesc[m_ObjIndex].m_pAttribDescArray;
szName = (char*)tpAttribDescArray[m_AttribIndex].m_szName;
}
else
{
char* szValue = (char*)m_szValue;
if(szValue[0])
{
szName = (char*)m_szValue;
}
else
{
szName = (char*)tpCocoObjectDesc[m_ObjIndex].m_szName;
}
}
}
else
{
if(m_AttribIndex >= 0)
{
char* pStringAddr = (char*)pCoco->GetCocoObjectDescArray() + pCoco->GetFileHeader()->m_lStringMemAddr ;
szName = m_ChildArray + pStringAddr;
}
else
{
szName = (char*)m_szValue;
}
}
return szName ;
char* szName = NULL ;
if(m_ObjIndex >= 0)
{
stExpCocoObjectDesc* tpCocoObjectDesc = pCoco->GetCocoObjectDescArray();
if( m_AttribIndex >= 0 )
{
stExpCocoAttribDesc* tpAttribDescArray = (stExpCocoAttribDesc*) tpCocoObjectDesc[m_ObjIndex].GetAttribDescArray(pCoco);
szName = tpAttribDescArray[m_AttribIndex].GetName(pCoco);
}
else
{
char* szValue = GetValue(pCoco);
if(szValue[0])
{
szName = GetValue(pCoco);
}
else
{
szName = tpCocoObjectDesc[m_ObjIndex].GetName(pCoco);
}
}
}
else
{
if(m_AttribIndex >= 0)
{
char* pStringAddr = (char*)pCoco->GetCocoObjectDescArray() + pCoco->GetFileHeader()->m_lStringMemAddr ;
szName = m_ChildArray + pStringAddr;
}
else
{
szName = (char*)GetValue(pCoco);
}
}
return szName ;
}
char* stExpCocoNode::GetValue()
char* stExpCocoNode::GetValue(CocoLoader* pCoco)
{
return (char*)m_szValue;
return ( pCoco->GetMemoryAddr_String() + m_szValue );
}
int stExpCocoNode::GetChildNum()
{
return m_ChildNum;
return m_ChildNum;
}
stExpCocoNode* stExpCocoNode::GetChildArray()
stExpCocoNode* stExpCocoNode::GetChildArray(CocoLoader* pCoco)
{
return (stExpCocoNode*)m_ChildArray;
}
void stExpCocoNode::ReBuild(char* cocoNodeAddr,char* pStringMemoryAddr)
{
m_szValue = m_szValue + (uint64_t)pStringMemoryAddr;
if( -1 == m_AttribIndex )
{
if(m_ChildNum > 0)
{
m_ChildArray = m_ChildArray + (uint64_t)cocoNodeAddr;
stExpCocoNode* tpChildArray = (stExpCocoNode*)m_ChildArray;
for(int i = 0 ; i < m_ChildNum ; i++)
{
tpChildArray[i].ReBuild(cocoNodeAddr,pStringMemoryAddr);
}
}
}
return (stExpCocoNode*)( pCoco->GetMemoryAddr_CocoNode() + m_ChildArray );
}
CocoLoader::CocoLoader()
{
m_pRootNode = NULL;
m_pObjectDescArray = NULL;
m_pRootNode = NULL;
m_pObjectDescArray = NULL;
m_pMemoryBuff = NULL;
}
CocoLoader::~CocoLoader()
{
if(m_pMemoryBuff)
{
delete[] m_pMemoryBuff;
m_pMemoryBuff = NULL;
}
}
bool CocoLoader::ReadCocoBinBuff(char* pBinBuff)
bool CocoLoader::ReadCocoBinBuff(char* pBinBuff)
{
if(m_pMemoryBuff)return true;
char* pTempBuff = pBinBuff;
m_pFileHeader = (stCocoFileHeader*)pTempBuff;
pTempBuff += sizeof(stCocoFileHeader);
char* pStartAddr = pTempBuff;
m_pObjectDescArray = (stExpCocoObjectDesc*)pStartAddr;
char* pAttrAddr = pStartAddr + m_pFileHeader->m_lAttribMemAddr ;
char* pCocoMemAddr = pStartAddr + m_pFileHeader->m_CocoNodeMemAddr;
char* pStringAddr = pStartAddr + m_pFileHeader->m_lStringMemAddr ;
m_pRootNode = (stExpCocoNode*)pCocoMemAddr;
if(1 == m_pFileHeader->m_nFirstUsed)
{
for(int i = 0 ; i < m_pFileHeader->m_ObjectCount ; i++)
{
m_pObjectDescArray[i].ReBuild(pAttrAddr,pStringAddr) ;
}
m_pRootNode->ReBuild(pCocoMemAddr,pStringAddr);
m_pFileHeader->m_nFirstUsed = 0;
char* pStartAddr = m_pMemoryBuff = pTempBuff;
if( m_pFileHeader->m_nCompressSize > 0 )
{
char* pDestBuff = new char[m_pFileHeader->m_nDataSize];
uLongf dwSrcSize = m_pFileHeader->m_nCompressSize;
uLongf dwDestSize = m_pFileHeader->m_nDataSize;
int nRes = uncompress((Bytef*)pDestBuff,&dwDestSize,(Bytef*)m_pMemoryBuff,dwSrcSize);
pStartAddr = m_pMemoryBuff = pDestBuff;
}
m_pObjectDescArray = (stExpCocoObjectDesc*)pStartAddr;
char* pCocoMemAddr = pStartAddr + m_pFileHeader->m_CocoNodeMemAddr;
m_pRootNode = (stExpCocoNode*)pCocoMemAddr;
return true;
}
stExpCocoObjectDesc* CocoLoader::GetCocoObjectDesc(const char* szObjDesc)
{
for(int i = 0 ; i < m_pFileHeader->m_ObjectCount ; i++)
{
if(0 == strcmp((char*)m_pObjectDescArray[i].m_szName,szObjDesc))
{
return &m_pObjectDescArray[i];
}
}
return NULL;
for(int i = 0 ; i < m_pFileHeader->m_ObjectCount ; i++)
{
if(0 == strcmp((char*)m_pObjectDescArray[i].m_szName,szObjDesc))
{
return &m_pObjectDescArray[i];
}
}
return NULL;
}
stExpCocoObjectDesc* CocoLoader::GetCocoObjectDesc(int vIndex)
{
if(vIndex >= 0 && vIndex < m_pFileHeader->m_ObjectCount)
{
return &m_pObjectDescArray[vIndex];
}
return NULL;
}
char* CocoLoader::GetMemoryAddr_AttribDesc()
{
return m_pMemoryBuff + m_pFileHeader->m_lAttribMemAddr ;
}
char* CocoLoader::GetMemoryAddr_CocoNode()
{
return m_pMemoryBuff + m_pFileHeader->m_CocoNodeMemAddr;
}
char* CocoLoader::GetMemoryAddr_String()
{
return m_pMemoryBuff + m_pFileHeader->m_lStringMemAddr ;
}
}

View File

@ -36,101 +36,80 @@
namespace cocostudio{
class CocoLoader;
struct stExpCocoAttribDesc
{
rapidjson::Type m_Type;
uint64_t m_szName;
uint64_t m_szDefaultValue;
char m_cTypeName;
uint32_t m_szName;
public:
void ReBuild(char* pStringMemoryAddr)
{
m_szName = m_szName + (uint64_t)pStringMemoryAddr;
m_szDefaultValue = m_szDefaultValue + (uint64_t)pStringMemoryAddr;
}
char* GetName(CocoLoader* pCoco);
};
struct stExpCocoObjectDesc
{
uint32_t m_nAttribNum;
uint64_t m_szName;
uint64_t m_pAttribDescArray;
unsigned char m_cAttribNum;
uint32_t m_szName;
uint32_t m_pAttribDescArray;
public:
stExpCocoObjectDesc()
{
m_nAttribNum = 0;
m_szName = 0;
m_pAttribDescArray = 0;
}
void ReBuild(char* pAttribMemoryAddr,char* pStringMemoryAddr)
{
m_szName = m_szName + (uint64_t)pStringMemoryAddr;
m_pAttribDescArray = m_pAttribDescArray + (uint64_t)pAttribMemoryAddr;
stExpCocoAttribDesc* tpAttribDescArray = (stExpCocoAttribDesc*)m_pAttribDescArray;
for(uint32_t i = 0 ; i < m_nAttribNum ; i++)
{
tpAttribDescArray[i].ReBuild(pStringMemoryAddr);
}
}
char* GetName(CocoLoader* pCoco);
int GetAttribNum();
stExpCocoAttribDesc* GetAttribDescArray(CocoLoader* pCoco);
};
class CocoLoader;
struct stExpCocoNode
struct stExpCocoNode
{
protected:
int32_t m_ObjIndex;
int32_t m_AttribIndex;
uint32_t m_ChildNum;
uint64_t m_szValue;
uint64_t m_ChildArray;
public:
rapidjson::Type GetType(CocoLoader* pCoco);
char* GetName(CocoLoader* pCoco);
char* GetValue();
int GetChildNum();
stExpCocoNode* GetChildArray();
int16_t m_ObjIndex;
int16_t m_AttribIndex;
unsigned char m_ChildNum;
uint32_t m_szValue;
uint32_t m_ChildArray;
public:
inline void ReBuild(char* cocoNodeAddr,char* pStringMemoryAddr);
void WriteJson(CocoLoader* pCoco, void* pFileName = NULL, int vLayer = 0, bool bEndNode = false, bool bParentNodeIsArray = false);
rapidjson::Type GetType(CocoLoader* pCoco);
char* GetName(CocoLoader* pCoco);
char* GetValue(CocoLoader* pCoco);
int GetChildNum();
stExpCocoNode* GetChildArray(CocoLoader* pCoco);
public:
void WriteJson(CocoLoader* pCoco,void* pFileName = nullptr, int vLayer = 0, bool bEndNode = false, bool bParentNodeIsArray = false);
};
struct stCocoFileHeader
{
char m_FileDesc[32];
char m_Version[32];
uint32_t m_nFirstUsed;
uint32_t m_ObjectCount;
uint64_t m_lAttribMemAddr;
uint64_t m_CocoNodeMemAddr;
uint64_t m_lStringMemAddr;
char m_FileDesc[32];
char m_Version[32];
uint32_t m_nDataSize;
uint32_t m_nCompressSize;
uint32_t m_ObjectCount;
uint32_t m_lAttribMemAddr;
uint32_t m_CocoNodeMemAddr;
uint32_t m_lStringMemAddr;
};
class CocoLoader
{
private:
stCocoFileHeader* m_pFileHeader;
stExpCocoNode* m_pRootNode;
stExpCocoObjectDesc* m_pObjectDescArray;
stCocoFileHeader* m_pFileHeader;
stExpCocoNode* m_pRootNode;
stExpCocoObjectDesc* m_pObjectDescArray;
char* m_pMemoryBuff;
public:
CocoLoader();
~CocoLoader();
CocoLoader();
~CocoLoader();
public:
bool ReadCocoBinBuff(char* pBinBuff);
stCocoFileHeader* GetFileHeader(){return m_pFileHeader;}
stExpCocoNode* GetRootCocoNode(){return m_pRootNode;}
stExpCocoObjectDesc* GetCocoObjectDescArray(){return m_pObjectDescArray;}
stExpCocoObjectDesc* GetCocoObjectDesc(const char* szObjDesc);
bool ReadCocoBinBuff(char* pBinBuff);
stCocoFileHeader* GetFileHeader(){return m_pFileHeader;}
stExpCocoNode* GetRootCocoNode(){return m_pRootNode;}
stExpCocoObjectDesc* GetCocoObjectDescArray(){return m_pObjectDescArray;}
stExpCocoObjectDesc* GetCocoObjectDesc(const char* szObjDesc);
stExpCocoObjectDesc* GetCocoObjectDesc(int vIndex);
char* GetMemoryAddr_AttribDesc();
char* GetMemoryAddr_CocoNode();
char* GetMemoryAddr_String();
};
}

View File

@ -111,7 +111,7 @@ void TriggerMng::parse(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCoc
CCLOG("%s", triggerMngVersion());
int count = pCocoNode[13].GetChildNum();
stExpCocoNode *pTriggersArray = pCocoNode[13].GetChildArray();
stExpCocoNode *pTriggersArray = pCocoNode[13].GetChildArray(pCocoLoader);
#if CC_ENABLE_SCRIPT_BINDING
ScriptEngineProtocol* engine = ScriptEngineManager::getInstance()->getScriptEngine();
@ -200,7 +200,7 @@ bool TriggerMng::isEmpty(void) const
int extent = 0;
int border = 0;
std::string key0;
stExpCocoNode *pTriggersArray = pCocoNode[13].GetChildArray();
stExpCocoNode *pTriggersArray = pCocoNode[13].GetChildArray(pCocoLoader);
document.SetArray();
@ -210,28 +210,28 @@ bool TriggerMng::isEmpty(void) const
rapidjson::Value vElemItem(rapidjson::kObjectType);
border = pTriggersArray[i0].GetChildNum();
stExpCocoNode *pTriggerArray = pTriggersArray[i0].GetChildArray();
stExpCocoNode *pTriggerArray = pTriggersArray[i0].GetChildArray(pCocoLoader);
for (int i1 = 0; i1 < border; ++i1)
{
std::string key1 = pTriggerArray[i1].GetName(pCocoLoader);
const char *str1 = pTriggerArray[i1].GetValue();
const char *str1 = pTriggerArray[i1].GetValue(pCocoLoader);
if (key1.compare("actions") == 0)
{
rapidjson::Value actionsItem(rapidjson::kArrayType);
length = pTriggerArray[i1].GetChildNum();
stExpCocoNode *pActionsArray = pTriggerArray[i1].GetChildArray();
stExpCocoNode *pActionsArray = pTriggerArray[i1].GetChildArray(pCocoLoader);
for (int i2 = 0; i2 < length; ++i2)
{
rapidjson::Value action(rapidjson::kObjectType);
num = pActionsArray[i2].GetChildNum();
stExpCocoNode *pActionArray = pActionsArray[i2].GetChildArray();
stExpCocoNode *pActionArray = pActionsArray[i2].GetChildArray(pCocoLoader);
for (int i3 = 0; i3 < num; ++i3)
{
std::string key2 = pActionArray[i3].GetName(pCocoLoader);
const char *str2 = pActionArray[i3].GetValue();
const char *str2 = pActionArray[i3].GetValue(pCocoLoader);
if (key2.compare("classname") == 0)
{
if (str2 != NULL)
@ -243,16 +243,16 @@ bool TriggerMng::isEmpty(void) const
{
rapidjson::Value dataitems(rapidjson::kArrayType);
size = pActionArray[i3].GetChildNum();
stExpCocoNode *pDataItemsArray = pActionArray[i3].GetChildArray();
stExpCocoNode *pDataItemsArray = pActionArray[i3].GetChildArray(pCocoLoader);
for (int i4 = 0; i4 < size; ++i4)
{
rapidjson::Value dataitem(rapidjson::kObjectType);
extent = pDataItemsArray[i4].GetChildNum();
stExpCocoNode *pDataItemArray = pDataItemsArray[i4].GetChildArray();
stExpCocoNode *pDataItemArray = pDataItemsArray[i4].GetChildArray(pCocoLoader);
for (int i5 = 0; i5 < extent; ++i5)
{
std::string key3 = pDataItemArray[i5].GetName(pCocoLoader);
const char *str3 = pDataItemArray[i5].GetValue();
const char *str3 = pDataItemArray[i5].GetValue(pCocoLoader);
if (key3.compare("key") == 0)
{
if (str3 != NULL)
@ -297,17 +297,17 @@ bool TriggerMng::isEmpty(void) const
rapidjson::Value condsItem(rapidjson::kArrayType);
length = pTriggerArray[i1].GetChildNum();
stExpCocoNode *pConditionsArray = pTriggerArray[i1].GetChildArray();
stExpCocoNode *pConditionsArray = pTriggerArray[i1].GetChildArray(pCocoLoader);
for (int i6 = 0; i6 < length; ++i6)
{
rapidjson::Value cond(rapidjson::kObjectType);
num = pConditionsArray[i6].GetChildNum();
stExpCocoNode *pConditionArray = pConditionsArray[i6].GetChildArray();
stExpCocoNode *pConditionArray = pConditionsArray[i6].GetChildArray(pCocoLoader);
for (int i7 = 0; i7 < num; ++i7)
{
std::string key4 = pConditionArray[i7].GetName(pCocoLoader);
const char *str4 = pConditionArray[i7].GetValue();
const char *str4 = pConditionArray[i7].GetValue(pCocoLoader);
if (key4.compare("classname") == 0)
{
if (str4 != NULL)
@ -319,16 +319,16 @@ bool TriggerMng::isEmpty(void) const
{
rapidjson::Value dataitems(rapidjson::kArrayType);
size = pConditionArray[i7].GetChildNum();
stExpCocoNode *pDataItemsArray = pConditionArray[i7].GetChildArray();
stExpCocoNode *pDataItemsArray = pConditionArray[i7].GetChildArray(pCocoLoader);
for (int i8 = 0; i8 < size; ++i8)
{
rapidjson::Value dataitem(rapidjson::kObjectType);
extent = pDataItemsArray[i8].GetChildNum();
stExpCocoNode *pDataItemArray = pDataItemsArray[i8].GetChildArray();
stExpCocoNode *pDataItemArray = pDataItemsArray[i8].GetChildArray(pCocoLoader);
for (int i9 = 0; i9 < extent; ++i9)
{
std::string key5 = pDataItemArray[i9].GetName(pCocoLoader);
const char *str5 = pDataItemArray[i9].GetValue();
const char *str5 = pDataItemArray[i9].GetValue(pCocoLoader);
if (key5.compare("key") == 0)
{
if (str5 != NULL)
@ -373,13 +373,13 @@ bool TriggerMng::isEmpty(void) const
rapidjson::Value eventsItem(rapidjson::kArrayType);
length = pTriggerArray[i1].GetChildNum();
stExpCocoNode *pEventsArray = pTriggerArray[i1].GetChildArray();
stExpCocoNode *pEventsArray = pTriggerArray[i1].GetChildArray(pCocoLoader);
for (int i10 = 0; i10 < length; ++i10)
{
rapidjson::Value event(rapidjson::kObjectType);
stExpCocoNode *pEventArray = pEventsArray->GetChildArray();
stExpCocoNode *pEventArray = pEventsArray->GetChildArray(pCocoLoader);
std::string key6 = pEventArray[0].GetName(pCocoLoader);
const char *str6 = pEventArray[0].GetValue();
const char *str6 = pEventArray[0].GetValue(pCocoLoader);
if (key6.compare("id") == 0 && str6 != NULL)
{
event.AddMember("id", atoi(str6), allocator);

View File

@ -246,11 +246,11 @@ void TriggerObj::serialize(const rapidjson::Value &val)
int length = pCocoNode->GetChildNum();
int count = 0;
int num = 0;
stExpCocoNode *pTriggerObjArray = pCocoNode->GetChildArray();
stExpCocoNode *pTriggerObjArray = pCocoNode->GetChildArray(pCocoLoader);
for (int i0 = 0; i0 < length; ++i0)
{
std::string key = pTriggerObjArray[i0].GetName(pCocoLoader);
const char* str0 = pTriggerObjArray[i0].GetValue();
const char* str0 = pTriggerObjArray[i0].GetValue(pCocoLoader);
if (key.compare("id") == 0)
{
if (str0 != NULL)
@ -261,12 +261,12 @@ void TriggerObj::serialize(const rapidjson::Value &val)
else if (key.compare("conditions") == 0)
{
count = pTriggerObjArray[i0].GetChildNum();
stExpCocoNode *pConditionsArray = pTriggerObjArray[i0].GetChildArray();
stExpCocoNode *pConditionsArray = pTriggerObjArray[i0].GetChildArray(pCocoLoader);
for (int i1 = 0; i1 < count; ++i1)
{
num = pConditionsArray[i1].GetChildNum();
stExpCocoNode *pConditionArray = pConditionsArray[i1].GetChildArray();
const char *classname = pConditionArray[0].GetValue();
stExpCocoNode *pConditionArray = pConditionsArray[i1].GetChildArray(pCocoLoader);
const char *classname = pConditionArray[0].GetValue(pCocoLoader);
if (classname == nullptr)
{
continue;
@ -281,12 +281,12 @@ void TriggerObj::serialize(const rapidjson::Value &val)
else if (key.compare("actions") == 0)
{
count = pTriggerObjArray[i0].GetChildNum();
stExpCocoNode *pActionsArray = pTriggerObjArray[i0].GetChildArray();
stExpCocoNode *pActionsArray = pTriggerObjArray[i0].GetChildArray(pCocoLoader);
for (int i2 = 0; i2 < count; ++i2)
{
num = pActionsArray[i2].GetChildNum();
stExpCocoNode *pActionArray = pActionsArray[i2].GetChildArray();
const char *classname = pActionArray[0].GetValue();
stExpCocoNode *pActionArray = pActionsArray[i2].GetChildArray(pCocoLoader);
const char *classname = pActionArray[0].GetValue(pCocoLoader);
if (classname == nullptr)
{
continue;
@ -301,12 +301,12 @@ void TriggerObj::serialize(const rapidjson::Value &val)
else if (key.compare("events") == 0)
{
count = pTriggerObjArray[i0].GetChildNum();
stExpCocoNode *pEventsArray = pTriggerObjArray[i0].GetChildArray();
stExpCocoNode *pEventsArray = pTriggerObjArray[i0].GetChildArray(pCocoLoader);
for (int i3 = 0; i3 < count; ++i3)
{
num = pEventsArray[i3].GetChildNum();
stExpCocoNode *pEventArray = pEventsArray[i3].GetChildArray();
const char *str1 = pEventArray[0].GetValue();
stExpCocoNode *pEventArray = pEventsArray[i3].GetChildArray(pCocoLoader);
const char *str1 = pEventArray[0].GetValue(pCocoLoader);
if (str1 == nullptr)
{
continue;

View File

@ -63,7 +63,7 @@ namespace cocostudio
Button *button = static_cast<Button*>(widget);
stExpCocoNode *stChildArray = cocoNode->GetChildArray();
stExpCocoNode *stChildArray = cocoNode->GetChildArray(cocoLoader);
this->beginSetBasicProperties(widget);
@ -72,7 +72,7 @@ namespace cocostudio
float scale9Width = 0.0f, scale9Height = 0.0f;
for (int i = 0; i < cocoNode->GetChildNum(); ++i) {
std::string key = stChildArray[i].GetName(cocoLoader);
std::string value = stChildArray[i].GetValue();
std::string value = stChildArray[i].GetValue(cocoLoader);
// CCLOG("Button: key = %s, value = %d", key.c_str(), i);
//read all basic properties of widget
@ -86,8 +86,8 @@ namespace cocostudio
}
else if (key == P_NormalData){
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray();
std::string resType = backGroundChildren[2].GetValue();;
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray(cocoLoader);
std::string resType = backGroundChildren[2].GetValue(cocoLoader);;
Widget::TextureResType imageFileNameType = (Widget::TextureResType)valueToInt(resType);
@ -98,8 +98,8 @@ namespace cocostudio
}
else if (key == P_PressedData){
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray();
std::string resType = backGroundChildren[2].GetValue();;
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray(cocoLoader);
std::string resType = backGroundChildren[2].GetValue(cocoLoader);;
Widget::TextureResType imageFileNameType = (Widget::TextureResType)valueToInt(resType);
@ -110,8 +110,8 @@ namespace cocostudio
}
else if (key == P_DisabledData){
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray();
std::string resType = backGroundChildren[2].GetValue();;
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray(cocoLoader);
std::string resType = backGroundChildren[2].GetValue(cocoLoader);;
Widget::TextureResType imageFileNameType = (Widget::TextureResType)valueToInt(resType);
@ -216,23 +216,18 @@ namespace cocostudio
}
}
bool cr = DICTOOL->checkObjectExist_json(options, P_TextColorR);
bool cg = DICTOOL->checkObjectExist_json(options, P_TextColorG);
bool cb = DICTOOL->checkObjectExist_json(options, P_TextColorB);
int cri = cr?DICTOOL->getIntValue_json(options, P_TextColorR):255;
int cgi = cg?DICTOOL->getIntValue_json(options, P_TextColorG):255;
int cbi = cb?DICTOOL->getIntValue_json(options, P_TextColorB):255;
int cri = DICTOOL->getIntValue_json(options, P_TextColorR,255);
int cgi = DICTOOL->getIntValue_json(options, P_TextColorG,255);
int cbi = DICTOOL->getIntValue_json(options, P_TextColorB,255);
button->setTitleColor(Color3B(cri,cgi,cbi));
bool fs = DICTOOL->checkObjectExist_json(options, P_FontSize);
if (fs)
{
button->setTitleFontSize(DICTOOL->getIntValue_json(options, P_FontSize));
}
bool fn = DICTOOL->checkObjectExist_json(options, P_FontName);
if (fn)
{
button->setTitleFontName(DICTOOL->getStringValue_json(options, P_FontName));
}
button->setTitleFontSize(DICTOOL->getIntValue_json(options, P_FontSize,14));
button->setTitleFontName(DICTOOL->getStringValue_json(options, P_FontName,"微软雅黑"));
WidgetReader::setColorPropsFromJsonDictionary(widget, options);

View File

@ -43,11 +43,11 @@ namespace cocostudio
CheckBox *checkBox = static_cast<CheckBox*>(widget);
this->beginSetBasicProperties(widget);
stExpCocoNode *stChildArray = cocoNode->GetChildArray();
stExpCocoNode *stChildArray = cocoNode->GetChildArray(cocoLoader);
for (int i = 0; i < cocoNode->GetChildNum(); ++i) {
std::string key = stChildArray[i].GetName(cocoLoader);
std::string value = stChildArray[i].GetValue();
std::string value = stChildArray[i].GetValue(cocoLoader);
// CCLOG("key = %s, index : %d", key.c_str(), i);
//read all basic properties of widget
CC_BASIC_PROPERTY_BINARY_READER
@ -56,8 +56,8 @@ namespace cocostudio
else if (key == P_BackGroundBoxData){
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray();
std::string resType = backGroundChildren[2].GetValue();;
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray(cocoLoader);
std::string resType = backGroundChildren[2].GetValue(cocoLoader);;
Widget::TextureResType imageFileNameType = (Widget::TextureResType)valueToInt(resType);
@ -65,8 +65,8 @@ namespace cocostudio
checkBox->loadTextureBackGround(backgroundValue, imageFileNameType);
}else if(key == P_BackGroundBoxSelectedData){
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray();
std::string resType = backGroundChildren[2].GetValue();;
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray(cocoLoader);
std::string resType = backGroundChildren[2].GetValue(cocoLoader);;
Widget::TextureResType imageFileNameType = (Widget::TextureResType)valueToInt(resType);
@ -74,8 +74,8 @@ namespace cocostudio
checkBox->loadTextureBackGroundSelected(backgroundValue, imageFileNameType);
}else if(key == P_FrontCrossData){
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray();
std::string resType = backGroundChildren[2].GetValue();;
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray(cocoLoader);
std::string resType = backGroundChildren[2].GetValue(cocoLoader);;
Widget::TextureResType imageFileNameType = (Widget::TextureResType)valueToInt(resType);
@ -83,8 +83,8 @@ namespace cocostudio
checkBox->loadTextureFrontCross(backgroundValue, imageFileNameType);
}else if(key == P_BackGroundBoxDisabledData){
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray();
std::string resType = backGroundChildren[2].GetValue();;
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray(cocoLoader);
std::string resType = backGroundChildren[2].GetValue(cocoLoader);;
Widget::TextureResType imageFileNameType = (Widget::TextureResType)valueToInt(resType);
@ -92,8 +92,8 @@ namespace cocostudio
checkBox->loadTextureBackGroundDisabled(backgroundValue, imageFileNameType);
}else if (key == P_FrontCrossDisabledData){
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray();
std::string resType = backGroundChildren[2].GetValue();;
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray(cocoLoader);
std::string resType = backGroundChildren[2].GetValue(cocoLoader);;
Widget::TextureResType imageFileNameType = (Widget::TextureResType)valueToInt(resType);

View File

@ -50,11 +50,11 @@ namespace cocostudio
this->beginSetBasicProperties(widget);
float capsx = 0.0f, capsy = 0.0, capsWidth = 0.0, capsHeight = 0.0f;
stExpCocoNode *stChildArray = cocoNode->GetChildArray();
stExpCocoNode *stChildArray = cocoNode->GetChildArray(cocoLoader);
for (int i = 0; i < cocoNode->GetChildNum(); ++i) {
std::string key = stChildArray[i].GetName(cocoLoader);
std::string value = stChildArray[i].GetValue();
std::string value = stChildArray[i].GetValue(cocoLoader);
//read all basic properties of widget
CC_BASIC_PROPERTY_BINARY_READER
@ -65,8 +65,8 @@ namespace cocostudio
imageView->setScale9Enabled(valueToBool(value));
}
else if (key == P_FileNameData){
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray();
std::string resType = backGroundChildren[2].GetValue();;
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray(cocoLoader);
std::string resType = backGroundChildren[2].GetValue(cocoLoader);;
Widget::TextureResType imageFileNameType = (Widget::TextureResType)valueToInt(resType);
@ -125,19 +125,16 @@ namespace cocostudio
if (scale9Enable)
{
bool sw = DICTOOL->checkObjectExist_json(options, P_Scale9Width);
bool sh = DICTOOL->checkObjectExist_json(options, P_Scale9Height);
if (sw && sh)
{
float swf = DICTOOL->getFloatValue_json(options, P_Scale9Width);
float shf = DICTOOL->getFloatValue_json(options, P_Scale9Height);
imageView->setSize(Size(swf, shf));
}
float swf = DICTOOL->getFloatValue_json(options, P_Scale9Width,80.0f);
float shf = DICTOOL->getFloatValue_json(options, P_Scale9Height,80.0f);
imageView->setSize(Size(swf, shf));
float cx = DICTOOL->getFloatValue_json(options, P_CapInsetsX);
float cy = DICTOOL->getFloatValue_json(options, P_CapInsetsY);
float cw = DICTOOL->getFloatValue_json(options, P_CapInsetsWidth);
float ch = DICTOOL->getFloatValue_json(options, P_CapInsetsHeight);
float cw = DICTOOL->getFloatValue_json(options, P_CapInsetsWidth,1.0f);
float ch = DICTOOL->getFloatValue_json(options, P_CapInsetsHeight,1.0f);
imageView->setCapInsets(Rect(cx, cy, cw, ch));

View File

@ -3,6 +3,9 @@
#include "LayoutReader.h"
#include "ui/UILayout.h"
#include "cocostudio/CocoLoader.h"
#include "ui/UIScrollView.h"
#include "ui/UIPageView.h"
#include "ui/UIListView.h"
USING_NS_CC;
using namespace ui;
@ -61,7 +64,7 @@ namespace cocostudio
Layout* panel = static_cast<Layout*>(widget);
stExpCocoNode *stChildArray = cocoNode->GetChildArray();
stExpCocoNode *stChildArray = cocoNode->GetChildArray(cocoLoader);
this->beginSetBasicProperties(widget);
int cr=0, cg = 0, cb = 0;
@ -69,12 +72,12 @@ namespace cocostudio
int ecr=0, ecg=0, ecb= 0;
float bgcv1 = 0.0f, bgcv2= 0.0f;
float capsx = 0.0f, capsy = 0.0, capsWidth = 0.0, capsHeight = 0.0f;
Layout::Type layoutType;
Layout::Type layoutType = Layout::Type::ABSOLUTE;
int bgColorOpacity = panel->getBackGroundColorOpacity();
for (int i = 0; i < cocoNode->GetChildNum(); ++i) {
std::string key = stChildArray[i].GetName(cocoLoader);
std::string value = stChildArray[i].GetValue();
std::string value = stChildArray[i].GetValue(cocoLoader);
//read all basic properties of widget
CC_BASIC_PROPERTY_BINARY_READER
@ -120,9 +123,9 @@ namespace cocostudio
panel->setBackGroundColorType(Layout::BackGroundColorType(valueToInt(value)));
}else if (key == P_BackGroundImageData){
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray();
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray(cocoLoader);
if (backGroundChildren) {
std::string resType = backGroundChildren[2].GetValue();;
std::string resType = backGroundChildren[2].GetValue(cocoLoader);;
Widget::TextureResType imageFileNameType = (Widget::TextureResType)valueToInt(resType);
@ -194,26 +197,77 @@ namespace cocostudio
bool backGroundScale9Enable = DICTOOL->getBooleanValue_json(options, P_BackGroundScale9Enable);
panel->setBackGroundImageScale9Enabled(backGroundScale9Enable);
int cr = DICTOOL->getIntValue_json(options, P_BgColorR);
int cg = DICTOOL->getIntValue_json(options, P_BgColorG);
int cb = DICTOOL->getIntValue_json(options, P_BgColorB);
int scr = DICTOOL->getIntValue_json(options, P_BgStartColorR);
int scg = DICTOOL->getIntValue_json(options, P_BgStartColorG);
int scb = DICTOOL->getIntValue_json(options, P_BgStartColorB);
int ecr = DICTOOL->getIntValue_json(options, P_BgEndColorR);
int ecg = DICTOOL->getIntValue_json(options, P_BgEndColorG);
int ecb = DICTOOL->getIntValue_json(options, P_BgEndColorB);
int cr;
int cg;
int cb;
int scr;
int scg;
int scb;
int ecr;
int ecg;
int ecb;
if (dynamic_cast<ui::PageView*>(widget)) {
cr = DICTOOL->getIntValue_json(options, "bgColorR",150);
cg = DICTOOL->getIntValue_json(options, "bgColorG",150);
cb = DICTOOL->getIntValue_json(options, "bgColorB",100);
scr = DICTOOL->getIntValue_json(options, "bgStartColorR",255);
scg = DICTOOL->getIntValue_json(options, "bgStartColorG",255);
scb = DICTOOL->getIntValue_json(options, "bgStartColorB",255);
ecr = DICTOOL->getIntValue_json(options, "bgEndColorR",255);
ecg = DICTOOL->getIntValue_json(options, "bgEndColorG",150);
ecb = DICTOOL->getIntValue_json(options, "bgEndColorB",100);
}else if(dynamic_cast<ui::ListView*>(widget)){
cr = DICTOOL->getIntValue_json(options, "bgColorR",150);
cg = DICTOOL->getIntValue_json(options, "bgColorG",150);
cb = DICTOOL->getIntValue_json(options, "bgColorB",255);
scr = DICTOOL->getIntValue_json(options, "bgStartColorR",255);
scg = DICTOOL->getIntValue_json(options, "bgStartColorG",255);
scb = DICTOOL->getIntValue_json(options, "bgStartColorB",255);
ecr = DICTOOL->getIntValue_json(options, "bgEndColorR",150);
ecg = DICTOOL->getIntValue_json(options, "bgEndColorG",150);
ecb = DICTOOL->getIntValue_json(options, "bgEndColorB",255);
}else if(dynamic_cast<ui::ScrollView*>(widget)){
cr = DICTOOL->getIntValue_json(options, "bgColorR",255);
cg = DICTOOL->getIntValue_json(options, "bgColorG",150);
cb = DICTOOL->getIntValue_json(options, "bgColorB",100);
scr = DICTOOL->getIntValue_json(options, "bgStartColorR",255);
scg = DICTOOL->getIntValue_json(options, "bgStartColorG",255);
scb = DICTOOL->getIntValue_json(options, "bgStartColorB",255);
ecr = DICTOOL->getIntValue_json(options, "bgEndColorR",255);
ecg = DICTOOL->getIntValue_json(options, "bgEndColorG",150);
ecb = DICTOOL->getIntValue_json(options, "bgEndColorB",100);
}else{
cr = DICTOOL->getIntValue_json(options, "bgColorR",150);
cg = DICTOOL->getIntValue_json(options, "bgColorG",200);
cb = DICTOOL->getIntValue_json(options, "bgColorB",255);
scr = DICTOOL->getIntValue_json(options, "bgStartColorR",255);
scg = DICTOOL->getIntValue_json(options, "bgStartColorG",255);
scb = DICTOOL->getIntValue_json(options, "bgStartColorB",255);
ecr = DICTOOL->getIntValue_json(options, "bgEndColorR",150);
ecg = DICTOOL->getIntValue_json(options, "bgEndColorG",200);
ecb = DICTOOL->getIntValue_json(options, "bgEndColorB",255);
}
float bgcv1 = DICTOOL->getFloatValue_json(options, P_VectorX);
float bgcv2 = DICTOOL->getFloatValue_json(options, P_VectorY);
float bgcv2 = DICTOOL->getFloatValue_json(options, P_VectorY,-0.5);
panel->setBackGroundColorVector(Vec2(bgcv1, bgcv2));
int co = DICTOOL->getIntValue_json(options, P_BgColorOpacity);
int co = DICTOOL->getIntValue_json(options, P_BgColorOpacity,100);
int colorType = DICTOOL->getIntValue_json(options, P_ColorType);
int colorType = DICTOOL->getIntValue_json(options, P_ColorType,1);
panel->setBackGroundColorType(Layout::BackGroundColorType(colorType));
panel->setBackGroundColor(Color3B(scr, scg, scb),Color3B(ecr, ecg, ecb));
panel->setBackGroundColor(Color3B(cr, cg, cb));
panel->setBackGroundColorOpacity(co);
@ -229,18 +283,21 @@ namespace cocostudio
{
float cx = DICTOOL->getFloatValue_json(options, P_CapInsetsX);
float cy = DICTOOL->getFloatValue_json(options, P_CapInsetsY);
float cw = DICTOOL->getFloatValue_json(options, P_CapInsetsWidth);
float ch = DICTOOL->getFloatValue_json(options, P_CapInsetsHeight);
float cw = DICTOOL->getFloatValue_json(options, P_CapInsetsWidth,1);
float ch = DICTOOL->getFloatValue_json(options, P_CapInsetsHeight,1);
panel->setBackGroundImageCapInsets(Rect(cx, cy, cw, ch));
}
panel->setLayoutType((Layout::Type)DICTOOL->getIntValue_json(options, P_LayoutType));
int bgimgcr = DICTOOL->getIntValue_json(options, P_ColorR);
int bgimgcg = DICTOOL->getIntValue_json(options, P_ColorG);
int bgimgcb = DICTOOL->getIntValue_json(options, P_ColorB);
int bgimgcr = DICTOOL->getIntValue_json(options, P_ColorR,255);
int bgimgcg = DICTOOL->getIntValue_json(options, P_ColorG,255);
int bgimgcb = DICTOOL->getIntValue_json(options, P_ColorB,255);
panel->setBackGroundImageColor(Color3B(bgimgcr, bgimgcg, bgimgcb));
int bgimgopacity = DICTOOL->getIntValue_json(options, "opacity",255);
panel->setBackGroundImageOpacity(bgimgopacity);
WidgetReader::setColorPropsFromJsonDictionary(widget, options);
}

View File

@ -41,11 +41,11 @@ namespace cocostudio
ListView* listView = static_cast<ListView*>(widget);
stExpCocoNode *stChildArray = cocoNode->GetChildArray();
stExpCocoNode *stChildArray = cocoNode->GetChildArray(cocoLoader);
for (int i = 0; i < cocoNode->GetChildNum(); ++i) {
std::string key = stChildArray[i].GetName(cocoLoader);
std::string value = stChildArray[i].GetValue();
std::string value = stChildArray[i].GetValue(cocoLoader);
if (key == P_Direction) {
listView->setDirection((ScrollView::Direction)valueToInt(value));
@ -66,10 +66,10 @@ namespace cocostudio
ListView* listView = static_cast<ListView*>(widget);
int direction = DICTOOL->getFloatValue_json(options, P_Direction);
int direction = DICTOOL->getFloatValue_json(options, P_Direction,2);
listView->setDirection((ScrollView::Direction)direction);
ListView::Gravity gravity = (ListView::Gravity)DICTOOL->getIntValue_json(options, P_Gravity);
ListView::Gravity gravity = (ListView::Gravity)DICTOOL->getIntValue_json(options, P_Gravity,3);
listView->setGravity(gravity);
float itemMargin = DICTOOL->getFloatValue_json(options, P_ItemMargin);

View File

@ -51,11 +51,11 @@ namespace cocostudio
float capsx = 0.0f, capsy = 0.0, capsWidth = 0.0, capsHeight = 0.0f;
int percent = loadingBar->getPercent();
stExpCocoNode *stChildArray = cocoNode->GetChildArray();
stExpCocoNode *stChildArray = cocoNode->GetChildArray(cocoLoader);
for (int i = 0; i < cocoNode->GetChildNum(); ++i) {
std::string key = stChildArray[i].GetName(cocoLoader);
std::string value = stChildArray[i].GetValue();
std::string value = stChildArray[i].GetValue(cocoLoader);
//read all basic properties of widget
CC_BASIC_PROPERTY_BINARY_READER
@ -67,8 +67,8 @@ namespace cocostudio
}
else if (key == P_TextureData){
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray();
std::string resType = backGroundChildren[2].GetValue();;
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray(cocoLoader);
std::string resType = backGroundChildren[2].GetValue(cocoLoader);;
Widget::TextureResType imageFileNameType = (Widget::TextureResType)valueToInt(resType);
@ -117,23 +117,25 @@ namespace cocostudio
bool scale9Enable = DICTOOL->getBooleanValue_json(options, P_Scale9Enable);
loadingBar->setScale9Enabled(scale9Enable);
if (scale9Enable)
{
float cx = DICTOOL->getFloatValue_json(options, P_CapInsetsX);
float cy = DICTOOL->getFloatValue_json(options, P_CapInsetsY);
float cw = DICTOOL->getFloatValue_json(options, P_CapInsetsWidth);
float ch = DICTOOL->getFloatValue_json(options, P_CapInsetsHeight);
float cx = DICTOOL->getFloatValue_json(options, P_CapInsetsX);
float cy = DICTOOL->getFloatValue_json(options, P_CapInsetsY);
float cw = DICTOOL->getFloatValue_json(options, P_CapInsetsWidth,1);
float ch = DICTOOL->getFloatValue_json(options, P_CapInsetsHeight,1);
if (scale9Enable) {
loadingBar->setCapInsets(Rect(cx, cy, cw, ch));
float width = DICTOOL->getFloatValue_json(options, P_Width);
float height = DICTOOL->getFloatValue_json(options, P_Height);
loadingBar->setSize(Size(width, height));
}
float width = DICTOOL->getFloatValue_json(options, P_Width);
float height = DICTOOL->getFloatValue_json(options, P_Height);
loadingBar->setSize(Size(width, height));
/**/
loadingBar->setDirection(LoadingBar::Direction(DICTOOL->getIntValue_json(options, P_Direction)));
loadingBar->setPercent(DICTOOL->getIntValue_json(options, P_Percent));
loadingBar->setPercent(DICTOOL->getIntValue_json(options, P_Percent,100));
WidgetReader::setColorPropsFromJsonDictionary(widget, options);

View File

@ -44,12 +44,12 @@ namespace cocostudio
ScrollView* scrollView = static_cast<ScrollView*>(widget);
stExpCocoNode *stChildArray = cocoNode->GetChildArray();
stExpCocoNode *stChildArray = cocoNode->GetChildArray(cocoLoader);
float innerWidth;
float innerHeight;
for (int i = 0; i < cocoNode->GetChildNum(); ++i) {
std::string key = stChildArray[i].GetName(cocoLoader);
std::string value = stChildArray[i].GetValue();
std::string value = stChildArray[i].GetValue(cocoLoader);
if (key == P_InnerWidth) {
innerWidth = valueToFloat(value);
}
@ -72,10 +72,10 @@ namespace cocostudio
ScrollView* scrollView = static_cast<ScrollView*>(widget);
float innerWidth = DICTOOL->getFloatValue_json(options, P_InnerWidth);
float innerHeight = DICTOOL->getFloatValue_json(options, P_InnerHeight);
float innerWidth = DICTOOL->getFloatValue_json(options, P_InnerWidth,200);
float innerHeight = DICTOOL->getFloatValue_json(options, P_InnerHeight,200);
scrollView->setInnerContainerSize(Size(innerWidth, innerHeight));
int direction = DICTOOL->getFloatValue_json(options, P_Direction);
int direction = DICTOOL->getFloatValue_json(options, P_Direction,1);
scrollView->setDirection((ScrollView::Direction)direction);
scrollView->setBounceEnabled(DICTOOL->getBooleanValue_json(options, P_BounceEnable));

View File

@ -51,11 +51,11 @@ namespace cocostudio
float barLength = 0.0f;
int percent = slider->getPercent();
stExpCocoNode *stChildArray = cocoNode->GetChildArray();
stExpCocoNode *stChildArray = cocoNode->GetChildArray(cocoLoader);
for (int i = 0; i < cocoNode->GetChildNum(); ++i) {
std::string key = stChildArray[i].GetName(cocoLoader);
std::string value = stChildArray[i].GetValue();
std::string value = stChildArray[i].GetValue(cocoLoader);
//read all basic properties of widget
CC_BASIC_PROPERTY_BINARY_READER
@ -69,8 +69,8 @@ namespace cocostudio
else if(key == P_Percent){
percent = valueToInt(value);
}else if(key == P_BarFileNameData){
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray();
std::string resType = backGroundChildren[2].GetValue();;
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray(cocoLoader);
std::string resType = backGroundChildren[2].GetValue(cocoLoader);;
Widget::TextureResType imageFileNameType = (Widget::TextureResType)valueToInt(resType);
@ -81,8 +81,8 @@ namespace cocostudio
}else if(key == P_Length){
barLength = valueToFloat(value);
}else if(key == P_BallNormalData){
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray();
std::string resType = backGroundChildren[2].GetValue();;
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray(cocoLoader);
std::string resType = backGroundChildren[2].GetValue(cocoLoader);;
Widget::TextureResType imageFileNameType = (Widget::TextureResType)valueToInt(resType);
@ -91,8 +91,8 @@ namespace cocostudio
slider->loadSlidBallTextureNormal(backgroundValue, imageFileNameType);
}else if(key == P_BallPressedData){
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray();
std::string resType = backGroundChildren[2].GetValue();;
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray(cocoLoader);
std::string resType = backGroundChildren[2].GetValue(cocoLoader);;
Widget::TextureResType imageFileNameType = (Widget::TextureResType)valueToInt(resType);
@ -101,8 +101,8 @@ namespace cocostudio
slider->loadSlidBallTexturePressed(backgroundValue, imageFileNameType);
}else if(key == P_BallDisabledData){
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray();
std::string resType = backGroundChildren[2].GetValue();;
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray(cocoLoader);
std::string resType = backGroundChildren[2].GetValue(cocoLoader);;
Widget::TextureResType imageFileNameType = (Widget::TextureResType)valueToInt(resType);
@ -111,8 +111,8 @@ namespace cocostudio
slider->loadSlidBallTextureDisabled(backgroundValue, imageFileNameType);
}else if(key == P_ProgressBarData){
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray();
std::string resType = backGroundChildren[2].GetValue();;
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray(cocoLoader);
std::string resType = backGroundChildren[2].GetValue(cocoLoader);;
Widget::TextureResType imageFileNameType = (Widget::TextureResType)valueToInt(resType);
@ -145,25 +145,24 @@ namespace cocostudio
slider->setPercent(DICTOOL->getIntValue_json(options, P_Percent));
bool bt = DICTOOL->checkObjectExist_json(options, P_BarFileName);
float barLength = DICTOOL->getFloatValue_json(options, P_Length);
if (bt)
{
const rapidjson::Value& imageFileNameDic = DICTOOL->getSubDictionary_json(options, P_BarFileNameData);
int imageFileNameType = DICTOOL->getIntValue_json(imageFileNameDic, P_ResourceType);
std::string imageFileName = this->getResourcePath(imageFileNameDic, P_Path, (Widget::TextureResType)imageFileNameType);
slider->loadBarTexture(imageFileName, (Widget::TextureResType)imageFileNameType);
// bool bt = DICTOOL->checkObjectExist_json(options, P_BarFileName);
float barLength = DICTOOL->getFloatValue_json(options, P_Length,290);
const rapidjson::Value& imageFileNameDic = DICTOOL->getSubDictionary_json(options, P_BarFileNameData);
int imageFileNameType = DICTOOL->getIntValue_json(imageFileNameDic, P_ResourceType);
std::string imageFileName = this->getResourcePath(imageFileNameDic, P_Path, (Widget::TextureResType)imageFileNameType);
slider->loadBarTexture(imageFileName, (Widget::TextureResType)imageFileNameType);
if (barTextureScale9Enable)
{
slider->setContentSize(Size(barLength, slider->getContentSize().height));
}
if (barTextureScale9Enable)
{
slider->setContentSize(Size(barLength, slider->getContentSize().height));
}
//loading normal slider ball texture
const rapidjson::Value& normalDic = DICTOOL->getSubDictionary_json(options, P_BallNormalData);
int normalType = DICTOOL->getIntValue_json(normalDic, P_ResourceType);
std::string imageFileName = this->getResourcePath(normalDic, P_Path, (Widget::TextureResType)normalType);
imageFileName = this->getResourcePath(normalDic, P_Path, (Widget::TextureResType)normalType);
slider->loadSlidBallTextureNormal(imageFileName, (Widget::TextureResType)normalType);

View File

@ -48,7 +48,7 @@ namespace cocostudio
TextAtlas* labelAtlas = static_cast<TextAtlas*>(widget);
stExpCocoNode *stChildArray = cocoNode->GetChildArray();
stExpCocoNode *stChildArray = cocoNode->GetChildArray(cocoLoader);
Widget::TextureResType type;
std::string charMapFileName;
std::string stringValue;
@ -57,7 +57,7 @@ namespace cocostudio
float itemHeight;
for (int i = 0; i < cocoNode->GetChildNum(); ++i) {
std::string key = stChildArray[i].GetName(cocoLoader);
std::string value = stChildArray[i].GetValue();
std::string value = stChildArray[i].GetValue(cocoLoader);
//read all basic properties of widget
CC_BASIC_PROPERTY_BINARY_READER
@ -68,8 +68,8 @@ namespace cocostudio
stringValue = value;
}
else if(key == P_CharMapFileData){
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray();
std::string resType = backGroundChildren[2].GetValue();;
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray(cocoLoader);
std::string resType = backGroundChildren[2].GetValue(cocoLoader);;
Widget::TextureResType imageFileNameType = (Widget::TextureResType)valueToInt(resType);
@ -101,34 +101,37 @@ namespace cocostudio
std::string jsonPath = GUIReader::getInstance()->getFilePath();
TextAtlas* labelAtlas = static_cast<TextAtlas*>(widget);
bool sv = DICTOOL->checkObjectExist_json(options, P_StringValue);
bool cmf = DICTOOL->checkObjectExist_json(options, P_CharMapFile);
bool iw = DICTOOL->checkObjectExist_json(options, P_ItemWidth);
bool ih = DICTOOL->checkObjectExist_json(options, P_ItemHeight);
bool scm = DICTOOL->checkObjectExist_json(options, P_StartCharMap);
if (sv && cmf && iw && ih && scm)
// bool sv = DICTOOL->checkObjectExist_json(options, P_StringValue);
// bool cmf = DICTOOL->checkObjectExist_json(options, P_CharMapFile);
// bool iw = DICTOOL->checkObjectExist_json(options, P_ItemWidth);
// bool ih = DICTOOL->checkObjectExist_json(options, P_ItemHeight);
// bool scm = DICTOOL->checkObjectExist_json(options, P_StartCharMap);
const rapidjson::Value& cmftDic = DICTOOL->getSubDictionary_json(options, P_CharMapFileData);
int cmfType = DICTOOL->getIntValue_json(cmftDic, P_ResourceType);
switch (cmfType)
{
const rapidjson::Value& cmftDic = DICTOOL->getSubDictionary_json(options, P_CharMapFileData);
int cmfType = DICTOOL->getIntValue_json(cmftDic, P_ResourceType);
switch (cmfType)
case 0:
{
case 0:
{
std::string tp_c = jsonPath;
const char* cmfPath = DICTOOL->getStringValue_json(cmftDic, P_Path);
const char* cmf_tp = tp_c.append(cmfPath).c_str();
labelAtlas->setProperty(DICTOOL->getStringValue_json(options, P_StringValue),cmf_tp,DICTOOL->getIntValue_json(options, P_ItemWidth),DICTOOL->getIntValue_json(options,P_ItemHeight), DICTOOL->getStringValue_json(options, P_StartCharMap));
break;
}
case 1:
CCLOG("Wrong res type of LabelAtlas!");
break;
default:
break;
std::string tp_c = jsonPath;
const char* cmfPath = DICTOOL->getStringValue_json(cmftDic, P_Path);
const char* cmf_tp = tp_c.append(cmfPath).c_str();
labelAtlas->setProperty(DICTOOL->getStringValue_json(options, P_StringValue,"12345678"),
cmf_tp,
DICTOOL->getIntValue_json(options, P_ItemWidth,24),
DICTOOL->getIntValue_json(options,P_ItemHeight,32),
DICTOOL->getStringValue_json(options, P_StartCharMap));
break;
}
case 1:
CCLOG("Wrong res type of LabelAtlas!");
break;
default:
break;
}
WidgetReader::setColorPropsFromJsonDictionary(widget, options);
}
}

View File

@ -42,19 +42,19 @@ namespace cocostudio
TextBMFont* labelBMFont = static_cast<TextBMFont*>(widget);
stExpCocoNode *stChildArray = cocoNode->GetChildArray();
stExpCocoNode *stChildArray = cocoNode->GetChildArray(cocoLoader);
for (int i = 0; i < cocoNode->GetChildNum(); ++i) {
std::string key = stChildArray[i].GetName(cocoLoader);
std::string value = stChildArray[i].GetValue();
std::string value = stChildArray[i].GetValue(cocoLoader);
//read all basic properties of widget
CC_BASIC_PROPERTY_BINARY_READER
//read all color related properties of widget
CC_COLOR_PROPERTY_BINARY_READER
else if(key == P_FileNameData){
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray();
std::string resType = backGroundChildren[2].GetValue();;
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray(cocoLoader);
std::string resType = backGroundChildren[2].GetValue(cocoLoader);;
Widget::TextureResType imageFileNameType = (Widget::TextureResType)valueToInt(resType);
@ -98,7 +98,7 @@ namespace cocostudio
break;
}
const char* text = DICTOOL->getStringValue_json(options, P_Text);
const char* text = DICTOOL->getStringValue_json(options, P_Text,"Text Label");
labelBMFont->setString(text);

View File

@ -49,11 +49,11 @@ namespace cocostudio
TextField* textField = static_cast<TextField*>(widget);
stExpCocoNode *stChildArray = cocoNode->GetChildArray();
stExpCocoNode *stChildArray = cocoNode->GetChildArray(cocoLoader);
for (int i = 0; i < cocoNode->GetChildNum(); ++i) {
std::string key = stChildArray[i].GetName(cocoLoader);
std::string value = stChildArray[i].GetValue();
std::string value = stChildArray[i].GetValue(cocoLoader);
//read all basic properties of widget
CC_BASIC_PROPERTY_BINARY_READER
@ -94,19 +94,15 @@ namespace cocostudio
bool ph = DICTOOL->checkObjectExist_json(options, P_PlaceHolder);
if (ph)
{
textField->setPlaceHolder(DICTOOL->getStringValue_json(options, P_PlaceHolder));
}
textField->setText(DICTOOL->getStringValue_json(options, P_Text));
bool fs = DICTOOL->checkObjectExist_json(options, P_FontSize);
if (fs)
{
textField->setFontSize(DICTOOL->getIntValue_json(options, P_FontSize));
}
bool fn = DICTOOL->checkObjectExist_json(options, P_FontName);
if (fn)
{
textField->setFontName(DICTOOL->getStringValue_json(options, P_FontName));
textField->setPlaceHolder(DICTOOL->getStringValue_json(options, P_PlaceHolder,"input words here"));
}
textField->setText(DICTOOL->getStringValue_json(options, P_Text,"Text Tield"));
textField->setFontSize(DICTOOL->getIntValue_json(options, P_FontSize,20));
textField->setFontName(DICTOOL->getStringValue_json(options, P_FontName,"微软雅黑"));
bool tsw = DICTOOL->checkObjectExist_json(options, P_TouchSizeWidth);
bool tsh = DICTOOL->checkObjectExist_json(options, P_TouchSizeHeight);
if (tsw && tsh)
@ -125,14 +121,14 @@ namespace cocostudio
if (maxLengthEnable)
{
int maxLength = DICTOOL->getIntValue_json(options, P_MaxLength);
int maxLength = DICTOOL->getIntValue_json(options, P_MaxLength,10);
textField->setMaxLength(maxLength);
}
bool passwordEnable = DICTOOL->getBooleanValue_json(options, P_PasswordEnable);
textField->setPasswordEnabled(passwordEnable);
if (passwordEnable)
{
textField->setPasswordStyleText(DICTOOL->getStringValue_json(options, P_PasswordStyleText));
textField->setPasswordStyleText(DICTOOL->getStringValue_json(options, P_PasswordStyleText,"*"));
}

View File

@ -45,7 +45,7 @@ namespace cocostudio
{
this->beginSetBasicProperties(widget);
stExpCocoNode *stChildArray = cocoNode->GetChildArray();
stExpCocoNode *stChildArray = cocoNode->GetChildArray(cocoLoader);
Text* label = static_cast<Text*>(widget);
@ -54,7 +54,7 @@ namespace cocostudio
for (int i = 0; i < cocoNode->GetChildNum(); ++i) {
std::string key = stChildArray[i].GetName(cocoLoader);
std::string value = stChildArray[i].GetValue();
std::string value = stChildArray[i].GetValue(cocoLoader);
//read all basic properties of widget
CC_BASIC_PROPERTY_BINARY_READER
//read all color related properties of widget
@ -69,7 +69,12 @@ namespace cocostudio
}else if(key == P_FontSize){
label->setFontSize(valueToInt(value));
}else if(key == P_FontName){
std::string fontFilePath = jsonPath.append(value);
std::string fontFilePath;
if(FileUtils::getInstance()->isFileExist(value)){
fontFilePath = jsonPath.append(value);
}else{
fontFilePath = value;
}
label->setFontName(fontFilePath);
}else if(key == P_AreaWidth){
label->setTextAreaSize(Size(valueToFloat(value), label->getTextAreaSize().height));
@ -95,20 +100,15 @@ namespace cocostudio
Text* label = static_cast<Text*>(widget);
bool touchScaleChangeAble = DICTOOL->getBooleanValue_json(options, P_TouchScaleEnable);
label->setTouchScaleChangeEnabled(touchScaleChangeAble);
const char* text = DICTOOL->getStringValue_json(options, P_Text);
const char* text = DICTOOL->getStringValue_json(options, P_Text,"Text Label");
label->setString(text);
bool fs = DICTOOL->checkObjectExist_json(options, P_FontSize);
if (fs)
{
label->setFontSize(DICTOOL->getIntValue_json(options, P_FontSize));
}
bool fn = DICTOOL->checkObjectExist_json(options, P_FontName);
if (fn)
{
std::string fontName = DICTOOL->getStringValue_json(options, P_FontName);
std::string fontFilePath = jsonPath.append(fontName);
label->setFontName(fontFilePath);
}
label->setFontSize(DICTOOL->getIntValue_json(options, P_FontSize,20));
std::string fontName = DICTOOL->getStringValue_json(options, P_FontName, "微软雅黑");
std::string fontFilePath = jsonPath.append(fontName);
label->setFontName(fontFilePath);
bool aw = DICTOOL->checkObjectExist_json(options, P_AreaWidth);
bool ah = DICTOOL->checkObjectExist_json(options, P_AreaHeight);
if (aw && ah)

View File

@ -113,11 +113,9 @@ namespace cocostudio
void WidgetReader::setPropsFromJsonDictionary(Widget *widget, const rapidjson::Value &options)
{
bool ignoreSizeExsit = DICTOOL->checkObjectExist_json(options, P_IgnoreSize);
if (ignoreSizeExsit)
{
widget->ignoreContentAdaptWithSize(DICTOOL->getBooleanValue_json(options, P_IgnoreSize));
}
widget->ignoreContentAdaptWithSize(DICTOOL->getBooleanValue_json(options, P_IgnoreSize,false));
widget->setSizeType((Widget::SizeType)DICTOOL->getIntValue_json(options, P_SizeType));
widget->setPositionType((Widget::PositionType)DICTOOL->getIntValue_json(options, P_PositionType));
@ -151,21 +149,15 @@ namespace cocostudio
float x = DICTOOL->getFloatValue_json(options, P_X);
float y = DICTOOL->getFloatValue_json(options, P_Y);
widget->setPosition(Vec2(x,y));
bool sx = DICTOOL->checkObjectExist_json(options, P_ScaleX);
if (sx)
{
widget->setScaleX(DICTOOL->getFloatValue_json(options, P_ScaleX));
}
bool sy = DICTOOL->checkObjectExist_json(options, P_ScaleY);
if (sy)
{
widget->setScaleY(DICTOOL->getFloatValue_json(options, P_ScaleY));
}
bool rt = DICTOOL->checkObjectExist_json(options, P_Rotation);
if (rt)
{
widget->setRotation(DICTOOL->getFloatValue_json(options, P_Rotation));
}
widget->setScaleX(DICTOOL->getFloatValue_json(options, P_ScaleX,1.0));
widget->setScaleY(DICTOOL->getFloatValue_json(options, P_ScaleY,1.0));
widget->setRotation(DICTOOL->getFloatValue_json(options, P_Rotation,0));
bool vb = DICTOOL->checkObjectExist_json(options, P_Visbile);
if (vb)
{
@ -295,8 +287,8 @@ namespace cocostudio
std::string WidgetReader::getResourcePath(CocoLoader *cocoLoader, stExpCocoNode *cocoNode, cocos2d::ui::Widget::TextureResType texType)
{
stExpCocoNode *backGroundChildren = cocoNode->GetChildArray();
std::string backgroundValue = backGroundChildren[0].GetValue();
stExpCocoNode *backGroundChildren = cocoNode->GetChildArray(cocoLoader);
std::string backgroundValue = backGroundChildren[0].GetValue(cocoLoader);
if (backgroundValue.size() < 3) {
return "";
@ -346,13 +338,13 @@ namespace cocostudio
void WidgetReader::setPropsFromBinary(cocos2d::ui::Widget *widget, cocostudio::CocoLoader *cocoLoader, cocostudio::stExpCocoNode *cocoNode)
{
stExpCocoNode *stChildArray = cocoNode->GetChildArray();
stExpCocoNode *stChildArray = cocoNode->GetChildArray(cocoLoader);
this->beginSetBasicProperties(widget);
for (int i = 0; i < cocoNode->GetChildNum(); ++i) {
std::string key = stChildArray[i].GetName(cocoLoader);
std::string value = stChildArray[i].GetValue();
std::string value = stChildArray[i].GetValue(cocoLoader);
CC_BASIC_PROPERTY_BINARY_READER
}

View File

@ -176,14 +176,14 @@ namespace cocostudio
}else if(key == P_ZOrder){ \
widget->setZOrder(valueToInt(value)); \
}else if(key == P_LayoutParameter){ \
stExpCocoNode *layoutCocosNode = stChildArray[i].GetChildArray(); \
stExpCocoNode *layoutCocosNode = stChildArray[i].GetChildArray(cocoLoader); \
ui::LinearLayoutParameter *linearParameter = ui::LinearLayoutParameter::create(); \
ui::RelativeLayoutParameter *relativeParameter = ui::RelativeLayoutParameter::create(); \
ui::Margin mg; \
int paramType = -1; \
for (int j = 0; j < stChildArray[i].GetChildNum(); ++j) { \
std::string innerKey = layoutCocosNode[j].GetName(cocoLoader); \
std::string innerValue = layoutCocosNode[j].GetValue(); \
std::string innerValue = layoutCocosNode[j].GetValue(cocoLoader); \
if (innerKey == P_Type) { \
paramType = valueToInt(innerValue); \
}else if(innerKey == P_Gravity){ \

View File

@ -188,7 +188,7 @@
<Optimization>Disabled</Optimization>
<SDLCheck>
</SDLCheck>
<AdditionalIncludeDirectories>$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\editor-support;$(EngineRoot)external;$(EngineRoot)external\tinyxml2;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AdditionalIncludeDirectories>$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\editor-support;$(EngineRoot)external;$(EngineRoot)external\tinyxml2;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;$(EngineRoot)external\win32-specific\zlib\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_LIB;COCOS2DXWIN32_EXPORTS;GL_GLEXT_PROTOTYPES;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
<DisableSpecificWarnings>4267;4251;4244;%(DisableSpecificWarnings)</DisableSpecificWarnings>
@ -208,7 +208,7 @@
<SDLCheck>
</SDLCheck>
<PreprocessorDefinitions>WIN32;_WINDOWS;_LIB;COCOS2DXWIN32_EXPORTS;GL_GLEXT_PROTOTYPES;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\editor-support;$(EngineRoot)external;$(EngineRoot)external\tinyxml2;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AdditionalIncludeDirectories>$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\editor-support;$(EngineRoot)external;$(EngineRoot)external\tinyxml2;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;$(EngineRoot)external\win32-specific\zlib\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<DebugInformationFormat>None</DebugInformationFormat>
<WholeProgramOptimization>false</WholeProgramOptimization>
</ClCompile>

View File

@ -77,7 +77,7 @@
<PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<AdditionalUsingDirectories>$(WindowsSDK_MetadataPath);$(AdditionalUsingDirectories)</AdditionalUsingDirectories>
<AdditionalIncludeDirectories>$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\editor-support;$(EngineRoot)external;$(EngineRoot)external\tinyxml2;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AdditionalIncludeDirectories>$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\editor-support;$(EngineRoot)external;$(EngineRoot)external\tinyxml2;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)external\wp8-specific\zlib\include;$(EngineRoot)extensions;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WP8;_DEBUG;_LIB;COCOS2DXWIN32_EXPORTS;GL_GLEXT_PROTOTYPES;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<DisableSpecificWarnings>4267;4251;4244;%(DisableSpecificWarnings)</DisableSpecificWarnings>
<AdditionalOptions>/Zm200 %(AdditionalOptions)</AdditionalOptions>

View File

@ -36,9 +36,6 @@ LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/..
LOCAL_C_INCLUDES := $(LOCAL_PATH)/../.. \
$(LOCAL_PATH)/..
LOCAL_CFLAGS += -Wno-psabi
LOCAL_EXPORT_CFLAGS += -Wno-psabi
LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static
include $(BUILD_STATIC_LIBRARY)

View File

@ -15,8 +15,6 @@ LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/..
LOCAL_C_INCLUDES := $(LOCAL_PATH)/../.. \
$(LOCAL_PATH)/..
LOCAL_CFLAGS += -Wno-psabi
LOCAL_EXPORT_CFLAGS += -Wno-psabi
LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static
LOCAL_WHOLE_STATIC_LIBRARIES += cocos_curl_static

View File

@ -35,6 +35,7 @@ import android.view.InputDevice;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.util.Log;
import android.util.SparseArray;
public abstract class GameControllerActivity extends Cocos2dxActivity implements InputDeviceListener {
// ===========================================================
@ -189,14 +190,16 @@ public abstract class GameControllerActivity extends Cocos2dxActivity implements
if (mControllerNibiru != null) {
handled |= mControllerNibiru.dispatchKeyEvent(event);
}
if (mControllerMoga != null) {
if (handled == false && mControllerMoga != null) {
handled |= mControllerMoga.dispatchKeyEvent(event);
}
if (mControllerOuya != null) {
if (handled == false && mControllerOuya != null) {
handled |= mControllerOuya.dispatchKeyEvent(event);
}
handled |= mControllerHelper.dispatchKeyEvent(event);
if (handled == false) {
handled |= mControllerHelper.dispatchKeyEvent(event);
}
return handled || super.dispatchKeyEvent(event);
}
@ -207,31 +210,44 @@ public abstract class GameControllerActivity extends Cocos2dxActivity implements
if (mControllerNibiru != null) {
handled |= mControllerNibiru.dispatchGenericMotionEvent(event);
}
if (mControllerMoga != null) {
if (handled == false && mControllerMoga != null) {
handled |= mControllerMoga.dispatchGenericMotionEvent(event);
}
if (mControllerOuya != null) {
if (handled == false && mControllerOuya != null) {
handled |= mControllerOuya.dispatchGenericMotionEvent(event);
}
handled |= mControllerHelper.dispatchGenericMotionEvent(event);
if (handled == false) {
handled |= mControllerHelper.dispatchGenericMotionEvent(event);
}
return handled || super.dispatchGenericMotionEvent(event);
}
protected SparseArray<String> mGameController = null;
@Override
public void onInputDeviceAdded(int deviceId) {
public void onInputDeviceAdded(int deviceId) {
Log.d(TAG,"onInputDeviceAdded:" + deviceId);
InputDevice device = InputDevice.getDevice(deviceId);
int deviceSource = device.getSources();
if ( ((deviceSource & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD)
|| ((deviceSource & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK) )
{
GameControllerAdapter.onConnected("Standard", deviceId);
try {
InputDevice device = InputDevice.getDevice(deviceId);
int deviceSource = device.getSources();
if ( ((deviceSource & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD)
|| ((deviceSource & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK) )
{
if (mGameController == null) {
mGameController = new SparseArray<String>();
}
String deviceName = device.getName();
mGameController.append(deviceId, deviceName);
GameControllerAdapter.onConnected(deviceName, deviceId);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* This is an unusual case. Input devices don't typically change, but they
@ -244,7 +260,7 @@ public abstract class GameControllerActivity extends Cocos2dxActivity implements
*/
@Override
public void onInputDeviceChanged(int deviceId) {
Log.d(TAG,"onInputDeviceChanged:" + deviceId);
Log.w(TAG,"onInputDeviceChanged:" + deviceId);
}
/*
@ -258,13 +274,9 @@ public abstract class GameControllerActivity extends Cocos2dxActivity implements
public void onInputDeviceRemoved(int deviceId) {
Log.d(TAG,"onInputDeviceRemoved:" + deviceId);
InputDevice device = InputDevice.getDevice(deviceId);
int deviceSource = device.getSources();
if ( ((deviceSource & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD)
|| ((deviceSource & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK) )
{
GameControllerAdapter.onDisconnected("Standard", deviceId);
if (mGameController != null && mGameController.get(deviceId) != null) {
GameControllerAdapter.onDisconnected(mGameController.get(deviceId), deviceId);
mGameController.delete(deviceId);
}
}

View File

@ -77,86 +77,67 @@ public class GameControllerHelper {
{
if (event.getAction() == MotionEvent.ACTION_MOVE) {
int devicedId = event.getDeviceId();
String deviceName = event.getDevice().getName();
float newAXIS_LX = event.getAxisValue(AXIS_X);
if (Float.compare(newAXIS_LX , mOldLeftThumbstickX) != 0) {
GameControllerAdapter.onAxisEvent(StandardControllerName, devicedId, GameControllerDelegate.THUMBSTICK_LEFT_X, newAXIS_LX, true);
GameControllerAdapter.onAxisEvent(deviceName, devicedId, GameControllerDelegate.THUMBSTICK_LEFT_X, newAXIS_LX, true);
mOldLeftThumbstickX = newAXIS_LX;
handled = true;
}
float newAXIS_LY = event.getAxisValue(AXIS_Y);
if (Float.compare(newAXIS_LY , mOldLeftThumbstickY) != 0) {
GameControllerAdapter.onAxisEvent(StandardControllerName, devicedId, GameControllerDelegate.THUMBSTICK_LEFT_Y, newAXIS_LY, true);
GameControllerAdapter.onAxisEvent(deviceName, devicedId, GameControllerDelegate.THUMBSTICK_LEFT_Y, newAXIS_LY, true);
mOldLeftThumbstickY = newAXIS_LY;
handled = true;
}
float newAXIS_RX = event.getAxisValue(AXIS_Z);
if (Float.compare(newAXIS_RX , mOldRightThumbstickX) != 0) {
GameControllerAdapter.onAxisEvent(StandardControllerName, devicedId, GameControllerDelegate.THUMBSTICK_RIGHT_X, newAXIS_RX, true);
GameControllerAdapter.onAxisEvent(deviceName, devicedId, GameControllerDelegate.THUMBSTICK_RIGHT_X, newAXIS_RX, true);
mOldRightThumbstickX = newAXIS_RX;
handled = true;
}
float newAXIS_RY = event.getAxisValue(AXIS_RZ);
if (Float.compare(newAXIS_RY , mOldRightThumbstickY) != 0) {
GameControllerAdapter.onAxisEvent(StandardControllerName, devicedId, GameControllerDelegate.THUMBSTICK_RIGHT_Y, newAXIS_RY, true);
GameControllerAdapter.onAxisEvent(deviceName, devicedId, GameControllerDelegate.THUMBSTICK_RIGHT_Y, newAXIS_RY, true);
mOldRightThumbstickY = newAXIS_RY;
handled = true;
}
float newAXIS_LTRIGGER = event.getAxisValue(AXIS_LTRIGGER);
if (Float.compare(newAXIS_LTRIGGER , mOldLeftTrigger) != 0) {
if (Float.compare(newAXIS_LTRIGGER, 0.0f) == 0) {
GameControllerAdapter.onButtonEvent(StandardControllerName, devicedId, GameControllerDelegate.BUTTON_LEFT_TRIGGER, false, 0.0f, true);
}else {
GameControllerAdapter.onButtonEvent(StandardControllerName, devicedId, GameControllerDelegate.BUTTON_LEFT_TRIGGER, true, newAXIS_LTRIGGER, true);
}
GameControllerAdapter.onAxisEvent(deviceName, devicedId, GameControllerDelegate.BUTTON_LEFT_TRIGGER, newAXIS_LTRIGGER, true);
mOldLeftTrigger = newAXIS_LTRIGGER;
handled = true;
}
float newAXIS_RTRIGGER = event.getAxisValue(AXIS_RTRIGGER);
if (Float.compare(newAXIS_RTRIGGER , mOldRightTrigger) != 0) {
if (Float.compare(newAXIS_RTRIGGER, 0.0f) == 0) {
GameControllerAdapter.onButtonEvent(StandardControllerName, devicedId, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, false, 0.0f, true);
}else {
GameControllerAdapter.onButtonEvent(StandardControllerName, devicedId, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, true, newAXIS_RTRIGGER, true);
}
GameControllerAdapter.onAxisEvent(deviceName, devicedId, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, newAXIS_RTRIGGER, true);
mOldRightTrigger = newAXIS_RTRIGGER;
handled = true;
}
float newAXIS_BRAKE = event.getAxisValue(AXIS_BRAKE);
if (Float.compare(newAXIS_BRAKE , mOldBrake) != 0) {
if (Float.compare(newAXIS_BRAKE, 0.0f) == 0) {
GameControllerAdapter.onButtonEvent(StandardControllerName, devicedId, GameControllerDelegate.BUTTON_LEFT_TRIGGER, false, 0.0f, true);
}else {
GameControllerAdapter.onButtonEvent(StandardControllerName, devicedId, GameControllerDelegate.BUTTON_LEFT_TRIGGER, true, newAXIS_BRAKE, true);
}
GameControllerAdapter.onAxisEvent(deviceName, devicedId, GameControllerDelegate.BUTTON_LEFT_TRIGGER, newAXIS_BRAKE, true);
mOldBrake = newAXIS_BRAKE;
handled = true;
}
float newAXIS_THROTTLE = event.getAxisValue(AXIS_THROTTLE);
if (Float.compare(newAXIS_THROTTLE , mOldThrottle) != 0) {
if (Float.compare(newAXIS_THROTTLE, 0.0f) == 0) {
GameControllerAdapter.onButtonEvent(StandardControllerName, devicedId, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, false, 0.0f, true);
}else {
GameControllerAdapter.onButtonEvent(StandardControllerName, devicedId, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, true, newAXIS_THROTTLE, true);
}
GameControllerAdapter.onAxisEvent(deviceName, devicedId, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, newAXIS_THROTTLE, true);
mOldThrottle = newAXIS_THROTTLE;
handled = true;
}
float newAXIS_GAS = event.getAxisValue(AXIS_GAS);
if (Float.compare(newAXIS_GAS , mOldGas) != 0) {
if (Float.compare(newAXIS_GAS, 0.0f) == 0) {
GameControllerAdapter.onButtonEvent(StandardControllerName, devicedId, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, false, 0.0f, true);
}else {
GameControllerAdapter.onButtonEvent(StandardControllerName, devicedId, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, true, newAXIS_GAS, true);
}
GameControllerAdapter.onAxisEvent(deviceName, devicedId, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, newAXIS_GAS, true);
mOldGas = newAXIS_GAS;
handled = true;
}
@ -170,19 +151,19 @@ public class GameControllerHelper {
boolean handled = false;
int eventSource = event.getSource();
int controllerKey = ControllerKeyMap.get(event.getKeyCode());
int keyCode = event.getKeyCode();
int controllerKey = ControllerKeyMap.get(keyCode);
if (controllerKey != 0 && (((eventSource & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD)
|| ((eventSource & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK)
|| ((eventSource & InputDevice.SOURCE_DPAD) == InputDevice.SOURCE_DPAD)))
|| ((eventSource & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK) ))
{
int action = event.getAction();
if (action == KeyEvent.ACTION_DOWN) {
handled = true;
GameControllerAdapter.onButtonEvent(StandardControllerName,event.getDeviceId(), controllerKey,true, 1.0f, false);
GameControllerAdapter.onButtonEvent(event.getDevice().getName(),event.getDeviceId(), controllerKey,true, 1.0f, false);
}else if (action == KeyEvent.ACTION_UP) {
handled = true;
GameControllerAdapter.onButtonEvent(StandardControllerName,event.getDeviceId(), controllerKey,false, 0.0f, false);
GameControllerAdapter.onButtonEvent(event.getDevice().getName(),event.getDeviceId(), controllerKey,false, 0.0f, false);
}
}

View File

@ -129,28 +129,18 @@ public class GameControllerMoga implements ControllerListener, GameControllerDel
float newLeftTrigger = event.getAxisValue(MotionEvent.AXIS_LTRIGGER);
if (newLeftTrigger != mOldLeftTrigger) {
boolean isPressed = true;
if (Float.compare(newLeftTrigger, 0.0f) == 0) {
isPressed = false;
}
mControllerEventListener.onButtonEvent(mVendorName,
mControllerEventListener.onAxisEvent(mVendorName,
controllerId,
GameControllerDelegate.BUTTON_LEFT_TRIGGER,
isPressed,
newLeftTrigger, true);
mOldLeftTrigger = newLeftTrigger;
}
float newRightTrigger = event.getAxisValue(MotionEvent.AXIS_RTRIGGER);
if (newRightTrigger != mOldRightTrigger) {
boolean isPressed = true;
if (Float.compare(newRightTrigger, 0.0f) == 0) {
isPressed = false;
}
mControllerEventListener.onButtonEvent(mVendorName,
mControllerEventListener.onAxisEvent(mVendorName,
controllerId,
GameControllerDelegate.BUTTON_RIGHT_TRIGGER,
isPressed,
newRightTrigger, true);
mOldRightTrigger = newRightTrigger;
}

View File

@ -66,21 +66,13 @@ public class GameControllerOuya implements GameControllerDelegate{
float newLeftTrigger = c.getAxisValue(OuyaController.AXIS_L2);
if (Float.compare(newLeftTrigger, mOldLeftTrigger) != 0) {
if (Float.compare(newLeftTrigger, 0.0f) == 0) {
mControllerEventListener.onButtonEvent(sVendorName, controllerID, GameControllerDelegate.BUTTON_LEFT_TRIGGER, false, 0.0f, true);
}else {
mControllerEventListener.onButtonEvent(sVendorName, controllerID, GameControllerDelegate.BUTTON_LEFT_TRIGGER, true, newLeftTrigger, true);
}
mControllerEventListener.onAxisEvent(sVendorName, controllerID, GameControllerDelegate.BUTTON_LEFT_TRIGGER, newLeftTrigger, true);
mOldLeftTrigger = newLeftTrigger;
}
float newRightTrigger = c.getAxisValue(OuyaController.AXIS_R2);
if (Float.compare(newRightTrigger, mOldRightTrigger) != 0) {
if (Float.compare(newRightTrigger, 0.0f) == 0) {
mControllerEventListener.onButtonEvent(sVendorName, controllerID, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, false, 0.0f, true);
}else {
mControllerEventListener.onButtonEvent(sVendorName, controllerID, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, true, newRightTrigger, true);
}
mControllerEventListener.onAxisEvent(sVendorName, controllerID, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, newRightTrigger, true);
mOldRightTrigger = newRightTrigger;
}

View File

@ -6,34 +6,36 @@ import android.view.MotionEvent;
public interface GameControllerDelegate {
public static final int THUMBSTICK_LEFT_X = 100;
public static final int THUMBSTICK_LEFT_Y = 101;
public static final int THUMBSTICK_RIGHT_X = 102;
public static final int THUMBSTICK_RIGHT_Y = 103;
static final int KEY_BASE = 1000;
public static final int THUMBSTICK_LEFT_X = KEY_BASE;
public static final int THUMBSTICK_LEFT_Y = KEY_BASE + 1;
public static final int THUMBSTICK_RIGHT_X = KEY_BASE + 2;
public static final int THUMBSTICK_RIGHT_Y = KEY_BASE + 3;
public static final int BUTTON_A = 110;
public static final int BUTTON_B = 111;
public static final int BUTTON_C = 112;
public static final int BUTTON_X = 113;
public static final int BUTTON_Y = 114;
public static final int BUTTON_Z = 115;
public static final int BUTTON_A = KEY_BASE + 4;
public static final int BUTTON_B = KEY_BASE + 5;
public static final int BUTTON_C = KEY_BASE + 6;
public static final int BUTTON_X = KEY_BASE + 7;
public static final int BUTTON_Y = KEY_BASE + 8;
public static final int BUTTON_Z = KEY_BASE + 9;
public static final int BUTTON_LEFT_SHOULDER = 120;
public static final int BUTTON_RIGHT_SHOULDER = 121;
public static final int BUTTON_LEFT_TRIGGER = 122;
public static final int BUTTON_RIGHT_TRIGGER = 123;
public static final int BUTTON_DPAD_UP = KEY_BASE + 10;
public static final int BUTTON_DPAD_DOWN = KEY_BASE + 11;
public static final int BUTTON_DPAD_LEFT = KEY_BASE + 12;
public static final int BUTTON_DPAD_RIGHT = KEY_BASE + 13;
public static final int BUTTON_DPAD_CENTER = KEY_BASE + 14;
public static final int BUTTON_DPAD_UP = 130;
public static final int BUTTON_DPAD_DOWN = 131;
public static final int BUTTON_DPAD_LEFT = 132;
public static final int BUTTON_DPAD_RIGHT = 133;
public static final int BUTTON_DPAD_CENTER = 134;
public static final int BUTTON_LEFT_SHOULDER = KEY_BASE + 15;
public static final int BUTTON_RIGHT_SHOULDER = KEY_BASE + 16;
public static final int BUTTON_LEFT_TRIGGER = KEY_BASE + 17;
public static final int BUTTON_RIGHT_TRIGGER = KEY_BASE + 18;
public static final int BUTTON_LEFT_THUMBSTICK = 140;
public static final int BUTTON_RIGHT_THUMBSTICK = 141;
public static final int BUTTON_LEFT_THUMBSTICK = KEY_BASE + 19;
public static final int BUTTON_RIGHT_THUMBSTICK = KEY_BASE + 20;
public static final int BUTTON_START = 150;
public static final int BUTTON_SELECT = 151;
public static final int BUTTON_START = KEY_BASE + 21;
public static final int BUTTON_SELECT = KEY_BASE + 22;
void onCreate(Context context);
void onPause();

View File

@ -160,6 +160,7 @@ bool LuaStack::init(void)
register_all_cocos2dx_ui(_state);
register_all_cocos2dx_studio(_state);
register_all_cocos2dx_manual(_state);
register_all_cocos2dx_module_manual(_state);
register_all_cocos2dx_extension_manual(_state);
register_all_cocos2dx_coco_studio_manual(_state);
register_all_cocos2dx_ui_manual(_state);

View File

@ -6429,3 +6429,90 @@ int register_all_cocos2dx_manual(lua_State* tolua_S)
return 0;
}
static int tolua_cocos2d_utils_captureScreen(lua_State* tolua_S)
{
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
if (!tolua_istable(tolua_S,1,0, &tolua_err) ||
!toluafix_isfunction(tolua_S,2,"LUA_FUNCTION",0,&tolua_err) ||
!tolua_isstring(tolua_S, 3, 0, &tolua_err)
)
goto tolua_lerror;
else
#endif
{
LUA_FUNCTION handler = toluafix_ref_function(tolua_S,2,0);
std::string fileName = tolua_tocppstring(tolua_S, 3, "");
cocos2d::utils::captureScreen([=](bool succeed, const std::string& name ){
tolua_pushboolean(tolua_S, succeed);
tolua_pushstring(tolua_S, name.c_str());
LuaEngine::getInstance()->getLuaStack()->executeFunctionByHandler(handler, 2);
LuaEngine::getInstance()->removeScriptHandler(handler);
}, fileName);
return 0;
}
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'captureScreen'.",&tolua_err);
return 0;
#endif
}
static int tolua_cocos2d_utils_findChildren(lua_State* tolua_S)
{
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
if (!tolua_istable(tolua_S,1,0, &tolua_err) ||
!tolua_isusertype(tolua_S, 2, "cc.Node", 0, &tolua_err) ||
!tolua_isstring(tolua_S, 3, 0, &tolua_err)
)
goto tolua_lerror;
else
#endif
{
cocos2d::Node* node = static_cast<Node*>(tolua_tousertype(tolua_S, 2, nullptr));
std::string name = tolua_tocppstring(tolua_S, 3, "");
std::vector<Node*> children = cocos2d::utils::findChildren(*node, name);
lua_newtable(tolua_S);
int index = 1;
for (const auto& obj : children)
{
if (nullptr == obj)
continue;
lua_pushnumber(tolua_S, (lua_Number)index);
int ID = (obj) ? (int)obj->_ID : -1;
int* luaID = (obj) ? &obj->_luaID : NULL;
toluafix_pushusertype_ccobject(tolua_S, ID, luaID, (void*)obj, "cc.Node");
lua_rawset(tolua_S, -3);
++index;
}
return 1;
}
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'findChildren'.",&tolua_err);
return 0;
#endif
}
int register_all_cocos2dx_module_manual(lua_State* tolua_S)
{
if (nullptr == tolua_S)
return 0;
tolua_open(tolua_S);
tolua_module(tolua_S, "cc", 0);
tolua_beginmodule(tolua_S, "cc");
tolua_module(tolua_S, "utils", 0);
tolua_beginmodule(tolua_S,"utils");
tolua_function(tolua_S, "captureScreen", tolua_cocos2d_utils_captureScreen);
tolua_function(tolua_S, "findChildren", tolua_cocos2d_utils_findChildren);
tolua_endmodule(tolua_S);
tolua_endmodule(tolua_S);
return 0;
}

View File

@ -55,6 +55,8 @@ TOLUA_API int register_all_cocos2dx_manual(lua_State* tolua_S);
TOLUA_API int register_cocos2dx_event_releated(lua_State* tolua_S);
TOLUA_API int register_all_cocos2dx_module_manual(lua_State* tolua_S);
struct LuaEventAccelerationData
{
void* acc;

File diff suppressed because it is too large Load Diff

View File

@ -41,8 +41,6 @@ $(LOCAL_PATH)/.. \
$(LOCAL_PATH)/../.. \
$(LOCAL_PATH)/../editor-support
LOCAL_CFLAGS += -Wno-psabi
LOCAL_EXPORT_CFLAGS += -Wno-psabi
LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static
LOCAL_WHOLE_STATIC_LIBRARIES += cocos_extension_static

View File

@ -134,7 +134,7 @@ void PageView::addPage(Layout* page)
}
addProtectedChild(page);
addChild(page);
_pages.pushBack(page);
_doLayoutDirty = true;
@ -156,7 +156,7 @@ void PageView::insertPage(Layout* page, int idx)
else
{
_pages.insert(idx, page);
addProtectedChild(page);
addChild(page);
}
@ -169,7 +169,7 @@ void PageView::removePage(Layout* page)
{
return;
}
removeProtectedChild(page);
removeChild(page);
_pages.eraseObject(page);
_doLayoutDirty = true;
@ -189,7 +189,7 @@ void PageView::removeAllPages()
{
for(const auto& node : _pages)
{
removeProtectedChild(node);
removeChild(node);
}
_pages.clear();
}

View File

@ -623,7 +623,6 @@ bool TextField::isPasswordEnabled()const
void TextField::setPasswordStyleText(const char *styleText)
{
_textFieldRenderer->setPasswordStyleText(styleText);
_passwordStyleText = styleText;
setText(getStringValue());

View File

@ -280,17 +280,8 @@
"cocos/base/CCConsole.h",
"cocos/base/CCController-android.cpp",
"cocos/base/CCController-iOS.mm",
"cocos/base/CCController.cpp",
"cocos/base/CCController.h",
"cocos/base/CCControllerAxisInput.cpp",
"cocos/base/CCControllerAxisInput.h",
"cocos/base/CCControllerButtonInput.cpp",
"cocos/base/CCControllerButtonInput.h",
"cocos/base/CCControllerDirectionPad.cpp",
"cocos/base/CCControllerDirectionPad.h",
"cocos/base/CCControllerElement.cpp",
"cocos/base/CCControllerElement.h",
"cocos/base/CCControllerThumbstick.cpp",
"cocos/base/CCControllerThumbstick.h",
"cocos/base/CCData.cpp",
"cocos/base/CCData.h",
"cocos/base/CCDataVisitor.cpp",
@ -333,8 +324,6 @@
"cocos/base/CCEventTouch.h",
"cocos/base/CCEventType.h",
"cocos/base/CCGameController.h",
"cocos/base/CCGamepad.cpp",
"cocos/base/CCGamepad.h",
"cocos/base/CCIMEDelegate.h",
"cocos/base/CCIMEDispatcher.cpp",
"cocos/base/CCIMEDispatcher.h",

View File

@ -1,5 +1,9 @@
APP_STL := gnustl_static
APP_STL := c++_static
NDK_TOOLCHAIN_VERSION=clang
APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -std=c++11 -fsigned-char
APP_LDFLAGS := -latomic
APP_DEBUG := $(strip $(NDK_DEBUG))
ifeq ($(APP_DEBUG),1)
@ -8,4 +12,4 @@ ifeq ($(APP_DEBUG),1)
else
APP_CPPFLAGS += -DNDEBUG
APP_OPTIM := release
endif
endif

View File

@ -1,5 +1,9 @@
APP_STL := gnustl_static
APP_STL := c++_static
NDK_TOOLCHAIN_VERSION=clang
APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -std=c++11 -fsigned-char
APP_LDFLAGS := -latomic
APP_DEBUG := $(strip $(NDK_DEBUG))
ifeq ($(APP_DEBUG),1)
@ -8,4 +12,4 @@ ifeq ($(APP_DEBUG),1)
else
APP_CPPFLAGS += -DNDEBUG
APP_OPTIM := release
endif
endif

View File

@ -573,6 +573,7 @@
5023813117EBBCE400990C9B /* Sources */,
5023813617EBBCE400990C9B /* Frameworks */,
5023814617EBBCE400990C9B /* Resources */,
3EC03837196544AA00D72B70 /* ShellScript */,
);
buildRules = (
);
@ -596,6 +597,7 @@
F293B3C415EB7BE500256477 /* Sources */,
F293B3C515EB7BE500256477 /* Frameworks */,
F293B3C615EB7BE500256477 /* Resources */,
3EC03838196544BB00D72B70 /* ShellScript */,
);
buildRules = (
);
@ -814,6 +816,35 @@
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
3EC03837196544AA00D72B70 /* ShellScript */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "find ${SRCROOT}/../../../src/ -name \"*\" -exec touch -cm {} \\;\nfind ${SRCROOT}/../../../res/ -name \"*\" -exec touch -cm {} \\;";
};
3EC03838196544BB00D72B70 /* ShellScript */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "find ${SRCROOT}/../../../src/ -name \"*\" -exec touch -cm {} \\;\nfind ${SRCROOT}/../../../res/ -name \"*\" -exec touch -cm {} \\;";
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
5023813117EBBCE400990C9B /* Sources */ = {
isa = PBXSourcesBuildPhase;

View File

@ -10,7 +10,4 @@
<nature>org.ccdt.cocosproject</nature>
<nature>org.eclipse.koneki.ldt.nature</nature>
</natures>
<cocosprojecttemplate>
<version>1.1</version>
</cocosprojecttemplate>
</projectDescription>

View File

@ -0,0 +1,4 @@
{
"templateVersion":"1.2",
"runtimeVersion":"1.2"
}

View File

@ -13,21 +13,6 @@
]
},
"append_dir": [
{
"from": "templates/lua-template-runtime/runtime/rtres",
"to": "runtime/mac/PrebuiltRuntimeLua.app/Contents/Resources/rtres",
"exclude": []
},
{
"from": "templates/lua-template-runtime/runtime/rtres",
"to": "runtime/ios/PrebuiltRuntimeLua.app/rtres",
"exclude": []
},
{
"from": "templates/lua-template-runtime/runtime/rtres",
"to": "runtime/win32/rtres",
"exclude": []
},
{
"from": "cocos/scripting/lua-bindings/script",
"to": "runtime/mac/PrebuiltRuntimeLua.app/Contents/Resources",

View File

@ -54,6 +54,9 @@ bool AppDelegate::applicationDidFinishLaunching()
auto engine = LuaEngine::getInstance();
ScriptEngineManager::getInstance()->setScriptEngine(engine);
LuaStack* stack = engine->getLuaStack();
stack->setXXTEAKeyAndSign("2dxLua", strlen("2dxLua"), "XXTEA", strlen("XXTEA"));
//register custom function
//LuaStack* stack = engine->getLuaStack();

View File

@ -1,901 +0,0 @@
/****************************************************************************
Copyright (c) 2013 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "Runtime.h"
#include "lua_debugger.h"
#include "CCLuaEngine.h"
#include "cocos2d.h"
#include "json/document.h"
#include "json/filestream.h"
#include "json/stringbuffer.h"
#include "json/writer.h"
#include "LuaBasicConversions.h"
#include "VisibleRect.h"
#include "ConfigParser.h"
#ifdef _WIN32
#include <direct.h>
#else
#include <sys/stat.h>
#endif
#include <vector>
#include <string>
using namespace std;
using namespace cocos2d;
std::string g_resourcePath;
static rapidjson::Document g_filecfgjson;
class ConnectWaitLayer;
static ConnectWaitLayer* s_pConnectLayer;
extern string getIPAddress();
const char* getRuntimeVersion()
{
return "1.1";
}
void hideRcvFile() {
s_pConnectLayer = nullptr;
}
void startScript(string strDebugArg)
{
hideRcvFile();
// register lua engine
auto engine = LuaEngine::getInstance();
if (!strDebugArg.empty())
{
engine->executeString(strDebugArg.c_str());
}
cocos2d::log("debug args = %s",strDebugArg.c_str());
engine->executeScriptFile(ConfigParser::getInstance()->getEntryFile().c_str());
}
bool reloadScript(const string& modulefile)
{
string strfile = modulefile;
if (strfile.empty())
{
strfile = ConfigParser::getInstance()->getEntryFile().c_str();
}
auto director = Director::getInstance();
FontFNT::purgeCachedData();
if (director->getOpenGLView())
{
SpriteFrameCache::getInstance()->removeSpriteFrames();
director->getTextureCache()->removeAllTextures();
}
FileUtils::getInstance()->purgeCachedEntries();
director->getScheduler()->unscheduleAll();
director->getScheduler()->scheduleUpdate(director->getActionManager(), Scheduler::PRIORITY_SYSTEM, false);
return (LuaEngine::getInstance()->reload(strfile.c_str())==0);
}
class ConnectWaitLayer: public Layer
{
private:
Label* _labelUploadFile;
public:
ConnectWaitLayer()
{
int designWidth = 1280;
int designHeight = 800;
Director::getInstance()->getOpenGLView()->setDesignResolutionSize(designWidth,designHeight,ResolutionPolicy::EXACT_FIT);
string playEnbleFile = "rtres/Play1.png";
string shineFile = "rtres/shine.png";
string backgroundFile = "rtres/landscape.png";
if (!ConfigParser::getInstance()->isLanscape())
{
backgroundFile = "rtres/portrait.png";
Director::getInstance()->getOpenGLView()->setDesignResolutionSize(designHeight,designWidth,ResolutionPolicy::EXACT_FIT);
}
auto background = Sprite::create(backgroundFile.c_str());
if (background)
{
background->setAnchorPoint(Vec2(0,0));
addChild(background,9999);
}
auto playSprite = Sprite::create(playEnbleFile.c_str());
if (playSprite)
{
playSprite->setPosition(Vec2(902,400));
addChild(playSprite,9999);
}else
{
auto labelPlay = LabelTTF::create("play", "Arial", 108);
auto menuItem = MenuItemLabel::create(labelPlay, CC_CALLBACK_1(ConnectWaitLayer::playerCallback, this));
auto menu = Menu::create(menuItem, NULL);
menu->setPosition( Point::ZERO );
menuItem->setPosition(Vec2(902,400));
if (!ConfigParser::getInstance()->isLanscape()) menuItem->setPosition(Vec2(400,500));
addChild(menu, 1);
}
auto shineSprite = Sprite::create(shineFile.c_str());
if (shineSprite)
{
shineSprite->setPosition(Vec2(902,400));
shineSprite->runAction(RepeatForever::create(Sequence::createWithTwoActions(ScaleBy::create(1.0f, 1.08f),ScaleTo::create(1.0f, 1))));
addChild(shineSprite,9999);
}
string strip = getIPAddress();
char szIPAddress[512]={0};
sprintf(szIPAddress, "IP: %s",strip.c_str());
auto IPlabel = Label::create(szIPAddress, "Arial", 72);
IPlabel->setAnchorPoint(Vec2(0,0));
int spaceSizex = 72;
int spaceSizey = 200;
IPlabel->setPosition( Point(VisibleRect::leftTop().x+spaceSizex, VisibleRect::top().y -spaceSizey) );
addChild(IPlabel, 9999);
string strShowMsg = "waiting for file transfer ...";
if (CC_PLATFORM_WIN32 == CC_TARGET_PLATFORM || CC_PLATFORM_MAC == CC_TARGET_PLATFORM)
{
strShowMsg = "waiting for debugger to connect ...";
}
_labelUploadFile = Label::create(strShowMsg.c_str(), "Arial", 36);
_labelUploadFile->setAnchorPoint(Vec2(0,0));
_labelUploadFile->setPosition( Point(VisibleRect::leftTop().x+spaceSizex, IPlabel->getPositionY()-spaceSizex) );
_labelUploadFile->setAlignment(TextHAlignment::LEFT);
addChild(_labelUploadFile, 10000);
if (!ConfigParser::getInstance()->isLanscape())
{
if (playSprite) playSprite->setPosition(400,500);
if (shineSprite) shineSprite->setPosition(400,500);
_labelUploadFile->setAlignment(TextHAlignment::LEFT);
}
if (playSprite)
{
auto listener = EventListenerTouchOneByOne::create();
listener->onTouchBegan = [](Touch* touch, Event *event)->bool{
auto target = static_cast<Sprite*>(event->getCurrentTarget());
Vec2 point = target->convertToNodeSpace(Director::getInstance()->convertToGL(touch->getLocationInView()));
auto rect = Rect(0, 0, target->getContentSize().width, target->getContentSize().height);
if (!rect.containsPoint(point)) return false;
target->stopAllActions();
target->runAction(Sequence::createWithTwoActions(ScaleBy::create(0.05f, 0.9f),ScaleTo::create(0.125f, 1)));
return true;
};
listener->onTouchEnded = [](Touch* touch, Event *event){
auto target = static_cast<Sprite*>(event->getCurrentTarget());
Vec2 point = target->convertToNodeSpace(Director::getInstance()->convertToGL(touch->getLocationInView()));
auto rect = Rect(0, 0, target->getContentSize().width, target->getContentSize().height);
if (!rect.containsPoint(point)) return;
startScript("");
};
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, playSprite);
}
}
void playerCallback(Object* sender)
{
startScript("");
}
void showCurRcvFile(string fileName) {
_labelUploadFile->setString(fileName);
}
};
void showCurRcvFile(string fileName) {
if (NULL == s_pConnectLayer) return;
s_pConnectLayer->showCurRcvFile(fileName);
}
#if defined(_MSC_VER) || defined(__MINGW32__)
#include <io.h>
#include <WS2tcpip.h>
#define bzero(a, b) memset(a, 0, b);
#else
#include <netdb.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/un.h>
#endif
class FileServer
{
public:
FileServer()
{
_listenfd = -1;
_running = false;
_endThread = false;
}
bool listenOnTCP(int port);
void stop();
private:
bool receiveFile(int fd);
void addClient();
void loop();
// file descriptor: socket, console, etc.
int _listenfd;
int _maxfd;
std::vector<int> _fds;
std::thread _thread;
fd_set _read_set;
bool _running;
bool _endThread;
};
bool FileServer::listenOnTCP(int port)
{
int listenfd, n;
const int on = 1;
struct addrinfo hints, *res, *ressave;
char serv[30];
snprintf(serv, sizeof(serv)-1, "%d", port );
serv[sizeof(serv)-1]=0;
bzero(&hints, sizeof(struct addrinfo));
hints.ai_flags = AI_PASSIVE;
hints.ai_family = AF_INET; // AF_UNSPEC: Do we need IPv6 ?
hints.ai_socktype = SOCK_STREAM;
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
WSADATA wsaData;
n = WSAStartup(MAKEWORD(2, 2),&wsaData);
#endif
if ( (n = getaddrinfo(NULL, serv, &hints, &res)) != 0) {
fprintf(stderr,"net_listen error for %s: %s", serv, gai_strerror(n));
return false;
}
ressave = res;
do {
listenfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (listenfd < 0)
continue; /* error, try next one */
setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
if (::bind(listenfd, res->ai_addr, res->ai_addrlen) == 0)
break; /* success */
close(listenfd); /* bind error, close and try next one */
} while ( (res = res->ai_next) != NULL);
if (res == NULL) {
perror("net_listen:");
freeaddrinfo(ressave);
return false;
}
listen(listenfd, 1);
if (res->ai_family == AF_INET)
{
char buf[INET_ADDRSTRLEN] = "";
struct sockaddr_in *sin = (struct sockaddr_in*) res->ai_addr;
if( inet_ntop(res->ai_family, &sin->sin_addr, buf, sizeof(buf)) != NULL )
cocos2d::log("Console: listening on %s : %d", buf, ntohs(sin->sin_port));
else
perror("inet_ntop");
} else if (res->ai_family == AF_INET6)
{
char buf[INET6_ADDRSTRLEN] = "";
struct sockaddr_in6 *sin = (struct sockaddr_in6*) res->ai_addr;
if( inet_ntop(res->ai_family, &sin->sin6_addr, buf, sizeof(buf)) != NULL )
cocos2d::log("Console: listening on %s : %d", buf, ntohs(sin->sin6_port));
else
perror("inet_ntop");
}
freeaddrinfo(ressave);
_listenfd = listenfd;
_thread = std::thread( std::bind( &FileServer::loop, this) );
return true;
}
void FileServer::stop()
{
if( _running ) {
_endThread = true;
_thread.join();
}
}
string& replaceAll(string& str,const string& old_value,const string& new_value)
{
while(true)
{
int pos=0;
if((pos=str.find(old_value,0))!=string::npos)
str.replace(pos,old_value.length(),new_value);
else break;
}
return str;
}
bool CreateDir(const char *sPathName)
{
char DirName[256]={0};
strcpy(DirName, sPathName);
int i,len = strlen(DirName);
if(DirName[len-1]!='/')
strcat(DirName, "/");
len = strlen(DirName);
for(i=1; i<len; i++)
{
if(DirName[i]=='/')
{
DirName[i] = 0;
if(access(DirName, NULL)!=0 )
{
#ifdef _WIN32
if(mkdir(DirName/*, 0755*/)==-1)
#else
if(mkdir(DirName, 0755)==-1)
#endif
{
perror("mkdir error");
return false;
}
}
DirName[i] = '/';
}
}
return true;
}
static bool updateResFileInfo()
{
rapidjson::StringBuffer buffer;
rapidjson::Writer< rapidjson::StringBuffer > writer(buffer);
g_filecfgjson.Accept(writer);
const char* str = buffer.GetString();
string filecfg = g_resourcePath;
filecfg.append("/");
filecfg.append("fileinfo_debug.json");
FILE * pFile = fopen (filecfg.c_str() , "w");
if (!pFile)
return false;
fwrite(str,sizeof(char),strlen(str),pFile);
fclose(pFile);
return true;
}
static void readResFileFinfo()
{
string filecfg = g_resourcePath;
filecfg.append("/");
filecfg.append("fileinfo_debug.json");
FILE * pFile = fopen (filecfg.c_str() , "r");
if(pFile)
{
rapidjson::FileStream inputStream(pFile);
g_filecfgjson.ParseStream<0>(inputStream);
fclose(pFile);
}
if(!g_filecfgjson.IsObject())
{
g_filecfgjson.SetObject();
}
}
bool FileServer::receiveFile(int fd)
{
char headlen[5]={0};
if (recv(fd, headlen, 4,0)<=0) {
return false;
}
char *headSeg = new char[atoi(headlen)+1];
if (!headSeg)
{
return false;
}
memset(headSeg,0,atoi(headlen)+1);
if (recv(fd, headSeg, atoi(headlen),0)<=0) {
return false;
}
rapidjson::Document headjson;
headjson.Parse<0>(headSeg);
if (headjson.HasMember("filename"))
{
string filename = headjson["filename"].GetString();
char fullfilename[1024]={0};
sprintf(fullfilename,"%s%s",g_resourcePath.c_str(),filename.c_str());
string file(fullfilename);
file=replaceAll(file,"\\","/");
sprintf(fullfilename, "%s", file.c_str());
showCurRcvFile(filename.c_str());
cocos2d::log("recv fullfilename = %s",fullfilename);
CreateDir(file.substr(0,file.find_last_of("/")).c_str());
FILE *fp =fopen(fullfilename, "wb");
int length =0;
while ((length=recv(fd, fullfilename, sizeof(fullfilename),0)) > 0) {
fwrite(fullfilename, sizeof(char), length,fp);
}
fclose(fp);
if (headjson.HasMember("lastmodifytime"))
{
string filemodifytime = headjson["lastmodifytime"].GetString();
if (g_filecfgjson.HasMember(filename.c_str()))
{
g_filecfgjson.RemoveMember(filename.c_str());
}
rapidjson::Value filetimeValue(rapidjson::kStringType);
filetimeValue.SetString(filemodifytime.c_str(),g_filecfgjson.GetAllocator());
rapidjson::Value filenameValue(rapidjson::kStringType);
filenameValue.SetString(filename.c_str(),g_filecfgjson.GetAllocator());
g_filecfgjson.AddMember(filenameValue.GetString(),filetimeValue,g_filecfgjson.GetAllocator());
updateResFileInfo();
}
}
if (headSeg)
{
delete [] headSeg;
headSeg =nullptr;
}
string finish("finish\n");
send(fd, finish.c_str(), finish.size(),0);
return true;
}
void FileServer::addClient()
{
struct sockaddr client;
socklen_t client_len;
/* new client */
client_len = sizeof( client );
int fd = accept(_listenfd, (struct sockaddr *)&client, &client_len );
// add fd to list of FD
if( fd != -1 ) {
FD_SET(fd, &_read_set);
_fds.push_back(fd);
_maxfd = std::max(_maxfd,fd);
}
}
void FileServer::loop()
{
fd_set copy_set;
struct timeval timeout, timeout_copy;
_running = true;
FD_ZERO(&_read_set);
FD_SET(_listenfd, &_read_set);
_maxfd = _listenfd;
timeout.tv_sec = 0;
/* 0.016 seconds. Wake up once per frame at 60PFS */
timeout.tv_usec = 16000;
while(!_endThread) {
copy_set = _read_set;
timeout_copy = timeout;
int nready = select(_maxfd+1, &copy_set, NULL, NULL, &timeout_copy);
if( nready == -1 )
{
/* error */
if(errno != EINTR)
log("Abnormal error in select()\n");
continue;
}
else if( nready == 0 )
{
/* timeout. do somethig ? */
}
else
{
/* new client */
if(FD_ISSET(_listenfd, &copy_set)) {
addClient();
if(--nready <= 0)
continue;
}
/* data from client */
std::vector<int> to_remove;
for(const auto &fd: _fds) {
if(FD_ISSET(fd,&copy_set)) {
if( ! receiveFile(fd) ) {
to_remove.push_back(fd);
}
if(--nready <= 0)
break;
}
}
/* remove closed conections */
for(int fd: to_remove) {
FD_CLR(fd, &_read_set);
_fds.erase(std::remove(_fds.begin(), _fds.end(), fd), _fds.end());
}
}
}
// clean up: ignore stdin, stdout and stderr
for(const auto &fd: _fds )
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
closesocket(fd);
#else
close(fd);
#endif
}
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
closesocket(_listenfd);
WSACleanup();
#else
close(_listenfd);
#endif
_running = false;
}
class ConsoleCustomCommand
{
public:
ConsoleCustomCommand():_fileserver(nullptr)
{
cocos2d::Console *_console = Director::getInstance()->getConsole();
static struct Console::Command commands[] = {
{"sendrequest","send command to runtime.Args[json format]",std::bind(&ConsoleCustomCommand::onSendCommand, this, std::placeholders::_1, std::placeholders::_2)},
};
for (int i=0;i< sizeof(commands)/sizeof(Console::Command);i++) {
_console->addCommand(commands[i]);
}
_console->listenOnTCP(6010);
_fileserver=new FileServer();
_fileserver->listenOnTCP(6020);
}
~ConsoleCustomCommand()
{
Director::getInstance()->getConsole()->stop();
_fileserver->stop();
if (_fileserver) {
delete _fileserver;
_fileserver = nullptr;
}
}
void onSendCommand(int fd, const std::string &args)
{
Director::getInstance()->getScheduler()->performFunctionInCocosThread([=](){
rapidjson::Document dArgParse;
dArgParse.Parse<0>(args.c_str());
if (dArgParse.HasMember("cmd"))
{
string strcmd = dArgParse["cmd"].GetString();
rapidjson::Document dReplyParse;
dReplyParse.SetObject();
dReplyParse.AddMember("cmd",strcmd.c_str(),dReplyParse.GetAllocator());
if (dArgParse.HasMember("seq")) {
dReplyParse.AddMember("seq",dArgParse["seq"],dReplyParse.GetAllocator());
}
if(strcmp(strcmd.c_str(),"start-logic")==0)
{
char szDebugArg[1024]={0};
sprintf(szDebugArg, "require('debugger')(%s,'%s')",dArgParse["debugcfg"].GetString(),g_resourcePath.c_str());
startScript(szDebugArg);
dReplyParse.AddMember("code",0,dReplyParse.GetAllocator());
}else if(strcmp(strcmd.c_str(),"reload")==0)
{
if (dArgParse.HasMember("modulefiles"))
{
rapidjson::Value bodyvalue(rapidjson::kObjectType);
const rapidjson::Value& objectfiles = dArgParse["modulefiles"];
for (rapidjson::SizeType i = 0; i < objectfiles.Size(); i++)
{
if (!reloadScript(objectfiles[i].GetString())) {
bodyvalue.AddMember(objectfiles[i].GetString(),1,dReplyParse.GetAllocator());
}
}
if (0 == objectfiles.Size())
{
reloadScript("");
}
dReplyParse.AddMember("body",bodyvalue,dReplyParse.GetAllocator());
}
dReplyParse.AddMember("code",0,dReplyParse.GetAllocator());
}else if(strcmp(strcmd.c_str(),"getversion")==0)
{
rapidjson::Value bodyvalue(rapidjson::kObjectType);
bodyvalue.AddMember("version",getRuntimeVersion(),dReplyParse.GetAllocator());
dReplyParse.AddMember("body",bodyvalue,dReplyParse.GetAllocator());
dReplyParse.AddMember("code",0,dReplyParse.GetAllocator());
}else if(strcmp(strcmd.c_str(),"getfileinfo")==0)
{
rapidjson::Value bodyvalue(rapidjson::kObjectType);
for (auto it=g_filecfgjson.MemberonBegin();it!=g_filecfgjson.MemberonEnd();++it)
{
bodyvalue.AddMember(it->name.GetString(),it->value.GetString(),dReplyParse.GetAllocator());
}
dReplyParse.AddMember("body",bodyvalue,dReplyParse.GetAllocator());
dReplyParse.AddMember("code",0,dReplyParse.GetAllocator());
}else if (strcmp(strcmd.c_str(),"getEntryfile")==0)
{
rapidjson::Value bodyvalue(rapidjson::kObjectType);
rapidjson::Value entryFileValue(rapidjson::kStringType);
entryFileValue.SetString(ConfigParser::getInstance()->getEntryFile().c_str(),dReplyParse.GetAllocator());
bodyvalue.AddMember("entryfile",entryFileValue,dReplyParse.GetAllocator());
dReplyParse.AddMember("body",bodyvalue,dReplyParse.GetAllocator());
dReplyParse.AddMember("code",0,dReplyParse.GetAllocator());
}else if(strcmp(strcmd.c_str(),"getIP")==0)
{
rapidjson::Value bodyvalue(rapidjson::kObjectType);
rapidjson::Value IPValue(rapidjson::kStringType);
IPValue.SetString(getIPAddress().c_str(),dReplyParse.GetAllocator());
bodyvalue.AddMember("IP",IPValue,dReplyParse.GetAllocator());
dReplyParse.AddMember("body",bodyvalue,dReplyParse.GetAllocator());
dReplyParse.AddMember("code",0,dReplyParse.GetAllocator());
}else if(strcmp(strcmd.c_str(),"updatefileinfo")==0)
{
if(updateResFileInfo())
{
dReplyParse.AddMember("code",0,dReplyParse.GetAllocator());
}else
{
dReplyParse.AddMember("code",1,dReplyParse.GetAllocator());
}
}else if(strcmp(strcmd.c_str(),"remove")==0)
{
if (dArgParse.HasMember("files"))
{
rapidjson::Value bodyvalue(rapidjson::kObjectType);
const rapidjson::Value& objectfiles = dArgParse["files"];
for (rapidjson::SizeType i = 0; i < objectfiles.Size(); i++)
{
string filename(g_resourcePath);
filename.append("/");
filename.append(objectfiles[i].GetString());
if (FileUtils::getInstance()->isFileExist(filename))
{
if(remove(filename.c_str())==0)
{
if (g_filecfgjson.HasMember(objectfiles[i].GetString())) {
g_filecfgjson.RemoveMember(objectfiles[i].GetString());
}
}
else
{
bodyvalue.AddMember(objectfiles[i].GetString(),2,dReplyParse.GetAllocator());
}
}else
{
bodyvalue.AddMember(objectfiles[i].GetString(),1,dReplyParse.GetAllocator());
}
}
dReplyParse.AddMember("body",bodyvalue,dReplyParse.GetAllocator());
updateResFileInfo();
}
dReplyParse.AddMember("code",0,dReplyParse.GetAllocator());
}else if(strcmp(strcmd.c_str(),"shutdownapp")==0)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
extern void shutDownApp();
shutDownApp();
#else
exit(0);
#endif
}
rapidjson::StringBuffer buffer;
rapidjson::Writer< rapidjson::StringBuffer > writer(buffer);
dReplyParse.Accept(writer);
const char* str = buffer.GetString();
char msgSize[64]={0x1,0};
sprintf(msgSize+1,"%d:",strlen(str));
string replymsg(msgSize);
replymsg.append(str);
send(fd,replymsg.c_str(),replymsg.size(),0);
}
});
}
private:
FileServer* _fileserver;
};
int lua_cocos2dx_runtime_addSearchPath(lua_State* tolua_S)
{
int argc = 0;
cocos2d::FileUtils* 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.FileUtils",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::FileUtils*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_FileUtils_addSearchPath'", 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);
if(!ok)
return 0;
if (!FileUtils::getInstance()->isAbsolutePath(arg0))
arg0 = g_resourcePath+arg0;
cobj->addSearchPath(arg0);
return 0;
}
CCLOG("%s has wrong number of arguments: %d, was expecting %d \n", "addSearchPath",argc, 1);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_FileUtils_addSearchPath'.",&tolua_err);
#endif
return 0;
}
static void register_runtime_override_function(lua_State* tolua_S)
{
lua_pushstring(tolua_S, "cc.FileUtils");
lua_rawget(tolua_S, LUA_REGISTRYINDEX);
if (lua_istable(tolua_S,-1))
{
tolua_function(tolua_S,"addSearchPath",lua_cocos2dx_runtime_addSearchPath);
}
lua_pop(tolua_S, 1);
}
bool initRuntime()
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
#ifndef _DEBUG
return false;
#endif
#elif(CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#ifdef NDEBUG
return false;
#endif
#elif(CC_TARGET_PLATFORM == CC_PLATFORM_MAC || CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
#ifndef COCOS2D_DEBUG
return false;
#endif
#endif
vector<string> searchPathArray;
searchPathArray=FileUtils::getInstance()->getSearchPaths();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 || CC_TARGET_PLATFORM == CC_PLATFORM_MAC)
if (g_resourcePath.empty())
{
extern std::string getCurAppPath();
string resourcePath = getCurAppPath();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
resourcePath.append("/../../");
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_MAC)
resourcePath.append("/../../../");
#endif
resourcePath =replaceAll(resourcePath,"\\","/");
g_resourcePath = resourcePath;
}
#else
g_resourcePath = FileUtils::getInstance()->getWritablePath();
g_resourcePath += "debugruntime/";
#endif
g_resourcePath=replaceAll(g_resourcePath,"\\","/");
if (g_resourcePath.at(g_resourcePath.length()-1) != '/')
{
g_resourcePath.append("/");
}
searchPathArray.insert(searchPathArray.begin(),g_resourcePath);
FileUtils::getInstance()->setSearchPaths(searchPathArray);
return true;
}
bool startRuntime()
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
#ifndef _DEBUG
return false;
#endif
#elif(CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#ifdef NDEBUG
return false;
#endif
#elif(CC_TARGET_PLATFORM == CC_PLATFORM_MAC || CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
#ifndef COCOS2D_DEBUG
return false;
#endif
#endif
static ConsoleCustomCommand s_customCommand;
auto engine = LuaEngine::getInstance();
ScriptEngineManager::getInstance()->setScriptEngine(engine);
LuaStack* stack = engine->getLuaStack();
register_runtime_override_function(stack->getLuaState());
luaopen_debugger(engine->getLuaStack()->getLuaState());
readResFileFinfo();
auto scene = Scene::create();
s_pConnectLayer = new ConnectWaitLayer();
s_pConnectLayer->autorelease();
auto director = Director::getInstance();
scene->addChild(s_pConnectLayer);
director->runWithScene(scene);
return true;
}

View File

@ -0,0 +1,185 @@
/* Version number of package */
#define VERSION "2.5.0"
#ifdef _WIN32
/* protobuf config.h for MSVC. On other platforms, this is generated
* automatically by autoheader / autoconf / configure. */
/* the location of <hash_map> */
#define HASH_MAP_H <hash_map>
/* the namespace of hash_map/hash_set */
// Apparently Microsoft decided to move hash_map *back* to the std namespace
// in MSVC 2010:
// http://blogs.msdn.com/vcblog/archive/2009/05/25/stl-breaking-changes-in-visual-studio-2010-beta-1.aspx
// TODO(kenton): Use unordered_map instead, which is available in MSVC 2010.
#if _MSC_VER < 1310 || _MSC_VER >= 1600
#define HASH_NAMESPACE std
#else
#define HASH_NAMESPACE stdext
#endif
/* the location of <hash_set> */
#define HASH_SET_H <hash_set>
/* define if the compiler has hash_map */
#define HAVE_HASH_MAP 1
/* define if the compiler has hash_set */
#define HAVE_HASH_SET 1
/* define if you want to use zlib. See readme.txt for additional
* requirements. */
// #define HAVE_ZLIB 1
#else
/* config.h. Generated from config.h.in by configure. */
/* config.h.in. Generated from configure.ac by autoheader. */
/* the name of <hash_map> */
#define HASH_MAP_CLASS unordered_map
/* the location of <unordered_map> or <hash_map> */
#define HASH_MAP_H <unordered_map>
/* the namespace of hash_map/hash_set */
#define HASH_NAMESPACE std
/* the name of <hash_set> */
#define HASH_SET_CLASS unordered_set
/* the location of <unordered_set> or <hash_set> */
#define HASH_SET_H <unordered_set>
/* Define to 1 if you have the <dlfcn.h> header file. */
#define HAVE_DLFCN_H 1
/* Define to 1 if you have the <fcntl.h> header file. */
#define HAVE_FCNTL_H 1
/* Define to 1 if you have the `ftruncate' function. */
#define HAVE_FTRUNCATE 1
/* define if the compiler has hash_map */
#define HAVE_HASH_MAP 1
/* define if the compiler has hash_set */
#define HAVE_HASH_SET 1
/* Define to 1 if you have the <inttypes.h> header file. */
#define HAVE_INTTYPES_H 1
/* Define to 1 if you have the <limits.h> header file. */
#define HAVE_LIMITS_H 1
/* Define to 1 if you have the <memory.h> header file. */
#define HAVE_MEMORY_H 1
/* Define to 1 if you have the `memset' function. */
#define HAVE_MEMSET 1
/* Define to 1 if you have the `mkdir' function. */
#define HAVE_MKDIR 1
/* Define if you have POSIX threads libraries and header files. */
#define HAVE_PTHREAD 1
/* Define to 1 if you have the <stdint.h> header file. */
#define HAVE_STDINT_H 1
/* Define to 1 if you have the <stdlib.h> header file. */
#define HAVE_STDLIB_H 1
/* Define to 1 if you have the `strchr' function. */
#define HAVE_STRCHR 1
/* Define to 1 if you have the `strerror' function. */
#define HAVE_STRERROR 1
/* Define to 1 if you have the <strings.h> header file. */
#define HAVE_STRINGS_H 1
/* Define to 1 if you have the <string.h> header file. */
#define HAVE_STRING_H 1
/* Define to 1 if you have the `strtol' function. */
#define HAVE_STRTOL 1
/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H 1
/* Define to 1 if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H 1
/* Define to 1 if you have the <unistd.h> header file. */
#define HAVE_UNISTD_H 1
/* Enable classes using zlib compression. */
#define HAVE_ZLIB 1
/* Define to the sub-directory in which libtool stores uninstalled libraries.
*/
#define LT_OBJDIR ".libs/"
/* Name of package */
#define PACKAGE "protobuf"
/* Define to the address where bug reports for this package should be sent. */
#define PACKAGE_BUGREPORT "protobuf@googlegroups.com"
/* Define to the full name of this package. */
#define PACKAGE_NAME "Protocol Buffers"
/* Define to the full name and version of this package. */
#define PACKAGE_STRING "Protocol Buffers 2.5.0"
/* Define to the one symbol short name of this package. */
#define PACKAGE_TARNAME "protobuf"
/* Define to the home page for this package. */
#define PACKAGE_URL ""
/* Define to the version of this package. */
#define PACKAGE_VERSION "2.5.0"
/* Define to necessary symbol if this constant uses a non-standard name on
your system. */
/* #undef PTHREAD_CREATE_JOINABLE */
/* Define to 1 if you have the ANSI C header files. */
#define STDC_HEADERS 1
/* Enable extensions on AIX 3, Interix. */
#ifndef _ALL_SOURCE
# define _ALL_SOURCE 1
#endif
/* Enable GNU extensions on systems that have them. */
#ifndef _GNU_SOURCE
# define _GNU_SOURCE 1
#endif
/* Enable threading extensions on Solaris. */
#ifndef _POSIX_PTHREAD_SEMANTICS
# define _POSIX_PTHREAD_SEMANTICS 1
#endif
/* Enable extensions on HP NonStop. */
#ifndef _TANDEM_SOURCE
# define _TANDEM_SOURCE 1
#endif
/* Enable general extensions on Solaris. */
#ifndef __EXTENSIONS__
# define __EXTENSIONS__ 1
#endif
/* Define to 1 if on MINIX. */
/* #undef _MINIX */
/* Define to 2 if the system does not provide POSIX.1 features except with
this defined. */
/* #undef _POSIX_1_SOURCE */
/* Define to 1 if you need to in order for `stat' and other things to work. */
/* #undef _POSIX_SOURCE */
#endif

View File

@ -0,0 +1,54 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
#include <google/protobuf/generated_message_util.h>
#include <limits>
namespace google {
namespace protobuf {
namespace internal {
double Infinity() {
return std::numeric_limits<double>::infinity();
}
double NaN() {
return std::numeric_limits<double>::quiet_NaN();
}
const ::std::string kEmptyString;
} // namespace internal
} // namespace protobuf
} // namespace google

View File

@ -0,0 +1,77 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// This file contains miscellaneous helper code used by generated code --
// including lite types -- but which should not be used directly by users.
#ifndef GOOGLE_PROTOBUF_GENERATED_MESSAGE_UTIL_H__
#define GOOGLE_PROTOBUF_GENERATED_MESSAGE_UTIL_H__
#include <string>
#include <google/protobuf/stubs/common.h>
namespace google {
namespace protobuf {
namespace internal {
// Annotation for the compiler to emit a deprecation message if a field marked
// with option 'deprecated=true' is used in the code, or for other things in
// generated code which are deprecated.
//
// For internal use in the pb.cc files, deprecation warnings are suppressed
// there.
#undef DEPRECATED_PROTOBUF_FIELD
#define PROTOBUF_DEPRECATED
// Constants for special floating point values.
LIBPROTOBUF_EXPORT double Infinity();
LIBPROTOBUF_EXPORT double NaN();
// Constant used for empty default strings.
LIBPROTOBUF_EXPORT extern const ::std::string kEmptyString;
// Defined in generated_message_reflection.cc -- not actually part of the lite
// library.
//
// TODO(jasonh): The various callers get this declaration from a variety of
// places: probably in most cases repeated_field.h. Clean these up so they all
// get the declaration from this file.
LIBPROTOBUF_EXPORT int StringSpaceUsedExcludingSelf(const string& str);
} // namespace internal
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_GENERATED_MESSAGE_UTIL_H__

View File

@ -0,0 +1,857 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// This implementation is heavily optimized to make reads and writes
// of small values (especially varints) as fast as possible. In
// particular, we optimize for the common case that a read or a write
// will not cross the end of the buffer, since we can avoid a lot
// of branching in this case.
#include <google/protobuf/io/coded_stream_inl.h>
#include <algorithm>
#include <limits.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/stl_util.h>
namespace google {
namespace protobuf {
namespace io {
namespace {
static const int kMaxVarintBytes = 10;
static const int kMaxVarint32Bytes = 5;
inline bool NextNonEmpty(ZeroCopyInputStream* input,
const void** data, int* size) {
bool success;
do {
success = input->Next(data, size);
} while (success && *size == 0);
return success;
}
} // namespace
// CodedInputStream ==================================================
CodedInputStream::~CodedInputStream() {
if (input_ != NULL) {
BackUpInputToCurrentPosition();
}
if (total_bytes_warning_threshold_ == -2) {
GOOGLE_LOG(WARNING) << "The total number of bytes read was " << total_bytes_read_;
}
}
// Static.
int CodedInputStream::default_recursion_limit_ = 100;
void CodedInputStream::BackUpInputToCurrentPosition() {
int backup_bytes = BufferSize() + buffer_size_after_limit_ + overflow_bytes_;
if (backup_bytes > 0) {
input_->BackUp(backup_bytes);
// total_bytes_read_ doesn't include overflow_bytes_.
total_bytes_read_ -= BufferSize() + buffer_size_after_limit_;
buffer_end_ = buffer_;
buffer_size_after_limit_ = 0;
overflow_bytes_ = 0;
}
}
inline void CodedInputStream::RecomputeBufferLimits() {
buffer_end_ += buffer_size_after_limit_;
int closest_limit = min(current_limit_, total_bytes_limit_);
if (closest_limit < total_bytes_read_) {
// The limit position is in the current buffer. We must adjust
// the buffer size accordingly.
buffer_size_after_limit_ = total_bytes_read_ - closest_limit;
buffer_end_ -= buffer_size_after_limit_;
} else {
buffer_size_after_limit_ = 0;
}
}
CodedInputStream::Limit CodedInputStream::PushLimit(int byte_limit) {
// Current position relative to the beginning of the stream.
int current_position = CurrentPosition();
Limit old_limit = current_limit_;
// security: byte_limit is possibly evil, so check for negative values
// and overflow.
if (byte_limit >= 0 &&
byte_limit <= INT_MAX - current_position) {
current_limit_ = current_position + byte_limit;
} else {
// Negative or overflow.
current_limit_ = INT_MAX;
}
// We need to enforce all limits, not just the new one, so if the previous
// limit was before the new requested limit, we continue to enforce the
// previous limit.
current_limit_ = min(current_limit_, old_limit);
RecomputeBufferLimits();
return old_limit;
}
void CodedInputStream::PopLimit(Limit limit) {
// The limit passed in is actually the *old* limit, which we returned from
// PushLimit().
current_limit_ = limit;
RecomputeBufferLimits();
// We may no longer be at a legitimate message end. ReadTag() needs to be
// called again to find out.
legitimate_message_end_ = false;
}
int CodedInputStream::BytesUntilLimit() const {
if (current_limit_ == INT_MAX) return -1;
int current_position = CurrentPosition();
return current_limit_ - current_position;
}
void CodedInputStream::SetTotalBytesLimit(
int total_bytes_limit, int warning_threshold) {
// Make sure the limit isn't already past, since this could confuse other
// code.
int current_position = CurrentPosition();
total_bytes_limit_ = max(current_position, total_bytes_limit);
if (warning_threshold >= 0) {
total_bytes_warning_threshold_ = warning_threshold;
} else {
// warning_threshold is negative
total_bytes_warning_threshold_ = -1;
}
RecomputeBufferLimits();
}
void CodedInputStream::PrintTotalBytesLimitError() {
GOOGLE_LOG(ERROR) << "A protocol message was rejected because it was too "
"big (more than " << total_bytes_limit_
<< " bytes). To increase the limit (or to disable these "
"warnings), see CodedInputStream::SetTotalBytesLimit() "
"in google/protobuf/io/coded_stream.h.";
}
bool CodedInputStream::Skip(int count) {
if (count < 0) return false; // security: count is often user-supplied
const int original_buffer_size = BufferSize();
if (count <= original_buffer_size) {
// Just skipping within the current buffer. Easy.
Advance(count);
return true;
}
if (buffer_size_after_limit_ > 0) {
// We hit a limit inside this buffer. Advance to the limit and fail.
Advance(original_buffer_size);
return false;
}
count -= original_buffer_size;
buffer_ = NULL;
buffer_end_ = buffer_;
// Make sure this skip doesn't try to skip past the current limit.
int closest_limit = min(current_limit_, total_bytes_limit_);
int bytes_until_limit = closest_limit - total_bytes_read_;
if (bytes_until_limit < count) {
// We hit the limit. Skip up to it then fail.
if (bytes_until_limit > 0) {
total_bytes_read_ = closest_limit;
input_->Skip(bytes_until_limit);
}
return false;
}
total_bytes_read_ += count;
return input_->Skip(count);
}
bool CodedInputStream::GetDirectBufferPointer(const void** data, int* size) {
if (BufferSize() == 0 && !Refresh()) return false;
*data = buffer_;
*size = BufferSize();
return true;
}
bool CodedInputStream::ReadRaw(void* buffer, int size) {
int current_buffer_size;
while ((current_buffer_size = BufferSize()) < size) {
// Reading past end of buffer. Copy what we have, then refresh.
memcpy(buffer, buffer_, current_buffer_size);
buffer = reinterpret_cast<uint8*>(buffer) + current_buffer_size;
size -= current_buffer_size;
Advance(current_buffer_size);
if (!Refresh()) return false;
}
memcpy(buffer, buffer_, size);
Advance(size);
return true;
}
bool CodedInputStream::ReadString(string* buffer, int size) {
if (size < 0) return false; // security: size is often user-supplied
return InternalReadStringInline(buffer, size);
}
bool CodedInputStream::ReadStringFallback(string* buffer, int size) {
if (!buffer->empty()) {
buffer->clear();
}
int current_buffer_size;
while ((current_buffer_size = BufferSize()) < size) {
// Some STL implementations "helpfully" crash on buffer->append(NULL, 0).
if (current_buffer_size != 0) {
// Note: string1.append(string2) is O(string2.size()) (as opposed to
// O(string1.size() + string2.size()), which would be bad).
buffer->append(reinterpret_cast<const char*>(buffer_),
current_buffer_size);
}
size -= current_buffer_size;
Advance(current_buffer_size);
if (!Refresh()) return false;
}
buffer->append(reinterpret_cast<const char*>(buffer_), size);
Advance(size);
return true;
}
bool CodedInputStream::ReadLittleEndian32Fallback(uint32* value) {
uint8 bytes[sizeof(*value)];
const uint8* ptr;
if (BufferSize() >= sizeof(*value)) {
// Fast path: Enough bytes in the buffer to read directly.
ptr = buffer_;
Advance(sizeof(*value));
} else {
// Slow path: Had to read past the end of the buffer.
if (!ReadRaw(bytes, sizeof(*value))) return false;
ptr = bytes;
}
ReadLittleEndian32FromArray(ptr, value);
return true;
}
bool CodedInputStream::ReadLittleEndian64Fallback(uint64* value) {
uint8 bytes[sizeof(*value)];
const uint8* ptr;
if (BufferSize() >= sizeof(*value)) {
// Fast path: Enough bytes in the buffer to read directly.
ptr = buffer_;
Advance(sizeof(*value));
} else {
// Slow path: Had to read past the end of the buffer.
if (!ReadRaw(bytes, sizeof(*value))) return false;
ptr = bytes;
}
ReadLittleEndian64FromArray(ptr, value);
return true;
}
namespace {
inline const uint8* ReadVarint32FromArray(
const uint8* buffer, uint32* value) GOOGLE_ATTRIBUTE_ALWAYS_INLINE;
inline const uint8* ReadVarint32FromArray(const uint8* buffer, uint32* value) {
// Fast path: We have enough bytes left in the buffer to guarantee that
// this read won't cross the end, so we can skip the checks.
const uint8* ptr = buffer;
uint32 b;
uint32 result;
b = *(ptr++); result = (b & 0x7F) ; if (!(b & 0x80)) goto done;
b = *(ptr++); result |= (b & 0x7F) << 7; if (!(b & 0x80)) goto done;
b = *(ptr++); result |= (b & 0x7F) << 14; if (!(b & 0x80)) goto done;
b = *(ptr++); result |= (b & 0x7F) << 21; if (!(b & 0x80)) goto done;
b = *(ptr++); result |= b << 28; if (!(b & 0x80)) goto done;
// If the input is larger than 32 bits, we still need to read it all
// and discard the high-order bits.
for (int i = 0; i < kMaxVarintBytes - kMaxVarint32Bytes; i++) {
b = *(ptr++); if (!(b & 0x80)) goto done;
}
// We have overrun the maximum size of a varint (10 bytes). Assume
// the data is corrupt.
return NULL;
done:
*value = result;
return ptr;
}
} // namespace
bool CodedInputStream::ReadVarint32Slow(uint32* value) {
uint64 result;
// Directly invoke ReadVarint64Fallback, since we already tried to optimize
// for one-byte varints.
if (!ReadVarint64Fallback(&result)) return false;
*value = (uint32)result;
return true;
}
bool CodedInputStream::ReadVarint32Fallback(uint32* value) {
if (BufferSize() >= kMaxVarintBytes ||
// Optimization: If the varint ends at exactly the end of the buffer,
// we can detect that and still use the fast path.
(buffer_end_ > buffer_ && !(buffer_end_[-1] & 0x80))) {
const uint8* end = ReadVarint32FromArray(buffer_, value);
if (end == NULL) return false;
buffer_ = end;
return true;
} else {
// Really slow case: we will incur the cost of an extra function call here,
// but moving this out of line reduces the size of this function, which
// improves the common case. In micro benchmarks, this is worth about 10-15%
return ReadVarint32Slow(value);
}
}
uint32 CodedInputStream::ReadTagSlow() {
if (buffer_ == buffer_end_) {
// Call refresh.
if (!Refresh()) {
// Refresh failed. Make sure that it failed due to EOF, not because
// we hit total_bytes_limit_, which, unlike normal limits, is not a
// valid place to end a message.
int current_position = total_bytes_read_ - buffer_size_after_limit_;
if (current_position >= total_bytes_limit_) {
// Hit total_bytes_limit_. But if we also hit the normal limit,
// we're still OK.
legitimate_message_end_ = current_limit_ == total_bytes_limit_;
} else {
legitimate_message_end_ = true;
}
return 0;
}
}
// For the slow path, just do a 64-bit read. Try to optimize for one-byte tags
// again, since we have now refreshed the buffer.
uint64 result = 0;
if (!ReadVarint64(&result)) return 0;
return static_cast<uint32>(result);
}
uint32 CodedInputStream::ReadTagFallback() {
const int buf_size = BufferSize();
if (buf_size >= kMaxVarintBytes ||
// Optimization: If the varint ends at exactly the end of the buffer,
// we can detect that and still use the fast path.
(buf_size > 0 && !(buffer_end_[-1] & 0x80))) {
uint32 tag;
const uint8* end = ReadVarint32FromArray(buffer_, &tag);
if (end == NULL) {
return 0;
}
buffer_ = end;
return tag;
} else {
// We are commonly at a limit when attempting to read tags. Try to quickly
// detect this case without making another function call.
if ((buf_size == 0) &&
((buffer_size_after_limit_ > 0) ||
(total_bytes_read_ == current_limit_)) &&
// Make sure that the limit we hit is not total_bytes_limit_, since
// in that case we still need to call Refresh() so that it prints an
// error.
total_bytes_read_ - buffer_size_after_limit_ < total_bytes_limit_) {
// We hit a byte limit.
legitimate_message_end_ = true;
return 0;
}
return ReadTagSlow();
}
}
bool CodedInputStream::ReadVarint64Slow(uint64* value) {
// Slow path: This read might cross the end of the buffer, so we
// need to check and refresh the buffer if and when it does.
uint64 result = 0;
int count = 0;
uint32 b;
do {
if (count == kMaxVarintBytes) return false;
while (buffer_ == buffer_end_) {
if (!Refresh()) return false;
}
b = *buffer_;
result |= static_cast<uint64>(b & 0x7F) << (7 * count);
Advance(1);
++count;
} while (b & 0x80);
*value = result;
return true;
}
bool CodedInputStream::ReadVarint64Fallback(uint64* value) {
if (BufferSize() >= kMaxVarintBytes ||
// Optimization: If the varint ends at exactly the end of the buffer,
// we can detect that and still use the fast path.
(buffer_end_ > buffer_ && !(buffer_end_[-1] & 0x80))) {
// Fast path: We have enough bytes left in the buffer to guarantee that
// this read won't cross the end, so we can skip the checks.
const uint8* ptr = buffer_;
uint32 b;
// Splitting into 32-bit pieces gives better performance on 32-bit
// processors.
uint32 part0 = 0, part1 = 0, part2 = 0;
b = *(ptr++); part0 = (b & 0x7F) ; if (!(b & 0x80)) goto done;
b = *(ptr++); part0 |= (b & 0x7F) << 7; if (!(b & 0x80)) goto done;
b = *(ptr++); part0 |= (b & 0x7F) << 14; if (!(b & 0x80)) goto done;
b = *(ptr++); part0 |= (b & 0x7F) << 21; if (!(b & 0x80)) goto done;
b = *(ptr++); part1 = (b & 0x7F) ; if (!(b & 0x80)) goto done;
b = *(ptr++); part1 |= (b & 0x7F) << 7; if (!(b & 0x80)) goto done;
b = *(ptr++); part1 |= (b & 0x7F) << 14; if (!(b & 0x80)) goto done;
b = *(ptr++); part1 |= (b & 0x7F) << 21; if (!(b & 0x80)) goto done;
b = *(ptr++); part2 = (b & 0x7F) ; if (!(b & 0x80)) goto done;
b = *(ptr++); part2 |= (b & 0x7F) << 7; if (!(b & 0x80)) goto done;
// We have overrun the maximum size of a varint (10 bytes). The data
// must be corrupt.
return false;
done:
Advance(ptr - buffer_);
*value = (static_cast<uint64>(part0) ) |
(static_cast<uint64>(part1) << 28) |
(static_cast<uint64>(part2) << 56);
return true;
} else {
return ReadVarint64Slow(value);
}
}
bool CodedInputStream::Refresh() {
GOOGLE_DCHECK_EQ(0, BufferSize());
if (buffer_size_after_limit_ > 0 || overflow_bytes_ > 0 ||
total_bytes_read_ == current_limit_) {
// We've hit a limit. Stop.
int current_position = total_bytes_read_ - buffer_size_after_limit_;
if (current_position >= total_bytes_limit_ &&
total_bytes_limit_ != current_limit_) {
// Hit total_bytes_limit_.
PrintTotalBytesLimitError();
}
return false;
}
if (total_bytes_warning_threshold_ >= 0 &&
total_bytes_read_ >= total_bytes_warning_threshold_) {
GOOGLE_LOG(WARNING) << "Reading dangerously large protocol message. If the "
"message turns out to be larger than "
<< total_bytes_limit_ << " bytes, parsing will be halted "
"for security reasons. To increase the limit (or to "
"disable these warnings), see "
"CodedInputStream::SetTotalBytesLimit() in "
"google/protobuf/io/coded_stream.h.";
// Don't warn again for this stream, and print total size at the end.
total_bytes_warning_threshold_ = -2;
}
const void* void_buffer;
int buffer_size;
if (NextNonEmpty(input_, &void_buffer, &buffer_size)) {
buffer_ = reinterpret_cast<const uint8*>(void_buffer);
buffer_end_ = buffer_ + buffer_size;
GOOGLE_CHECK_GE(buffer_size, 0);
if (total_bytes_read_ <= INT_MAX - buffer_size) {
total_bytes_read_ += buffer_size;
} else {
// Overflow. Reset buffer_end_ to not include the bytes beyond INT_MAX.
// We can't get that far anyway, because total_bytes_limit_ is guaranteed
// to be less than it. We need to keep track of the number of bytes
// we discarded, though, so that we can call input_->BackUp() to back
// up over them on destruction.
// The following line is equivalent to:
// overflow_bytes_ = total_bytes_read_ + buffer_size - INT_MAX;
// except that it avoids overflows. Signed integer overflow has
// undefined results according to the C standard.
overflow_bytes_ = total_bytes_read_ - (INT_MAX - buffer_size);
buffer_end_ -= overflow_bytes_;
total_bytes_read_ = INT_MAX;
}
RecomputeBufferLimits();
return true;
} else {
buffer_ = NULL;
buffer_end_ = NULL;
return false;
}
}
// CodedOutputStream =================================================
CodedOutputStream::CodedOutputStream(ZeroCopyOutputStream* output)
: output_(output),
buffer_(NULL),
buffer_size_(0),
total_bytes_(0),
had_error_(false) {
// Eagerly Refresh() so buffer space is immediately available.
Refresh();
// The Refresh() may have failed. If the client doesn't write any data,
// though, don't consider this an error. If the client does write data, then
// another Refresh() will be attempted and it will set the error once again.
had_error_ = false;
}
CodedOutputStream::~CodedOutputStream() {
if (buffer_size_ > 0) {
output_->BackUp(buffer_size_);
}
}
bool CodedOutputStream::Skip(int count) {
if (count < 0) return false;
while (count > buffer_size_) {
count -= buffer_size_;
if (!Refresh()) return false;
}
Advance(count);
return true;
}
bool CodedOutputStream::GetDirectBufferPointer(void** data, int* size) {
if (buffer_size_ == 0 && !Refresh()) return false;
*data = buffer_;
*size = buffer_size_;
return true;
}
void CodedOutputStream::WriteRaw(const void* data, int size) {
while (buffer_size_ < size) {
memcpy(buffer_, data, buffer_size_);
size -= buffer_size_;
data = reinterpret_cast<const uint8*>(data) + buffer_size_;
if (!Refresh()) return;
}
memcpy(buffer_, data, size);
Advance(size);
}
uint8* CodedOutputStream::WriteRawToArray(
const void* data, int size, uint8* target) {
memcpy(target, data, size);
return target + size;
}
void CodedOutputStream::WriteLittleEndian32(uint32 value) {
uint8 bytes[sizeof(value)];
bool use_fast = buffer_size_ >= sizeof(value);
uint8* ptr = use_fast ? buffer_ : bytes;
WriteLittleEndian32ToArray(value, ptr);
if (use_fast) {
Advance(sizeof(value));
} else {
WriteRaw(bytes, sizeof(value));
}
}
void CodedOutputStream::WriteLittleEndian64(uint64 value) {
uint8 bytes[sizeof(value)];
bool use_fast = buffer_size_ >= sizeof(value);
uint8* ptr = use_fast ? buffer_ : bytes;
WriteLittleEndian64ToArray(value, ptr);
if (use_fast) {
Advance(sizeof(value));
} else {
WriteRaw(bytes, sizeof(value));
}
}
inline uint8* CodedOutputStream::WriteVarint32FallbackToArrayInline(
uint32 value, uint8* target) {
target[0] = static_cast<uint8>(value | 0x80);
if (value >= (1 << 7)) {
target[1] = static_cast<uint8>((value >> 7) | 0x80);
if (value >= (1 << 14)) {
target[2] = static_cast<uint8>((value >> 14) | 0x80);
if (value >= (1 << 21)) {
target[3] = static_cast<uint8>((value >> 21) | 0x80);
if (value >= (1 << 28)) {
target[4] = static_cast<uint8>(value >> 28);
return target + 5;
} else {
target[3] &= 0x7F;
return target + 4;
}
} else {
target[2] &= 0x7F;
return target + 3;
}
} else {
target[1] &= 0x7F;
return target + 2;
}
} else {
target[0] &= 0x7F;
return target + 1;
}
}
void CodedOutputStream::WriteVarint32(uint32 value) {
if (buffer_size_ >= kMaxVarint32Bytes) {
// Fast path: We have enough bytes left in the buffer to guarantee that
// this write won't cross the end, so we can skip the checks.
uint8* target = buffer_;
uint8* end = WriteVarint32FallbackToArrayInline(value, target);
int size = end - target;
Advance(size);
} else {
// Slow path: This write might cross the end of the buffer, so we
// compose the bytes first then use WriteRaw().
uint8 bytes[kMaxVarint32Bytes];
int size = 0;
while (value > 0x7F) {
bytes[size++] = (static_cast<uint8>(value) & 0x7F) | 0x80;
value >>= 7;
}
bytes[size++] = static_cast<uint8>(value) & 0x7F;
WriteRaw(bytes, size);
}
}
uint8* CodedOutputStream::WriteVarint32FallbackToArray(
uint32 value, uint8* target) {
return WriteVarint32FallbackToArrayInline(value, target);
}
inline uint8* CodedOutputStream::WriteVarint64ToArrayInline(
uint64 value, uint8* target) {
// Splitting into 32-bit pieces gives better performance on 32-bit
// processors.
uint32 part0 = static_cast<uint32>(value );
uint32 part1 = static_cast<uint32>(value >> 28);
uint32 part2 = static_cast<uint32>(value >> 56);
int size;
// Here we can't really optimize for small numbers, since the value is
// split into three parts. Cheking for numbers < 128, for instance,
// would require three comparisons, since you'd have to make sure part1
// and part2 are zero. However, if the caller is using 64-bit integers,
// it is likely that they expect the numbers to often be very large, so
// we probably don't want to optimize for small numbers anyway. Thus,
// we end up with a hardcoded binary search tree...
if (part2 == 0) {
if (part1 == 0) {
if (part0 < (1 << 14)) {
if (part0 < (1 << 7)) {
size = 1; goto size1;
} else {
size = 2; goto size2;
}
} else {
if (part0 < (1 << 21)) {
size = 3; goto size3;
} else {
size = 4; goto size4;
}
}
} else {
if (part1 < (1 << 14)) {
if (part1 < (1 << 7)) {
size = 5; goto size5;
} else {
size = 6; goto size6;
}
} else {
if (part1 < (1 << 21)) {
size = 7; goto size7;
} else {
size = 8; goto size8;
}
}
}
} else {
if (part2 < (1 << 7)) {
size = 9; goto size9;
} else {
size = 10; goto size10;
}
}
GOOGLE_LOG(FATAL) << "Can't get here.";
size10: target[9] = static_cast<uint8>((part2 >> 7) | 0x80);
size9 : target[8] = static_cast<uint8>((part2 ) | 0x80);
size8 : target[7] = static_cast<uint8>((part1 >> 21) | 0x80);
size7 : target[6] = static_cast<uint8>((part1 >> 14) | 0x80);
size6 : target[5] = static_cast<uint8>((part1 >> 7) | 0x80);
size5 : target[4] = static_cast<uint8>((part1 ) | 0x80);
size4 : target[3] = static_cast<uint8>((part0 >> 21) | 0x80);
size3 : target[2] = static_cast<uint8>((part0 >> 14) | 0x80);
size2 : target[1] = static_cast<uint8>((part0 >> 7) | 0x80);
size1 : target[0] = static_cast<uint8>((part0 ) | 0x80);
target[size-1] &= 0x7F;
return target + size;
}
void CodedOutputStream::WriteVarint64(uint64 value) {
if (buffer_size_ >= kMaxVarintBytes) {
// Fast path: We have enough bytes left in the buffer to guarantee that
// this write won't cross the end, so we can skip the checks.
uint8* target = buffer_;
uint8* end = WriteVarint64ToArrayInline(value, target);
int size = end - target;
Advance(size);
} else {
// Slow path: This write might cross the end of the buffer, so we
// compose the bytes first then use WriteRaw().
uint8 bytes[kMaxVarintBytes];
int size = 0;
while (value > 0x7F) {
bytes[size++] = (static_cast<uint8>(value) & 0x7F) | 0x80;
value >>= 7;
}
bytes[size++] = static_cast<uint8>(value) & 0x7F;
WriteRaw(bytes, size);
}
}
uint8* CodedOutputStream::WriteVarint64ToArray(
uint64 value, uint8* target) {
return WriteVarint64ToArrayInline(value, target);
}
bool CodedOutputStream::Refresh() {
void* void_buffer;
if (output_->Next(&void_buffer, &buffer_size_)) {
buffer_ = reinterpret_cast<uint8*>(void_buffer);
total_bytes_ += buffer_size_;
return true;
} else {
buffer_ = NULL;
buffer_size_ = 0;
had_error_ = true;
return false;
}
}
int CodedOutputStream::VarintSize32Fallback(uint32 value) {
if (value < (1 << 7)) {
return 1;
} else if (value < (1 << 14)) {
return 2;
} else if (value < (1 << 21)) {
return 3;
} else if (value < (1 << 28)) {
return 4;
} else {
return 5;
}
}
int CodedOutputStream::VarintSize64(uint64 value) {
if (value < (1ull << 35)) {
if (value < (1ull << 7)) {
return 1;
} else if (value < (1ull << 14)) {
return 2;
} else if (value < (1ull << 21)) {
return 3;
} else if (value < (1ull << 28)) {
return 4;
} else {
return 5;
}
} else {
if (value < (1ull << 42)) {
return 6;
} else if (value < (1ull << 49)) {
return 7;
} else if (value < (1ull << 56)) {
return 8;
} else if (value < (1ull << 63)) {
return 9;
} else {
return 10;
}
}
}
} // namespace io
} // namespace protobuf
} // namespace google

View File

@ -0,0 +1,68 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: jasonh@google.com (Jason Hsueh)
//
// Implements methods of coded_stream.h that need to be inlined for performance
// reasons, but should not be defined in a public header.
#ifndef GOOGLE_PROTOBUF_IO_CODED_STREAM_INL_H__
#define GOOGLE_PROTOBUF_IO_CODED_STREAM_INL_H__
#include <google/protobuf/io/coded_stream.h>
#include <string>
#include <google/protobuf/stubs/stl_util.h>
namespace google {
namespace protobuf {
namespace io {
inline bool CodedInputStream::InternalReadStringInline(string* buffer,
int size) {
if (size < 0) return false; // security: size is often user-supplied
if (BufferSize() >= size) {
STLStringResizeUninitialized(buffer, size);
// When buffer is empty, string_as_array(buffer) will return NULL but memcpy
// requires non-NULL pointers even when size is 0. Hench this check.
if (size > 0) {
memcpy(string_as_array(buffer), buffer_, size);
Advance(size);
}
return true;
}
return ReadStringFallback(buffer, size);
}
} // namespace io
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_IO_CODED_STREAM_INL_H__

View File

@ -0,0 +1,48 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
#include <google/protobuf/io/zero_copy_stream.h>
namespace google {
namespace protobuf {
namespace io {
ZeroCopyInputStream::~ZeroCopyInputStream() {}
ZeroCopyOutputStream::~ZeroCopyOutputStream() {}
} // namespace io
} // namespace protobuf
} // namespace google

View File

@ -0,0 +1,238 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// This file contains the ZeroCopyInputStream and ZeroCopyOutputStream
// interfaces, which represent abstract I/O streams to and from which
// protocol buffers can be read and written. For a few simple
// implementations of these interfaces, see zero_copy_stream_impl.h.
//
// These interfaces are different from classic I/O streams in that they
// try to minimize the amount of data copying that needs to be done.
// To accomplish this, responsibility for allocating buffers is moved to
// the stream object, rather than being the responsibility of the caller.
// So, the stream can return a buffer which actually points directly into
// the final data structure where the bytes are to be stored, and the caller
// can interact directly with that buffer, eliminating an intermediate copy
// operation.
//
// As an example, consider the common case in which you are reading bytes
// from an array that is already in memory (or perhaps an mmap()ed file).
// With classic I/O streams, you would do something like:
// char buffer[BUFFER_SIZE];
// input->Read(buffer, BUFFER_SIZE);
// DoSomething(buffer, BUFFER_SIZE);
// Then, the stream basically just calls memcpy() to copy the data from
// the array into your buffer. With a ZeroCopyInputStream, you would do
// this instead:
// const void* buffer;
// int size;
// input->Next(&buffer, &size);
// DoSomething(buffer, size);
// Here, no copy is performed. The input stream returns a pointer directly
// into the backing array, and the caller ends up reading directly from it.
//
// If you want to be able to read the old-fashion way, you can create
// a CodedInputStream or CodedOutputStream wrapping these objects and use
// their ReadRaw()/WriteRaw() methods. These will, of course, add a copy
// step, but Coded*Stream will handle buffering so at least it will be
// reasonably efficient.
//
// ZeroCopyInputStream example:
// // Read in a file and print its contents to stdout.
// int fd = open("myfile", O_RDONLY);
// ZeroCopyInputStream* input = new FileInputStream(fd);
//
// const void* buffer;
// int size;
// while (input->Next(&buffer, &size)) {
// cout.write(buffer, size);
// }
//
// delete input;
// close(fd);
//
// ZeroCopyOutputStream example:
// // Copy the contents of "infile" to "outfile", using plain read() for
// // "infile" but a ZeroCopyOutputStream for "outfile".
// int infd = open("infile", O_RDONLY);
// int outfd = open("outfile", O_WRONLY);
// ZeroCopyOutputStream* output = new FileOutputStream(outfd);
//
// void* buffer;
// int size;
// while (output->Next(&buffer, &size)) {
// int bytes = read(infd, buffer, size);
// if (bytes < size) {
// // Reached EOF.
// output->BackUp(size - bytes);
// break;
// }
// }
//
// delete output;
// close(infd);
// close(outfd);
#ifndef GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_H__
#define GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_H__
#include <string>
#include <google/protobuf/stubs/common.h>
namespace google {
namespace protobuf {
namespace io {
// Defined in this file.
class ZeroCopyInputStream;
class ZeroCopyOutputStream;
// Abstract interface similar to an input stream but designed to minimize
// copying.
class LIBPROTOBUF_EXPORT ZeroCopyInputStream {
public:
inline ZeroCopyInputStream() {}
virtual ~ZeroCopyInputStream();
// Obtains a chunk of data from the stream.
//
// Preconditions:
// * "size" and "data" are not NULL.
//
// Postconditions:
// * If the returned value is false, there is no more data to return or
// an error occurred. All errors are permanent.
// * Otherwise, "size" points to the actual number of bytes read and "data"
// points to a pointer to a buffer containing these bytes.
// * Ownership of this buffer remains with the stream, and the buffer
// remains valid only until some other method of the stream is called
// or the stream is destroyed.
// * It is legal for the returned buffer to have zero size, as long
// as repeatedly calling Next() eventually yields a buffer with non-zero
// size.
virtual bool Next(const void** data, int* size) = 0;
// Backs up a number of bytes, so that the next call to Next() returns
// data again that was already returned by the last call to Next(). This
// is useful when writing procedures that are only supposed to read up
// to a certain point in the input, then return. If Next() returns a
// buffer that goes beyond what you wanted to read, you can use BackUp()
// to return to the point where you intended to finish.
//
// Preconditions:
// * The last method called must have been Next().
// * count must be less than or equal to the size of the last buffer
// returned by Next().
//
// Postconditions:
// * The last "count" bytes of the last buffer returned by Next() will be
// pushed back into the stream. Subsequent calls to Next() will return
// the same data again before producing new data.
virtual void BackUp(int count) = 0;
// Skips a number of bytes. Returns false if the end of the stream is
// reached or some input error occurred. In the end-of-stream case, the
// stream is advanced to the end of the stream (so ByteCount() will return
// the total size of the stream).
virtual bool Skip(int count) = 0;
// Returns the total number of bytes read since this object was created.
virtual int64 ByteCount() const = 0;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ZeroCopyInputStream);
};
// Abstract interface similar to an output stream but designed to minimize
// copying.
class LIBPROTOBUF_EXPORT ZeroCopyOutputStream {
public:
inline ZeroCopyOutputStream() {}
virtual ~ZeroCopyOutputStream();
// Obtains a buffer into which data can be written. Any data written
// into this buffer will eventually (maybe instantly, maybe later on)
// be written to the output.
//
// Preconditions:
// * "size" and "data" are not NULL.
//
// Postconditions:
// * If the returned value is false, an error occurred. All errors are
// permanent.
// * Otherwise, "size" points to the actual number of bytes in the buffer
// and "data" points to the buffer.
// * Ownership of this buffer remains with the stream, and the buffer
// remains valid only until some other method of the stream is called
// or the stream is destroyed.
// * Any data which the caller stores in this buffer will eventually be
// written to the output (unless BackUp() is called).
// * It is legal for the returned buffer to have zero size, as long
// as repeatedly calling Next() eventually yields a buffer with non-zero
// size.
virtual bool Next(void** data, int* size) = 0;
// Backs up a number of bytes, so that the end of the last buffer returned
// by Next() is not actually written. This is needed when you finish
// writing all the data you want to write, but the last buffer was bigger
// than you needed. You don't want to write a bunch of garbage after the
// end of your data, so you use BackUp() to back up.
//
// Preconditions:
// * The last method called must have been Next().
// * count must be less than or equal to the size of the last buffer
// returned by Next().
// * The caller must not have written anything to the last "count" bytes
// of that buffer.
//
// Postconditions:
// * The last "count" bytes of the last buffer returned by Next() will be
// ignored.
virtual void BackUp(int count) = 0;
// Returns the total number of bytes written since this object was created.
virtual int64 ByteCount() const = 0;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ZeroCopyOutputStream);
};
} // namespace io
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_H__

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