From e241cdd1e3d8a7c2776b2fc7c5a4f8972e32f880 Mon Sep 17 00:00:00 2001 From: poweredbypie <67135060+poweredbypie@users.noreply.github.com> Date: Wed, 3 Mar 2021 20:28:58 -0800 Subject: [PATCH] v2.0a refactor to be inline with GManager class, rob's savefile managing system. makes the source more readable for rob, hopefully. also cleaned up visuals a lot and added an options / credits menu. --- include/cocos2dx/base_nodes/CCNode.h | 6 +- include/cocos2dx/include/cocos2d.h | 4 + .../cocos2dx/platform/CCApplicationProtocol.h | 9 + include/cocos2dx/platform/CCPlatformMacros.h | 2 +- .../cocos2dx/platform/win32/CCApplication.h | 10 +- .../platform/win32/CCPlatformDefine.h | 10 +- .../robtop/mouse_dispatcher/CCMouseDelegate.h | 6 - include/cocos2dx/robtop/xml/DS_Dictionary.h | 94 + include/cocos2dx/robtop/xml/pugiconfig.hpp | 69 + include/cocos2dx/robtop/xml/pugixml.hpp | 1267 ++++++++ include/cocos2dx/robtop/xml/readme.txt | 52 + .../extensions/AssetsManager/AssetsManager.h | 221 ++ .../CCBReader/CCBAnimationManager.h | 251 ++ include/extensions/CCBReader/CCBFileLoader.h | 28 + include/extensions/CCBReader/CCBKeyframe.h | 39 + .../CCBReader/CCBMemberVariableAssigner.h | 58 + include/extensions/CCBReader/CCBReader.h | 440 +++ .../CCBReader/CCBSelectorResolver.h | 46 + include/extensions/CCBReader/CCBSequence.h | 50 + .../CCBReader/CCBSequenceProperty.h | 37 + include/extensions/CCBReader/CCBValue.h | 74 + .../CCBReader/CCControlButtonLoader.h | 32 + .../extensions/CCBReader/CCControlLoader.h | 28 + include/extensions/CCBReader/CCData.h | 30 + .../CCBReader/CCLabelBMFontLoader.h | 31 + .../extensions/CCBReader/CCLabelTTFLoader.h | 34 + .../extensions/CCBReader/CCLayerColorLoader.h | 29 + .../CCBReader/CCLayerGradientLoader.h | 30 + include/extensions/CCBReader/CCLayerLoader.h | 27 + .../CCBReader/CCMenuItemImageLoader.h | 27 + .../extensions/CCBReader/CCMenuItemLoader.h | 27 + include/extensions/CCBReader/CCMenuLoader.h | 25 + .../CCBReader/CCNode+CCBRelativePositioning.h | 15 + include/extensions/CCBReader/CCNodeLoader.h | 128 + .../CCBReader/CCNodeLoaderLibrary.h | 45 + .../CCBReader/CCNodeLoaderListener.h | 20 + .../CCBReader/CCParticleSystemQuadLoader.h | 34 + .../CCBReader/CCScale9SpriteLoader.h | 34 + .../extensions/CCBReader/CCScrollViewLoader.h | 31 + include/extensions/CCBReader/CCSpriteLoader.h | 31 + .../CocoStudio/Action/CCActionEaseEx.h | 363 +++ .../CocoStudio/Action/CCActionFrame.h | 453 +++ .../CocoStudio/Action/CCActionFrameEasing.h | 76 + .../CocoStudio/Action/CCActionManager.h | 108 + .../CocoStudio/Action/CCActionNode.h | 182 ++ .../CocoStudio/Action/CCActionObject.h | 181 ++ .../CocoStudio/Armature/CCArmature.h | 216 ++ .../extensions/CocoStudio/Armature/CCBone.h | 242 ++ .../Armature/animation/CCArmatureAnimation.h | 324 +++ .../Armature/animation/CCProcessBase.h | 168 ++ .../CocoStudio/Armature/animation/CCTween.h | 147 + .../CocoStudio/Armature/datas/CCDatas.h | 473 +++ .../CocoStudio/Armature/display/CCBatchNode.h | 69 + .../Armature/display/CCDecorativeDisplay.h | 64 + .../Armature/display/CCDisplayFactory.h | 65 + .../Armature/display/CCDisplayManager.h | 156 + .../CocoStudio/Armature/display/CCSkin.h | 67 + .../Armature/external_tool/sigslot.h | 2540 +++++++++++++++++ .../Armature/physics/CCColliderDetector.h | 160 ++ .../Armature/utils/CCArmatureDataManager.h | 203 ++ .../Armature/utils/CCArmatureDefine.h | 71 + .../Armature/utils/CCDataReaderHelper.h | 133 + .../Armature/utils/CCSpriteFrameCacheHelper.h | 60 + .../Armature/utils/CCTransformHelp.h | 64 + .../Armature/utils/CCTweenFunction.h | 141 + .../CocoStudio/Armature/utils/CCUtilMath.h | 55 + .../CocoStudio/Components/CCComAttribute.h | 70 + .../CocoStudio/Components/CCComAudio.h | 90 + .../CocoStudio/Components/CCComBase.h | 51 + .../CocoStudio/Components/CCComController.h | 59 + .../CocoStudio/Components/CCComRender.h | 66 + .../CocoStudio/Components/CCInputDelegate.h | 83 + .../CocoStudio/GUI/BaseClasses/UIWidget.h | 730 +++++ .../CocoStudio/GUI/Layouts/UILayout.h | 316 ++ .../CocoStudio/GUI/Layouts/UILayoutDefine.h | 96 + .../GUI/Layouts/UILayoutParameter.h | 226 ++ .../CocoStudio/GUI/System/CocosGUI.h | 55 + .../CocoStudio/GUI/System/GUIDefine.h | 75 + .../CocoStudio/GUI/System/UIHelper.h | 81 + .../CocoStudio/GUI/System/UITouchGroup.h | 132 + .../UIWidgets/Compatible/CompatibleClasses.h | 58 + .../GUI/UIWidgets/ScrollWidget/UIListView.h | 215 ++ .../GUI/UIWidgets/ScrollWidget/UIPageView.h | 221 ++ .../ScrollWidget/UIScrollInterface.h | 49 + .../GUI/UIWidgets/ScrollWidget/UIScrollView.h | 442 +++ .../CocoStudio/GUI/UIWidgets/UIButton.h | 225 ++ .../CocoStudio/GUI/UIWidgets/UICheckBox.h | 210 ++ .../CocoStudio/GUI/UIWidgets/UIImageView.h | 129 + .../CocoStudio/GUI/UIWidgets/UILabel.h | 164 ++ .../CocoStudio/GUI/UIWidgets/UILabelAtlas.h | 128 + .../CocoStudio/GUI/UIWidgets/UILabelBMFont.h | 92 + .../CocoStudio/GUI/UIWidgets/UILoadingBar.h | 161 ++ .../CocoStudio/GUI/UIWidgets/UIRichText.h | 133 + .../CocoStudio/GUI/UIWidgets/UISlider.h | 249 ++ .../CocoStudio/GUI/UIWidgets/UITextField.h | 195 ++ .../CocoStudio/Json/DictionaryHelper.h | 81 + .../CocoStudio/Json/rapidjson/document.h | 821 ++++++ .../CocoStudio/Json/rapidjson/filestream.h | 46 + .../Json/rapidjson/internal/pow10.h | 54 + .../Json/rapidjson/internal/stack.h | 82 + .../Json/rapidjson/internal/strfunc.h | 24 + .../CocoStudio/Json/rapidjson/prettywriter.h | 156 + .../CocoStudio/Json/rapidjson/rapidjson.h | 525 ++++ .../CocoStudio/Json/rapidjson/reader.h | 683 +++++ .../CocoStudio/Json/rapidjson/stringbuffer.h | 49 + .../CocoStudio/Json/rapidjson/writer.h | 241 ++ .../extensions/CocoStudio/Reader/GUIReader.h | 185 ++ .../CocoStudio/Reader/SceneReader.h | 70 + .../WidgetReader/ButtonReader/ButtonReader.h | 48 + .../CheckBoxReader/CheckBoxReader.h | 48 + .../ImageViewReader/ImageViewReader.h | 48 + .../LabelAtlasReader/LabelAtlasReader.h | 47 + .../LabelBMFontReader/LabelBMFontReader.h | 48 + .../WidgetReader/LabelReader/LabelReader.h | 48 + .../WidgetReader/LayoutReader/LayoutReader.h | 48 + .../ListViewReader/ListViewReader.h | 48 + .../LoadingBarReader/LoadingBarReader.h | 48 + .../PageViewReader/PageViewReader.h | 48 + .../ScrollViewReader/ScrollViewReader.h | 48 + .../WidgetReader/SliderReader/SliderReader.h | 48 + .../TextFieldReader/TextFieldReader.h | 48 + .../Reader/WidgetReader/WidgetReader.h | 52 + .../WidgetReader/WidgetReaderProtocol.h | 48 + .../CocoStudio/Trigger/ObjectFactory.h | 81 + .../CocoStudio/Trigger/TriggerBase.h | 54 + .../CocoStudio/Trigger/TriggerMng.h | 86 + .../CocoStudio/Trigger/TriggerObj.h | 89 + include/extensions/ExtensionMacros.h | 34 + .../GUI/CCControlExtension/CCControl.h | 292 ++ .../GUI/CCControlExtension/CCControlButton.h | 253 ++ .../CCControlColourPicker.h | 85 + .../CCControlExtension/CCControlExtensions.h | 37 + .../CCControlExtension/CCControlHuePicker.h | 83 + .../CCControlPotentiometer.h | 110 + .../CCControlSaturationBrightnessPicker.h | 91 + .../GUI/CCControlExtension/CCControlSlider.h | 119 + .../GUI/CCControlExtension/CCControlStepper.h | 114 + .../GUI/CCControlExtension/CCControlSwitch.h | 106 + .../GUI/CCControlExtension/CCControlUtils.h | 90 + .../GUI/CCControlExtension/CCInvocation.h | 74 + .../GUI/CCControlExtension/CCScale9Sprite.h | 332 +++ include/extensions/GUI/CCEditBox/CCEditBox.h | 429 +++ .../extensions/GUI/CCEditBox/CCEditBoxImpl.h | 90 + .../GUI/CCEditBox/CCEditBoxImplAndroid.h | 97 + .../GUI/CCEditBox/CCEditBoxImplIOS.h | 130 + .../GUI/CCEditBox/CCEditBoxImplMac.h | 120 + .../GUI/CCEditBox/CCEditBoxImplTizen.h | 98 + .../GUI/CCEditBox/CCEditBoxImplWin.h | 103 + .../GUI/CCEditBox/CCEditBoxImplWp8.h | 87 + .../GUI/CCScrollView/CCScrollView.h | 356 +++ .../extensions/GUI/CCScrollView/CCSorting.h | 116 + .../extensions/GUI/CCScrollView/CCTableView.h | 305 ++ .../GUI/CCScrollView/CCTableViewCell.h | 60 + .../extensions/LocalStorage/LocalStorage.h | 51 + include/extensions/cocos-ext.h | 90 + include/extensions/libExtensions.lib | Bin 0 -> 357688 bytes include/extensions/network/HttpClient.h | 120 + include/extensions/network/HttpRequest.h | 235 ++ include/extensions/network/HttpResponse.h | 185 ++ include/extensions/network/WebSocket.h | 166 ++ .../physics_nodes/CCPhysicsDebugNode.h | 70 + .../physics_nodes/CCPhysicsSprite.h | 134 + include/extensions/spine/Animation.h | 132 + include/extensions/spine/AnimationState.h | 66 + include/extensions/spine/AnimationStateData.h | 49 + include/extensions/spine/Atlas.h | 106 + .../extensions/spine/AtlasAttachmentLoader.h | 43 + include/extensions/spine/Attachment.h | 49 + include/extensions/spine/AttachmentLoader.h | 52 + include/extensions/spine/Bone.h | 59 + include/extensions/spine/BoneData.h | 46 + include/extensions/spine/CCSkeleton.h | 100 + .../extensions/spine/CCSkeletonAnimation.h | 73 + include/extensions/spine/Json.h | 77 + include/extensions/spine/RegionAttachment.h | 60 + include/extensions/spine/Skeleton.h | 92 + include/extensions/spine/SkeletonData.h | 66 + include/extensions/spine/SkeletonJson.h | 52 + include/extensions/spine/Skin.h | 55 + include/extensions/spine/Slot.h | 58 + include/extensions/spine/SlotData.h | 48 + include/extensions/spine/extension.h | 145 + include/extensions/spine/spine-cocos2dx.h | 40 + include/extensions/spine/spine.h | 46 + include/gd/audio_nodes/FMODAudioEngine.h | 59 + include/gd/include/GDProtocols.h | 16 + include/gd/include/gd.h | 6 + .../FLAlertLayer.h | 93 +- .../GJDropDownLayer.h | 22 +- .../GJListLayer.h | 7 +- .../MenuLayer.h | 5 +- include/gd/manager_nodes/GManager.h | 23 +- include/gd/manager_nodes/GameSoundManager.h | 26 + include/gd/menu_nodes/CCMenuItemSpriteExtra.h | 14 +- include/gd/menu_nodes/CCMenuItemToggler.h | 45 + src/Entry.cpp | 7 +- src/logic/layers/LoaderLayer.cpp | 307 +- src/logic/layers/LoaderLayer.h | 46 +- src/logic/layers/LoaderOptionsLayer.cpp | 26 - src/logic/layers/LoaderOptionsLayer.h | 18 - src/logic/layers/more/LoaderAboutLayer.cpp | 104 + src/logic/layers/more/LoaderAboutLayer.h | 17 + src/logic/layers/more/LoaderDropDownLayer.cpp | 49 + src/logic/layers/more/LoaderDropDownLayer.h | 21 + src/logic/layers/more/LoaderOptionsLayer.cpp | 144 + src/logic/layers/more/LoaderOptionsLayer.h | 27 + src/logic/nodes/List.cpp | 481 ++-- src/logic/nodes/List.h | 81 +- src/logic/nodes/LoaderManager.cpp | 309 ++ src/logic/nodes/LoaderManager.h | 40 + src/memory/Hooks.h | 17 +- src/pch.h | 5 + src/textureldr.vcxproj | 61 +- src/textureldr.vcxproj.filters | 193 +- todo.txt | 17 - 215 files changed, 27037 insertions(+), 688 deletions(-) create mode 100644 include/cocos2dx/robtop/xml/DS_Dictionary.h create mode 100644 include/cocos2dx/robtop/xml/pugiconfig.hpp create mode 100644 include/cocos2dx/robtop/xml/pugixml.hpp create mode 100644 include/cocos2dx/robtop/xml/readme.txt create mode 100644 include/extensions/AssetsManager/AssetsManager.h create mode 100644 include/extensions/CCBReader/CCBAnimationManager.h create mode 100644 include/extensions/CCBReader/CCBFileLoader.h create mode 100644 include/extensions/CCBReader/CCBKeyframe.h create mode 100644 include/extensions/CCBReader/CCBMemberVariableAssigner.h create mode 100644 include/extensions/CCBReader/CCBReader.h create mode 100644 include/extensions/CCBReader/CCBSelectorResolver.h create mode 100644 include/extensions/CCBReader/CCBSequence.h create mode 100644 include/extensions/CCBReader/CCBSequenceProperty.h create mode 100644 include/extensions/CCBReader/CCBValue.h create mode 100644 include/extensions/CCBReader/CCControlButtonLoader.h create mode 100644 include/extensions/CCBReader/CCControlLoader.h create mode 100644 include/extensions/CCBReader/CCData.h create mode 100644 include/extensions/CCBReader/CCLabelBMFontLoader.h create mode 100644 include/extensions/CCBReader/CCLabelTTFLoader.h create mode 100644 include/extensions/CCBReader/CCLayerColorLoader.h create mode 100644 include/extensions/CCBReader/CCLayerGradientLoader.h create mode 100644 include/extensions/CCBReader/CCLayerLoader.h create mode 100644 include/extensions/CCBReader/CCMenuItemImageLoader.h create mode 100644 include/extensions/CCBReader/CCMenuItemLoader.h create mode 100644 include/extensions/CCBReader/CCMenuLoader.h create mode 100644 include/extensions/CCBReader/CCNode+CCBRelativePositioning.h create mode 100644 include/extensions/CCBReader/CCNodeLoader.h create mode 100644 include/extensions/CCBReader/CCNodeLoaderLibrary.h create mode 100644 include/extensions/CCBReader/CCNodeLoaderListener.h create mode 100644 include/extensions/CCBReader/CCParticleSystemQuadLoader.h create mode 100644 include/extensions/CCBReader/CCScale9SpriteLoader.h create mode 100644 include/extensions/CCBReader/CCScrollViewLoader.h create mode 100644 include/extensions/CCBReader/CCSpriteLoader.h create mode 100644 include/extensions/CocoStudio/Action/CCActionEaseEx.h create mode 100644 include/extensions/CocoStudio/Action/CCActionFrame.h create mode 100644 include/extensions/CocoStudio/Action/CCActionFrameEasing.h create mode 100644 include/extensions/CocoStudio/Action/CCActionManager.h create mode 100644 include/extensions/CocoStudio/Action/CCActionNode.h create mode 100644 include/extensions/CocoStudio/Action/CCActionObject.h create mode 100644 include/extensions/CocoStudio/Armature/CCArmature.h create mode 100644 include/extensions/CocoStudio/Armature/CCBone.h create mode 100644 include/extensions/CocoStudio/Armature/animation/CCArmatureAnimation.h create mode 100644 include/extensions/CocoStudio/Armature/animation/CCProcessBase.h create mode 100644 include/extensions/CocoStudio/Armature/animation/CCTween.h create mode 100644 include/extensions/CocoStudio/Armature/datas/CCDatas.h create mode 100644 include/extensions/CocoStudio/Armature/display/CCBatchNode.h create mode 100644 include/extensions/CocoStudio/Armature/display/CCDecorativeDisplay.h create mode 100644 include/extensions/CocoStudio/Armature/display/CCDisplayFactory.h create mode 100644 include/extensions/CocoStudio/Armature/display/CCDisplayManager.h create mode 100644 include/extensions/CocoStudio/Armature/display/CCSkin.h create mode 100644 include/extensions/CocoStudio/Armature/external_tool/sigslot.h create mode 100644 include/extensions/CocoStudio/Armature/physics/CCColliderDetector.h create mode 100644 include/extensions/CocoStudio/Armature/utils/CCArmatureDataManager.h create mode 100644 include/extensions/CocoStudio/Armature/utils/CCArmatureDefine.h create mode 100644 include/extensions/CocoStudio/Armature/utils/CCDataReaderHelper.h create mode 100644 include/extensions/CocoStudio/Armature/utils/CCSpriteFrameCacheHelper.h create mode 100644 include/extensions/CocoStudio/Armature/utils/CCTransformHelp.h create mode 100644 include/extensions/CocoStudio/Armature/utils/CCTweenFunction.h create mode 100644 include/extensions/CocoStudio/Armature/utils/CCUtilMath.h create mode 100644 include/extensions/CocoStudio/Components/CCComAttribute.h create mode 100644 include/extensions/CocoStudio/Components/CCComAudio.h create mode 100644 include/extensions/CocoStudio/Components/CCComBase.h create mode 100644 include/extensions/CocoStudio/Components/CCComController.h create mode 100644 include/extensions/CocoStudio/Components/CCComRender.h create mode 100644 include/extensions/CocoStudio/Components/CCInputDelegate.h create mode 100644 include/extensions/CocoStudio/GUI/BaseClasses/UIWidget.h create mode 100644 include/extensions/CocoStudio/GUI/Layouts/UILayout.h create mode 100644 include/extensions/CocoStudio/GUI/Layouts/UILayoutDefine.h create mode 100644 include/extensions/CocoStudio/GUI/Layouts/UILayoutParameter.h create mode 100644 include/extensions/CocoStudio/GUI/System/CocosGUI.h create mode 100644 include/extensions/CocoStudio/GUI/System/GUIDefine.h create mode 100644 include/extensions/CocoStudio/GUI/System/UIHelper.h create mode 100644 include/extensions/CocoStudio/GUI/System/UITouchGroup.h create mode 100644 include/extensions/CocoStudio/GUI/UIWidgets/Compatible/CompatibleClasses.h create mode 100644 include/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIListView.h create mode 100644 include/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIPageView.h create mode 100644 include/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIScrollInterface.h create mode 100644 include/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIScrollView.h create mode 100644 include/extensions/CocoStudio/GUI/UIWidgets/UIButton.h create mode 100644 include/extensions/CocoStudio/GUI/UIWidgets/UICheckBox.h create mode 100644 include/extensions/CocoStudio/GUI/UIWidgets/UIImageView.h create mode 100644 include/extensions/CocoStudio/GUI/UIWidgets/UILabel.h create mode 100644 include/extensions/CocoStudio/GUI/UIWidgets/UILabelAtlas.h create mode 100644 include/extensions/CocoStudio/GUI/UIWidgets/UILabelBMFont.h create mode 100644 include/extensions/CocoStudio/GUI/UIWidgets/UILoadingBar.h create mode 100644 include/extensions/CocoStudio/GUI/UIWidgets/UIRichText.h create mode 100644 include/extensions/CocoStudio/GUI/UIWidgets/UISlider.h create mode 100644 include/extensions/CocoStudio/GUI/UIWidgets/UITextField.h create mode 100644 include/extensions/CocoStudio/Json/DictionaryHelper.h create mode 100644 include/extensions/CocoStudio/Json/rapidjson/document.h create mode 100644 include/extensions/CocoStudio/Json/rapidjson/filestream.h create mode 100644 include/extensions/CocoStudio/Json/rapidjson/internal/pow10.h create mode 100644 include/extensions/CocoStudio/Json/rapidjson/internal/stack.h create mode 100644 include/extensions/CocoStudio/Json/rapidjson/internal/strfunc.h create mode 100644 include/extensions/CocoStudio/Json/rapidjson/prettywriter.h create mode 100644 include/extensions/CocoStudio/Json/rapidjson/rapidjson.h create mode 100644 include/extensions/CocoStudio/Json/rapidjson/reader.h create mode 100644 include/extensions/CocoStudio/Json/rapidjson/stringbuffer.h create mode 100644 include/extensions/CocoStudio/Json/rapidjson/writer.h create mode 100644 include/extensions/CocoStudio/Reader/GUIReader.h create mode 100644 include/extensions/CocoStudio/Reader/SceneReader.h create mode 100644 include/extensions/CocoStudio/Reader/WidgetReader/ButtonReader/ButtonReader.h create mode 100644 include/extensions/CocoStudio/Reader/WidgetReader/CheckBoxReader/CheckBoxReader.h create mode 100644 include/extensions/CocoStudio/Reader/WidgetReader/ImageViewReader/ImageViewReader.h create mode 100644 include/extensions/CocoStudio/Reader/WidgetReader/LabelAtlasReader/LabelAtlasReader.h create mode 100644 include/extensions/CocoStudio/Reader/WidgetReader/LabelBMFontReader/LabelBMFontReader.h create mode 100644 include/extensions/CocoStudio/Reader/WidgetReader/LabelReader/LabelReader.h create mode 100644 include/extensions/CocoStudio/Reader/WidgetReader/LayoutReader/LayoutReader.h create mode 100644 include/extensions/CocoStudio/Reader/WidgetReader/ListViewReader/ListViewReader.h create mode 100644 include/extensions/CocoStudio/Reader/WidgetReader/LoadingBarReader/LoadingBarReader.h create mode 100644 include/extensions/CocoStudio/Reader/WidgetReader/PageViewReader/PageViewReader.h create mode 100644 include/extensions/CocoStudio/Reader/WidgetReader/ScrollViewReader/ScrollViewReader.h create mode 100644 include/extensions/CocoStudio/Reader/WidgetReader/SliderReader/SliderReader.h create mode 100644 include/extensions/CocoStudio/Reader/WidgetReader/TextFieldReader/TextFieldReader.h create mode 100644 include/extensions/CocoStudio/Reader/WidgetReader/WidgetReader.h create mode 100644 include/extensions/CocoStudio/Reader/WidgetReader/WidgetReaderProtocol.h create mode 100644 include/extensions/CocoStudio/Trigger/ObjectFactory.h create mode 100644 include/extensions/CocoStudio/Trigger/TriggerBase.h create mode 100644 include/extensions/CocoStudio/Trigger/TriggerMng.h create mode 100644 include/extensions/CocoStudio/Trigger/TriggerObj.h create mode 100644 include/extensions/ExtensionMacros.h create mode 100644 include/extensions/GUI/CCControlExtension/CCControl.h create mode 100644 include/extensions/GUI/CCControlExtension/CCControlButton.h create mode 100644 include/extensions/GUI/CCControlExtension/CCControlColourPicker.h create mode 100644 include/extensions/GUI/CCControlExtension/CCControlExtensions.h create mode 100644 include/extensions/GUI/CCControlExtension/CCControlHuePicker.h create mode 100644 include/extensions/GUI/CCControlExtension/CCControlPotentiometer.h create mode 100644 include/extensions/GUI/CCControlExtension/CCControlSaturationBrightnessPicker.h create mode 100644 include/extensions/GUI/CCControlExtension/CCControlSlider.h create mode 100644 include/extensions/GUI/CCControlExtension/CCControlStepper.h create mode 100644 include/extensions/GUI/CCControlExtension/CCControlSwitch.h create mode 100644 include/extensions/GUI/CCControlExtension/CCControlUtils.h create mode 100644 include/extensions/GUI/CCControlExtension/CCInvocation.h create mode 100644 include/extensions/GUI/CCControlExtension/CCScale9Sprite.h create mode 100644 include/extensions/GUI/CCEditBox/CCEditBox.h create mode 100644 include/extensions/GUI/CCEditBox/CCEditBoxImpl.h create mode 100644 include/extensions/GUI/CCEditBox/CCEditBoxImplAndroid.h create mode 100644 include/extensions/GUI/CCEditBox/CCEditBoxImplIOS.h create mode 100644 include/extensions/GUI/CCEditBox/CCEditBoxImplMac.h create mode 100644 include/extensions/GUI/CCEditBox/CCEditBoxImplTizen.h create mode 100644 include/extensions/GUI/CCEditBox/CCEditBoxImplWin.h create mode 100644 include/extensions/GUI/CCEditBox/CCEditBoxImplWp8.h create mode 100644 include/extensions/GUI/CCScrollView/CCScrollView.h create mode 100644 include/extensions/GUI/CCScrollView/CCSorting.h create mode 100644 include/extensions/GUI/CCScrollView/CCTableView.h create mode 100644 include/extensions/GUI/CCScrollView/CCTableViewCell.h create mode 100644 include/extensions/LocalStorage/LocalStorage.h create mode 100644 include/extensions/cocos-ext.h create mode 100644 include/extensions/libExtensions.lib create mode 100644 include/extensions/network/HttpClient.h create mode 100644 include/extensions/network/HttpRequest.h create mode 100644 include/extensions/network/HttpResponse.h create mode 100644 include/extensions/network/WebSocket.h create mode 100644 include/extensions/physics_nodes/CCPhysicsDebugNode.h create mode 100644 include/extensions/physics_nodes/CCPhysicsSprite.h create mode 100644 include/extensions/spine/Animation.h create mode 100644 include/extensions/spine/AnimationState.h create mode 100644 include/extensions/spine/AnimationStateData.h create mode 100644 include/extensions/spine/Atlas.h create mode 100644 include/extensions/spine/AtlasAttachmentLoader.h create mode 100644 include/extensions/spine/Attachment.h create mode 100644 include/extensions/spine/AttachmentLoader.h create mode 100644 include/extensions/spine/Bone.h create mode 100644 include/extensions/spine/BoneData.h create mode 100644 include/extensions/spine/CCSkeleton.h create mode 100644 include/extensions/spine/CCSkeletonAnimation.h create mode 100644 include/extensions/spine/Json.h create mode 100644 include/extensions/spine/RegionAttachment.h create mode 100644 include/extensions/spine/Skeleton.h create mode 100644 include/extensions/spine/SkeletonData.h create mode 100644 include/extensions/spine/SkeletonJson.h create mode 100644 include/extensions/spine/Skin.h create mode 100644 include/extensions/spine/Slot.h create mode 100644 include/extensions/spine/SlotData.h create mode 100644 include/extensions/spine/extension.h create mode 100644 include/extensions/spine/spine-cocos2dx.h create mode 100644 include/extensions/spine/spine.h create mode 100644 include/gd/audio_nodes/FMODAudioEngine.h create mode 100644 include/gd/include/GDProtocols.h create mode 100644 include/gd/manager_nodes/GameSoundManager.h create mode 100644 include/gd/menu_nodes/CCMenuItemToggler.h delete mode 100644 src/logic/layers/LoaderOptionsLayer.cpp delete mode 100644 src/logic/layers/LoaderOptionsLayer.h create mode 100644 src/logic/layers/more/LoaderAboutLayer.cpp create mode 100644 src/logic/layers/more/LoaderAboutLayer.h create mode 100644 src/logic/layers/more/LoaderDropDownLayer.cpp create mode 100644 src/logic/layers/more/LoaderDropDownLayer.h create mode 100644 src/logic/layers/more/LoaderOptionsLayer.cpp create mode 100644 src/logic/layers/more/LoaderOptionsLayer.h create mode 100644 src/logic/nodes/LoaderManager.cpp create mode 100644 src/logic/nodes/LoaderManager.h delete mode 100644 todo.txt diff --git a/include/cocos2dx/base_nodes/CCNode.h b/include/cocos2dx/base_nodes/CCNode.h index 77da537..648b4ed 100644 --- a/include/cocos2dx/base_nodes/CCNode.h +++ b/include/cocos2dx/base_nodes/CCNode.h @@ -418,9 +418,6 @@ class CC_DLL CCNode : public CCObject * @return The anchor point in absolute pixels. */ virtual const CCPoint& getAnchorPointInPoints(); - - RT_ADD( virtual CCSize getScaledContentSize(void); ) - /** * Sets the untransformed size of the node. @@ -440,7 +437,8 @@ class CC_DLL CCNode : public CCObject */ virtual const CCSize& getContentSize() const; - + RT_ADD(virtual CCSize getScaledContentSize(void); ) + /** * Sets whether the node is visible * diff --git a/include/cocos2dx/include/cocos2d.h b/include/cocos2dx/include/cocos2d.h index 69af161..4ceb848 100644 --- a/include/cocos2dx/include/cocos2d.h +++ b/include/cocos2dx/include/cocos2d.h @@ -302,10 +302,14 @@ THE SOFTWARE. //robtop #include "robtop/keyboard_dispatcher/CCKeyboardDelegate.h" #include "robtop/keyboard_dispatcher/CCKeyboardDispatcher.h" + #include "robtop/mouse_dispatcher/CCMouseDelegate.h" #include "robtop/mouse_dispatcher/CCMouseDispatcher.h" + #include "robtop/scene_nodes/CCSceneTransitionDelegate.h" +#include "robtop/xml/DS_Dictionary.h" + NS_CC_BEGIN CC_DLL const char* cocos2dVersion(); diff --git a/include/cocos2dx/platform/CCApplicationProtocol.h b/include/cocos2dx/platform/CCApplicationProtocol.h index 2dcd554..260a5c3 100644 --- a/include/cocos2dx/platform/CCApplicationProtocol.h +++ b/include/cocos2dx/platform/CCApplicationProtocol.h @@ -75,6 +75,13 @@ class CC_DLL CCApplicationProtocol */ virtual void applicationWillEnterForeground() = 0; + RT_ADD( + virtual void applicationWillBecomeActive(); + virtual void applicationWillResignActive(); + virtual void trySaveGame(); + virtual void gameDidSave(); + ) + /** @brief Callback by CCDirector for limit FPS. @interval The time, expressed in seconds, between current frame and next. @@ -91,6 +98,8 @@ class CC_DLL CCApplicationProtocol @brief Get target platform */ virtual TargetPlatform getTargetPlatform() = 0; + + RT_ADD( virtual void openURL(const char* url) ); }; // end of platform group diff --git a/include/cocos2dx/platform/CCPlatformMacros.h b/include/cocos2dx/platform/CCPlatformMacros.h index 353bcd1..e3e0d9f 100644 --- a/include/cocos2dx/platform/CCPlatformMacros.h +++ b/include/cocos2dx/platform/CCPlatformMacros.h @@ -264,7 +264,7 @@ private: \ */ #if defined(__GNUC__) && (__GNUC__ >= 4) #define CC_FORMAT_PRINTF(formatPos, argPos) __attribute__((__format__(printf, formatPos, argPos))) -/** @mod CC_FORMAT_PRINTF +/** CC_FORMAT_PRINTF * Visual Studio 2019 has __has_attribute, * but __has_attribute(format) is undefined, * leaving CC_FORMAT_PRINTF undefined by default. diff --git a/include/cocos2dx/platform/win32/CCApplication.h b/include/cocos2dx/platform/win32/CCApplication.h index 9c23b41..ee621c9 100644 --- a/include/cocos2dx/platform/win32/CCApplication.h +++ b/include/cocos2dx/platform/win32/CCApplication.h @@ -19,7 +19,8 @@ class CC_DLL CCApplication : public CCApplicationProtocol /** @brief Run the message loop. */ - virtual int run(); + RT_REMOVE( virtual int run(); ) + RT_ADD( virtual void gameDidSave(); ) /** @brief Get current applicaiton instance. @@ -36,6 +37,13 @@ class CC_DLL CCApplication : public CCApplicationProtocol */ virtual TargetPlatform getTargetPlatform(); + RT_ADD( + virtual void openURL(const char* url); + virtual int run(); + virtual void setupGLView(); + virtual void platformShutdown(); + ) + /** * Sets the Resource root path. * @deprecated Please use CCFileUtils::sharedFileUtils()->setSearchPaths() instead. diff --git a/include/cocos2dx/platform/win32/CCPlatformDefine.h b/include/cocos2dx/platform/win32/CCPlatformDefine.h index f3b87da..23abec6 100644 --- a/include/cocos2dx/platform/win32/CCPlatformDefine.h +++ b/include/cocos2dx/platform/win32/CCPlatformDefine.h @@ -13,12 +13,12 @@ #define CC_DLL __declspec(dllimport) #endif*/ -/** @mod CC_DLL -* Since we want to use the functions exported by -* libcocos2d.dll used by GeometryDash.exe, we have to -* change the classes to import DLL functions, not export them. +/** CC_DLL +* Since we are linking a lib containing the functions +* provided by libcocos2d.dll used by GeometryDash.exe, +* we do not need to define this macro to do anything. */ -#define CC_DLL +#define CC_DLL #include diff --git a/include/cocos2dx/robtop/mouse_dispatcher/CCMouseDelegate.h b/include/cocos2dx/robtop/mouse_dispatcher/CCMouseDelegate.h index 640a13a..a2eeb99 100644 --- a/include/cocos2dx/robtop/mouse_dispatcher/CCMouseDelegate.h +++ b/include/cocos2dx/robtop/mouse_dispatcher/CCMouseDelegate.h @@ -7,12 +7,6 @@ RT_ADD( NS_CC_BEGIN - /*no clue if this is accurate. - * https://github.com/cocos2d/cocos2d-x/blob/cocos2d-x-3.13/cocos/base/CCEventMouse.h#L48 - * https://github.com/reneklacan/cocos2d-x/wiki/Mouse-keycodes-enum - * not sure which one is which - */ - class CC_DLL CCMouseDelegate { public: diff --git a/include/cocos2dx/robtop/xml/DS_Dictionary.h b/include/cocos2dx/robtop/xml/DS_Dictionary.h new file mode 100644 index 0000000..1be5807 --- /dev/null +++ b/include/cocos2dx/robtop/xml/DS_Dictionary.h @@ -0,0 +1,94 @@ +#ifndef __DS_DICTIONARY_H__ +#define __DS_DICTIONARY_H__ + +#include "pugixml.hpp" +#include +#include + +class CC_DLL DS_Dictionary { +private: + pugi::xml_document doc; + std::vector dictTree; + bool m_bCompatible; + +private: + std::string cleanStringWhiteSpace(const std::string&); + void split(const std::string&, char*, const std::vector&); + bool splitWithForm(const std::string&, std::vector&); + bool rectFromString(const std::string&, cocos2d::CCRect&); + bool vec2FromString(const std::string&, cocos2d::CCPoint&); + +public: + DS_Dictionary(); + ~DS_Dictionary(); + + static void copyFile(const char*, const char*); + + cocos2d::CCObject* decodeObjectForKey(const char*, bool, int); + + bool loadRootSubDictFromFile(const char*); + bool loadRootSubDictFromCompressedFile(const char*); + bool loadRootSubDictFromString(std::string); + + bool saveRootSubDictToFile(const char*); + bool saveRootSubDictToCompressedFile(const char*); + std::string saveRootSubDictToString(); + + bool stepIntoSubDictWithKey(const char*); + void stepOutOfSubDict(); + void stepBackToRootSubDict(); + + unsigned int getNumKeys(); + std::string getKey(unsigned int); + std::vector getAllKeys(); + unsigned int getIndexOfKey(const char*); + unsigned int getIndexOfKeyWithClosestAlphaNumericalMatch(const char*); + void removeKey(unsigned int); + void removeKey(const char*); + void removeAllKeys(); + + int getIntegerForKey(const char*); + bool getBoolForKey(const char*); + float getFloatForKey(const char*); + std::string getStringForKey(const char*); + cocos2d::CCPoint getVec2ForKey(const char*); + cocos2d::CCRect getRectForKey(const char*); + std::vector getStringArrayForKey(const char*); + std::vector getVec2ArrayForKey(const char*); + std::vector getRectArrayForKey(const char*); + cocos2d::CCArray* getArrayForKey(const char*, bool); + cocos2d::CCDictionary* getDictForKey(const char*, bool); + cocos2d::CCObject* getObjectForKey(const char*); + + void setIntegerForKey(const char*, int); + void setIntegerForKey(const char*, int, bool); + void setBoolForKey(const char*, bool); + void setBoolForKey(const char*, bool, bool); + void setFloatForKey(const char*, float); + void setFloatForKey(const char*, float, bool); + void setStringForKey(const char*, const std::string&); + void setStringForKey(const char*, const std::string&, bool); + void setVec2ForKey(const char*, const cocos2d::CCPoint&); + void setVec2ForKey(const char*, const cocos2d::CCPoint&, bool); + void setRectForKey(const char*, const cocos2d::CCRect&); + void setRectForKey(const char*, const cocos2d::CCRect&, bool); + void setStringArrayForKey(const char*, const std::vector&); + void setStringArrayForKey(const char*, const std::vector&, bool); + void setVec2ArrayForKey(const char*, const std::vector&); + void setVec2ArrayForKey(const char*, const std::vector&, bool); + void setRectArrayForKey(const char*, const std::vector&); + void setRectArrayForKey(const char*, const std::vector&, bool); + void setArrayForKey(const char*, cocos2d::CCArray*); + void setBoolMapForKey(const char*, const std::map&); + void setSubDictForKey(const char*); + void setSubDictForKey(const char*, bool, bool); + void setDictForKey(const char*, cocos2d::CCDictionary*); + void setObjectForKey(const char*, cocos2d::CCObject*); + + void addBoolValuesToMapForKey(const std::map&, const char*, bool); + void addBoolValuesToMapForKeySpecial(const std::map&, const char*, bool); + + void checkCompatibility(); +}; + +#endif \ No newline at end of file diff --git a/include/cocos2dx/robtop/xml/pugiconfig.hpp b/include/cocos2dx/robtop/xml/pugiconfig.hpp new file mode 100644 index 0000000..c219671 --- /dev/null +++ b/include/cocos2dx/robtop/xml/pugiconfig.hpp @@ -0,0 +1,69 @@ +/** + * pugixml parser - version 1.2 + * -------------------------------------------------------- + * Copyright (C) 2006-2012, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com) + * Report bugs and download new versions at http://pugixml.org/ + * + * This library is distributed under the MIT License. See notice at the end + * of this file. + * + * This work is based on the pugxml parser, which is: + * Copyright (C) 2003, by Kristen Wegner (kristen@tima.net) + */ + +#ifndef HEADER_PUGICONFIG_HPP +#define HEADER_PUGICONFIG_HPP + +// Uncomment this to enable wchar_t mode +// #define PUGIXML_WCHAR_MODE + +// Uncomment this to disable XPath +// #define PUGIXML_NO_XPATH + +// Uncomment this to disable STL +// #define PUGIXML_NO_STL + +// Uncomment this to disable exceptions +// #define PUGIXML_NO_EXCEPTIONS + +// Set this to control attributes for public classes/functions, i.e.: +// #define PUGIXML_API __declspec(dllexport) // to export all public symbols from DLL +// #define PUGIXML_CLASS __declspec(dllimport) // to import all classes from DLL +// #define PUGIXML_FUNCTION __fastcall // to set calling conventions to all public functions to fastcall +// In absence of PUGIXML_CLASS/PUGIXML_FUNCTION definitions PUGIXML_API is used instead + +// Uncomment this to switch to header-only version +// #define PUGIXML_HEADER_ONLY +// #include "pugixml.cpp" + +// Tune these constants to adjust memory-related behavior +// #define PUGIXML_MEMORY_PAGE_SIZE 32768 +// #define PUGIXML_MEMORY_OUTPUT_STACK 10240 +// #define PUGIXML_MEMORY_XPATH_PAGE_SIZE 4096 + +#endif + +/** + * Copyright (c) 2006-2012 Arseny Kapoulkine + * + * 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. + */ diff --git a/include/cocos2dx/robtop/xml/pugixml.hpp b/include/cocos2dx/robtop/xml/pugixml.hpp new file mode 100644 index 0000000..5042d66 --- /dev/null +++ b/include/cocos2dx/robtop/xml/pugixml.hpp @@ -0,0 +1,1267 @@ +/** + * pugixml parser - version 1.2 + * -------------------------------------------------------- + * Copyright (C) 2006-2012, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com) + * Report bugs and download new versions at http://pugixml.org/ + * + * This library is distributed under the MIT License. See notice at the end + * of this file. + * + * This work is based on the pugxml parser, which is: + * Copyright (C) 2003, by Kristen Wegner (kristen@tima.net) + */ + +#include + +#ifndef PUGIXML_VERSION +// Define version macro; evaluates to major * 100 + minor so that it's safe to use in less-than comparisons +# define PUGIXML_VERSION 120 +#endif + +// Include user configuration file (this can define various configuration macros) +#include "pugiconfig.hpp" + +#ifndef HEADER_PUGIXML_HPP +#define HEADER_PUGIXML_HPP + +// Include stddef.h for size_t and ptrdiff_t +#include + +// Include exception header for XPath +#if !defined(PUGIXML_NO_XPATH) && !defined(PUGIXML_NO_EXCEPTIONS) +# include +#endif + +// Include STL headers +#ifndef PUGIXML_NO_STL +# include +# include +# include +#endif + +// Macro for deprecated features +#ifndef PUGIXML_DEPRECATED +# if defined(__GNUC__) +# define PUGIXML_DEPRECATED __attribute__((deprecated)) +# elif defined(_MSC_VER) && _MSC_VER >= 1300 +# define PUGIXML_DEPRECATED __declspec(deprecated) +# else +# define PUGIXML_DEPRECATED +# endif +#endif + +// If no API is defined, assume default +#ifndef PUGIXML_API +# define PUGIXML_API +#endif + +// If no API for classes is defined, assume default +#ifndef PUGIXML_CLASS +# define PUGIXML_CLASS PUGIXML_API +#endif + +// If no API for functions is defined, assume default +#ifndef PUGIXML_FUNCTION +# define PUGIXML_FUNCTION PUGIXML_API +#endif + +// Character interface macros +#ifdef PUGIXML_WCHAR_MODE +# define PUGIXML_TEXT(t) L ## t +# define PUGIXML_CHAR wchar_t +#else +# define PUGIXML_TEXT(t) t +# define PUGIXML_CHAR char +#endif + +namespace pugi +{ + // Character type used for all internal storage and operations; depends on PUGIXML_WCHAR_MODE + typedef PUGIXML_CHAR char_t; + +#ifndef PUGIXML_NO_STL + // String type used for operations that work with STL string; depends on PUGIXML_WCHAR_MODE + typedef std::basic_string, std::allocator > string_t; +#endif +} + +// The PugiXML namespace +namespace pugi +{ + // Tree node types + enum xml_node_type + { + node_null, // Empty (null) node handle + node_document, // A document tree's absolute root + node_element, // Element tag, i.e. '' + node_pcdata, // Plain character data, i.e. 'text' + node_cdata, // Character data, i.e. '' + node_comment, // Comment tag, i.e. '' + node_pi, // Processing instruction, i.e. '' + node_declaration, // Document declaration, i.e. '' + node_doctype // Document type declaration, i.e. '' + }; + + // Parsing options + + // Minimal parsing mode (equivalent to turning all other flags off). + // Only elements and PCDATA sections are added to the DOM tree, no text conversions are performed. + const unsigned int parse_minimal = 0x0000; + + // This flag determines if processing instructions (node_pi) are added to the DOM tree. This flag is off by default. + const unsigned int parse_pi = 0x0001; + + // This flag determines if comments (node_comment) are added to the DOM tree. This flag is off by default. + const unsigned int parse_comments = 0x0002; + + // This flag determines if CDATA sections (node_cdata) are added to the DOM tree. This flag is on by default. + const unsigned int parse_cdata = 0x0004; + + // This flag determines if plain character data (node_pcdata) that consist only of whitespace are added to the DOM tree. + // This flag is off by default; turning it on usually results in slower parsing and more memory consumption. + const unsigned int parse_ws_pcdata = 0x0008; + + // This flag determines if character and entity references are expanded during parsing. This flag is on by default. + const unsigned int parse_escapes = 0x0010; + + // This flag determines if EOL characters are normalized (converted to #xA) during parsing. This flag is on by default. + const unsigned int parse_eol = 0x0020; + + // This flag determines if attribute values are normalized using CDATA normalization rules during parsing. This flag is on by default. + const unsigned int parse_wconv_attribute = 0x0040; + + // This flag determines if attribute values are normalized using NMTOKENS normalization rules during parsing. This flag is off by default. + const unsigned int parse_wnorm_attribute = 0x0080; + + // This flag determines if document declaration (node_declaration) is added to the DOM tree. This flag is off by default. + const unsigned int parse_declaration = 0x0100; + + // This flag determines if document type declaration (node_doctype) is added to the DOM tree. This flag is off by default. + const unsigned int parse_doctype = 0x0200; + + // This flag determines if plain character data (node_pcdata) that is the only child of the parent node and that consists only + // of whitespace is added to the DOM tree. + // This flag is off by default; turning it on may result in slower parsing and more memory consumption. + const unsigned int parse_ws_pcdata_single = 0x0400; + + // The default parsing mode. + // Elements, PCDATA and CDATA sections are added to the DOM tree, character/reference entities are expanded, + // End-of-Line characters are normalized, attribute values are normalized using CDATA normalization rules. + const unsigned int parse_default = parse_cdata | parse_escapes | parse_wconv_attribute | parse_eol; + + // The full parsing mode. + // Nodes of all types are added to the DOM tree, character/reference entities are expanded, + // End-of-Line characters are normalized, attribute values are normalized using CDATA normalization rules. + const unsigned int parse_full = parse_default | parse_pi | parse_comments | parse_declaration | parse_doctype; + + // These flags determine the encoding of input data for XML document + enum xml_encoding + { + encoding_auto, // Auto-detect input encoding using BOM or < / class xml_object_range + { + public: + typedef It const_iterator; + + xml_object_range(It b, It e): _begin(b), _end(e) + { + } + + It begin() const { return _begin; } + It end() const { return _end; } + + private: + It _begin, _end; + }; + + // Writer interface for node printing (see xml_node::print) + class PUGIXML_CLASS xml_writer + { + public: + virtual ~xml_writer() {} + + // Write memory chunk into stream/file/whatever + virtual void write(const void* data, size_t size) = 0; + }; + + // xml_writer implementation for FILE* + class PUGIXML_CLASS xml_writer_file: public xml_writer + { + public: + // Construct writer from a FILE* object; void* is used to avoid header dependencies on stdio + xml_writer_file(void* file); + + virtual void write(const void* data, size_t size); + + private: + void* file; + }; + + #ifndef PUGIXML_NO_STL + // xml_writer implementation for streams + class PUGIXML_CLASS xml_writer_stream: public xml_writer + { + public: + // Construct writer from an output stream object + xml_writer_stream(std::basic_ostream >& stream); + xml_writer_stream(std::basic_ostream >& stream); + + virtual void write(const void* data, size_t size); + + private: + std::basic_ostream >* narrow_stream; + std::basic_ostream >* wide_stream; + }; + #endif + + // A light-weight handle for manipulating attributes in DOM tree + class PUGIXML_CLASS xml_attribute + { + friend class xml_attribute_iterator; + friend class xml_node; + + private: + xml_attribute_struct* _attr; + + typedef void (*unspecified_bool_type)(xml_attribute***); + + public: + // Default constructor. Constructs an empty attribute. + xml_attribute(); + + // Constructs attribute from internal pointer + explicit xml_attribute(xml_attribute_struct* attr); + + // Safe bool conversion operator + operator unspecified_bool_type() const; + + // Borland C++ workaround + bool operator!() const; + + // Comparison operators (compares wrapped attribute pointers) + bool operator==(const xml_attribute& r) const; + bool operator!=(const xml_attribute& r) const; + bool operator<(const xml_attribute& r) const; + bool operator>(const xml_attribute& r) const; + bool operator<=(const xml_attribute& r) const; + bool operator>=(const xml_attribute& r) const; + + // Check if attribute is empty + bool empty() const; + + // Get attribute name/value, or "" if attribute is empty + const char_t* name() const; + const char_t* value() const; + + // Get attribute value, or the default value if attribute is empty + const char_t* as_string(const char_t* def = PUGIXML_TEXT("")) const; + + // Get attribute value as a number, or the default value if conversion did not succeed or attribute is empty + int as_int(int def = 0) const; + unsigned int as_uint(unsigned int def = 0) const; + double as_double(double def = 0) const; + float as_float(float def = 0) const; + + // Get attribute value as bool (returns true if first character is in '1tTyY' set), or the default value if attribute is empty + bool as_bool(bool def = false) const; + + // Set attribute name/value (returns false if attribute is empty or there is not enough memory) + bool set_name(const char_t* rhs); + bool set_value(const char_t* rhs); + + // Set attribute value with type conversion (numbers are converted to strings, boolean is converted to "true"/"false") + bool set_value(int rhs); + bool set_value(unsigned int rhs); + bool set_value(double rhs); + bool set_value(bool rhs); + + // Set attribute value (equivalent to set_value without error checking) + xml_attribute& operator=(const char_t* rhs); + xml_attribute& operator=(int rhs); + xml_attribute& operator=(unsigned int rhs); + xml_attribute& operator=(double rhs); + xml_attribute& operator=(bool rhs); + + // Get next/previous attribute in the attribute list of the parent node + xml_attribute next_attribute() const; + xml_attribute previous_attribute() const; + + // Get hash value (unique for handles to the same object) + size_t hash_value() const; + + // Get internal pointer + xml_attribute_struct* internal_object() const; + }; + +#ifdef __BORLANDC__ + // Borland C++ workaround + bool PUGIXML_FUNCTION operator&&(const xml_attribute& lhs, bool rhs); + bool PUGIXML_FUNCTION operator||(const xml_attribute& lhs, bool rhs); +#endif + + // A light-weight handle for manipulating nodes in DOM tree + class PUGIXML_CLASS xml_node + { + friend class xml_attribute_iterator; + friend class xml_node_iterator; + friend class xml_named_node_iterator; + + protected: + xml_node_struct* _root; + + typedef void (*unspecified_bool_type)(xml_node***); + + public: + // Default constructor. Constructs an empty node. + xml_node(); + + // Constructs node from internal pointer + explicit xml_node(xml_node_struct* p); + + // Safe bool conversion operator + operator unspecified_bool_type() const; + + // Borland C++ workaround + bool operator!() const; + + // Comparison operators (compares wrapped node pointers) + bool operator==(const xml_node& r) const; + bool operator!=(const xml_node& r) const; + bool operator<(const xml_node& r) const; + bool operator>(const xml_node& r) const; + bool operator<=(const xml_node& r) const; + bool operator>=(const xml_node& r) const; + + // Check if node is empty. + bool empty() const; + + // Get node type + xml_node_type type() const; + + // Get node name/value, or "" if node is empty or it has no name/value + const char_t* name() const; + const char_t* value() const; + + // Get attribute list + xml_attribute first_attribute() const; + xml_attribute last_attribute() const; + + // Get children list + xml_node first_child() const; + xml_node last_child() const; + + // Get next/previous sibling in the children list of the parent node + xml_node next_sibling() const; + xml_node previous_sibling() const; + + // Get parent node + xml_node parent() const; + + // Get root of DOM tree this node belongs to + xml_node root() const; + + // Get text object for the current node + xml_text text() const; + + // Get child, attribute or next/previous sibling with the specified name + xml_node child(const char_t* name) const; + xml_attribute attribute(const char_t* name) const; + xml_node next_sibling(const char_t* name) const; + xml_node previous_sibling(const char_t* name) const; + + // Get child value of current node; that is, value of the first child node of type PCDATA/CDATA + const char_t* child_value() const; + + // Get child value of child with specified name. Equivalent to child(name).child_value(). + const char_t* child_value(const char_t* name) const; + + // Set node name/value (returns false if node is empty, there is not enough memory, or node can not have name/value) + bool set_name(const char_t* rhs); + bool set_value(const char_t* rhs); + + // Add attribute with specified name. Returns added attribute, or empty attribute on errors. + xml_attribute append_attribute(const char_t* name); + xml_attribute prepend_attribute(const char_t* name); + xml_attribute insert_attribute_after(const char_t* name, const xml_attribute& attr); + xml_attribute insert_attribute_before(const char_t* name, const xml_attribute& attr); + + // Add a copy of the specified attribute. Returns added attribute, or empty attribute on errors. + xml_attribute append_copy(const xml_attribute& proto); + xml_attribute prepend_copy(const xml_attribute& proto); + xml_attribute insert_copy_after(const xml_attribute& proto, const xml_attribute& attr); + xml_attribute insert_copy_before(const xml_attribute& proto, const xml_attribute& attr); + + // Add child node with specified type. Returns added node, or empty node on errors. + xml_node append_child(xml_node_type type = node_element); + xml_node prepend_child(xml_node_type type = node_element); + xml_node insert_child_after(xml_node_type type, const xml_node& node); + xml_node insert_child_before(xml_node_type type, const xml_node& node); + + // Add child element with specified name. Returns added node, or empty node on errors. + xml_node append_child(const char_t* name); + xml_node prepend_child(const char_t* name); + xml_node insert_child_after(const char_t* name, const xml_node& node); + xml_node insert_child_before(const char_t* name, const xml_node& node); + + // Add a copy of the specified node as a child. Returns added node, or empty node on errors. + xml_node append_copy(const xml_node& proto); + xml_node prepend_copy(const xml_node& proto); + xml_node insert_copy_after(const xml_node& proto, const xml_node& node); + xml_node insert_copy_before(const xml_node& proto, const xml_node& node); + + // Remove specified attribute + bool remove_attribute(const xml_attribute& a); + bool remove_attribute(const char_t* name); + + // Remove specified child + bool remove_child(const xml_node& n); + bool remove_child(const char_t* name); + + // Find attribute using predicate. Returns first attribute for which predicate returned true. + template xml_attribute find_attribute(Predicate pred) const + { + if (!_root) return xml_attribute(); + + for (xml_attribute attrib = first_attribute(); attrib; attrib = attrib.next_attribute()) + if (pred(attrib)) + return attrib; + + return xml_attribute(); + } + + // Find child node using predicate. Returns first child for which predicate returned true. + template xml_node find_child(Predicate pred) const + { + if (!_root) return xml_node(); + + for (xml_node node = first_child(); node; node = node.next_sibling()) + if (pred(node)) + return node; + + return xml_node(); + } + + // Find node from subtree using predicate. Returns first node from subtree (depth-first), for which predicate returned true. + template xml_node find_node(Predicate pred) const + { + if (!_root) return xml_node(); + + xml_node cur = first_child(); + + while (cur._root && cur._root != _root) + { + if (pred(cur)) return cur; + + if (cur.first_child()) cur = cur.first_child(); + else if (cur.next_sibling()) cur = cur.next_sibling(); + else + { + while (!cur.next_sibling() && cur._root != _root) cur = cur.parent(); + + if (cur._root != _root) cur = cur.next_sibling(); + } + } + + return xml_node(); + } + + // Find child node by attribute name/value + xml_node find_child_by_attribute(const char_t* name, const char_t* attr_name, const char_t* attr_value) const; + xml_node find_child_by_attribute(const char_t* attr_name, const char_t* attr_value) const; + + #ifndef PUGIXML_NO_STL + // Get the absolute node path from root as a text string. + string_t path(char_t delimiter = '/') const; + #endif + + // Search for a node by path consisting of node names and . or .. elements. + xml_node first_element_by_path(const char_t* path, char_t delimiter = '/') const; + + // Recursively traverse subtree with xml_tree_walker + bool traverse(xml_tree_walker& walker); + + #ifndef PUGIXML_NO_XPATH + // Select single node by evaluating XPath query. Returns first node from the resulting node set. + xpath_node select_single_node(const char_t* query, xpath_variable_set* variables = 0) const; + xpath_node select_single_node(const xpath_query& query) const; + + // Select node set by evaluating XPath query + xpath_node_set select_nodes(const char_t* query, xpath_variable_set* variables = 0) const; + xpath_node_set select_nodes(const xpath_query& query) const; + #endif + + // Print subtree using a writer object + void print(xml_writer& writer, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, xml_encoding encoding = encoding_auto, unsigned int depth = 0) const; + + #ifndef PUGIXML_NO_STL + // Print subtree to stream + void print(std::basic_ostream >& os, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, xml_encoding encoding = encoding_auto, unsigned int depth = 0) const; + void print(std::basic_ostream >& os, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, unsigned int depth = 0) const; + #endif + + // Child nodes iterators + typedef xml_node_iterator iterator; + + iterator begin() const; + iterator end() const; + + // Attribute iterators + typedef xml_attribute_iterator attribute_iterator; + + attribute_iterator attributes_begin() const; + attribute_iterator attributes_end() const; + + // Range-based for support + xml_object_range children() const; + xml_object_range children(const char_t* name) const; + xml_object_range attributes() const; + + // Get node offset in parsed file/string (in char_t units) for debugging purposes + ptrdiff_t offset_debug() const; + + // Get hash value (unique for handles to the same object) + size_t hash_value() const; + + // Get internal pointer + xml_node_struct* internal_object() const; + }; + +#ifdef __BORLANDC__ + // Borland C++ workaround + bool PUGIXML_FUNCTION operator&&(const xml_node& lhs, bool rhs); + bool PUGIXML_FUNCTION operator||(const xml_node& lhs, bool rhs); +#endif + + // A helper for working with text inside PCDATA nodes + class PUGIXML_CLASS xml_text + { + friend class xml_node; + + xml_node_struct* _root; + + typedef void (*unspecified_bool_type)(xml_text***); + + explicit xml_text(xml_node_struct* root); + + xml_node_struct* _data_new(); + xml_node_struct* _data() const; + + public: + // Default constructor. Constructs an empty object. + xml_text(); + + // Safe bool conversion operator + operator unspecified_bool_type() const; + + // Borland C++ workaround + bool operator!() const; + + // Check if text object is empty + bool empty() const; + + // Get text, or "" if object is empty + const char_t* get() const; + + // Get text, or the default value if object is empty + const char_t* as_string(const char_t* def = PUGIXML_TEXT("")) const; + + // Get text as a number, or the default value if conversion did not succeed or object is empty + int as_int(int def = 0) const; + unsigned int as_uint(unsigned int def = 0) const; + double as_double(double def = 0) const; + float as_float(float def = 0) const; + + // Get text as bool (returns true if first character is in '1tTyY' set), or the default value if object is empty + bool as_bool(bool def = false) const; + + // Set text (returns false if object is empty or there is not enough memory) + bool set(const char_t* rhs); + + // Set text with type conversion (numbers are converted to strings, boolean is converted to "true"/"false") + bool set(int rhs); + bool set(unsigned int rhs); + bool set(double rhs); + bool set(bool rhs); + + // Set text (equivalent to set without error checking) + xml_text& operator=(const char_t* rhs); + xml_text& operator=(int rhs); + xml_text& operator=(unsigned int rhs); + xml_text& operator=(double rhs); + xml_text& operator=(bool rhs); + + // Get the data node (node_pcdata or node_cdata) for this object + xml_node data() const; + }; + +#ifdef __BORLANDC__ + // Borland C++ workaround + bool PUGIXML_FUNCTION operator&&(const xml_text& lhs, bool rhs); + bool PUGIXML_FUNCTION operator||(const xml_text& lhs, bool rhs); +#endif + + // Child node iterator (a bidirectional iterator over a collection of xml_node) + class PUGIXML_CLASS xml_node_iterator + { + friend class xml_node; + + private: + mutable xml_node _wrap; + xml_node _parent; + + xml_node_iterator(xml_node_struct* ref, xml_node_struct* parent); + + public: + // Iterator traits + typedef ptrdiff_t difference_type; + typedef xml_node value_type; + typedef xml_node* pointer; + typedef xml_node& reference; + + #ifndef PUGIXML_NO_STL + typedef std::bidirectional_iterator_tag iterator_category; + #endif + + // Default constructor + xml_node_iterator(); + + // Construct an iterator which points to the specified node + xml_node_iterator(const xml_node& node); + + // Iterator operators + bool operator==(const xml_node_iterator& rhs) const; + bool operator!=(const xml_node_iterator& rhs) const; + + xml_node& operator*() const; + xml_node* operator->() const; + + const xml_node_iterator& operator++(); + xml_node_iterator operator++(int); + + const xml_node_iterator& operator--(); + xml_node_iterator operator--(int); + }; + + // Attribute iterator (a bidirectional iterator over a collection of xml_attribute) + class PUGIXML_CLASS xml_attribute_iterator + { + friend class xml_node; + + private: + mutable xml_attribute _wrap; + xml_node _parent; + + xml_attribute_iterator(xml_attribute_struct* ref, xml_node_struct* parent); + + public: + // Iterator traits + typedef ptrdiff_t difference_type; + typedef xml_attribute value_type; + typedef xml_attribute* pointer; + typedef xml_attribute& reference; + + #ifndef PUGIXML_NO_STL + typedef std::bidirectional_iterator_tag iterator_category; + #endif + + // Default constructor + xml_attribute_iterator(); + + // Construct an iterator which points to the specified attribute + xml_attribute_iterator(const xml_attribute& attr, const xml_node& parent); + + // Iterator operators + bool operator==(const xml_attribute_iterator& rhs) const; + bool operator!=(const xml_attribute_iterator& rhs) const; + + xml_attribute& operator*() const; + xml_attribute* operator->() const; + + const xml_attribute_iterator& operator++(); + xml_attribute_iterator operator++(int); + + const xml_attribute_iterator& operator--(); + xml_attribute_iterator operator--(int); + }; + + // Named node range helper + class xml_named_node_iterator + { + public: + // Iterator traits + typedef ptrdiff_t difference_type; + typedef xml_node value_type; + typedef xml_node* pointer; + typedef xml_node& reference; + + #ifndef PUGIXML_NO_STL + typedef std::forward_iterator_tag iterator_category; + #endif + + // Default constructor + xml_named_node_iterator(); + + // Construct an iterator which points to the specified node + xml_named_node_iterator(const xml_node& node, const char_t* name); + + // Iterator operators + bool operator==(const xml_named_node_iterator& rhs) const; + bool operator!=(const xml_named_node_iterator& rhs) const; + + xml_node& operator*() const; + xml_node* operator->() const; + + const xml_named_node_iterator& operator++(); + xml_named_node_iterator operator++(int); + + private: + mutable xml_node _node; + const char_t* _name; + }; + + // Abstract tree walker class (see xml_node::traverse) + class PUGIXML_CLASS xml_tree_walker + { + friend class xml_node; + + private: + int _depth; + + protected: + // Get current traversal depth + int depth() const; + + public: + xml_tree_walker(); + virtual ~xml_tree_walker(); + + // Callback that is called when traversal begins + virtual bool begin(xml_node& node); + + // Callback that is called for each node traversed + virtual bool for_each(xml_node& node) = 0; + + // Callback that is called when traversal ends + virtual bool end(xml_node& node); + }; + + // Parsing status, returned as part of xml_parse_result object + enum xml_parse_status + { + status_ok = 0, // No error + + status_file_not_found, // File was not found during load_file() + status_io_error, // Error reading from file/stream + status_out_of_memory, // Could not allocate memory + status_internal_error, // Internal error occurred + + status_unrecognized_tag, // Parser could not determine tag type + + status_bad_pi, // Parsing error occurred while parsing document declaration/processing instruction + status_bad_comment, // Parsing error occurred while parsing comment + status_bad_cdata, // Parsing error occurred while parsing CDATA section + status_bad_doctype, // Parsing error occurred while parsing document type declaration + status_bad_pcdata, // Parsing error occurred while parsing PCDATA section + status_bad_start_element, // Parsing error occurred while parsing start element tag + status_bad_attribute, // Parsing error occurred while parsing element attribute + status_bad_end_element, // Parsing error occurred while parsing end element tag + status_end_element_mismatch // There was a mismatch of start-end tags (closing tag had incorrect name, some tag was not closed or there was an excessive closing tag) + }; + + // Parsing result + struct PUGIXML_CLASS xml_parse_result + { + // Parsing status (see xml_parse_status) + xml_parse_status status; + + // Last parsed offset (in char_t units from start of input data) + ptrdiff_t offset; + + // Source document encoding + xml_encoding encoding; + + // Default constructor, initializes object to failed state + xml_parse_result(); + + // Cast to bool operator + operator bool() const; + + // Get error description + const char* description() const; + }; + + // Document class (DOM tree root) + class PUGIXML_CLASS xml_document: public xml_node + { + private: + char_t* _buffer; + + char _memory[192]; + + // Non-copyable semantics + xml_document(const xml_document&); + const xml_document& operator=(const xml_document&); + + void create(); + void destroy(); + + xml_parse_result load_buffer_impl(void* contents, size_t size, unsigned int options, xml_encoding encoding, bool is_mutable, bool own); + + public: + // Default constructor, makes empty document + xml_document(); + + // Destructor, invalidates all node/attribute handles to this document + ~xml_document(); + + // Removes all nodes, leaving the empty document + void reset(); + + // Removes all nodes, then copies the entire contents of the specified document + void reset(const xml_document& proto); + + #ifndef PUGIXML_NO_STL + // Load document from stream. + xml_parse_result load(std::basic_istream >& stream, unsigned int options = parse_default, xml_encoding encoding = encoding_auto); + xml_parse_result load(std::basic_istream >& stream, unsigned int options = parse_default); + #endif + + // Load document from zero-terminated string. No encoding conversions are applied. + xml_parse_result load(const char_t* contents, unsigned int options = parse_default); + + // Load document from file + xml_parse_result load_file(const char* path, unsigned int options = parse_default, xml_encoding encoding = encoding_auto); + xml_parse_result load_file(const wchar_t* path, unsigned int options = parse_default, xml_encoding encoding = encoding_auto); + + // Load document from buffer. Copies/converts the buffer, so it may be deleted or changed after the function returns. + xml_parse_result load_buffer(const void* contents, size_t size, unsigned int options = parse_default, xml_encoding encoding = encoding_auto); + + // Load document from buffer, using the buffer for in-place parsing (the buffer is modified and used for storage of document data). + // You should ensure that buffer data will persist throughout the document's lifetime, and free the buffer memory manually once document is destroyed. + xml_parse_result load_buffer_inplace(void* contents, size_t size, unsigned int options = parse_default, xml_encoding encoding = encoding_auto); + + // Load document from buffer, using the buffer for in-place parsing (the buffer is modified and used for storage of document data). + // You should allocate the buffer with pugixml allocation function; document will free the buffer when it is no longer needed (you can't use it anymore). + xml_parse_result load_buffer_inplace_own(void* contents, size_t size, unsigned int options = parse_default, xml_encoding encoding = encoding_auto); + + // Save XML document to writer (semantics is slightly different from xml_node::print, see documentation for details). + void save(xml_writer& writer, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, xml_encoding encoding = encoding_auto) const; + + #ifndef PUGIXML_NO_STL + // Save XML document to stream (semantics is slightly different from xml_node::print, see documentation for details). + void save(std::basic_ostream >& stream, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, xml_encoding encoding = encoding_auto) const; + void save(std::basic_ostream >& stream, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default) const; + #endif + + // Save XML to file + bool save_file(const char* path, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, xml_encoding encoding = encoding_auto) const; + bool save_file(const wchar_t* path, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, xml_encoding encoding = encoding_auto) const; + + // Get document element + xml_node document_element() const; + }; + +#ifndef PUGIXML_NO_XPATH + // XPath query return type + enum xpath_value_type + { + xpath_type_none, // Unknown type (query failed to compile) + xpath_type_node_set, // Node set (xpath_node_set) + xpath_type_number, // Number + xpath_type_string, // String + xpath_type_boolean // Boolean + }; + + // XPath parsing result + struct PUGIXML_CLASS xpath_parse_result + { + // Error message (0 if no error) + const char* error; + + // Last parsed offset (in char_t units from string start) + ptrdiff_t offset; + + // Default constructor, initializes object to failed state + xpath_parse_result(); + + // Cast to bool operator + operator bool() const; + + // Get error description + const char* description() const; + }; + + // A single XPath variable + class PUGIXML_CLASS xpath_variable + { + friend class xpath_variable_set; + + protected: + xpath_value_type _type; + xpath_variable* _next; + + xpath_variable(); + + // Non-copyable semantics + xpath_variable(const xpath_variable&); + xpath_variable& operator=(const xpath_variable&); + + public: + // Get variable name + const char_t* name() const; + + // Get variable type + xpath_value_type type() const; + + // Get variable value; no type conversion is performed, default value (false, NaN, empty string, empty node set) is returned on type mismatch error + bool get_boolean() const; + double get_number() const; + const char_t* get_string() const; + const xpath_node_set& get_node_set() const; + + // Set variable value; no type conversion is performed, false is returned on type mismatch error + bool set(bool value); + bool set(double value); + bool set(const char_t* value); + bool set(const xpath_node_set& value); + }; + + // A set of XPath variables + class PUGIXML_CLASS xpath_variable_set + { + private: + xpath_variable* _data[64]; + + // Non-copyable semantics + xpath_variable_set(const xpath_variable_set&); + xpath_variable_set& operator=(const xpath_variable_set&); + + xpath_variable* find(const char_t* name) const; + + public: + // Default constructor/destructor + xpath_variable_set(); + ~xpath_variable_set(); + + // Add a new variable or get the existing one, if the types match + xpath_variable* add(const char_t* name, xpath_value_type type); + + // Set value of an existing variable; no type conversion is performed, false is returned if there is no such variable or if types mismatch + bool set(const char_t* name, bool value); + bool set(const char_t* name, double value); + bool set(const char_t* name, const char_t* value); + bool set(const char_t* name, const xpath_node_set& value); + + // Get existing variable by name + xpath_variable* get(const char_t* name); + const xpath_variable* get(const char_t* name) const; + }; + + // A compiled XPath query object + class PUGIXML_CLASS xpath_query + { + private: + void* _impl; + xpath_parse_result _result; + + typedef void (*unspecified_bool_type)(xpath_query***); + + // Non-copyable semantics + xpath_query(const xpath_query&); + xpath_query& operator=(const xpath_query&); + + public: + // Construct a compiled object from XPath expression. + // If PUGIXML_NO_EXCEPTIONS is not defined, throws xpath_exception on compilation errors. + explicit xpath_query(const char_t* query, xpath_variable_set* variables = 0); + + // Destructor + ~xpath_query(); + + // Get query expression return type + xpath_value_type return_type() const; + + // Evaluate expression as boolean value in the specified context; performs type conversion if necessary. + // If PUGIXML_NO_EXCEPTIONS is not defined, throws std::bad_alloc on out of memory errors. + bool evaluate_boolean(const xpath_node& n) const; + + // Evaluate expression as double value in the specified context; performs type conversion if necessary. + // If PUGIXML_NO_EXCEPTIONS is not defined, throws std::bad_alloc on out of memory errors. + double evaluate_number(const xpath_node& n) const; + + #ifndef PUGIXML_NO_STL + // Evaluate expression as string value in the specified context; performs type conversion if necessary. + // If PUGIXML_NO_EXCEPTIONS is not defined, throws std::bad_alloc on out of memory errors. + string_t evaluate_string(const xpath_node& n) const; + #endif + + // Evaluate expression as string value in the specified context; performs type conversion if necessary. + // At most capacity characters are written to the destination buffer, full result size is returned (includes terminating zero). + // If PUGIXML_NO_EXCEPTIONS is not defined, throws std::bad_alloc on out of memory errors. + // If PUGIXML_NO_EXCEPTIONS is defined, returns empty set instead. + size_t evaluate_string(char_t* buffer, size_t capacity, const xpath_node& n) const; + + // Evaluate expression as node set in the specified context. + // If PUGIXML_NO_EXCEPTIONS is not defined, throws xpath_exception on type mismatch and std::bad_alloc on out of memory errors. + // If PUGIXML_NO_EXCEPTIONS is defined, returns empty node set instead. + xpath_node_set evaluate_node_set(const xpath_node& n) const; + + // Get parsing result (used to get compilation errors in PUGIXML_NO_EXCEPTIONS mode) + const xpath_parse_result& result() const; + + // Safe bool conversion operator + operator unspecified_bool_type() const; + + // Borland C++ workaround + bool operator!() const; + }; + + #ifndef PUGIXML_NO_EXCEPTIONS + // XPath exception class + class PUGIXML_CLASS xpath_exception: public std::exception + { + private: + xpath_parse_result _result; + + public: + // Construct exception from parse result + explicit xpath_exception(const xpath_parse_result& result); + + // Get error message + virtual const char* what() const throw(); + + // Get parse result + const xpath_parse_result& result() const; + }; + #endif + + // XPath node class (either xml_node or xml_attribute) + class PUGIXML_CLASS xpath_node + { + private: + xml_node _node; + xml_attribute _attribute; + + typedef void (*unspecified_bool_type)(xpath_node***); + + public: + // Default constructor; constructs empty XPath node + xpath_node(); + + // Construct XPath node from XML node/attribute + xpath_node(const xml_node& node); + xpath_node(const xml_attribute& attribute, const xml_node& parent); + + // Get node/attribute, if any + xml_node node() const; + xml_attribute attribute() const; + + // Get parent of contained node/attribute + xml_node parent() const; + + // Safe bool conversion operator + operator unspecified_bool_type() const; + + // Borland C++ workaround + bool operator!() const; + + // Comparison operators + bool operator==(const xpath_node& n) const; + bool operator!=(const xpath_node& n) const; + }; + +#ifdef __BORLANDC__ + // Borland C++ workaround + bool PUGIXML_FUNCTION operator&&(const xpath_node& lhs, bool rhs); + bool PUGIXML_FUNCTION operator||(const xpath_node& lhs, bool rhs); +#endif + + // A fixed-size collection of XPath nodes + class PUGIXML_CLASS xpath_node_set + { + public: + // Collection type + enum type_t + { + type_unsorted, // Not ordered + type_sorted, // Sorted by document order (ascending) + type_sorted_reverse // Sorted by document order (descending) + }; + + // Constant iterator type + typedef const xpath_node* const_iterator; + + // Default constructor. Constructs empty set. + xpath_node_set(); + + // Constructs a set from iterator range; data is not checked for duplicates and is not sorted according to provided type, so be careful + xpath_node_set(const_iterator begin, const_iterator end, type_t type = type_unsorted); + + // Destructor + ~xpath_node_set(); + + // Copy constructor/assignment operator + xpath_node_set(const xpath_node_set& ns); + xpath_node_set& operator=(const xpath_node_set& ns); + + // Get collection type + type_t type() const; + + // Get collection size + size_t size() const; + + // Indexing operator + const xpath_node& operator[](size_t index) const; + + // Collection iterators + const_iterator begin() const; + const_iterator end() const; + + // Sort the collection in ascending/descending order by document order + void sort(bool reverse = false); + + // Get first node in the collection by document order + xpath_node first() const; + + // Check if collection is empty + bool empty() const; + + private: + type_t _type; + + xpath_node _storage; + + xpath_node* _begin; + xpath_node* _end; + + void _assign(const_iterator begin, const_iterator end); + }; +#endif + +#ifndef PUGIXML_NO_STL + // Convert wide string to UTF8 + std::basic_string, std::allocator > PUGIXML_FUNCTION as_utf8(const wchar_t* str); + std::basic_string, std::allocator > PUGIXML_FUNCTION as_utf8(const std::basic_string, std::allocator >& str); + + // Convert UTF8 to wide string + std::basic_string, std::allocator > PUGIXML_FUNCTION as_wide(const char* str); + std::basic_string, std::allocator > PUGIXML_FUNCTION as_wide(const std::basic_string, std::allocator >& str); +#endif + + // Memory allocation function interface; returns pointer to allocated memory or NULL on failure + typedef void* (*allocation_function)(size_t size); + + // Memory deallocation function interface + typedef void (*deallocation_function)(void* ptr); + + // Override default memory management functions. All subsequent allocations/deallocations will be performed via supplied functions. + void PUGIXML_FUNCTION set_memory_management_functions(allocation_function allocate, deallocation_function deallocate); + + // Get current memory management functions + allocation_function PUGIXML_FUNCTION get_memory_allocation_function(); + deallocation_function PUGIXML_FUNCTION get_memory_deallocation_function(); +} + +#if !defined(PUGIXML_NO_STL) && (defined(_MSC_VER) || defined(__ICC)) +namespace std +{ + // Workarounds for (non-standard) iterator category detection for older versions (MSVC7/IC8 and earlier) + std::bidirectional_iterator_tag PUGIXML_FUNCTION _Iter_cat(const pugi::xml_node_iterator&); + std::bidirectional_iterator_tag PUGIXML_FUNCTION _Iter_cat(const pugi::xml_attribute_iterator&); + std::forward_iterator_tag PUGIXML_FUNCTION _Iter_cat(const pugi::xml_named_node_iterator&); +} +#endif + +#if !defined(PUGIXML_NO_STL) && defined(__SUNPRO_CC) +namespace std +{ + // Workarounds for (non-standard) iterator category detection + std::bidirectional_iterator_tag PUGIXML_FUNCTION __iterator_category(const pugi::xml_node_iterator&); + std::bidirectional_iterator_tag PUGIXML_FUNCTION __iterator_category(const pugi::xml_attribute_iterator&); + std::forward_iterator_tag PUGIXML_FUNCTION __iterator_category(const pugi::xml_named_node_iterator&); +} +#endif + +#endif + +/** + * Copyright (c) 2006-2012 Arseny Kapoulkine + * + * 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. + */ diff --git a/include/cocos2dx/robtop/xml/readme.txt b/include/cocos2dx/robtop/xml/readme.txt new file mode 100644 index 0000000..aa3353d --- /dev/null +++ b/include/cocos2dx/robtop/xml/readme.txt @@ -0,0 +1,52 @@ +pugixml 1.2 - an XML processing library + +Copyright (C) 2006-2012, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com) +Report bugs and download new versions at http://pugixml.org/ + +This is the distribution of pugixml, which is a C++ XML processing library, +which consists of a DOM-like interface with rich traversal/modification +capabilities, an extremely fast XML parser which constructs the DOM tree from +an XML file/buffer, and an XPath 1.0 implementation for complex data-driven +tree queries. Full Unicode support is also available, with Unicode interface +variants and conversions between different Unicode encodings (which happen +automatically during parsing/saving). + +The distribution contains the following folders: + + contrib/ - various contributions to pugixml + + docs/ - documentation + docs/samples - pugixml usage examples + docs/quickstart.html - quick start guide + docs/manual.html - complete manual + + scripts/ - project files for IDE/build systems + + src/ - header and source files + + readme.txt - this file. + +This library is distributed under the MIT License: + +Copyright (c) 2006-2012 Arseny Kapoulkine + +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. diff --git a/include/extensions/AssetsManager/AssetsManager.h b/include/extensions/AssetsManager/AssetsManager.h new file mode 100644 index 0000000..bad245a --- /dev/null +++ b/include/extensions/AssetsManager/AssetsManager.h @@ -0,0 +1,221 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + Copyright (c) Microsoft Open 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 __AssetsManager__ +#define __AssetsManager__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" + +#if (CC_TARGET_PLATFORM != CC_PLATFORM_WINRT) && (CC_TARGET_PLATFORM != CC_PLATFORM_WP8) +#include +#include +#include + +NS_CC_EXT_BEGIN + +class AssetsManagerDelegateProtocol; + +/* + * This class is used to auto update resources, such as pictures or scripts. + * The updated package should be a zip file. And there should be a file named + * version in the server, which contains version code. + * @js NA + * @lua NA + */ +class AssetsManager +{ +public: + enum ErrorCode + { + // Error caused by creating a file to store downloaded data + kCreateFile, + /** Error caused by network + -- network unavaivable + -- timeout + -- ... + */ + kNetwork, + /** There is not a new version + */ + kNoNewVersion, + /** Error caused in uncompressing stage + -- can not open zip file + -- can not read file global information + -- can not read file information + -- can not create a directory + -- ... + */ + kUncompress, + }; + + /* @brief Creates a AssetsManager with new package url, version code url and storage path. + * + * @param packageUrl URL of new package, the package should be a zip file. + * @param versionFileUrl URL of version file. It should contain version code of new package. + * @param storagePath The path to store downloaded resources. + */ + AssetsManager(const char* packageUrl = NULL, const char* versionFileUrl = NULL, const char* storagePath = NULL); + + virtual ~AssetsManager(); + + /* @brief Check out if there is a new version resource. + * You may use this method before updating, then let user determine whether + * he wants to update resources. + */ + virtual bool checkUpdate(); + + /* @brief Download new package if there is a new version, and uncompress downloaded zip file. + * Ofcourse it will set search path that stores downloaded files. + */ + virtual void update(); + + /* @brief Gets url of package. + */ + const char* getPackageUrl() const; + + /* @brief Sets package url. + */ + void setPackageUrl(const char* packageUrl); + + /* @brief Gets version file url. + */ + const char* getVersionFileUrl() const; + + /* @brief Gets version file url. + */ + void setVersionFileUrl(const char* versionFileUrl); + + /* @brief Gets current version code. + */ + std::string getVersion(); + + /* @brief Deletes recorded version code. + */ + void deleteVersion(); + + /* @brief Gets storage path. + */ + const char* getStoragePath() const; + + /* @brief Sets storage path. + * + * @param storagePath The path to store downloaded resources. + * @warm The path should be a valid path. + */ + void setStoragePath(const char* storagePath); + + /** @brief Sets delegate, the delegate will receive messages + */ + void setDelegate(AssetsManagerDelegateProtocol *delegate); + + /** @brief Sets connection time out in seconds + */ + void setConnectionTimeout(unsigned int timeout); + + /** @brief Gets connection time out in secondes + */ + unsigned int getConnectionTimeout(); + + /* downloadAndUncompress is the entry of a new thread + */ + friend void* assetsManagerDownloadAndUncompress(void*); + friend int assetsManagerProgressFunc(void *, double, double, double, double); + +protected: + bool downLoad(); + void checkStoragePath(); + bool uncompress(); + bool createDirectory(const char *path); + void setSearchPath(); + void sendErrorMessage(ErrorCode code); + +private: + typedef struct _Message + { + public: + _Message() : what(0), obj(NULL){} + unsigned int what; // message type + void* obj; + } Message; + + class Helper : public cocos2d::CCObject + { + public: + Helper(); + ~Helper(); + + virtual void update(float dt); + void sendMessage(Message *msg); + + private: + void handleUpdateSucceed(Message *msg); + + std::list *_messageQueue; + pthread_mutex_t _messageQueueMutex; + }; + +private: + //! The path to store downloaded resources. + std::string _storagePath; + + //! The version of downloaded resources. + std::string _version; + + std::string _packageUrl; + std::string _versionFileUrl; + + std::string _downloadedVersion; + + CURL *_curl; + Helper *_schedule; + pthread_t *_tid; + unsigned int _connectionTimeout; + + AssetsManagerDelegateProtocol *_delegate; // weak reference +}; + +class AssetsManagerDelegateProtocol +{ +public: + /* @brief Call back function for error + @param errorCode Type of error + */ + virtual void onError(AssetsManager::ErrorCode errorCode) {}; + /** @brief Call back function for recording downloading percent + @param percent How much percent downloaded + @warn This call back function just for recording downloading percent. + AssetsManager will do some other thing after downloading, you should + write code in onSuccess() after downloading. + */ + virtual void onProgress(int percent) {}; + /** @brief Call back function for success + */ + virtual void onSuccess() {}; +}; + +NS_CC_EXT_END; +#endif // CC_TARGET_PLATFORM != CC_PLATFORM_WINRT +#endif /* defined(__AssetsManager__) */ diff --git a/include/extensions/CCBReader/CCBAnimationManager.h b/include/extensions/CCBReader/CCBAnimationManager.h new file mode 100644 index 0000000..1e9dc6c --- /dev/null +++ b/include/extensions/CCBReader/CCBAnimationManager.h @@ -0,0 +1,251 @@ +#ifndef __CCB_CCBANIMATION_MANAGER_H__ +#define __CCB_CCBANIMATION_MANAGER_H__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" +#include "CCBSequence.h" +#include "CCBValue.h" +#include "CCBSequenceProperty.h" +#include "GUI/CCControlExtension/CCControl.h" + +NS_CC_EXT_BEGIN +/** + * @js NA + * @lua NA + */ +class CCBAnimationManagerDelegate +{ +public: + virtual void completedAnimationSequenceNamed(const char *name) = 0; +}; + +class CCBAnimationManager : public CCObject +{ +private: + CCArray *mSequences; + CCDictionary *mNodeSequences; + CCDictionary *mBaseValues; + int mAutoPlaySequenceId; + + CCNode *mRootNode; + + CCSize mRootContainerSize; + + CCBAnimationManagerDelegate *mDelegate; + CCBSequence *mRunningSequence; + + CCArray *mDocumentOutletNames; + CCArray *mDocumentOutletNodes; + CCArray *mDocumentCallbackNames; + CCArray *mDocumentCallbackNodes; + CCArray *mDocumentCallbackControlEvents; + CCArray *mKeyframeCallbacks; + CCDictionary *mKeyframeCallFuncs; + + std::string mDocumentControllerName; + std::string lastCompletedSequenceName; + + SEL_CallFunc mAnimationCompleteCallbackFunc; + CCObject *mTarget; + + +public: + bool jsControlled; + /** + * @js ctor + */ + CCBAnimationManager(); + /** + * @js NA + */ + ~CCBAnimationManager(); + + + CCObject *mOwner; + + virtual bool init(); + + CCArray* getSequences(); + void setSequences(CCArray* seq); + + + int getAutoPlaySequenceId(); + void setAutoPlaySequenceId(int autoPlaySequenceId); + + CCNode* getRootNode(); + void setRootNode(CCNode* pRootNode); // weak reference + + + void addDocumentCallbackNode(CCNode *node); + void addDocumentCallbackName(std::string name); + void addDocumentCallbackControlEvents(CCControlEvent eventType); + void addDocumentOutletNode(CCNode *node); + void addDocumentOutletName(std::string name); + + void setDocumentControllerName(const std::string &name); + + std::string getDocumentControllerName(); + CCArray* getDocumentCallbackNames(); + CCArray* getDocumentCallbackNodes(); + CCArray* getDocumentCallbackControlEvents(); + CCArray* getDocumentOutletNames(); + CCArray* getDocumentOutletNodes(); + std::string getLastCompletedSequenceName(); + + CCArray* getKeyframeCallbacks(); + + const CCSize& getRootContainerSize(); + void setRootContainerSize(const CCSize &rootContainerSize); + + CCBAnimationManagerDelegate* getDelegate(); + void setDelegate(CCBAnimationManagerDelegate* pDelegate); // retain + + const char* getRunningSequenceName(); + + const CCSize& getContainerSize(CCNode* pNode); + + void addNode(CCNode *pNode, CCDictionary *pSeq); + void setBaseValue(CCObject *pValue, CCNode *pNode, const char *pPropName); + void moveAnimationsFromNode(CCNode* fromNode, CCNode* toNode); + + /** @deprecated This interface will be deprecated sooner or later.*/ + CC_DEPRECATED_ATTRIBUTE void runAnimations(const char *pName, float fTweenDuration); + /** @deprecated This interface will be deprecated sooner or later.*/ + CC_DEPRECATED_ATTRIBUTE void runAnimations(const char *pName); + /** @deprecated This interface will be deprecated sooner or later.*/ + CC_DEPRECATED_ATTRIBUTE void runAnimations(int nSeqId, float fTweenDuraiton); + + void runAnimationsForSequenceNamedTweenDuration(const char *pName, float fTweenDuration); + void runAnimationsForSequenceNamed(const char *pName); + void runAnimationsForSequenceIdTweenDuration(int nSeqId, float fTweenDuraiton); + /** + * @lua NA + */ + void setAnimationCompletedCallback(CCObject *target, SEL_CallFunc callbackFunc); + + void debug(); + /** + * @js setCallFuncForJSCallbackNamed + */ + void setCallFunc(CCCallFunc *callFunc, const std::string &callbackNamed); + + CCObject* actionForCallbackChannel(CCBSequenceProperty* channel); + CCObject* actionForSoundChannel(CCBSequenceProperty* channel); + +private: + CCObject* getBaseValue(CCNode *pNode, const char* pPropName); + int getSequenceId(const char* pSequenceName); + CCBSequence* getSequence(int nSequenceId); + CCActionInterval* getAction(CCBKeyframe *pKeyframe0, CCBKeyframe *pKeyframe1, const char *pPropName, CCNode *pNode); + void setAnimatedProperty(const char *pPropName, CCNode *pNode, CCObject *pValue, float fTweenDuraion); + void setFirstFrame(CCNode *pNode, CCBSequenceProperty *pSeqProp, float fTweenDuration); + CCActionInterval* getEaseAction(CCActionInterval *pAction, int nEasingType, float fEasingOpt); + void runAction(CCNode *pNode, CCBSequenceProperty *pSeqProp, float fTweenDuration); + void sequenceCompleted(); +}; +/** + * @js NA + * @lua NA + */ +class CCBSetSpriteFrame : public CCActionInstant +{ +private: + CCSpriteFrame *mSpriteFrame; + +public: + ~CCBSetSpriteFrame(); + + /** creates a Place action with a position */ + static CCBSetSpriteFrame* create(CCSpriteFrame *pSpriteFrame); + bool initWithSpriteFrame(CCSpriteFrame *pSpriteFrame); + virtual void update(float time); + virtual CCObject* copyWithZone(CCZone *pZone); +}; + + +/** + * @js NA + * @lua NA + */ +class CCBSoundEffect : public CCActionInstant +{ +private: + std::string mSoundFile; + float mPitch, mPan, mGain; + +public: + ~CCBSoundEffect(); + + static CCBSoundEffect* actionWithSoundFile(const std::string &file, float pitch, float pan, float gain); + bool initWithSoundFile(const std::string &file, float pitch, float pan, float gain); + virtual void update(float time); + virtual CCObject* copyWithZone(CCZone *pZone); +}; + +/** + * @js NA + * @lua NA + */ +class CCBRotateTo : public CCActionInterval +{ +private: + float mStartAngle; + float mDstAngle; + float mDiffAngle; + +public: + static CCBRotateTo* create(float fDuration, float fAngle); + bool initWithDuration(float fDuration, float fAngle); + virtual void update(float time); + virtual CCObject* copyWithZone(CCZone *pZone); + virtual void startWithTarget(CCNode *pNode); +}; + +/** + * @js NA + * @lua NA + */ +class CCBRotateXTo: public CCActionInterval { +private: + float mStartAngle; + float mDstAngle; + float mDiffAngle; +public: + static CCBRotateXTo* create(float fDuration, float fAngle); + bool initWithDuration(float fDuration, float fAngle); + virtual void startWithTarget(CCNode *pNode); + virtual CCObject* copyWithZone(CCZone *pZone); + virtual void update(float time); +}; + +/** + * @js NA + * @lua NA + */ +class CCBRotateYTo: public CCActionInterval { +private: + float mStartAngle; + float mDstAngle; + float mDiffAngle; + +public: + static CCBRotateYTo* create(float fDuration, float fAngle); + bool initWithDuration(float fDuration, float fAngle); + virtual void startWithTarget(CCNode *pNode); + virtual CCObject* copyWithZone(CCZone *pZone); + virtual void update(float time); +}; + + +class CCBEaseInstant : public CCActionEase +{ +public: + static CCBEaseInstant* create(CCActionInterval *pAction); + + virtual void update(float dt); +}; + + +NS_CC_EXT_END + +#endif // __CCB_CCBANIMATION_MANAGER_H__ diff --git a/include/extensions/CCBReader/CCBFileLoader.h b/include/extensions/CCBReader/CCBFileLoader.h new file mode 100644 index 0000000..6a9a6d9 --- /dev/null +++ b/include/extensions/CCBReader/CCBFileLoader.h @@ -0,0 +1,28 @@ +#ifndef _CCB_CCBFILELOADER_H_ +#define _CCB_CCBFILELOADER_H_ + +#include "CCNodeLoader.h" +#include "CCBReader.h" + +NS_CC_EXT_BEGIN + +/* Forward declaration. */ +class CCBReader; +/** + * @js NA + * @lua NA + */ +class CCBFileLoader : public CCNodeLoader { + public: + virtual ~CCBFileLoader() {}; + CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(CCBFileLoader, loader); + + protected: + CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(CCBFile); + + virtual void onHandlePropTypeCCBFile(CCNode * pNode, CCNode * pParent, const char * pPropertyName, CCNode * pCCBFileNode, CCBReader * pCCBReader); +}; + +NS_CC_EXT_END + +#endif diff --git a/include/extensions/CCBReader/CCBKeyframe.h b/include/extensions/CCBReader/CCBKeyframe.h new file mode 100644 index 0000000..a602669 --- /dev/null +++ b/include/extensions/CCBReader/CCBKeyframe.h @@ -0,0 +1,39 @@ +#ifndef __CCB_KEYFRAME_H__ +#define __CCB_KEYFRAME_H__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" + +NS_CC_EXT_BEGIN +/** + * @js NA + * @lua NA + */ +class CCBKeyframe : public CCObject +{ +private: + CCObject *mValue; + float mTime; + int mEasingType; + float mEasingOpt; + +public: + CCBKeyframe(); + ~CCBKeyframe(); + + CCObject* getValue(); + void setValue(CCObject *pValue); // retain + + float getTime(); + void setTime(float fTime); + + int getEasingType(); + void setEasingType(int nEasingType); + + float getEasingOpt(); + void setEasingOpt(float fEasingOpt); +}; + +NS_CC_EXT_END + +#endif // __CCB_KEYFRAME_H__ diff --git a/include/extensions/CCBReader/CCBMemberVariableAssigner.h b/include/extensions/CCBReader/CCBMemberVariableAssigner.h new file mode 100644 index 0000000..2165d90 --- /dev/null +++ b/include/extensions/CCBReader/CCBMemberVariableAssigner.h @@ -0,0 +1,58 @@ +#ifndef _CCB_CCBMEMBERVARIABLEASSIGNER_H_ +#define _CCB_CCBMEMBERVARIABLEASSIGNER_H_ + +#include "cocos2d.h" +#include "CCBValue.h" + +NS_CC_EXT_BEGIN + +#define CCB_MEMBERVARIABLEASSIGNER_GLUE(TARGET, MEMBERVARIABLENAME, MEMBERVARIABLETYPE, MEMBERVARIABLE) \ + if (pTarget == TARGET && 0 == strcmp(pMemberVariableName, (MEMBERVARIABLENAME))) { \ + MEMBERVARIABLETYPE pOldVar = MEMBERVARIABLE; \ + MEMBERVARIABLE = dynamic_cast(pNode); \ + CC_ASSERT(MEMBERVARIABLE); \ + if (pOldVar != MEMBERVARIABLE) { \ + CC_SAFE_RELEASE(pOldVar); \ + MEMBERVARIABLE->retain(); \ + } \ + return true; \ + } + +#define CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(TARGET, MEMBERVARIABLENAME, MEMBERVARIABLETYPE, MEMBERVARIABLE) \ + if (pTarget == TARGET && 0 == strcmp(pMemberVariableName, MEMBERVARIABLENAME)) { \ + MEMBERVARIABLE = dynamic_cast(pNode); \ + CC_ASSERT(MEMBERVARIABLE); \ + return true; \ + } +/** + * @js NA + * @lua NA + */ +class CCBMemberVariableAssigner { + public: + virtual ~CCBMemberVariableAssigner() {}; + + /** + * The callback function of assigning member variable. + * @note The member variable must be CCNode or its subclass. + * @param pTarget The custom class. + * @param pMemberVariableName The name of the member variable. + * @param pNode The member variable. + * @return Whether the assignment was successful. + */ + virtual bool onAssignCCBMemberVariable(CCObject* pTarget, const char* pMemberVariableName, CCNode* pNode) = 0; + + /** + * The callback function of assigning custom properties. + * @note The member variable must be Integer, Float, Boolean or String. + * @param pTarget The custom class. + * @param pMemberVariableName The name of the member variable. + * @param pValue The value of the property. + * @return Whether the assignment was successful. + */ + virtual bool onAssignCCBCustomProperty(CCObject* pTarget, const char* pMemberVariableName, CCBValue* pCCBValue) { return false; }; +}; + +NS_CC_EXT_END + +#endif diff --git a/include/extensions/CCBReader/CCBReader.h b/include/extensions/CCBReader/CCBReader.h new file mode 100644 index 0000000..bb1c915 --- /dev/null +++ b/include/extensions/CCBReader/CCBReader.h @@ -0,0 +1,440 @@ +#ifndef _CCB_CCBREADER_H_ +#define _CCB_CCBREADER_H_ + +#include "cocos2d.h" +#include "ExtensionMacros.h" +#include +#include +#include "CCBSequence.h" +#include "GUI/CCControlExtension/CCControl.h" + + +#define CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(T, METHOD) static T * METHOD() { \ + T * ptr = new T(); \ + if(ptr != NULL) { \ + ptr->autorelease(); \ + return ptr; \ + } \ + CC_SAFE_DELETE(ptr); \ + return NULL; \ +} + +#define CCB_STATIC_NEW_AUTORELEASE_OBJECT_WITH_INIT_METHOD(T, METHOD) static T * METHOD() { \ + T * ptr = new T(); \ + if(ptr != NULL && ptr->init()) { \ + ptr->autorelease(); \ + return ptr; \ + } \ + CC_SAFE_DELETE(ptr); \ + return NULL; \ +} + +#define kCCBVersion 5 + +enum { + kCCBPropTypePosition = 0, + kCCBPropTypeSize, + kCCBPropTypePoint, + kCCBPropTypePointLock, + kCCBPropTypeScaleLock, + kCCBPropTypeDegrees, + kCCBPropTypeInteger, + kCCBPropTypeFloat, + kCCBPropTypeFloatVar, + kCCBPropTypeCheck, + kCCBPropTypeSpriteFrame, + kCCBPropTypeTexture, + kCCBPropTypeByte, + kCCBPropTypeColor3, + kCCBPropTypeColor4FVar, + kCCBPropTypeFlip, + kCCBPropTypeBlendmode, + kCCBPropTypeFntFile, + kCCBPropTypeText, + kCCBPropTypeFontTTF, + kCCBPropTypeIntegerLabeled, + kCCBPropTypeBlock, + kCCBPropTypeAnimation, + kCCBPropTypeCCBFile, + kCCBPropTypeString, + kCCBPropTypeBlockCCControl, + kCCBPropTypeFloatScale, + kCCBPropTypeFloatXY +}; + +enum { + kCCBFloat0 = 0, + kCCBFloat1, + kCCBFloatMinus1, + kCCBFloat05, + kCCBFloatInteger, + kCCBFloatFull +}; + +enum { + kCCBPlatformAll = 0, + kCCBPlatformIOS, + kCCBPlatformMac +}; + +enum { + kCCBTargetTypeNone = 0, + kCCBTargetTypeDocumentRoot = 1, + kCCBTargetTypeOwner = 2, +}; + +enum +{ + kCCBKeyframeEasingInstant, + + kCCBKeyframeEasingLinear, + + kCCBKeyframeEasingCubicIn, + kCCBKeyframeEasingCubicOut, + kCCBKeyframeEasingCubicInOut, + + kCCBKeyframeEasingElasticIn, + kCCBKeyframeEasingElasticOut, + kCCBKeyframeEasingElasticInOut, + + kCCBKeyframeEasingBounceIn, + kCCBKeyframeEasingBounceOut, + kCCBKeyframeEasingBounceInOut, + + kCCBKeyframeEasingBackIn, + kCCBKeyframeEasingBackOut, + kCCBKeyframeEasingBackInOut, +}; + +enum +{ + kCCBPositionTypeRelativeBottomLeft, + kCCBPositionTypeRelativeTopLeft, + kCCBPositionTypeRelativeTopRight, + kCCBPositionTypeRelativeBottomRight, + kCCBPositionTypePercent, + kCCBPositionTypeMultiplyResolution, +}; + +enum +{ + kCCBSizeTypeAbsolute, + kCCBSizeTypePercent, + kCCBSizeTypeRelativeContainer, + kCCBSizeTypeHorizontalPercent, + kCCBSizeTypeVerticalPercent, + kCCBSizeTypeMultiplyResolution, +}; + +enum +{ + kCCBScaleTypeAbsolute, + kCCBScaleTypeMultiplyResolution +}; + + +NS_CC_EXT_BEGIN + +/** + * @addtogroup cocosbuilder + * @{ + * @js NA + * @lua NA + */ + +class CCBFile : public CCNode +{ +private: + CCNode *mCCBFileNode; + +public: + CCBFile(); + + static CCBFile* create(); + + CCNode* getCCBFileNode(); + void setCCBFileNode(CCNode *pNode); // retain +}; + +/* Forward declaration. */ +class CCNodeLoader; +class CCNodeLoaderLibrary; +class CCNodeLoaderListener; +class CCBMemberVariableAssigner; +class CCBSelectorResolver; +class CCBAnimationManager; +class CCData; +class CCBKeyframe; + +/** + * @brief Parse CCBI file which is generated by CocosBuilder + */ +class CCBReader : public CCObject +{ +private: + + CCData *mData; + unsigned char *mBytes; + int mCurrentByte; + int mCurrentBit; + + std::vector mStringCache; + std::set mLoadedSpriteSheets; + + CCObject *mOwner; + + CCBAnimationManager *mActionManager; //retain + CCDictionary* mActionManagers; + + std::set *mAnimatedProps; + + CCNodeLoaderLibrary *mCCNodeLoaderLibrary; + CCNodeLoaderListener *mCCNodeLoaderListener; + CCBMemberVariableAssigner *mCCBMemberVariableAssigner; + CCBSelectorResolver *mCCBSelectorResolver; + + std::vector mOwnerOutletNames; + CCArray* mOwnerOutletNodes; + CCArray* mNodesWithAnimationManagers; + CCArray* mAnimationManagersForNodes; + + std::vector mOwnerCallbackNames; + CCArray* mOwnerCallbackNodes; + CCArray* mOwnerOwnerCallbackControlEvents; + std::string mCCBRootPath; + bool hasScriptingOwner; + bool init(); +public: + + bool jsControlled; + /** + * @js NA + * @lua NA + */ + CCBReader(CCNodeLoaderLibrary *pCCNodeLoaderLibrary, CCBMemberVariableAssigner *pCCBMemberVariableAssigner = NULL, CCBSelectorResolver *pCCBSelectorResolver = NULL, CCNodeLoaderListener *pCCNodeLoaderListener = NULL); + /** + * @js NA + * @lua NA + */ + CCBReader(CCBReader *pCCBReader); + /** + * @js NA + * @lua NA + */ + virtual ~CCBReader(); + /** + * @js ctor + */ + CCBReader(); + + void setCCBRootPath(const char* pCCBRootPath); + const std::string& getCCBRootPath() const; + /** + * @js load + * @lua NA + */ + CCNode* readNodeGraphFromFile(const char *pCCBFileName); + /** + * @js load + * @lua NA + */ + CCNode* readNodeGraphFromFile(const char *pCCBFileName, CCObject *pOwner); + /** + * @js load + * @lua NA + */ + CCNode* readNodeGraphFromFile(const char *pCCBFileName, CCObject *pOwner, const CCSize &parentSize); + /** + * @js NA + * @lua NA + */ + CCNode* readNodeGraphFromData(CCData *pData, CCObject *pOwner, const CCSize &parentSize); + /** + * @js loadScene + * @lua NA + */ + CCScene* createSceneWithNodeGraphFromFile(const char *pCCBFileName); + /** + * @js loadScene + * @lua NA + */ + CCScene* createSceneWithNodeGraphFromFile(const char *pCCBFileName, CCObject *pOwner); + /** + * @js loadScene + * @lua NA + */ + CCScene* createSceneWithNodeGraphFromFile(const char *pCCBFileName, CCObject *pOwner, const CCSize &parentSize); + /** + * @js NA + * @lua NA + */ + CCBMemberVariableAssigner* getCCBMemberVariableAssigner(); + /** + * @js NA + * @lua NA + */ + CCBSelectorResolver* getCCBSelectorResolver(); + /** + * @js getActionManager + */ + CCBAnimationManager* getAnimationManager(); + /** + * @js setActionManager + */ + void setAnimationManager(CCBAnimationManager *pAnimationManager); + + /** Used in CCNodeLoader::parseProperties() + * @js NA + * @lua NA + */ + std::set* getAnimatedProperties(); + /** + * @js NA + * @lua NA + */ + std::set& getLoadedSpriteSheet(); + CCObject* getOwner(); + + /** Utility methods. + * @js NA + * @lua NA + */ + static std::string lastPathComponent(const char* pString); + /** + * @js NA + * @lua NA + */ + static std::string deletePathExtension(const char* pString); + /** + * @js NA + * @lua NA + */ + static std::string toLowerCase(const char* pCCString); + /** + * @js NA + * @lua NA + */ + static bool endsWith(const char* pString, const char* pEnding); + + /** Parse methods. + * @js NA + * @lua NA + */ + int readInt(bool pSigned); + /** + * @js NA + * @lua NA + */ + unsigned char readByte(); + /** + * @js NA + * @lua NA + */ + bool readBool(); + std::string readUTF8(); + /** + * @js NA + * @lua NA + */ + float readFloat(); + /** + * @js NA + * @lua NA + */ + std::string readCachedString(); + /** + * @js NA + * @lua NA + */ + bool isJSControlled(); + + + bool readCallbackKeyframesForSeq(CCBSequence* seq); + bool readSoundKeyframesForSeq(CCBSequence* seq); + + + + CCArray* getOwnerCallbackNames(); + CCArray* getOwnerCallbackNodes(); + CCArray* getOwnerCallbackControlEvents(); + CCArray* getOwnerOutletNames(); + CCArray* getOwnerOutletNodes(); + CCArray* getNodesWithAnimationManagers(); + CCArray* getAnimationManagersForNodes(); + /** + * @js NA + * @lua NA + */ + CCDictionary* getAnimationManagers(); + /** + * @js NA + */ + void setAnimationManagers(CCDictionary* x); // weak reference + /** + * @js NA + * @lua NA + */ + void addOwnerCallbackName(const std::string& name); + /** + * @js NA + * @lua NA + */ + void addOwnerCallbackNode(CCNode *node); + /** + * @js NA + * @lua NA + */ + void addOwnerCallbackControlEvents(CCControlEvent type); + /** + * @js NA + * @lua NA + */ + void addDocumentCallbackName(const std::string& name); + /** + * @js NA + * @lua NA + */ + void addDocumentCallbackNode(CCNode *node); + /** + * @js NA + * @lua NA + */ + void addDocumentCallbackControlEvents(CCControlEvent eventType); + /** + * @js NA + * @lua NA + */ + static float getResolutionScale(); + static void setResolutionScale(float scale); + /** + * @js NA + * @lua NA + */ + CCNode* readFileWithCleanUp(bool bCleanUp, CCDictionary* am); + + void addOwnerOutletName(std::string name); + void addOwnerOutletNode(CCNode *node); + +private: + void cleanUpNodeGraph(CCNode *pNode); + bool readSequences(); + CCBKeyframe* readKeyframe(int type); + + bool readHeader(); + bool readStringCache(); + //void readStringCacheEntry(); + CCNode* readNodeGraph(); + CCNode* readNodeGraph(CCNode * pParent); + + bool getBit(); + void alignBits(); + + friend class CCNodeLoader; +}; + +// end of effects group +/// @} + +NS_CC_EXT_END + +#endif diff --git a/include/extensions/CCBReader/CCBSelectorResolver.h b/include/extensions/CCBReader/CCBSelectorResolver.h new file mode 100644 index 0000000..19766b4 --- /dev/null +++ b/include/extensions/CCBReader/CCBSelectorResolver.h @@ -0,0 +1,46 @@ +#ifndef _CCB_CCBSELECTORRESOLVER_H_ +#define _CCB_CCBSELECTORRESOLVER_H_ + +#include "cocos2d.h" +#include "ExtensionMacros.h" +#include "../GUI/CCControlExtension/CCInvocation.h" + + +NS_CC_EXT_BEGIN + +#define CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(TARGET, SELECTORNAME, METHOD) if(pTarget == TARGET && strcmp(pSelectorName, SELECTORNAME) == 0) { \ + return menu_selector(METHOD); \ +} + +#define CCB_SELECTORRESOLVER_CCCONTROL_GLUE(TARGET, SELECTORNAME, METHOD) if(pTarget == TARGET && strcmp(pSelectorName, SELECTORNAME) == 0) { \ + return cccontrol_selector(METHOD); \ +} + +#define CCB_SELECTORRESOLVER_CALLFUNC_GLUE(TARGET, SELECTORNAME, METHOD) if(pTarget == TARGET && strcmp(pSelectorName, SELECTORNAME) == 0) { \ + return callfuncN_selector(METHOD); \ +} +/** + * @js NA + * @lua NA + */ +class CCBSelectorResolver { + public: + virtual ~CCBSelectorResolver() {}; + virtual SEL_MenuHandler onResolveCCBCCMenuItemSelector(CCObject * pTarget, const char* pSelectorName) = 0; + virtual SEL_CallFuncN onResolveCCBCCCallFuncSelector(CCObject * pTarget, const char* pSelectorName) { return NULL; }; + virtual SEL_CCControlHandler onResolveCCBCCControlSelector(CCObject * pTarget, const char* pSelectorName) = 0; +}; + +/** + * @js NA + * @lua NA + */ +class CCBScriptOwnerProtocol { +public: + virtual ~CCBScriptOwnerProtocol() {}; + virtual CCBSelectorResolver * createNew() = 0; +}; + +NS_CC_EXT_END + +#endif diff --git a/include/extensions/CCBReader/CCBSequence.h b/include/extensions/CCBReader/CCBSequence.h new file mode 100644 index 0000000..f079a52 --- /dev/null +++ b/include/extensions/CCBReader/CCBSequence.h @@ -0,0 +1,50 @@ +#ifndef __CCB_CCSEQUENCE_H__ +#define __CCB_CCSEQUENCE_H__ + +#include +#include "cocos2d.h" +#include "ExtensionMacros.h" +#include "CCBSequenceProperty.h" + +NS_CC_EXT_BEGIN +/** + * @js NA + * @lua NA + */ +class CCBSequence : public CCObject +{ +private: + float mDuration; + std::string mName; + int mSequenceId; + int mChainedSequenceId; + CCBSequenceProperty* mCallbackChannel; + CCBSequenceProperty* mSoundChannel; + +public: + CCBSequence(); + ~CCBSequence(); + float getDuration(); + void setDuration(float fDuration); + + CCBSequenceProperty* getCallbackChannel(); + void setCallbackChannel(CCBSequenceProperty* callbackChannel); + + CCBSequenceProperty* getSoundChannel(); + void setSoundChannel(CCBSequenceProperty* soundChannel); + + const char* getName(); + void setName(const char *pName); + + int getSequenceId(); + void setSequenceId(int nSequenceId); + + int getChainedSequenceId(); + void setChainedSequenceId(int nChainedSequenceId); +}; + + +NS_CC_EXT_END + + +#endif // __CCB_CCSEQUENCE_H__ diff --git a/include/extensions/CCBReader/CCBSequenceProperty.h b/include/extensions/CCBReader/CCBSequenceProperty.h new file mode 100644 index 0000000..df7297a --- /dev/null +++ b/include/extensions/CCBReader/CCBSequenceProperty.h @@ -0,0 +1,37 @@ +#ifndef __CCB_SEQUENCE_PROPERTY_H__ +#define __CCB_SEQUENCE_PROPERTY_H__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" +#include "CCBKeyframe.h" + +NS_CC_EXT_BEGIN +/** + * @js NA + * @lua NA + */ +class CCBSequenceProperty : public CCObject +{ +private: + std::string mName; + int mType; + CCArray *mKeyframes; + +public: + CCBSequenceProperty(); + ~CCBSequenceProperty(); + + virtual bool init(); + + const char* getName(); + void setName(const char* pName); + + int getType(); + void setType(int nType); + + CCArray* getKeyframes(); +}; + +NS_CC_EXT_END + +#endif // __CCB_SEQUENCE_PROPERTY_H__ diff --git a/include/extensions/CCBReader/CCBValue.h b/include/extensions/CCBReader/CCBValue.h new file mode 100644 index 0000000..0e549be --- /dev/null +++ b/include/extensions/CCBReader/CCBValue.h @@ -0,0 +1,74 @@ +#ifndef __CCB_VALUE_H__ +#define __CCB_VALUE_H__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" + +/* + These classes are wrapper of basic types, such as ccColor3B + */ + +NS_CC_EXT_BEGIN +/** + * @js NA + * @lua NA + */ +class ccColor3BWapper : public CCObject +{ +private: + ccColor3B color; + +public: + static ccColor3BWapper* create(const ccColor3B& color); + + const ccColor3B& getColor() const; +}; + +enum +{ + kIntValue, + kFloatValue, + kBoolValue, + kUnsignedCharValue, + kStringValue, + kArrayValue +}; +/** + * @js NA + * @lua NA + */ +class CCBValue : public CCObject +{ +private: + union + { + int nValue; + float fValue; + } mValue; + + std::string m_strValue; + CCArray* m_arrValue; + int mType; + +public: + static CCBValue* create(int nValue); + static CCBValue* create(bool bValue); + static CCBValue* create(float fValue); + static CCBValue* create(unsigned char byte); + static CCBValue* create(const char* pStr); + static CCBValue* create(CCArray* pArr); + + + int getIntValue(); + float getFloatValue(); + bool getBoolValue(); + unsigned char getByteValue(); + const char* getStringValue(); + CCArray *getArrayValue(); + + int getType(); +}; + +NS_CC_EXT_END + +#endif // __CCB_VALUE_H__ diff --git a/include/extensions/CCBReader/CCControlButtonLoader.h b/include/extensions/CCBReader/CCControlButtonLoader.h new file mode 100644 index 0000000..ee9dbe0 --- /dev/null +++ b/include/extensions/CCBReader/CCControlButtonLoader.h @@ -0,0 +1,32 @@ +#ifndef _CCB_CCCONTROLBUTTONLOADER_H_ +#define _CCB_CCCONTROLBUTTONLOADER_H_ + +#include "CCControlLoader.h" +#include "../GUI/CCControlExtension/CCControlButton.h" + +NS_CC_EXT_BEGIN + +/* Forward declaration. */ +class CCBReader; + +class CCControlButtonLoader : public CCControlLoader { + public: + virtual ~CCControlButtonLoader() {}; + CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(CCControlButtonLoader, loader); + + protected: + CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(CCControlButton); + + virtual void onHandlePropTypeCheck(CCNode * pNode, CCNode * pParent, const char * pPropertyName, bool pCheck, CCBReader * pCCBReader); + virtual void onHandlePropTypeString(CCNode * pNode, CCNode * pParent, const char * pPropertyName, const char * pString, CCBReader * pCCBReader); + virtual void onHandlePropTypeFontTTF(CCNode * pNode, CCNode * pParent, const char * pPropertyName, const char * pFontTTF, CCBReader * pCCBReader); + virtual void onHandlePropTypeFloatScale(CCNode * pNode, CCNode * pParent, const char * pPropertyName, float pFloatScale, CCBReader * pCCBReader); + virtual void onHandlePropTypePoint(CCNode * pNode, CCNode * pParent, const char * pPropertyName, CCPoint pPoint, CCBReader * pCCBReader); + virtual void onHandlePropTypeSize(CCNode * pNode, CCNode * pParent, const char * pPropertyName, CCSize pSize, CCBReader * pCCBReader); + virtual void onHandlePropTypeSpriteFrame(CCNode * pNode, CCNode * pParent, const char * pPropertyName, CCSpriteFrame * pCCSpriteFrame, CCBReader * pCCBReader); + virtual void onHandlePropTypeColor3(CCNode * pNode, CCNode * pParent, const char * pPropertyName, ccColor3B pCCColor3B, CCBReader * pCCBReader); +}; + +NS_CC_EXT_END + +#endif diff --git a/include/extensions/CCBReader/CCControlLoader.h b/include/extensions/CCBReader/CCControlLoader.h new file mode 100644 index 0000000..e51dbe2 --- /dev/null +++ b/include/extensions/CCBReader/CCControlLoader.h @@ -0,0 +1,28 @@ +#ifndef _CCB_CCCONTROLLOADER_H_ +#define _CCB_CCCONTROLLOADER_H_ + +#include "CCNodeLoader.h" +#include "../GUI/CCControlExtension/CCControl.h" + +NS_CC_EXT_BEGIN + +/* Forward declaration. */ +class CCBReader; +/** + * @js NA + * @lua NA + */ +class CCControlLoader : public CCNodeLoader { + public: + virtual ~CCControlLoader() {}; + + protected: + CCB_PURE_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(CCControl); + + virtual void onHandlePropTypeBlockCCControl(CCNode * pNode, CCNode * pParent, const char * pPropertyName, BlockCCControlData * pBlockCCControlData, CCBReader * pCCBReader); + virtual void onHandlePropTypeCheck(CCNode * pNode, CCNode * pParent, const char * pPropertyName, bool pCheck, CCBReader * pCCBReader); +}; + +NS_CC_EXT_END + +#endif diff --git a/include/extensions/CCBReader/CCData.h b/include/extensions/CCBReader/CCData.h new file mode 100644 index 0000000..2b01778 --- /dev/null +++ b/include/extensions/CCBReader/CCData.h @@ -0,0 +1,30 @@ + +#ifndef __CCB_CCDATA_H__ +#define __CCB_CCDATA_H__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" + +NS_CC_EXT_BEGIN +/** + * @js NA + * @lua NA + */ +class CCData : public CCObject +{ +public: + CCData(unsigned char *pBytes, const unsigned long nSize); + CCData(CCData *pData); + ~CCData(); + + unsigned char* getBytes(); + unsigned long getSize(); + +private: + unsigned char* m_pBytes; + unsigned long m_nSize; +}; + +NS_CC_EXT_END + +#endif // __CCB_CCDATA_H__ diff --git a/include/extensions/CCBReader/CCLabelBMFontLoader.h b/include/extensions/CCBReader/CCLabelBMFontLoader.h new file mode 100644 index 0000000..7933d87 --- /dev/null +++ b/include/extensions/CCBReader/CCLabelBMFontLoader.h @@ -0,0 +1,31 @@ +#ifndef _CCB_CCLABELBMFONTLOADER_H_ +#define _CCB_CCLABELBMFONTLOADER_H_ + +#include "CCNodeLoader.h" + +NS_CC_EXT_BEGIN + +/* Forward declaration. */ +class CCBReader; +/** + * @js NA + * @lua NA + */ +class CCLabelBMFontLoader : public CCNodeLoader { + public: + virtual ~CCLabelBMFontLoader() {}; + CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(CCLabelBMFontLoader, loader); + + protected: + CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(CCLabelBMFont); + + virtual void onHandlePropTypeColor3(CCNode * pNode, CCNode * pParent, const char * pPropertyName, ccColor3B pCCColor3B, CCBReader * pCCBReader); + virtual void onHandlePropTypeByte(CCNode * pNode, CCNode * pParent, const char * pPropertyName, unsigned char pByte, CCBReader * pCCBReader); + virtual void onHandlePropTypeBlendFunc(CCNode * pNode, CCNode * pParent, const char * pPropertyName, ccBlendFunc pCCBlendFunc, CCBReader * pCCBReader); + virtual void onHandlePropTypeFntFile(CCNode * pNode, CCNode * pParent, const char * pPropertyName, const char* pFntFile, CCBReader * pCCBReader); + virtual void onHandlePropTypeText(CCNode * pNode, CCNode * pParent, const char * pPropertyName, const char* pText, CCBReader * pCCBReader); +}; + +NS_CC_EXT_END + +#endif diff --git a/include/extensions/CCBReader/CCLabelTTFLoader.h b/include/extensions/CCBReader/CCLabelTTFLoader.h new file mode 100644 index 0000000..d1d2eb3 --- /dev/null +++ b/include/extensions/CCBReader/CCLabelTTFLoader.h @@ -0,0 +1,34 @@ +#ifndef _CCB_CCLABELTTFLOADER_H_ +#define _CCB_CCLABELTTFLOADER_H_ + +#include "CCNodeLoader.h" + +NS_CC_EXT_BEGIN + +/* Forward declaration. */ +class CCBReader; +/** + * @js NA + * @lua NA + */ +class CCLabelTTFLoader : public CCNodeLoader { + public: + virtual ~CCLabelTTFLoader() {}; + CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(CCLabelTTFLoader, loader); + + protected: + CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(CCLabelTTF); + + virtual void onHandlePropTypeColor3(CCNode * pNode, CCNode * pParent, const char * pPropertyName, ccColor3B pCCColor3B, CCBReader * pCCBReader); + virtual void onHandlePropTypeByte(CCNode * pNode, CCNode * pParent, const char * pPropertyName, unsigned char pByte, CCBReader * pCCBReader); + virtual void onHandlePropTypeBlendFunc(CCNode * pNode, CCNode * pParent, const char * pPropertyName, ccBlendFunc pCCBlendFunc, CCBReader * pCCBReader); + virtual void onHandlePropTypeFontTTF(CCNode * pNode, CCNode * pParent, const char * pPropertyName, const char * pFontTTF, CCBReader * pCCBReader); + virtual void onHandlePropTypeText(CCNode * pNode, CCNode * pParent, const char * pPropertyName, const char * pText, CCBReader * pCCBReader); + virtual void onHandlePropTypeFloatScale(CCNode * pNode, CCNode * pParent, const char * pPropertyName, float pFloatScale, CCBReader * pCCBReader); + virtual void onHandlePropTypeIntegerLabeled(CCNode * pNode, CCNode * pParent, const char * pPropertyName, int pIntegerLabeled, CCBReader * pCCBReader); + virtual void onHandlePropTypeSize(CCNode * pNode, CCNode * pParent, const char * pPropertyName, CCSize pSize, CCBReader * pCCBReader); +}; + +NS_CC_EXT_END + +#endif diff --git a/include/extensions/CCBReader/CCLayerColorLoader.h b/include/extensions/CCBReader/CCLayerColorLoader.h new file mode 100644 index 0000000..0390381 --- /dev/null +++ b/include/extensions/CCBReader/CCLayerColorLoader.h @@ -0,0 +1,29 @@ +#ifndef _CCB_CCLAYERCOLORLOADER_H_ +#define _CCB_CCLAYERCOLORLOADER_H_ + +#include "CCLayerLoader.h" + +NS_CC_EXT_BEGIN + +/* Forward declaration. */ +class CCBReader; +/** + * @js NA + * @lua NA + */ +class CCLayerColorLoader : public CCLayerLoader { + public: + virtual ~CCLayerColorLoader() {}; + CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(CCLayerColorLoader, loader); + + protected: + CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(CCLayerColor); + + virtual void onHandlePropTypeColor3(CCNode * pNode, CCNode * pParent, const char * pPropertyName, ccColor3B pCCColor3B, CCBReader * pCCBReader); + virtual void onHandlePropTypeByte(CCNode * pNode, CCNode * pParent, const char * pPropertyName, unsigned char pByte, CCBReader * pCCBReader); + virtual void onHandlePropTypeBlendFunc(CCNode * pNode, CCNode * pParent, const char * pPropertyName, ccBlendFunc pCCBlendFunc, CCBReader * pCCBReader); +}; + +NS_CC_EXT_END + +#endif diff --git a/include/extensions/CCBReader/CCLayerGradientLoader.h b/include/extensions/CCBReader/CCLayerGradientLoader.h new file mode 100644 index 0000000..ed821ff --- /dev/null +++ b/include/extensions/CCBReader/CCLayerGradientLoader.h @@ -0,0 +1,30 @@ +#ifndef _CCB_CCLAYERGRADIENTLOADER_H_ +#define _CCB_CCLAYERGRADIENTLOADER_H_ + +#include "CCLayerLoader.h" + +NS_CC_EXT_BEGIN + +/* Forward declaration. */ +class CCBReader; +/** + * @js NA + * @lua NA + */ +class CCLayerGradientLoader : public CCLayerLoader { + public: + virtual ~CCLayerGradientLoader() {}; + CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(CCLayerGradientLoader, loader); + + protected: + CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(CCLayerGradient); + + virtual void onHandlePropTypeColor3(CCNode * pNode, CCNode * pParent, const char * pPropertyName, ccColor3B pCCColor3B, CCBReader * pCCBReader); + virtual void onHandlePropTypeByte(CCNode * pNode, CCNode * pParent, const char * pPropertyName, unsigned char pByte, CCBReader * pCCBReader); + virtual void onHandlePropTypePoint(CCNode * pNode, CCNode * pParent, const char * pPropertyName, CCPoint pPoint, CCBReader * pCCBReader); + virtual void onHandlePropTypeBlendFunc(CCNode * pNode, CCNode * pParent, const char * pPropertyName, ccBlendFunc pCCBlendFunc, CCBReader * pCCBReader); +}; + +NS_CC_EXT_END + +#endif diff --git a/include/extensions/CCBReader/CCLayerLoader.h b/include/extensions/CCBReader/CCLayerLoader.h new file mode 100644 index 0000000..aeae5ac --- /dev/null +++ b/include/extensions/CCBReader/CCLayerLoader.h @@ -0,0 +1,27 @@ +#ifndef _CCB_CCLAYERLOADER_H_ +#define _CCB_CCLAYERLOADER_H_ + +#include "CCNodeLoader.h" + +NS_CC_EXT_BEGIN + +/* Forward declaration. */ +class CCBReader; +/** + * @js NA + * @lua NA + */ +class CCLayerLoader : public CCNodeLoader { + public: + virtual ~CCLayerLoader() {}; + CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(CCLayerLoader, loader); + + protected: + CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(CCLayer); + + virtual void onHandlePropTypeCheck(CCNode * pNode, CCNode * pParent, const char * pPropertyName, bool pCheck, CCBReader * pCCBReader); +}; + +NS_CC_EXT_END + +#endif diff --git a/include/extensions/CCBReader/CCMenuItemImageLoader.h b/include/extensions/CCBReader/CCMenuItemImageLoader.h new file mode 100644 index 0000000..daa3d0f --- /dev/null +++ b/include/extensions/CCBReader/CCMenuItemImageLoader.h @@ -0,0 +1,27 @@ +#ifndef _CCB_CCMENUITEMIMAGELOADER_H_ +#define _CCB_CCMENUITEMIMAGELOADER_H_ + +#include "CCMenuItemLoader.h" + +NS_CC_EXT_BEGIN + +/* Forward declaration. */ +class CCBReader; +/** + * @js NA + * @lua NA + */ +class CCMenuItemImageLoader : public CCMenuItemLoader { + public: + virtual ~CCMenuItemImageLoader() {}; + CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(CCMenuItemImageLoader, loader); + + protected: + CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(CCMenuItemImage); + + virtual void onHandlePropTypeSpriteFrame(CCNode * pNode, CCNode * pParent, const char * pPropertyName, CCSpriteFrame * pCCSpriteFrame, CCBReader * pCCBReader); +}; + +NS_CC_EXT_END + +#endif diff --git a/include/extensions/CCBReader/CCMenuItemLoader.h b/include/extensions/CCBReader/CCMenuItemLoader.h new file mode 100644 index 0000000..41c2ad6 --- /dev/null +++ b/include/extensions/CCBReader/CCMenuItemLoader.h @@ -0,0 +1,27 @@ +#ifndef _CCB_CCMENUITEMLOADER_H_ +#define _CCB_CCMENUITEMLOADER_H_ + +#include "CCLayerLoader.h" + +NS_CC_EXT_BEGIN + +/* Forward declaration. */ +class CCBReader; +/** + * @js NA + * @lua NA + */ +class CCMenuItemLoader : public CCNodeLoader { + public: + virtual ~CCMenuItemLoader() {}; + + protected: + CCB_PURE_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(CCMenuItem); + + virtual void onHandlePropTypeBlock(CCNode * pNode, CCNode * pParent, const char * pPropertyName, BlockData * pBlockData, CCBReader * pCCBReader); + virtual void onHandlePropTypeCheck(CCNode * pNode, CCNode * pParent, const char * pPropertyName, bool pCheck, CCBReader * pCCBReader); +}; + +NS_CC_EXT_END + +#endif diff --git a/include/extensions/CCBReader/CCMenuLoader.h b/include/extensions/CCBReader/CCMenuLoader.h new file mode 100644 index 0000000..1b418ad --- /dev/null +++ b/include/extensions/CCBReader/CCMenuLoader.h @@ -0,0 +1,25 @@ +#ifndef _CCB_CCMENULOADER_H_ +#define _CCB_CCMENULOADER_H_ + +#include "CCLayerLoader.h" + +NS_CC_EXT_BEGIN + +/* Forward declaration. */ +class CCBReader; +/** + * @js NA + * @lua NA + */ +class CCMenuLoader : public CCLayerLoader { + public: + virtual ~CCMenuLoader() {}; + CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(CCMenuLoader, loader); + + protected: + CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(CCMenu); +}; + +NS_CC_EXT_END + +#endif diff --git a/include/extensions/CCBReader/CCNode+CCBRelativePositioning.h b/include/extensions/CCBReader/CCNode+CCBRelativePositioning.h new file mode 100644 index 0000000..5de7956 --- /dev/null +++ b/include/extensions/CCBReader/CCNode+CCBRelativePositioning.h @@ -0,0 +1,15 @@ +#ifndef __CCB_CCNODE_RELATIVEPOSITIONING_H__ +#define __CCB_CCNODE_RELATIVEPOSITIONING_H__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" + +NS_CC_EXT_BEGIN + +extern CCPoint getAbsolutePosition(const CCPoint &pt, int nType, const CCSize &containerSize, const char *pPropName); + +extern void setRelativeScale(CCNode *pNode, float fScaleX, float fScaleY, int nType, const char* pPropName); + +NS_CC_EXT_END + +#endif // __CCB_CCNODE_RELATIVEPOSITIONING_H__ diff --git a/include/extensions/CCBReader/CCNodeLoader.h b/include/extensions/CCBReader/CCNodeLoader.h new file mode 100644 index 0000000..fdbedb7 --- /dev/null +++ b/include/extensions/CCBReader/CCNodeLoader.h @@ -0,0 +1,128 @@ +#ifndef _CCB_CCNODELOADER_H_ +#define _CCB_CCNODELOADER_H_ + +#include "../GUI/CCControlExtension/CCInvocation.h" +#include "cocos2d.h" +#include "CCBReader.h" +#include "CCBValue.h" + +NS_CC_EXT_BEGIN + +#define PROPERTY_POSITION "position" +#define PROPERTY_CONTENTSIZE "contentSize" +#define PROPERTY_SKEW "skew" +#define PROPERTY_ANCHORPOINT "anchorPoint" +#define PROPERTY_SCALE "scale" +#define PROPERTY_ROTATION "rotation" +#define PROPERTY_ROTATIONX "rotationX" +#define PROPERTY_ROTATIONY "rotationY" +#define PROPERTY_TAG "tag" +#define PROPERTY_IGNOREANCHORPOINTFORPOSITION "ignoreAnchorPointForPosition" +#define PROPERTY_VISIBLE "visible" + +#define ASSERT_FAIL_UNEXPECTED_PROPERTY(PROPERTY) CCLog("Unexpected property: '%s'!\n", PROPERTY); assert(false) +#define ASSERT_FAIL_UNEXPECTED_PROPERTYTYPE(PROPERTYTYPE) CCLog("Unexpected property type: '%d'!\n", PROPERTYTYPE); assert(false) + +#define CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(T) virtual T * createCCNode(cocos2d::CCNode * pParent, cocos2d::extension::CCBReader * pCCBReader) { \ + return T::create(); \ +} + +#define CCB_PURE_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(T) virtual T * createCCNode(cocos2d::CCNode * pParent, cocos2d::extension::CCBReader * pCCBReader) = 0 + +struct BlockData { + SEL_MenuHandler mSELMenuHandler; + CCObject * mTarget; +}; + +struct BlockCCControlData { + SEL_CCControlHandler mSELCCControlHandler; + CCObject * mTarget; + int mControlEvents; +}; + +/* Forward declaration. */ +class CCBReader; +/** + * @js NA + * @lua NA + */ +class CCNodeLoader : public CCObject { + public: + CCNodeLoader(); + virtual ~CCNodeLoader(); + CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(CCNodeLoader, loader); + + virtual CCNode * loadCCNode(CCNode *, CCBReader * pCCBReader); + virtual void parseProperties(CCNode * pNode, CCNode * pParent, CCBReader * pCCBReader); + virtual CCDictionary* getCustomProperties(); + + protected: + CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(CCNode); + + virtual CCPoint parsePropTypePosition(CCNode * pNode, CCNode * pParent, CCBReader * pCCBReader, const char *pPropertyName); + virtual CCPoint parsePropTypePoint(CCNode * pNode, CCNode * pParent, CCBReader * pCCBReader); + virtual CCPoint parsePropTypePointLock(CCNode * pNode, CCNode * pParent, CCBReader * pCCBReader); + virtual CCSize parsePropTypeSize(CCNode * pNode, CCNode * pParent, CCBReader * pCCBReader); + virtual float * parsePropTypeScaleLock(CCNode * pNode, CCNode * pParent, CCBReader * pCCBReader, const char *pPropertyName); + virtual float parsePropTypeFloat(CCNode * pNode, CCNode * pParent, CCBReader * pCCBReader); + virtual float parsePropTypeDegrees(CCNode * pNode, CCNode * pParent, CCBReader * pCCBReader, const char *pPropertyName); + virtual float parsePropTypeFloatScale(CCNode * pNode, CCNode * pParent, CCBReader * pCCBReader); + virtual int parsePropTypeInteger(CCNode * pNode, CCNode * pParent, CCBReader * pCCBReader); + virtual int parsePropTypeIntegerLabeled(CCNode * pNode, CCNode * pParent, CCBReader * pCCBReader); + virtual float * parsePropTypeFloatVar(CCNode * pNode, CCNode * pParent, CCBReader * pCCBReader); + virtual bool parsePropTypeCheck(CCNode * pNode, CCNode * pParent, CCBReader * pCCBReader, const char *pPropertyName); + virtual CCSpriteFrame * parsePropTypeSpriteFrame(CCNode * pNode, CCNode * pParent, CCBReader * pCCBReader, const char *pPropertyName); + virtual CCAnimation * parsePropTypeAnimation(CCNode * pNode, CCNode * pParent, CCBReader * pCCBReader); + virtual CCTexture2D * parsePropTypeTexture(CCNode * pNode, CCNode * pParent, CCBReader * pCCBReader); + virtual unsigned char parsePropTypeByte(CCNode * pNode, CCNode * pParent, CCBReader * pCCBReader, const char *pPropertyName); + virtual ccColor3B parsePropTypeColor3(CCNode * pNode, CCNode * pParent, CCBReader * pCCBReader, const char *pPropertyName); + virtual ccColor4F * parsePropTypeColor4FVar(CCNode * pNode, CCNode * pParent, CCBReader * pCCBReader); + virtual bool * parsePropTypeFlip(CCNode * pNode, CCNode * pParent, CCBReader * pCCBReader); + virtual ccBlendFunc parsePropTypeBlendFunc(CCNode * pNode, CCNode * pParent, CCBReader * pCCBReader); + virtual std::string parsePropTypeFntFile(CCNode * pNode, CCNode * pParent, CCBReader * pCCBReader); + virtual std::string parsePropTypeString(CCNode * pNode, CCNode * pParent, CCBReader * pCCBReader); + virtual std::string parsePropTypeText(CCNode * pNode, CCNode * pParent, CCBReader * pCCBReader); + virtual std::string parsePropTypeFontTTF(CCNode * pNode, CCNode * pParent, CCBReader * pCCBReader); + virtual BlockData * parsePropTypeBlock(CCNode * pNode, CCNode * pParent, CCBReader * pCCBReader); + virtual BlockCCControlData * parsePropTypeBlockCCControl(CCNode * pNode, CCNode * pParent, CCBReader * pCCBReader); + virtual CCNode * parsePropTypeCCBFile(CCNode * pNode, CCNode * pParent, CCBReader * pCCBReader); + virtual float * parsePropTypeFloatXY(CCNode * pNode, CCNode * pParent, CCBReader * pCCBReader); + + + virtual void onHandlePropTypePosition(CCNode * pNode, CCNode * pParent, const char* pPropertyName, CCPoint pPosition, CCBReader * pCCBReader); + virtual void onHandlePropTypePoint(CCNode * pNode, CCNode * pParent, const char* pPropertyName, CCPoint pPoint, CCBReader * pCCBReader); + virtual void onHandlePropTypePointLock(CCNode * pNode, CCNode * pParent, const char* pPropertyName, CCPoint pPointLock, CCBReader * pCCBReader); + virtual void onHandlePropTypeSize(CCNode * pNode, CCNode * pParent, const char* pPropertyName, CCSize pSize, CCBReader * pCCBReader); + virtual void onHandlePropTypeScaleLock(CCNode * pNode, CCNode * pParent, const char* pPropertyName, float * pScaleLock, CCBReader * pCCBReader); + virtual void onHandlePropTypeFloat(CCNode * pNode, CCNode * pParent, const char* pPropertyName, float pFloat, CCBReader * pCCBReader); + virtual void onHandlePropTypeDegrees(CCNode * pNode, CCNode * pParent, const char* pPropertyName, float pDegrees, CCBReader * pCCBReader); + virtual void onHandlePropTypeFloatScale(CCNode * pNode, CCNode * pParent, const char* pPropertyName, float pFloatScale, CCBReader * pCCBReader); + virtual void onHandlePropTypeInteger(CCNode * pNode, CCNode * pParent, const char* pPropertyName, int pInteger, CCBReader * pCCBReader); + virtual void onHandlePropTypeIntegerLabeled(CCNode * pNode, CCNode * pParent, const char* pPropertyName, int pIntegerLabeled, CCBReader * pCCBReader); + virtual void onHandlePropTypeFloatVar(CCNode * pNode, CCNode * pParent, const char* pPropertyName, float * pFoatVar, CCBReader * pCCBReader); + virtual void onHandlePropTypeFloatXY(CCNode * pNode, CCNode * pParent, const char* pPropertyName, float * pFoatVar, CCBReader * pCCBReader); + + virtual void onHandlePropTypeCheck(CCNode * pNode, CCNode * pParent, const char* pPropertyName, bool pCheck, CCBReader * pCCBReader); + virtual void onHandlePropTypeSpriteFrame(CCNode * pNode, CCNode * pParent, const char* pPropertyName, CCSpriteFrame * pCCSpriteFrame, CCBReader * pCCBReader); + virtual void onHandlePropTypeAnimation(CCNode * pNode, CCNode * pParent, const char* pPropertyName, CCAnimation * pCCAnimation, CCBReader * pCCBReader); + virtual void onHandlePropTypeTexture(CCNode * pNode, CCNode * pParent, const char* pPropertyName, CCTexture2D * pCCTexture2D, CCBReader * pCCBReader); + virtual void onHandlePropTypeByte(CCNode * pNode, CCNode * pParent, const char* pPropertyName, unsigned char pByte, CCBReader * pCCBReader); + virtual void onHandlePropTypeColor3(CCNode * pNode, CCNode * pParent, const char* pPropertyName, ccColor3B pCCColor3B, CCBReader * pCCBReader); + virtual void onHandlePropTypeColor4FVar(CCNode * pNode, CCNode * pParent, const char* pPropertyName, ccColor4F * pCCColor4FVar, CCBReader * pCCBReader); + virtual void onHandlePropTypeFlip(CCNode * pNode, CCNode * pParent, const char* pPropertyName, bool * pFlip, CCBReader * pCCBReader); + virtual void onHandlePropTypeBlendFunc(CCNode * pNode, CCNode * pParent, const char* pPropertyName, ccBlendFunc pCCBlendFunc, CCBReader * pCCBReader); + virtual void onHandlePropTypeFntFile(CCNode * pNode, CCNode * pParent, const char* pPropertyName, const char * pFntFile, CCBReader * pCCBReader); + virtual void onHandlePropTypeString(CCNode * pNode, CCNode * pParent, const char* pPropertyName, const char * pString, CCBReader * pCCBReader); + virtual void onHandlePropTypeText(CCNode * pNode, CCNode * pParent, const char* pPropertyName, const char * pText, CCBReader * pCCBReader); + virtual void onHandlePropTypeFontTTF(CCNode * pNode, CCNode * pParent, const char* pPropertyName, const char * pFontTTF, CCBReader * pCCBReader); + virtual void onHandlePropTypeBlock(CCNode * pNode, CCNode * pParent, const char* pPropertyName, BlockData * pBlockData, CCBReader * pCCBReader); + virtual void onHandlePropTypeBlockCCControl(CCNode * pNode, CCNode * pParent, const char* pPropertyName, BlockCCControlData * pBlockCCControlData, CCBReader * pCCBReader); + virtual void onHandlePropTypeCCBFile(CCNode * pNode, CCNode * pParent, const char* pPropertyName, CCNode * pCCBFileNode, CCBReader * pCCBReader); + +protected: + CCDictionary* m_pCustomProperties; +}; + +NS_CC_EXT_END + +#endif diff --git a/include/extensions/CCBReader/CCNodeLoaderLibrary.h b/include/extensions/CCBReader/CCNodeLoaderLibrary.h new file mode 100644 index 0000000..2b159c2 --- /dev/null +++ b/include/extensions/CCBReader/CCNodeLoaderLibrary.h @@ -0,0 +1,45 @@ +#ifndef _CCB_CCNODELOADERLIBRARY_H_ +#define _CCB_CCNODELOADERLIBRARY_H_ + +#include "cocos2d.h" +#include "CCBReader.h" + +NS_CC_EXT_BEGIN + +class CCNodeLoader; + +typedef std::map CCNodeLoaderMap; +typedef std::pair CCNodeLoaderMapEntry; +/** + * @js NA + * @lua NA + */ +class CCNodeLoaderLibrary : public CCObject { + private: + CCNodeLoaderMap mCCNodeLoaders; + + public: + CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(CCNodeLoaderLibrary, library); + + CCNodeLoaderLibrary(); + virtual ~CCNodeLoaderLibrary(); + + void registerDefaultCCNodeLoaders(); + void registerCCNodeLoader(const char * pClassName, CCNodeLoader * pCCNodeLoader); + //void registerCCNodeLoader(CCString * pClassName, CCNodeLoader * pCCNodeLoader); + void unregisterCCNodeLoader(const char * pClassName); + //void unregisterCCNodeLoader(CCString * pClassName); + CCNodeLoader * getCCNodeLoader(const char * pClassName); + //CCNodeLoader * getCCNodeLoader(CCString * pClassName); + void purge(bool pDelete); + + public: + static CCNodeLoaderLibrary * sharedCCNodeLoaderLibrary(); + static void purgeSharedCCNodeLoaderLibrary(); + + static CCNodeLoaderLibrary * newDefaultCCNodeLoaderLibrary(); +}; + +NS_CC_EXT_END + +#endif diff --git a/include/extensions/CCBReader/CCNodeLoaderListener.h b/include/extensions/CCBReader/CCNodeLoaderListener.h new file mode 100644 index 0000000..91f831a --- /dev/null +++ b/include/extensions/CCBReader/CCNodeLoaderListener.h @@ -0,0 +1,20 @@ +#ifndef _CCB_CCNODELOADERLISTENER_H_ +#define _CCB_CCNODELOADERLISTENER_H_ + +#include "cocos2d.h" + +NS_CC_EXT_BEGIN +/** + * @js NA + * @lua NA + */ +class CCNodeLoaderListener { + public: + virtual ~CCNodeLoaderListener() {}; + + virtual void onNodeLoaded(CCNode * pNode, CCNodeLoader * pNodeLoader) = 0; +}; + +NS_CC_EXT_END + +#endif diff --git a/include/extensions/CCBReader/CCParticleSystemQuadLoader.h b/include/extensions/CCBReader/CCParticleSystemQuadLoader.h new file mode 100644 index 0000000..badf582 --- /dev/null +++ b/include/extensions/CCBReader/CCParticleSystemQuadLoader.h @@ -0,0 +1,34 @@ +#ifndef _CCB_CCPARTICLESYSTEMQUADLOADER_H_ +#define _CCB_CCPARTICLESYSTEMQUADLOADER_H_ + +#include "CCNodeLoader.h" + +NS_CC_EXT_BEGIN + +/* Forward declaration. */ +class CCBReader; +/** + * @js NA + * @lua NA + */ +class CCParticleSystemQuadLoader : public CCNodeLoader { + public: + virtual ~CCParticleSystemQuadLoader() {}; + CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(CCParticleSystemQuadLoader, loader); + + protected: + CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(CCParticleSystemQuad); + + virtual void onHandlePropTypeIntegerLabeled(CCNode * pNode, CCNode * pParent, const char * pPropertyName, int pIntegerLabeled, CCBReader * pCCBReader); + virtual void onHandlePropTypePoint(CCNode * pNode, CCNode * pParent, const char * pPropertyName, CCPoint pPoint, CCBReader * pCCBReader); + virtual void onHandlePropTypeFloat(CCNode * pNode, CCNode * pParent, const char * pPropertyName, float pFloat, CCBReader * pCCBReader); + virtual void onHandlePropTypeInteger(CCNode * pNode, CCNode * pParent, const char * pPropertyName, int pInteger, CCBReader * pCCBReader); + virtual void onHandlePropTypeFloatVar(CCNode * pNode, CCNode * pParent, const char * pPropertyName, float * pFloatVar, CCBReader * pCCBReader); + virtual void onHandlePropTypeColor4FVar(CCNode * pNode, CCNode * pParent, const char * pPropertyName, ccColor4F * pCCColor4FVar, CCBReader * pCCBReader); + virtual void onHandlePropTypeBlendFunc(CCNode * pNode, CCNode * pParent, const char * pPropertyName, ccBlendFunc pCCBlendFunc, CCBReader * pCCBReader); + virtual void onHandlePropTypeTexture(CCNode * pNode, CCNode * pParent, const char * pPropertyName, CCTexture2D * pCCTexture2D, CCBReader * pCCBReader); +}; + +NS_CC_EXT_END + +#endif diff --git a/include/extensions/CCBReader/CCScale9SpriteLoader.h b/include/extensions/CCBReader/CCScale9SpriteLoader.h new file mode 100644 index 0000000..7ffbaa8 --- /dev/null +++ b/include/extensions/CCBReader/CCScale9SpriteLoader.h @@ -0,0 +1,34 @@ +#ifndef _CCB_CCSCALE9SPRITELOADER_H_ +#define _CCB_CCSCALE9SPRITELOADER_H_ + +#include "CCNodeLoader.h" +#include "CCScale9SpriteLoader.h" +#include "../GUI/CCControlExtension/CCScale9Sprite.h" + +NS_CC_EXT_BEGIN + +/* Forward declaration. */ +class CCBReader; +/** + * @js NA + * @lua NA + */ +class CCScale9SpriteLoader : public CCNodeLoader { + public: + virtual ~CCScale9SpriteLoader() {}; + CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(CCScale9SpriteLoader, loader); + + protected: + CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(CCScale9Sprite); + + virtual void onHandlePropTypeColor3(CCNode * pNode, CCNode * pParent, const char * pPropertyName, ccColor3B pCCColor3B, CCBReader * pCCBReader); + virtual void onHandlePropTypeByte(CCNode * pNode, CCNode * pParent, const char * pPropertyName, unsigned char pByte, CCBReader * pCCBReader); + virtual void onHandlePropTypeBlendFunc(CCNode * pNode, CCNode * pParent, const char * pPropertyName, ccBlendFunc pCCBlendFunc, CCBReader * pCCBReader); + virtual void onHandlePropTypeSpriteFrame(CCNode * pNode, CCNode * pParent, const char * pPropertyName, CCSpriteFrame * pCCSpriteFrame, CCBReader * pCCBReader); + virtual void onHandlePropTypeSize(CCNode * pNode, CCNode * pParent, const char * pPropertyName, CCSize pSize, CCBReader * pCCBReader); + virtual void onHandlePropTypeFloat(CCNode * pNode, CCNode * pParent, const char * pPropertyName, float pFloat, CCBReader * pCCBReader); +}; + +NS_CC_EXT_END + +#endif diff --git a/include/extensions/CCBReader/CCScrollViewLoader.h b/include/extensions/CCBReader/CCScrollViewLoader.h new file mode 100644 index 0000000..b893369 --- /dev/null +++ b/include/extensions/CCBReader/CCScrollViewLoader.h @@ -0,0 +1,31 @@ +#ifndef _CCB_CCSCROLLVIEWLOADER_H_ +#define _CCB_CCSCROLLVIEWLOADER_H_ + +#include "CCNodeLoader.h" +#include "../GUI/CCScrollView/CCScrollView.h" + +NS_CC_EXT_BEGIN + +/* Forward declaration. */ +class CCBReader; +/** + * @js NA + * @lua NA + */ +class CCScrollViewLoader : public CCNodeLoader { + public: + virtual ~CCScrollViewLoader() {}; + CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(CCScrollViewLoader, loader); + + protected: + CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(CCScrollView); + virtual void onHandlePropTypeSize(CCNode * pNode, CCNode * pParent, const char * pPropertyName, CCSize pSize, CCBReader * pCCBReader); + virtual void onHandlePropTypeCCBFile(CCNode * pNode, CCNode * pParent, const char * pPropertyName, CCNode * pCCBFileNode, CCBReader * pCCBReader); + virtual void onHandlePropTypeCheck(CCNode * pNode, CCNode * pParent, const char * pPropertyName, bool pCheck, CCBReader * pCCBReader); + virtual void onHandlePropTypeFloat(CCNode * pNode, CCNode * pParent, const char * pPropertyName, float pFloat, CCBReader * pCCBReader); + virtual void onHandlePropTypeIntegerLabeled(CCNode * pNode, CCNode * pParent, const char * pPropertyName, int pIntegerLabeled, CCBReader * pCCBReader); +}; + +NS_CC_EXT_END + +#endif diff --git a/include/extensions/CCBReader/CCSpriteLoader.h b/include/extensions/CCBReader/CCSpriteLoader.h new file mode 100644 index 0000000..3c4e706 --- /dev/null +++ b/include/extensions/CCBReader/CCSpriteLoader.h @@ -0,0 +1,31 @@ +#ifndef _CCB_CCSPRITELOADER_H_ +#define _CCB_CCSPRITELOADER_H_ + +#include "CCNodeLoader.h" + +NS_CC_EXT_BEGIN + +/* Forward declaration. */ +class CCBReader; +/** + * @js NA + * @lua NA + */ +class CCSpriteLoader : public CCNodeLoader { + public: + virtual ~CCSpriteLoader() {}; + CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(CCSpriteLoader, loader); + + protected: + CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(CCSprite); + + virtual void onHandlePropTypeColor3(CCNode * pNode, CCNode * pParent, const char * pPropertyName, ccColor3B pCCColor3B, CCBReader * pCCBReader); + virtual void onHandlePropTypeByte(CCNode * pNode, CCNode * pParent, const char * pPropertyName, unsigned char pByte, CCBReader * pCCBReader); + virtual void onHandlePropTypeBlendFunc(CCNode * pNode, CCNode * pParent, const char * pPropertyName, ccBlendFunc pCCBBlendFunc, CCBReader * pCCBReader); + virtual void onHandlePropTypeSpriteFrame(CCNode * pNode, CCNode * pParent, const char * pPropertyName, CCSpriteFrame * pCCSpriteFrame, CCBReader * pCCBReader); + virtual void onHandlePropTypeFlip(CCNode * pNode, CCNode * pParent, const char * pPropertyName, bool * pFlip, CCBReader * pCCBReader); +}; + +NS_CC_EXT_END + +#endif diff --git a/include/extensions/CocoStudio/Action/CCActionEaseEx.h b/include/extensions/CocoStudio/Action/CCActionEaseEx.h new file mode 100644 index 0000000..6bae19d --- /dev/null +++ b/include/extensions/CocoStudio/Action/CCActionEaseEx.h @@ -0,0 +1,363 @@ +/**************************************************************************** +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. +****************************************************************************/ + +#ifndef __CCActionEaseEx_H__ +#define __CCActionEaseEx_H__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" + +NS_CC_EXT_BEGIN + +/** + @brief Ease Bezier + @ingroup Actions + */ +class CCEaseBezierAction:public CCActionEase +{ +public: + virtual void update(float time); + virtual CCActionInterval* reverse(void); + /** + * @js NA + * @lua NA + */ + virtual CCObject* copyWithZone(CCZone* pZone); + + virtual void setBezierParamer( float p0, float p1, float p2, float p3); + +public: + /** creates the action */ + static CCEaseBezierAction* create(CCActionInterval* pAction); + +private: + float m_p0; + float m_p1; + float m_p2; + float m_p3; +}; + +/** + @brief Ease Quadratic In + @ingroup Actions + */ +class CCEaseQuadraticActionIn:public CCActionEase +{ +public: + virtual void update(float time); + virtual CCActionInterval* reverse(void); + /** + * @js NA + * @lua NA + */ + virtual CCObject* copyWithZone(CCZone* pZone); + +public: + /** creates the action */ + static CCEaseQuadraticActionIn* create(CCActionInterval* pAction); +}; + +/** + @brief Ease Quadratic Out + @ingroup Actions + */ +class CCEaseQuadraticActionOut:public CCActionEase +{ +public: + virtual void update(float time); + virtual CCActionInterval* reverse(void); + /** + * @js NA + * @lua NA + */ + virtual CCObject* copyWithZone(CCZone* pZone); + +public: + /** creates the action */ + static CCEaseQuadraticActionOut* create(CCActionInterval* pAction); +}; + +/** + @brief Ease Quadratic InOut + @ingroup Actions + */ +class CCEaseQuadraticActionInOut:public CCActionEase +{ +public: + virtual void update(float time); + virtual CCActionInterval* reverse(void); + /** + * @js NA + * @lua NA + */ + virtual CCObject* copyWithZone(CCZone* pZone); + +public: + /** creates the action */ + static CCEaseQuadraticActionInOut* create(CCActionInterval* pAction); +}; + +/** + @brief Ease Quartic In + @ingroup Actions + */ +class CCEaseQuarticActionIn:public CCActionEase +{ +public: + virtual void update(float time); + virtual CCActionInterval* reverse(void); + /** + * @js NA + * @lua NA + */ + virtual CCObject* copyWithZone(CCZone* pZone); + +public: + /** creates the action */ + static CCEaseQuarticActionIn* create(CCActionInterval* pAction); +}; + +/** + @brief Ease Quartic Out + @ingroup Actions + */ +class CCEaseQuarticActionOut:public CCActionEase +{ +public: + virtual void update(float time); + virtual CCActionInterval* reverse(void); + /** + * @js NA + * @lua NA + */ + virtual CCObject* copyWithZone(CCZone* pZone); + +public: + /** creates the action */ + static CCEaseQuarticActionOut* create(CCActionInterval* pAction); +}; + +/** + @brief Ease Quartic InOut + @ingroup Actions + */ +class CCEaseQuarticActionInOut:public CCActionEase +{ +public: + virtual void update(float time); + virtual CCActionInterval* reverse(void); + /** + * @js NA + * @lua NA + */ + virtual CCObject* copyWithZone(CCZone* pZone); + +public: + /** creates the action */ + static CCEaseQuarticActionInOut* create(CCActionInterval* pAction); +}; + + +/** + @brief Ease Quintic In + @ingroup Actions + */ +class CCEaseQuinticActionIn:public CCActionEase +{ +public: + virtual void update(float time); + virtual CCActionInterval* reverse(void); + /** + * @js NA + * @lua NA + */ + virtual CCObject* copyWithZone(CCZone* pZone); + +public: + /** creates the action */ + static CCEaseQuinticActionIn* create(CCActionInterval* pAction); +}; + +/** + @brief Ease Quintic Out + @ingroup Actions + */ +class CCEaseQuinticActionOut:public CCActionEase +{ +public: + virtual void update(float time); + virtual CCActionInterval* reverse(void); + /** + * @js NA + * @lua NA + */ + virtual CCObject* copyWithZone(CCZone* pZone); + +public: + /** creates the action */ + static CCEaseQuinticActionOut* create(CCActionInterval* pAction); +}; + +/** + @brief Ease Quintic InOut + @ingroup Actions + */ +class CCEaseQuinticActionInOut:public CCActionEase +{ +public: + virtual void update(float time); + virtual CCActionInterval* reverse(void); + /** + * @js NA + * @lua NA + */ + virtual CCObject* copyWithZone(CCZone* pZone); + +public: + /** creates the action */ + static CCEaseQuinticActionInOut* create(CCActionInterval* pAction); +}; + +/** + @brief Ease Circle In + @ingroup Actions + */ +class CCEaseCircleActionIn:public CCActionEase +{ +public: + virtual void update(float time); + virtual CCActionInterval* reverse(void); + /** + * @js NA + * @lua NA + */ + virtual CCObject* copyWithZone(CCZone* pZone); + +public: + /** creates the action */ + static CCEaseCircleActionIn* create(CCActionInterval* pAction); +}; + +/** + @brief Ease Circle Out + @ingroup Actions + */ +class CCEaseCircleActionOut:public CCActionEase +{ +public: + virtual void update(float time); + virtual CCActionInterval* reverse(void); + /** + * @js NA + * @lua NA + */ + virtual CCObject* copyWithZone(CCZone* pZone); + +public: + /** creates the action */ + static CCEaseCircleActionOut* create(CCActionInterval* pAction); +}; + +/** + @brief Ease Circle InOut + @ingroup Actions + */ +class CCEaseCircleActionInOut:public CCActionEase +{ +public: + virtual void update(float time); + virtual CCActionInterval* reverse(void); + /** + * @js NA + * @lua NA + */ + virtual CCObject* copyWithZone(CCZone* pZone); + +public: + /** creates the action */ + static CCEaseCircleActionInOut* create(CCActionInterval* pAction); +}; + +/** + @brief Ease Cubic In + @ingroup Actions + */ +class CCEaseCubicActionIn:public CCActionEase +{ +public: + virtual void update(float time); + virtual CCActionInterval* reverse(void); + /** + * @js NA + * @lua NA + */ + virtual CCObject* copyWithZone(CCZone* pZone); + +public: + /** creates the action */ + static CCEaseCubicActionIn* create(CCActionInterval* pAction); +}; + +/** + @brief Ease Cubic Out + @ingroup Actions + */ +class CCEaseCubicActionOut:public CCActionEase +{ +public: + virtual void update(float time); + virtual CCActionInterval* reverse(void); + /** + * @js NA + * @lua NA + */ + virtual CCObject* copyWithZone(CCZone* pZone); + +public: + /** creates the action */ + static CCEaseCubicActionOut* create(CCActionInterval* pAction); +}; + +/** + @brief Ease Cubic InOut + @ingroup Actions + */ +class CCEaseCubicActionInOut:public CCActionEase +{ +public: + virtual void update(float time); + virtual CCActionInterval* reverse(void); + /** + * @js NA + * @lua NA + */ + virtual CCObject* copyWithZone(CCZone* pZone); + +public: + /** creates the action */ + static CCEaseCubicActionInOut* create(CCActionInterval* pAction); +}; +NS_CC_EXT_END + +#endif diff --git a/include/extensions/CocoStudio/Action/CCActionFrame.h b/include/extensions/CocoStudio/Action/CCActionFrame.h new file mode 100644 index 0000000..6c145d4 --- /dev/null +++ b/include/extensions/CocoStudio/Action/CCActionFrame.h @@ -0,0 +1,453 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +#ifndef __ActionFRAME_H__ +#define __ActionFRAME_H__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" + +NS_CC_EXT_BEGIN + +enum FrameType +{ + kKeyframeMove = 0, + kKeyframeScale, + kKeyframeRotate, + kKeyframeTint, + kKeyframeFade, + kKeyframeMax +}; + +enum FrameEaseType +{ + FrameEase_Custom = -1, + + FrameEase_Linear = 0, + + FrameEase_Sine_EaseIn, + FrameEase_Sine_EaseOut, + FrameEase_Sine_EaseInOut, + + + FrameEase_Quad_EaseIn, + FrameEase_Quad_EaseOut, + FrameEase_Quad_EaseInOut, + + FrameEase_Cubic_EaseIn, + FrameEase_Cubic_EaseOut, + FrameEase_Cubic_EaseInOut, + + FrameEase_Quart_EaseIn, + FrameEase_Quart_EaseOut, + FrameEase_Quart_EaseInOut, + + FrameEase_Quint_EaseIn, + FrameEase_Quint_EaseOut, + FrameEase_Quint_EaseInOut, + + FrameEase_Expo_EaseIn, + FrameEase_Expo_EaseOut, + FrameEase_Expo_EaseInOut, + + FrameEase_Circ_EaseIn, + FrameEase_Circ_EaseOut, + FrameEase_Circ_EaseInOut, + + FrameEase_Elastic_EaseIn, + FrameEase_Elastic_EaseOut, + FrameEase_Elastic_EaseInOut, + + FrameEase_Back_EaseIn, + FrameEase_Back_EaseOut, + FrameEase_Back_EaseInOut, + + FrameEase_Bounce_EaseIn, + FrameEase_Bounce_EaseOut, + FrameEase_Bounce_EaseInOut, + + FrameEase_TWEEN_EASING_MAX = 10000 +}; +/** +* @js NA +* @lua NA +*/ +class ActionFrame:public CCObject +{ + +public: + + /** + * Default constructor + */ + ActionFrame(); + + /** + * Default destructor + */ + virtual ~ActionFrame(); + + /** + * Changes the index of action frame + * + * @param index the index of action frame + */ + void setFrameIndex(int index); + + /** + * Gets the index of action frame + * + * @return the index of action frame + */ + int getFrameIndex(); + + /** + * Changes the time of action frame + * + * @param fTime the time of action frame + */ + void setFrameTime(float fTime); + + /** + * Gets the time of action frame + * + * @return fTime the time of action frame + */ + float getFrameTime(); + + /** + * Changes the type of action frame + * + * @param frameType the type of action frame + */ + void setFrameType(int frameType); + + /** + * Gets the type of action frame + * + * @return the type of action frame + */ + int getFrameType(); + + /** + * Changes the easing type. + * + * @param easingType the easing type. + */ + void setEasingType(int easingType); + + /** + * Gets the easing type. + * + * @return the easing type. + */ + int getEasingType(); + + /** + * Gets the CCAction of ActionFrame. + * + * @parame fDuration the duration time of ActionFrame + * + * @return CCAction + */ + virtual CCActionInterval* getAction(float fDuration); + /** + * Gets the CCAction of ActionFrame. + * + * @parame fDuration the duration time of ActionFrame + * + * @parame fDuration the source ActionFrame + * + * @return CCAction + */ + virtual CCActionInterval* getAction(float fDuration,ActionFrame* srcFrame); + + /** + *Set the CCAction easing parameter. + * + *@parame parameter the parameter for frame ease + * + */ + virtual void setEasingParameter(std::vector parameter); +protected: + /** + * Gets the Easing Action of ActionFrame. + * + * @parame action the duration time of ActionFrame + * + * @return CCAction + */ + virtual CCActionInterval* getEasingAction(CCActionInterval* action); +protected: + int m_frameType; + int m_frameIndex; + float m_fTime; + FrameEaseType m_easingType; + std::vector m_Parameter; +}; +/** +* @js NA +* @lua NA +*/ +class ActionMoveFrame:public ActionFrame +{ +public: + + /** + * Default constructor + */ + ActionMoveFrame(); + + /** + * Default destructor + */ + virtual ~ActionMoveFrame(); + + /** + * Changes the move action position. + * + * @param the move action position. + */ + void setPosition(CCPoint pos); + + /** + * Gets the move action position. + * + * @return the move action position. + */ + CCPoint getPosition(); + + /** + * Gets the CCAction of ActionFrame. + * + * @parame fDuration the duration time of ActionFrame + * + * @return CCAction + */ + virtual CCActionInterval* getAction(float fDuration); +protected: + CCPoint m_position; +}; +/** +* @js NA +* @lua NA +*/ +class ActionScaleFrame:public ActionFrame +{ +public: + + /** + * Default constructor + */ + ActionScaleFrame(); + + /** + * Default destructor + */ + virtual ~ActionScaleFrame(); + + /** + * Changes the scale action scaleX. + * + * @param the scale action scaleX. + */ + void setScaleX(float scaleX); + + /** + * Gets the scale action scaleX. + * + * @return the scale action scaleX. + */ + float getScaleX(); + + /** + * Changes the scale action scaleY. + * + * @param rotation the scale action scaleY. + */ + void setScaleY(float scaleY); + + /** + * Gets the scale action scaleY. + * + * @return the the scale action scaleY. + */ + float getScaleY(); + + /** + * Gets the CCAction of ActionFrame. + * + * @parame fDuration the duration time of ActionFrame + * + * @return CCAction + */ + virtual CCActionInterval* getAction(float fDuration); +protected: + float m_scaleX; + float m_scaleY; +}; +/** +* @js NA +* @lua NA +*/ +class ActionRotationFrame:public ActionFrame +{ +public: + + /** + * Default constructor + */ + ActionRotationFrame(); + + /** + * Default destructor + */ + virtual ~ActionRotationFrame(); + + /** + * Changes rotate action rotation. + * + * @param rotation rotate action rotation. + */ + void setRotation(float rotation); + + /** + * Gets the rotate action rotation. + * + * @return the rotate action rotation. + */ + float getRotation(); + + /** + * Gets the CCAction of ActionFrame. + * + * @parame fDuration the duration time of ActionFrame + * + * @return CCAction + */ + virtual CCActionInterval* getAction(float fDuration); + /** + * Gets the CCAction of ActionFrame. + * + * @parame fDuration the duration time of ActionFrame + * + * @parame fDuration the source ActionFrame + * + * @return CCAction + */ + virtual CCActionInterval* getAction(float fDuration,ActionFrame* srcFrame); +public: + float m_rotation; +}; +/** +* @js NA +* @lua NA +*/ +class ActionFadeFrame:public ActionFrame +{ +public: + + /** + * Default constructor + */ + ActionFadeFrame(); + + /** + * Default destructor + */ + virtual ~ActionFadeFrame(); + + /** + * Changes the fade action opacity. + * + * @param opacity the fade action opacity + */ + void setOpacity(int opacity); + + /** + * Gets the fade action opacity. + * + * @return the fade action opacity. + */ + int getOpacity(); + + /** + * Gets the CCAction of ActionFrame. + * + * @parame fDuration the duration time of ActionFrame + * + * @return CCAction + */ + virtual CCActionInterval* getAction(float fDuration); +protected: + float m_opacity; +}; +/** +* @js NA +* @lua NA +*/ +class ActionTintFrame:public ActionFrame +{ + +public: + + /** + * Default constructor + */ + ActionTintFrame(); + + /** + * Default destructor + */ + virtual ~ActionTintFrame(); + + /** + * Changes the tint action color. + * + * @param ccolor the tint action color + */ + void setColor(ccColor3B ccolor); + + /** + * Gets the tint action color. + * + * @return the tint action color. + */ + ccColor3B getColor(); + + /** + * Gets the CCAction of ActionFrame. + * + * @parame fDuration the duration time of ActionFrame + * + * @return CCAction + */ + virtual CCActionInterval* getAction(float fDuration); +protected: + ccColor3B m_color; +}; + +NS_CC_EXT_END + +#endif diff --git a/include/extensions/CocoStudio/Action/CCActionFrameEasing.h b/include/extensions/CocoStudio/Action/CCActionFrameEasing.h new file mode 100644 index 0000000..b35c128 --- /dev/null +++ b/include/extensions/CocoStudio/Action/CCActionFrameEasing.h @@ -0,0 +1,76 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +#ifndef __ActionFrameEasing_H__ +#define __ActionFrameEasing_H__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" +#include "../Json/DictionaryHelper.h" + +NS_CC_EXT_BEGIN + +enum FrameEasingType +{ + kCCBKeyframeEasingInstant, + + kCCBKeyframeEasingLinear, + + kCCBKeyframeEasingCubicIn, + kCCBKeyframeEasingCubicOut, + kCCBKeyframeEasingCubicInOut, + + kCCBKeyframeEasingElasticIn, + kCCBKeyframeEasingElasticOut, + kCCBKeyframeEasingElasticInOut, + + kCCBKeyframeEasingBounceIn, + kCCBKeyframeEasingBounceOut, + kCCBKeyframeEasingBounceInOut, + + kCCBKeyframeEasingBackIn, + kCCBKeyframeEasingBackOut, + kCCBKeyframeEasingBackInOut, +}; +/** +* @js NA +* @lua NA +*/ +class ActionFrameEasing:public cocos2d::CCObject +{ +protected: + FrameEasingType m_type; + float m_fValue; +public: + ActionFrameEasing(); + virtual ~ActionFrameEasing(); + + float bounceTime(float t); + + float easeValue(float t); +}; + +NS_CC_EXT_END + +#endif diff --git a/include/extensions/CocoStudio/Action/CCActionManager.h b/include/extensions/CocoStudio/Action/CCActionManager.h new file mode 100644 index 0000000..18a2bd6 --- /dev/null +++ b/include/extensions/CocoStudio/Action/CCActionManager.h @@ -0,0 +1,108 @@ +/**************************************************************************** +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. +****************************************************************************/ + +#ifndef __ActionMANAGER_H__ +#define __ActionMANAGER_H__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" +#include "CCActionObject.h" +#include "../Json/rapidjson/document.h" +NS_CC_EXT_BEGIN + /** + * @js NA + * @lua NA + */ +class ActionManager:public CCObject +{ +public: + + /** + * Default constructor + * @js ctor + */ + ActionManager(); + + /** + * Default destructor + * @js NA + */ + virtual ~ActionManager(); + + /** + * Gets the static instance of ActionManager. + */ + static ActionManager* shareManager(); + + /** + * Purges ActionManager point. + */ + static void purge(); + + /** + * Gets an ActionObject with a name. + * + * @param jsonName UI file name + * + * @param actionName action name in the UI file. + * + * @return ActionObject which named as the param name + */ + ActionObject* getActionByName(const char* jsonName,const char* actionName); + + /** + * Play an Action with a name. + * + * @param jsonName UI file name + * + * @param actionName action name in teh UIfile. + */ + ActionObject* playActionByName(const char* jsonName,const char* actionName); + + /** + * Play an Action with a name. + * + * @param jsonName UI file name + * + * @param actionName action name in teh UIfile. + * + * @param func ui action call back + */ + ActionObject* playActionByName(const char* jsonName,const char* actionName, CCCallFunc* func); + + /*init properties with json dictionay*/ + void initWithDictionary(const char* jsonName,const rapidjson::Value &dic,CCObject* root); + /** + * Release all actions. + * + */ + void releaseActions(); + +protected: + CCDictionary* m_pActionDic; +}; + +NS_CC_EXT_END + +#endif diff --git a/include/extensions/CocoStudio/Action/CCActionNode.h b/include/extensions/CocoStudio/Action/CCActionNode.h new file mode 100644 index 0000000..38ee24d --- /dev/null +++ b/include/extensions/CocoStudio/Action/CCActionNode.h @@ -0,0 +1,182 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +#ifndef __ActionNODE_H__ +#define __ActionNODE_H__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" +#include "CCActionFrame.h" +#include "../Json/DictionaryHelper.h" +#include "../Json/rapidjson/document.h" +NS_CC_EXT_BEGIN +/** +* @js NA +* @lua NA +*/ +class ActionNode:public CCObject +{ +public: + + /** + * Default constructor + */ + ActionNode(); + + /** + * Default destructor + */ + virtual ~ActionNode(); + /** + * Sets the time interval of frame. + * + * @param fTime the time interval of frame + */ + void setUnitTime(float fTime); + + /** + * Gets the time interval of frame. + * + * @return fTime the time interval of frame + */ + float getUnitTime(); + /** + * Sets tag for ActionNode + * + * @param tag tag of ActionNode + */ + void setActionTag(int tag); + + /** + * Gets tag for ActionNode + * + * @return tag tag of ActionNode + */ + int getActionTag(); + + /** + * Sets node which will run a action. + * + * @param node which will run a action + */ + void setObject(CCObject* node); + + /** + * Gets node which will run a action. + * + * @return node which will run a action + */ + CCObject* getObject(); + + /** + * Insets a ActionFrame to ActionNode. + * + * @param index the index of ActionFrame + * + * @param frame the ActionFrame which will be inserted + */ + void insertFrame(int index, ActionFrame* frame); + + /** + * Pushs back a ActionFrame to ActionNode. + * + * @param frame the ActionFrame which will be added + */ + void addFrame(ActionFrame* frame); + + /** + * Remove a ActionFrame from ActionNode. + * + * @param frame the ActionFrame which will be removed + */ + void deleteFrame(ActionFrame* frame ); + + /** + * Remove all ActionFrames from ActionNode. + */ + void clearAllFrame(); + + /** + * Gets index of first ActionFrame. + * + * @return index of first ActionFrame + */ + int getFirstFrameIndex(); + + /** + * Gets index of last ActionFrame. + * + * @return index of last ActionFrame + */ + int getLastFrameIndex(); + + /** + * Updates action states to some time. + * + * @param fTime the time when need to update + */ + virtual bool updateActionToTimeLine(float fTime); + + /** + * Play the action. + */ + virtual void playAction(); + + /** + * Stop the action. + */ + virtual void stopAction(); + + /*init properties with a json dictionary*/ + virtual void initWithDictionary(const rapidjson::Value& dic,CCObject* root); + /** + * Gets if the action is done once time. + * + * @return that if the action is done once time + */ + virtual bool isActionDoneOnce(); +protected: + int currentFrameIndex; + int destFrameIndex; + + float m_fUnitTime; + + int m_ActionTag; + CCObject* m_Object; + CCSpawn * m_actionSpawn; + CCAction* m_action; + CCArray* m_FrameArray; + int frameArrayNum; + +protected: + virtual CCNode* getActionNode(); + virtual CCSpawn * refreshActionProperty(); + virtual void runAction(); + virtual void initActionNodeFromRoot(CCObject* root); + virtual void easingToFrame(float duration,float delayTime,ActionFrame* srcFrame,ActionFrame* destFrame); +}; + +NS_CC_EXT_END + +#endif diff --git a/include/extensions/CocoStudio/Action/CCActionObject.h b/include/extensions/CocoStudio/Action/CCActionObject.h new file mode 100644 index 0000000..5360ab9 --- /dev/null +++ b/include/extensions/CocoStudio/Action/CCActionObject.h @@ -0,0 +1,181 @@ +/**************************************************************************** +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. +****************************************************************************/ + +#ifndef __ActionObject_H__ +#define __ActionObject_H__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" +#include "../Json/rapidjson/document.h" + +NS_CC_EXT_BEGIN + +class ActionNode; +/** +* @js NA +* @lua NA +*/ +class ActionObject:public CCObject +{ +public: + + /** + * Default constructor + */ + ActionObject(); + + /** + * Default destructor + */ + virtual ~ActionObject(); + + /** + * Sets name for object + * + * @param name name of object + */ + void setName(const char* name); + + /** + * Sets name for object + * + * @return name of object + */ + const char* getName(); + + /** + * Sets if the action will loop play. + * + * @param bLoop that if the action will loop play + */ + void setLoop(bool bLoop); + + /** + * Gets if the action will loop play. + * + * @return that if the action will loop play + */ + bool getLoop(); + + /** + * Sets the time interval of frame. + * + * @param fTime the time interval of frame + */ + void setUnitTime(float fTime); + + /** + * Gets the time interval of frame. + * + * @return fTime the time interval of frame + */ + float getUnitTime(); + + /** + * Sets the current time of frame. + * + * @param fTime the current time of frame + */ + void setCurrentTime(float fTime); + + /** + * Gets the current time of frame. + * + * @return fTime the current time of frame + */ + float getCurrentTime(); + + /** + * Gets the total time of frame. + * + * @return fTime the current time of frame + */ + float getTotalTime(); + /** + * Return if the action is playing. + * + * @return true if the action is playing, false the otherwise + */ + bool isPlaying(); + + /** + * Play the action. + */ + void play(); + + /** + * Play the action. + * + * @ Action Call Back + */ + void play(CCCallFunc* func); + + /** + * Pause the action. + */ + void pause(); + + /** + * Stop the action. + */ + void stop(); + + /** + * Adds a ActionNode to play the action. + * + * @node the ActionNode which will play the action + */ + void addActionNode(ActionNode* node); + + /** + * Removes a ActionNode which play the action. + * + * @node the ActionNode which play the action + */ + void removeActionNode(ActionNode* node); + + /*update frame method*/ + void updateToFrameByTime(float fTime); + + /*init properties with a json dictionary*/ + void initWithDictionary(const rapidjson::Value& dic,CCObject* root); + + void simulationActionUpdate(float dt); + +protected: + CCArray* m_ActionNodeList;/*actionnode*/ + std::string m_name; + bool m_loop; + bool m_bPause; + bool m_bPlaying; + float m_fUnitTime; + float m_CurrentTime; + CCScheduler *m_pScheduler; + CCCallFunc *m_CallBack; + float m_fTotalTime; +}; + +NS_CC_EXT_END + +#endif diff --git a/include/extensions/CocoStudio/Armature/CCArmature.h b/include/extensions/CocoStudio/Armature/CCArmature.h new file mode 100644 index 0000000..3766b88 --- /dev/null +++ b/include/extensions/CocoStudio/Armature/CCArmature.h @@ -0,0 +1,216 @@ + +/**************************************************************************** +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. +****************************************************************************/ + +#ifndef __CCARMATURE_H__ +#define __CCARMATURE_H__ + +#include "utils/CCArmatureDefine.h" +#include "CCBone.h" +#include "display/CCBatchNode.h" +#include "animation/CCArmatureAnimation.h" + +class b2Body; +struct cpBody; + +NS_CC_EXT_BEGIN +/** + * @lua NA + */ +class CCArmature : public CCNodeRGBA, public CCBlendProtocol +{ + +public: + + /** + * Allocates and initializes an armature. + * @return An initialized armature which is marked as "autorelease". + */ + static CCArmature *create(); + + /** + * Allocates an armature, and use the CCArmatureData named name in CCArmatureDataManager to initializes the armature. + * + * @param name CCArmature will use the name to find the CCArmatureData to initializes it. + * @return A initialized armature which is marked as "autorelease". + */ + static CCArmature *create(const char *name); + + static CCArmature *create(const char *name, CCBone *parentBone); + +public: + /** + * @js ctor + */ + CCArmature(); + /** + * @js NA + */ + ~CCArmature(void); + + /** + * Init the empty armature + */ + virtual bool init(); + + /** + * Init an armature with specified name + * @param name CCArmature name + */ + virtual bool init(const char *name); + + virtual bool init(const char *name, CCBone *parentBone); + /** + * Add a CCBone to this CCArmature, + * + * @param bone The CCBone you want to add to CCArmature + * @param parentName The parent CCBone's name you want to add to . If it's NULL, then set CCArmature to its parent + */ + virtual void addBone(CCBone *bone, const char *parentName); + /** + * Get a bone with the specified name + * + * @param name The bone's name you want to get + */ + virtual CCBone *getBone(const char *name) const; + /** + * Change a bone's parent with the specified parent name. + * + * @param bone The bone you want to change parent + * @param parentName The new parent's name. + */ + virtual void changeBoneParent(CCBone *bone, const char *parentName); + /** + * Remove a bone with the specified name. If recursion it will also remove child CCBone recursionly. + * + * @param bone The bone you want to remove + * @param recursion Determine whether remove the bone's child recursion. + */ + virtual void removeBone(CCBone *bone, bool recursion); + + /** + * Get CCArmature's bone dictionary + * @return CCArmature's bone dictionary + */ + CCDictionary *getBoneDic(); + + /** + * This boundingBox will calculate all bones' boundingBox every time + */ + virtual CCRect boundingBox(); + + CCBone *getBoneAtPoint(float x, float y); + + virtual void visit(); + virtual void update(float dt); + virtual void draw(); + + virtual CCAffineTransform nodeToParentTransform(); + + virtual void onEnter(); + virtual void onExit(); + + /** + * Set contentsize and Calculate anchor point. + */ + virtual void updateOffsetPoint(); + + inline void setBlendFunc(ccBlendFunc blendFunc) + { + m_sBlendFunc = blendFunc; + } + inline ccBlendFunc getBlendFunc(void) + { + return m_sBlendFunc; + } + + virtual void setAnimation(CCArmatureAnimation *animation); + virtual CCArmatureAnimation *getAnimation(); + + virtual CCTextureAtlas *getTexureAtlasWithTexture(CCTexture2D *texture); + +#if ENABLE_PHYSICS_BOX2D_DETECT || ENABLE_PHYSICS_CHIPMUNK_DETECT + virtual void setColliderFilter(CCColliderFilter *filter); +#elif ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX + virtual void drawContour(); +#endif + +#if ENABLE_PHYSICS_BOX2D_DETECT + /** + * @js NA + */ + virtual b2Fixture *getShapeList(); +#elif ENABLE_PHYSICS_CHIPMUNK_DETECT + /** + * @js NA + */ + virtual cpShape *getShapeList(); +#endif + +protected: + + /* + * Used to create CCBone internal + * @js NA + */ + CCBone *createBone(const char *boneName ); + + CC_SYNTHESIZE(CCArmatureData *, m_pArmatureData, ArmatureData); + + CC_SYNTHESIZE(CCBatchNode *, m_pBatchNode, BatchNode); + + CC_SYNTHESIZE(std::string, m_strName, Name); + + CC_SYNTHESIZE(CCTextureAtlas *, m_pAtlas, TextureAtlas); + + CC_PROPERTY(CCBone *, m_pParentBone, ParentBone); + + CC_SYNTHESIZE(float, m_fVersion, Version); + + CC_SYNTHESIZE_READONLY(bool, m_bArmatureTransformDirty, ArmatureTransformDirty); +protected: + CCDictionary *m_pBoneDic; //! The dictionary of the bones, include all bones in the armature, no matter it is the direct bone or the indirect bone. It is different from m_pChindren. + + CCArray *m_pTopBoneList; + + static std::map m_sArmatureIndexDic; //! Use to save armature zorder info, + + ccBlendFunc m_sBlendFunc; + + CCPoint m_pOffsetPoint; + + CCArmatureAnimation *m_pAnimation; + + CCDictionary *m_pTextureAtlasDic; + +#if ENABLE_PHYSICS_BOX2D_DETECT + CC_PROPERTY(b2Body *, m_pBody, Body); +#elif ENABLE_PHYSICS_CHIPMUNK_DETECT + CC_PROPERTY(cpBody *, m_pBody, Body); +#endif +}; + +NS_CC_EXT_END + +#endif /*__CCARMATURE_H__*/ diff --git a/include/extensions/CocoStudio/Armature/CCBone.h b/include/extensions/CocoStudio/Armature/CCBone.h new file mode 100644 index 0000000..b3a7687 --- /dev/null +++ b/include/extensions/CocoStudio/Armature/CCBone.h @@ -0,0 +1,242 @@ +/**************************************************************************** +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. +****************************************************************************/ + +#ifndef __CCBONE_H__ +#define __CCBONE_H__ + +#include "utils/CCArmatureDefine.h" +#include "datas/CCDatas.h" +#include "animation/CCTween.h" +#include "display/CCDecorativeDisplay.h" +#include "display/CCDisplayManager.h" + +NS_CC_EXT_BEGIN + +class CCArmature; +/** + * @lua NA + */ +class CCBone : public CCNodeRGBA +{ +public: + /** + * Allocates and initializes a bone. + * @return A initialized bone which is marked as "autorelease". + */ + static CCBone *create(); + /** + * Allocates and initializes a bone. + * + * @param name If name is not null, then set name to the bone's name + * @return A initialized bone which is marked as "autorelease". + */ + static CCBone *create(const char *name); + +public: + /** + * @js ctor + */ + CCBone(); + /** + * @js NA + */ + virtual ~CCBone(void); + + /** + * Initializes an empty CCBone with nothing init. + */ + virtual bool init(); + + /** + * Initializes a CCBone with the specified name + * @param name CCBone's name. + */ + virtual bool init(const char *name); + + /** + * Add display and use displayData to init the display. + * If index already have a display, then replace it. + * If index is current display index, then also change display to _index + * + * @param displayData it include the display information, like DisplayType. + * If you want to create a sprite display, then create a CCSpriteDisplayData param + * + * @param index the index of the display you want to replace or add to + * -1 : append display from back + */ + void addDisplay(CCDisplayData *displayData, int index); + + void addDisplay(CCNode *display, int index); + + void removeDisplay(int index); + + /** + * @deprecated please use changeDisplayWithIndex and changeDisplayWithName + */ + CC_DEPRECATED_ATTRIBUTE void changeDisplayByIndex(int index, bool force); + CC_DEPRECATED_ATTRIBUTE void changeDisplayByName(const char *name, bool force); + + void changeDisplayWithIndex(int index, bool force); + void changeDisplayWithName(const char *name, bool force); + + /** + * Add a child to this bone, and it will let this child call setParent(CCBone *parent) function to set self to it's parent + * @param child the child you want to add + */ + void addChildBone(CCBone *child); + + /** + * Set parent bone. + * If parent is NUll, then also remove this bone from armature. + * It will not set the CCArmature, if you want to add the bone to a CCArmature, you should use CCArmature::addBone(CCBone *bone, const char* parentName). + * + * @param parent the parent bone. + * NULL : remove this bone from armature + */ + void setParentBone(CCBone *parent); + + /** + * Get parent bone + * @return parent bone + */ + CCBone *getParentBone(); + + using CCNode::removeFromParent; + /** + * Remove itself from its parent. + * @param recursion whether or not to remove childBone's display + */ + void removeFromParent(bool recursion); + + /** + * Removes a child CCBone + * @param bone the bone you want to remove + */ + void removeChildBone(CCBone *bone, bool recursion); + + void update(float delta); + + void updateDisplayedColor(const ccColor3B &parentColor); + void updateDisplayedOpacity(GLubyte parentOpacity); + + void setColor(const ccColor3B &color); + void setOpacity(GLubyte opacity); + + //! Update color to render display + void updateColor(); + + //! Update zorder + void updateZOrder(); + + virtual void setZOrder(int zOrder); + + CCTween *getTween(); + + /* + * Whether or not the bone's transform property changed. if true, the bone will update the transform. + */ + virtual inline void setTransformDirty(bool dirty) { m_bBoneTransformDirty = dirty; } + virtual inline bool isTransformDirty() { return m_bBoneTransformDirty; } + + /* + * Set blend function + */ + virtual void setBlendFunc(const ccBlendFunc& blendFunc); + virtual ccBlendFunc getBlendFunc(void) { return m_sBlendFunc; } + + /* + * Set if blend function is dirty + */ + virtual void setBlendDirty(bool dirty) { m_bBlendDirty = dirty; } + virtual bool isBlendDirty(void) { return m_bBlendDirty; } + + virtual CCAffineTransform nodeToArmatureTransform(); + virtual CCAffineTransform nodeToWorldTransform(); + + CCNode *getDisplayRenderNode(); + DisplayType getDisplayRenderNodeType(); + + /* + * Get the ColliderBody list in this bone. The object in the CCArray is ColliderBody. + */ + virtual CCArray *getColliderBodyList(); + +#if ENABLE_PHYSICS_BOX2D_DETECT || ENABLE_PHYSICS_CHIPMUNK_DETECT + virtual void setColliderFilter(CCColliderFilter *filter); + virtual CCColliderFilter *getColliderFilter(); +#endif + +public: + /* + * The origin state of the CCBone. Display's state is effected by m_pBoneData, m_pNode, m_pTweenData + * when call setData function, it will copy from the CCBoneData. + */ + CC_PROPERTY(CCBoneData *, m_pBoneData, BoneData); + + //! A weak reference to the CCArmature + CC_PROPERTY(CCArmature *, m_pArmature, Armature); + + //! A weak reference to the child CCArmature + CC_PROPERTY(CCArmature *, m_pChildArmature, ChildArmature); + + CC_SYNTHESIZE(CCDisplayManager *, m_pDisplayManager, DisplayManager) + + /* + * When CCArmature play an animation, if there is not a CCMovementBoneData of this bone in this CCMovementData, this bone will be hidden. + * Set IgnoreMovementBoneData to true, then this bone will also be shown. + */ + CC_SYNTHESIZE(bool, m_bIgnoreMovementBoneData, IgnoreMovementBoneData) + +protected: + virtual void applyParentTransform(CCBone *parent); + + CCTween *m_pTween; //! Calculate tween effect + + //! Used for making tween effect in every frame + CC_SYNTHESIZE_READONLY(CCFrameData *, m_pTweenData, TweenData); + + CC_SYNTHESIZE(std::string, m_strName, Name); + + CCBone *m_pParentBone; //! A weak reference to its parent + bool m_bBoneTransformDirty; //! Whether or not transform dirty + + //! Transform in armature space, use this to change display's state + CCAffineTransform m_tWorldTransform; + + //! World Point, Scale, Rotation in armature space + CC_SYNTHESIZE_READONLY(CCBaseData *, m_tWorldInfo, WorldInfo); + + //! Armature's parent bone + CCBone *m_pArmatureParentBone; + + //! Data version + float m_fDataVersion; + + ccBlendFunc m_sBlendFunc; + bool m_bBlendDirty; +}; + +NS_CC_EXT_END + +#endif /*__CCBONE_H__*/ diff --git a/include/extensions/CocoStudio/Armature/animation/CCArmatureAnimation.h b/include/extensions/CocoStudio/Armature/animation/CCArmatureAnimation.h new file mode 100644 index 0000000..239e524 --- /dev/null +++ b/include/extensions/CocoStudio/Armature/animation/CCArmatureAnimation.h @@ -0,0 +1,324 @@ +/**************************************************************************** +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. +****************************************************************************/ + + +#ifndef __CCANIMATION_H__ +#define __CCANIMATION_H__ + +#include "CCProcessBase.h" +#include + +NS_CC_EXT_BEGIN + + +enum MovementEventType +{ + START, + COMPLETE, + LOOP_COMPLETE +}; + + +class CCArmature; +class CCBone; + +typedef void (CCObject::*SEL_MovementEventCallFunc)(CCArmature *, MovementEventType, const char *); +typedef void (CCObject::*SEL_FrameEventCallFunc)(CCBone *, const char *, int, int); + +#define movementEvent_selector(_SELECTOR) (SEL_MovementEventCallFunc)(&_SELECTOR) +#define frameEvent_selector(_SELECTOR) (SEL_FrameEventCallFunc)(&_SELECTOR) + +struct CCFrameEvent +{ + CCBone *bone; + const char *frameEventName; + int originFrameIndex; + int currentFrameIndex; +}; + +struct CCMovementEvent +{ + CCArmature *armature; + MovementEventType movementType; + const char *movementID; +}; + +/** + * @lua NA + */ +class CCArmatureAnimation : public CCProcessBase +{ +public: + /** + * Create with a CCArmature + * @param armature The CCArmature CCArmatureAnimation will bind to + */ + static CCArmatureAnimation *create(CCArmature *armature); +public: + /** + * @js ctor + */ + CCArmatureAnimation(); + /** + * @js NA + */ + virtual ~CCArmatureAnimation(void); + + /** + * Init with a CCArmature + * @param armature The CCArmature CCArmatureAnimation will bind to + */ + virtual bool init(CCArmature *armature); + + /** + * Scale animation play speed. + * This method is deprecated, please use setSpeedScale. + * @param animationScale Scale value + */ + CC_DEPRECATED_ATTRIBUTE virtual void setAnimationScale(float animationScale); + CC_DEPRECATED_ATTRIBUTE virtual float getAnimationScale() const; + + /** + * Scale animation play speed. + * @param animationScale Scale value + */ + virtual void setSpeedScale(float speedScale); + virtual float getSpeedScale() const; + + //! The animation update speed + CC_DEPRECATED_ATTRIBUTE virtual void setAnimationInternal(float animationInternal) {}; + + using CCProcessBase::play; + /** + * Play animation by animation name. + * + * @param animationName The animation name you want to play + * @param durationTo The frames between two animation changing-over. + * It's meaning is changing to this animation need how many frames + * + * -1 : use the value from CCMovementData get from flash design panel + * @param durationTween The frame count you want to play in the game. + * if _durationTween is 80, then the animation will played 80 frames in a loop + * + * -1 : use the value from CCMovementData get from flash design panel + * + * @param loop Whether the animation is loop + * + * loop < 0 : use the value from CCMovementData get from flash design panel + * loop = 0 : this animation is not loop + * loop > 0 : this animation is loop + * + * @param tweenEasing CCTween easing is used for calculate easing effect + * + * TWEEN_EASING_MAX : use the value from CCMovementData get from flash design panel + * -1 : fade out + * 0 : line + * 1 : fade in + * 2 : fade in and out + * + */ + virtual void play(const char *animationName, int durationTo = -1, int durationTween = -1, int loop = -1, int tweenEasing = TWEEN_EASING_MAX); + + /** + * Play animation by index, the other param is the same to play. + * Deprecated, please use playWithIndex + * @param animationIndex the animation index you want to play + */ + CC_DEPRECATED_ATTRIBUTE virtual void playByIndex(int animationIndex, int durationTo = -1, int durationTween = -1, int loop = -1, int tweenEasing = TWEEN_EASING_MAX); + virtual void playWithIndex(int animationIndex, int durationTo = -1, int durationTween = -1, int loop = -1, int tweenEasing = TWEEN_EASING_MAX); + + /** + * Play several animation by names + */ + virtual void playWithNames(const std::vector& movementNames, int durationTo = -1, bool loop = true); + + /** + * Play several animation by indexes + */ + virtual void playWithIndexes(const std::vector& movementIndexes, int durationTo = -1, bool loop = true); + + + // For bindings + virtual void playWithArray(cocos2d::CCArray *movementNames, int durationTo = -1, bool loop = true); + virtual void playWithIndexArray(cocos2d::CCArray *movementIndexes, int durationTo = -1, bool loop = true); + + /** + * Go to specified frame and play current movement. + * You need first switch to the movement you want to play, then call this function. + * + * example : playByIndex(0); + * gotoAndPlay(0); + * playByIndex(1); + * gotoAndPlay(0); + * gotoAndPlay(15); + */ + virtual void gotoAndPlay(int frameIndex); + + /** + * Go to specified frame and pause current movement. + */ + virtual void gotoAndPause(int frameIndex); + + /** + * Pause the Process + */ + virtual void pause(); + /** + * Resume the Process + */ + virtual void resume(); + /** + * Stop the Process + */ + virtual void stop(); + + + /** + * Get movement count + */ + int getMovementCount(); + + void update(float dt); + + /** + * Get current movementID + * @return The name of current movement + */ + std::string getCurrentMovementID(); + + /** + * Set armature's movement event callback function + * To disconnect this event, just setMovementEventCallFunc(NULL, NULL); + */ + void setMovementEventCallFunc(CCObject *target, SEL_MovementEventCallFunc callFunc); + + /** + * Set armature's frame event callback function + * To disconnect this event, just setFrameEventCallFunc(NULL, NULL); + */ + void setFrameEventCallFunc(CCObject *target, SEL_FrameEventCallFunc callFunc); + + + /** + * Returns a user assigned CCObject + * + * @return A user assigned CCObject + */ + virtual CCObject* getUserObject(); + /** + * Returns a user assigned CCObject + * + * The UserObject will be retained once in this method, + * and the previous UserObject (if existed) will be relese. + * The UserObject will be released in destructure. + * + * @param A user assigned CCObject + */ + virtual void setUserObject(CCObject *pUserObject); +protected: + + /** + * Update(float dt) will call this handler, you can handle your logic here + * @js NA + */ + void updateHandler(); + + /** + * Update current key frame, and process auto stop, pause + * @js NA + */ + void updateFrameData(float currentPercent); + + /** + * Emit a frame event + * @js NA + */ + void frameEvent(CCBone *bone, const char *frameEventName, int originFrameIndex, int currentFrameIndex); + + /** + * Emit a movement event + */ + void movementEvent(CCArmature *armature, MovementEventType movementType, const char *movementID); + + void updateMovementList(); + + inline bool isIgnoreFrameEvent() { return m_bIgnoreFrameEvent; } + + friend class CCTween; +protected: + //! CCAnimationData save all MovementDatas this animation used. + CC_SYNTHESIZE_RETAIN(CCAnimationData *, m_pAnimationData, AnimationData); + + //! Scale the animation speed + float m_fSpeedScale; + + CCMovementData *m_pMovementData; //! CCMovementData save all MovementFrameDatas this animation used. + + CCArmature *m_pArmature; //! A weak reference of armature + + std::string m_strMovementID; //! Current movment's name + + int m_iToIndex; //! The frame index in CCMovementData->m_pMovFrameDataArr, it's different from m_iFrameIndex. + + CCArray *m_pTweenList; + + bool m_bIgnoreFrameEvent; + + std::queue m_sFrameEventQueue; + std::queue m_sMovementEventQueue; + + std::vector m_sMovementList; + + bool m_bOnMovementList; + bool m_bMovementListLoop; + unsigned int m_uMovementIndex; + int m_iMovementListDurationTo; + + CCObject *m_pUserObject; +protected: + /** + * MovementEvent CallFunc. + * @param CCArmature* a CCArmature + * @param MovementEventType, Event Type, like START, COMPLETE. + * @param const char*, Movement ID, also called Movement Name + */ + SEL_MovementEventCallFunc m_sMovementEventCallFunc; + + /** + * FrameEvent CallFunc. + * @param CCBone*, a CCBone + * @param const char*, the name of this frame event + * @param int, origin frame index + * @param int, current frame index, animation may be delayed + */ + SEL_FrameEventCallFunc m_sFrameEventCallFunc; + + + CCObject *m_sMovementEventTarget; + CCObject *m_sFrameEventTarget; +}; + +NS_CC_EXT_END + +#endif /*__CCANIMATION_H__*/ diff --git a/include/extensions/CocoStudio/Armature/animation/CCProcessBase.h b/include/extensions/CocoStudio/Armature/animation/CCProcessBase.h new file mode 100644 index 0000000..3e83309 --- /dev/null +++ b/include/extensions/CocoStudio/Armature/animation/CCProcessBase.h @@ -0,0 +1,168 @@ +/**************************************************************************** +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. +****************************************************************************/ + + +#ifndef __CCPROCESSBASE_H__ +#define __CCPROCESSBASE_H__ + +#include "../utils/CCArmatureDefine.h" +#include "../datas/CCDatas.h" + +NS_CC_EXT_BEGIN + +enum AnimationType +{ + SINGLE_FRAME = -4, //! the animation just have one frame + ANIMATION_NO_LOOP, //! the animation isn't loop + + ANIMATION_TO_LOOP_FRONT, //! the animation loop from front + ANIMATION_TO_LOOP_BACK, //! the animation loop from back + + ANIMATION_LOOP_FRONT, //! the animation loop from front + ANIMATION_LOOP_BACK, //! the animation loop from back + + ANIMATION_MAX, + +}; + +/** + * @js NA + * @lua NA + */ +class CCProcessBase : public CCObject +{ +public: + CCProcessBase(void); + ~CCProcessBase(void); + + /** + * Play animation by animation name. + * + * @param durationTo The frames between two animation changing-over. + * It's meaning is changing to this animation need how many frames + * + * -1 : use the value from CCMovementData get from flash design panel + * @param durationTween The frame count you want to play in the game. + * if _durationTween is 80, then the animation will played 80 frames in a loop + * + * -1 : use the value from CCMovementData get from flash design panel + * + * @param loop Whether the animation is loop + * + * loop < 0 : use the value from CCMovementData get from flash design panel + * loop = 0 : this animation is not loop + * loop > 0 : this animation is loop + * + * @param tweenEasing CCTween easing is used for calculate easing effect + * + * TWEEN_EASING_MAX : use the value from CCMovementData get from flash design panel + * -1 : fade out + * 0 : line + * 1 : fade in + * 2 : fade in and out + * + */ + virtual void play(int durationTo, int durationTween, int loop, int tweenEasing); + + /** + * Pause the Process + */ + virtual void pause(); + /** + * Resume the Process + */ + virtual void resume(); + /** + * Stop the Process + */ + virtual void stop(); + + + + /** + * You should never call this function, unless you know what you do + * Update the Process, include current process, current frame and son on + * + * @param The duration since last update + */ + virtual void update(float dt); + + virtual int getCurrentFrameIndex(); + +protected: + + virtual void gotoFrame(int frameIndex); + + /** + * Update(float dt) will call this handler, you can handle your logic here + */ + virtual void updateHandler() {}; + +protected: + //! Scale the process speed + CC_SYNTHESIZE(float, m_fProcessScale, ProcessScale); + + //! Set and get whether the aniamtion is pause + CC_SYNTHESIZE(bool, m_bIsPause, IsPause); + + //! Set and get whether the aniamtion is complete + CC_SYNTHESIZE(bool, m_bIsComplete, IsComplete); + + //! Set and get whether the aniamtion is playing + CC_SYNTHESIZE(bool, m_bIsPlaying, IsPlaying); + + //! Current percent this process arrived + CC_SYNTHESIZE(float, m_fCurrentPercent, CurrentPercent); + + //! The raw duration + CC_SYNTHESIZE(int, m_iRawDuration, RawDuration); + + //! The animation whether or not loop + CC_SYNTHESIZE(AnimationType, m_eLoopType, LoopType); + + //! The tween easing effect + CC_SYNTHESIZE(CCTweenType, m_eTweenEasing, TweenEasing); + +protected: + //! The durantion frame count will run + int m_iDurationTween; + + //! Current frame this process arrived, this frame is tween frame + float m_fCurrentFrame; + //! Frame index it the time line + int m_iCurFrameIndex; + + //! Next frame this process need run to + int m_iNextFrameIndex; + + + bool m_bIsLoopBack; + + //! The animation update speed + float m_fAnimationInternal; +}; + +NS_CC_EXT_END + +#endif /*__CCPROCESSBASE_H__*/ diff --git a/include/extensions/CocoStudio/Armature/animation/CCTween.h b/include/extensions/CocoStudio/Armature/animation/CCTween.h new file mode 100644 index 0000000..b60878e --- /dev/null +++ b/include/extensions/CocoStudio/Armature/animation/CCTween.h @@ -0,0 +1,147 @@ +/**************************************************************************** +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. +****************************************************************************/ + + +#ifndef __CCTWEEN_H__ +#define __CCTWEEN_H__ + +#include "CCProcessBase.h" +#include "../utils/CCTweenFunction.h" + +NS_CC_EXT_BEGIN + +class CCBone; +class CCArmatureAnimation; +/** +* @js NA +* @lua NA +*/ +class CCTween : public CCProcessBase +{ +public: + /** + * Create with a CCBone + * @param bone the CCBone CCTween will bind to + */ + static CCTween *create(CCBone *bone); +public: + CCTween(void); + virtual ~CCTween(void); + + /** + * Init with a CCBone + * @param bone the CCBone CCTween will bind to + */ + virtual bool init(CCBone *bone); + + using CCProcessBase::play; + /** + * Start the Process + * + * @param movementBoneData the CCMovementBoneData include all CCFrameData + * @param durationTo the number of frames changing to this animation needs. + * @param durationTween the number of frames this animation actual last. + * + * @param loop whether the animation is loop + * + * loop < 0 : use the value from CCMovementData get from Action Editor + * loop = 0 : this animation is not loop + * loop > 0 : this animation is loop + * + * @param tweenEasing tween easing is used for calculate easing effect + * + * TWEEN_EASING_MAX : use the value from CCMovementData get from Action Editor + * -1 : fade out + * 0 : line + * 1 : fade in + * 2 : fade in and out + * + */ + virtual void play(CCMovementBoneData *movementBoneData, int durationTo, int durationTween, int loop, int tweenEasing); + + virtual void gotoAndPlay(int frameIndex); + virtual void gotoAndPause(int frameIndex); + + inline void setAnimation(CCArmatureAnimation *animation) { m_pAnimation = animation; } + inline CCArmatureAnimation *getAnimation() const { return m_pAnimation; } +protected: + + /** + * Update(float dt) will call this handler, you can handle your logic here + */ + virtual void updateHandler(); + + /** + * Calculate which frame arrived, and if current frame have event, then call the event listener + */ + virtual float updateFrameData(float currentPercent); + + /** + * Calculate the between value of _from and _to, and give it to between frame data + */ + virtual void setBetween(CCFrameData *from, CCFrameData *to, bool limit = true); + + /** + * According to the percent to calculate current CCFrameData with tween effect + */ + virtual CCFrameData *tweenNodeTo(float percent, CCFrameData *node = NULL); + + /** + * According to the percent to calculate current color with tween effect + */ + virtual void tweenColorTo(float percent, CCFrameData *node); + + /** + * Update display index and process the key frame event when arrived a key frame + */ + virtual void arriveKeyFrame(CCFrameData *keyFrameData); +protected: + //! A weak reference to the current CCMovementBoneData. The data is in the data pool + CC_SYNTHESIZE(CCMovementBoneData *, m_pMovementBoneData, MovementBoneData) + + CCFrameData *m_pTweenData; //! The computational tween frame data, //! A weak reference to the CCBone's tweenData + CCFrameData *m_pFrom; //! From frame data, used for calculate between value + CCFrameData *m_pTo; //! To frame data, used for calculate between value + CCFrameData *m_pBetween; //! Between frame data, used for calculate current CCFrameData(m_pNode) value + + + CCBone *m_pBone; //! A weak reference to the CCBone + + CCTweenType m_eFrameTweenEasing; //! Dedermine which tween effect current frame use + + int m_iBetweenDuration; //! Current key frame will last m_iBetweenDuration frames + int m_iTotalDuration; + + + int m_iFromIndex; //! The current frame index in FrameList of CCMovementBoneData, it's different from m_iFrameIndex + int m_iToIndex; //! The next frame index in FrameList of CCMovementBoneData, it's different from m_iFrameIndex + + CCArmatureAnimation *m_pAnimation; + + bool m_bPassLastFrame; +}; + +NS_CC_EXT_END + +#endif /*__CCTWEEN_H__*/ diff --git a/include/extensions/CocoStudio/Armature/datas/CCDatas.h b/include/extensions/CocoStudio/Armature/datas/CCDatas.h new file mode 100644 index 0000000..82eed69 --- /dev/null +++ b/include/extensions/CocoStudio/Armature/datas/CCDatas.h @@ -0,0 +1,473 @@ +/**************************************************************************** +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. +****************************************************************************/ + +#ifndef __CCARMATURE_DATAS_H__ +#define __CCARMATURE_DATAS_H__ + +#include "../utils/CCArmatureDefine.h" +#include "../utils/CCTweenFunction.h" + + +#define CC_CREATE_NO_PARAM_NO_INIT(varType)\ +public: \ + static inline varType *create(void){ \ + varType *var = new varType();\ + if (var)\ +{\ + var->autorelease();\ + return var;\ +}\ + CC_SAFE_DELETE(var);\ + return NULL;\ +} + +#define CC_CREATE_NO_PARAM(varType)\ +public: \ + static inline varType *create(void){ \ + varType *var = new varType();\ + if (var && var->init())\ +{\ + var->autorelease();\ + return var;\ +}\ + CC_SAFE_DELETE(var);\ + return NULL;\ +} + +NS_CC_EXT_BEGIN + +/** + * The base node include a lot of attributes. + * @lua NA + */ +class CCBaseData : public CCObject +{ +public: + CC_CREATE_NO_PARAM_NO_INIT(CCBaseData) +public: + /** + * @js ctor + */ + CCBaseData(); + /** + * @js NA + */ + ~CCBaseData(void); + + /* + * Copy data from node + * @param node A CCBaseData to copy data + */ + virtual void copy(const CCBaseData *node); + + /* + * Calculate two CCBaseData's between value(to - from) and set to self + * + * @param from from CCBaseData + * @param to to CCBaseData + */ + virtual void subtract(CCBaseData *from, CCBaseData *to, bool limit); + + virtual void setColor(const ccColor4B &color); + virtual ccColor4B getColor(); +public: + float x; //! position x attribute + float y; //! position y attribute + int zOrder; //! zorder attribute, used to order the CCBone's depth order + + /** + * x y skewX skewY scaleX scaleY used to calculate transform matrix + * skewX, skewY can have rotation effect + * To get more matrix information, you can have a look at this pape : http://www.senocular.com/flash/tutorials/transformmatrix/ + */ + float skewX; + float skewY; + float scaleX; + float scaleY; + + float tweenRotate; //! SkewX, SkewY, and TweenRotate effect the rotation + + bool isUseColorInfo; //! Whether or not this frame have the color changed Info + int a, r, g, b; + +}; + + +/** +* DisplayType distinguish which type your display is. +*/ +enum DisplayType +{ + CS_DISPLAY_SPRITE, //! display is a single CCSprite + CS_DISPLAY_ARMATURE, //! display is a CCArmature + CS_DISPLAY_PARTICLE, //! display is a CCParticle. + + CS_DISPLAY_MAX +}; +/** +* @js NA +* @lua NA +*/ +class CCDisplayData : public CCObject +{ +public: + CC_CREATE_NO_PARAM_NO_INIT(CCDisplayData) + + static const char *changeDisplayToTexture(const char *displayName); +public: + CCDisplayData(); + virtual ~CCDisplayData(void) {}; + + virtual void copy(CCDisplayData *displayData); + + DisplayType displayType; //! mark which type your display is + std::string displayName; +}; + + +/** +* @js NA +* @lua NA +*/ +class CCSpriteDisplayData : public CCDisplayData +{ +public: + CC_CREATE_NO_PARAM_NO_INIT(CCSpriteDisplayData) +public: + CCSpriteDisplayData(); + virtual ~CCSpriteDisplayData() {}; + + void copy(CCDisplayData *displayData); +public: + CCBaseData skinData; +}; + +/** +* @js NA +* @lua NA +*/ +class CCArmatureDisplayData : public CCDisplayData +{ +public: + CC_CREATE_NO_PARAM_NO_INIT(CCArmatureDisplayData) +public: + CCArmatureDisplayData(); + virtual ~CCArmatureDisplayData() {}; +}; + +/** +* @js NA +* @lua NA +*/ +class CCParticleDisplayData : public CCDisplayData +{ +public: + CC_CREATE_NO_PARAM_NO_INIT(CCParticleDisplayData) +public: + CCParticleDisplayData(); + virtual ~CCParticleDisplayData() {}; +public: +}; + + + +/** +* CCBoneData used to init a CCBone. +* CCBoneData keeps a CCDisplayData list, a CCBone can have many display to change. +* The display information saved in the CCDisplayData +* @js NA +* @lua NA +*/ +class CCBoneData : public CCBaseData +{ +public: + CC_CREATE_NO_PARAM(CCBoneData) +public: + CCBoneData(void); + ~CCBoneData(void); + + virtual bool init(); + + void addDisplayData(CCDisplayData *displayData); + CCDisplayData *getDisplayData(int index); +public: + std::string name; //! the bone's name + std::string parentName; //! the bone parent's name + CCArray displayDataList; //! save CCDisplayData informations for the CCBone + CCAffineTransform boneDataTransform; +}; + + +/** +* CCArmatureData saved the CCArmature name and Bonedata needed for the CCBones in this CCArmature +* When we create a CCArmature, we need to get each CCBone's CCBoneData as it's init information. +* So we can get a CCBoneData from the CCDictionary saved in the CCArmatureData. +* @js NA +* @lua NA +*/ +class CCArmatureData : public CCObject +{ +public: + CC_CREATE_NO_PARAM(CCArmatureData) +public: + CCArmatureData(); + ~CCArmatureData(); + + bool init(); + void addBoneData(CCBoneData *boneData); + CCBoneData *getBoneData(const char *boneName); +public: + std::string name; + CCDictionary boneDataDic; + float dataVersion; +}; + +enum CCBlendType +{ + BLEND_NORMAL, + BLEND_LAYER, + BLEND_DARKEN, + BLEND_MULTIPLY, + BLEND_LIGHTEN, + BLEND_SCREEN, + BLEND_OVERLAY, + BLEND_HARD_LIGHT, + BLEND_ADD, + BLEND_SUBSTRACT, + BLEND_DIFFERENCE, + BLEND_INVERT, + BLEND_ALPHA, + BLEND_ERASE +}; + +/** +* @js NA +* @lua NA +*/ +class CCFrameData : public CCBaseData +{ +public: + CC_CREATE_NO_PARAM_NO_INIT(CCFrameData) +public: + CCFrameData(); + ~CCFrameData(); + + virtual void copy(const CCBaseData *node); +public: + int frameID; + int duration; //! The frame will last duration frames + + CCTweenType tweenEasing; //! Every frame's tween easing effect + int easingParamNumber; + float *easingParams; + + bool isTween; //! Whether it's a tween key frame + + /** + * The current display index when change to this frame. + * If value is -1, then display will not be shown. + */ + int displayIndex; + + ccBlendFunc blendFunc; + + std::string strEvent; + /** + * strMovement, strEvent, strSound, strSoundEffect do not support yet + */ + std::string strMovement; + std::string strSound; + std::string strSoundEffect; +}; + +/** +* @js NA +* @lua NA +*/ +class CCMovementBoneData : public CCObject +{ +public: + CC_CREATE_NO_PARAM(CCMovementBoneData) +public: + CCMovementBoneData(); + ~CCMovementBoneData(void); + + virtual bool init(); + + void addFrameData(CCFrameData *frameData); + CCFrameData *getFrameData(int index); +public: + float delay; //! movement delay percent, this value can produce a delay effect + float scale; //! scale this movement + float duration; //! this CCBone in this movement will last m_iDuration frames + std::string name; //! bone name + + CCArray frameList; +}; + +/** +* @js NA +* @lua NA +*/ +class CCMovementData : public CCObject +{ +public: + CC_CREATE_NO_PARAM_NO_INIT(CCMovementData) +public: + CCMovementData(void); + ~CCMovementData(void); + + void addMovementBoneData(CCMovementBoneData *movBoneData); + CCMovementBoneData *getMovementBoneData(const char *boneName); +public: + std::string name; + int duration; //! the frames this movement will last + float scale; //! scale this movement + + /** + * Change to this movement will last durationTo frames. Use this effect can avoid too suddenly changing. + * + * Example : current movement is "stand", we want to change to "run", then we fill durationTo frames before + * change to "run" instead of changing to "run" directly. + */ + int durationTo; + + /* + * This is different from duration, durationTween contain tween effect. + * duration is the raw time that the animation will last, it's the same with the time you edit in the Action Editor. + * durationTween is the actual time you want this animation last. + * Example : If we edit 10 frames in the flash, then duration is 10. When we set durationTween to 50, the movement will last 50 frames, the extra 40 frames will auto filled with tween effect + */ + int durationTween; + + bool loop; //! whether the movement was looped + + /** + * Which tween easing effect the movement use + * TWEEN_EASING_MAX : use the value from CCMovementData get from flash design panel + */ + CCTweenType tweenEasing; + + /** + * @brief save movment bone data + * @key const char * + * @value CCMovementBoneData * + */ + CCDictionary movBoneDataDic; +}; + + +/** +* CCAnimationData include all movement infomation for the CCArmature +* The struct is CCAnimationData -> CCMovementData -> CCMovementBoneData -> CCFrameData +* -> MovementFrameData +* @js NA +* @lua NA +*/ +class CCAnimationData : public CCObject +{ +public: + CC_CREATE_NO_PARAM_NO_INIT(CCAnimationData) +public: + CCAnimationData(void); + ~CCAnimationData(void); + + void addMovement(CCMovementData *movData); + CCMovementData *getMovement(const char *movementName); + int getMovementCount(); +public: + std::string name; + CCDictionary movementDataDic; + std::vector movementNames; +}; + + +struct CCContourVertex2 : public CCObject +{ + CCContourVertex2(float xx, float yy) + { + this->x = xx; + this->y = yy; + } + + float x; + float y; +}; + +/* +* CCContourData include a contour vertex information +* @js NA +* @lua NA +*/ +class CCContourData : public CCObject +{ +public: + CC_CREATE_NO_PARAM(CCContourData) +public: + CCContourData(); + ~CCContourData(void); + + virtual bool init(); + virtual void addVertex(CCPoint *vertex); +public: + CCArray vertexList; //! Save contour vertex info, vertex saved in a CCPoint +}; + + + + +/* +* CCTextureData include a texture's information +* @js NA +* @lua NA +*/ +class CCTextureData : public CCObject +{ +public: + CC_CREATE_NO_PARAM(CCTextureData) +public: + CCTextureData(); + ~CCTextureData(void); + + virtual bool init(); + + void addContourData(CCContourData *contourData); + CCContourData *getContourData(int index); +public: + + float height; //! The texture's width, height + float width; + + float pivotX; //! The texture's anchor point + float pivotY; + + std::string name; //! The texture's name + + CCArray contourDataList; +}; + + +NS_CC_EXT_END + +#endif /*__CCARMATURE_DATAS_H__*/ diff --git a/include/extensions/CocoStudio/Armature/display/CCBatchNode.h b/include/extensions/CocoStudio/Armature/display/CCBatchNode.h new file mode 100644 index 0000000..e0ef642 --- /dev/null +++ b/include/extensions/CocoStudio/Armature/display/CCBatchNode.h @@ -0,0 +1,69 @@ +/**************************************************************************** +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. +****************************************************************************/ + +#ifndef __CCBATCHNODE_H__ +#define __CCBATCHNODE_H__ + +#include "../utils/CCArmatureDefine.h" + +NS_CC_EXT_BEGIN +/** + * @lua NA + */ +class CCBatchNode : public CCNode +{ +public: + static CCBatchNode *create(); +public: + /** + * @js ctor + */ + CCBatchNode(); + /** + * @js NA + */ + ~CCBatchNode(); + /** + * @js NA + */ + virtual bool init(); + virtual void addChild(CCNode *pChild); + virtual void addChild(CCNode *pChild, int zOrder); + virtual void addChild(CCNode *pChild, int zOrder, int tag); + virtual void removeChild(CCNode* child, bool cleanup); + virtual void visit(); + /** + * @js NA + */ + void draw(); + + virtual CCTextureAtlas *getTexureAtlasWithTexture(CCTexture2D *texture); +protected: + CCTextureAtlas *m_pAtlas; + CCDictionary *m_pTextureAtlasDic; +}; + +NS_CC_EXT_END + +#endif /*__CCBATCHNODE_H__*/ diff --git a/include/extensions/CocoStudio/Armature/display/CCDecorativeDisplay.h b/include/extensions/CocoStudio/Armature/display/CCDecorativeDisplay.h new file mode 100644 index 0000000..e3675c1 --- /dev/null +++ b/include/extensions/CocoStudio/Armature/display/CCDecorativeDisplay.h @@ -0,0 +1,64 @@ +/**************************************************************************** +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. +****************************************************************************/ + +#ifndef __CCDECORATIVEDISPLAY_H__ +#define __CCDECORATIVEDISPLAY_H__ + +#include "../utils/CCArmatureDefine.h" +#include "CCDisplayFactory.h" +#include "../datas/CCDatas.h" + + +#if ENABLE_PHYSICS_BOX2D_DETECT || ENABLE_PHYSICS_CHIPMUNK_DETECT || ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX +#include "../physics/CCColliderDetector.h" +#endif + +NS_CC_EXT_BEGIN +/** + * @js NA + * @lua NA + */ +class CCDecorativeDisplay: public CCObject +{ +public: + static CCDecorativeDisplay *create(); +public: + CCDecorativeDisplay(void); + ~CCDecorativeDisplay(void); + + virtual bool init(); + +protected: + + CC_SYNTHESIZE_RETAIN(CCNode *, m_pDisplay, Display); + CC_SYNTHESIZE_RETAIN(CCDisplayData *, m_pDisplayData, DisplayData); + +#if ENABLE_PHYSICS_BOX2D_DETECT || ENABLE_PHYSICS_CHIPMUNK_DETECT || ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX + CC_SYNTHESIZE_RETAIN(CCColliderDetector *, m_pColliderDetector, ColliderDetector); +#endif +}; + +NS_CC_EXT_END + +#endif /*__CCDECORATIVEDISPLAY_H__*/ diff --git a/include/extensions/CocoStudio/Armature/display/CCDisplayFactory.h b/include/extensions/CocoStudio/Armature/display/CCDisplayFactory.h new file mode 100644 index 0000000..ed3b59a --- /dev/null +++ b/include/extensions/CocoStudio/Armature/display/CCDisplayFactory.h @@ -0,0 +1,65 @@ +/**************************************************************************** +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. +****************************************************************************/ + +#ifndef __CCDISPLAYFACTORY_H__ +#define __CCDISPLAYFACTORY_H__ + +#include "../utils/CCArmatureDefine.h" +#include "../datas/CCDatas.h" + +NS_CC_EXT_BEGIN + +class CCSkin; +class CCBone; +class CCDecorativeDisplay; +class CCDisplayData; +/** + * @js NA + * @lua NA + */ +class CCDisplayFactory +{ +public: + static void addDisplay(CCBone *bone, CCDecorativeDisplay *decoDisplay, CCDisplayData *displayData); + static void createDisplay(CCBone *bone, CCDecorativeDisplay *decoDisplay); + static void updateDisplay(CCBone *bone, float dt, bool dirty); + + static void addSpriteDisplay(CCBone *bone, CCDecorativeDisplay *decoDisplay, CCDisplayData *displayData); + static void createSpriteDisplay(CCBone *bone, CCDecorativeDisplay *decoDisplay); + static void initSpriteDisplay(CCBone *bone, CCDecorativeDisplay *decoDisplay, const char *displayName, CCSkin *skin); + + + static void addArmatureDisplay(CCBone *bone, CCDecorativeDisplay *decoDisplay, CCDisplayData *displayData); + static void createArmatureDisplay(CCBone *bone, CCDecorativeDisplay *decoDisplay); + static void updateArmatureDisplay(CCBone *bone, CCNode *display, float dt); + + static void addParticleDisplay(CCBone *bone, CCDecorativeDisplay *decoDisplay, CCDisplayData *displayData); + static void createParticleDisplay(CCBone *bone, CCDecorativeDisplay *decoDisplay); + static void updateParticleDisplay(CCBone *bone, CCNode *display, float dt); +}; + + +NS_CC_EXT_END + +#endif /*__CCDISPLAYFACTORY_H__*/ diff --git a/include/extensions/CocoStudio/Armature/display/CCDisplayManager.h b/include/extensions/CocoStudio/Armature/display/CCDisplayManager.h new file mode 100644 index 0000000..cbaef10 --- /dev/null +++ b/include/extensions/CocoStudio/Armature/display/CCDisplayManager.h @@ -0,0 +1,156 @@ +/**************************************************************************** +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. +****************************************************************************/ + +#ifndef __CCDISPLAYMANAGER_H__ +#define __CCDISPLAYMANAGER_H__ + +#include "../utils/CCArmatureDefine.h" +#include "../display/CCDecorativeDisplay.h" +#include "../datas/CCDatas.h" + +NS_CC_EXT_BEGIN + +class CCBone; + +/**! CCDisplayManager manages CCBone's display + * @js NA + * @lua NA + */ +class CCDisplayManager : public CCObject +{ +public: + static CCDisplayManager *create(CCBone *bone); + +public: + CCDisplayManager(); + ~CCDisplayManager(); + + bool init(CCBone *bone); + + /** + * Use CCBoneData to init the display list. + * If display is a sprite, and it have texture info in the TexutreData, then use TexutreData to init the display's anchor point + * If the display is a CCArmature, then create a new CCArmature + */ + virtual void initDisplayList(CCBoneData *boneData); + + /** + * Add display and use _DisplayData init the display. + * If index already have a display, then replace it. + * If index is current display index, then also change display to _index + * + * @param displayData it include the display information, like DisplayType. + * If you want to create a sprite display, then create a CCSpriteDisplayData param + * + * @param index the index of the display you want to replace or add to + * -1 : append display from back + */ + void addDisplay(CCDisplayData *displayData, int index); + + void addDisplay(CCNode *display, int index); + + void removeDisplay(int index); + + CCArray *getDecorativeDisplayList(); + + /** + * @deprecated please use changeDisplayWithIndex and changeDisplayWithName + */ + CC_DEPRECATED_ATTRIBUTE void changeDisplayByIndex(int index, bool force); + CC_DEPRECATED_ATTRIBUTE void changeDisplayByName(const char *name, bool force); + + /** + * Change display by index. You can just use this method to change display in the display list. + * The display list is just used for this bone, and it is the displays you may use in every frame. + * + * Note : if index is the same with prev index, the method will not effect + * + * @param index The index of the display you want to change + * @param force If true, then force change display to specified display, or current display will set to display index edit in the flash every key frame. + */ + void changeDisplayWithIndex(int index, bool force); + void changeDisplayWithName(const char *name, bool force); + + CCNode *getDisplayRenderNode(); + DisplayType getDisplayRenderNodeType(); + + int getCurrentDisplayIndex(); + + virtual void setCurrentDecorativeDisplay(CCDecorativeDisplay *decoDisplay); + virtual CCDecorativeDisplay *getCurrentDecorativeDisplay(); + virtual CCDecorativeDisplay *getDecorativeDisplayByIndex( int index); + + /** + * Sets whether the display is visible + * The default value is true, a node is default to visible + * + * @param visible true if the node is visible, false if the node is hidden. + */ + virtual void setVisible(bool visible); + /** + * Determines if the display is visible + * + * @see setVisible(bool) + * @return true if the node is visible, false if the node is hidden. + */ + virtual bool isVisible(); + + CCSize getContentSize(); + CCRect getBoundingBox(); + + CCPoint getAnchorPoint(); + CCPoint getAnchorPointInPoints(); + + /** + * Check if the position is inside the bone. + */ + virtual bool containPoint(CCPoint &_point); + + /** + * Check if the position is inside the bone. + */ + virtual bool containPoint(float x, float y); + +protected: + CCArray *m_pDecoDisplayList; + //! Display render node. + CCNode *m_pDisplayRenderNode; + //! Display render node type + DisplayType m_eDisplayType; + //! Include current display information, like contour sprite, etc. + CCDecorativeDisplay *m_pCurrentDecoDisplay; + //! Current display index + int m_iDisplayIndex; + + CC_SYNTHESIZE(bool, m_bForceChangeDisplay, ForceChangeDisplay) + + //! Whether of not the bone is visible. Default is true + bool m_bVisible; + + CCBone *m_pBone; +}; + +NS_CC_EXT_END + +#endif /*__CCDISPLAYMANAGER_H__*/ diff --git a/include/extensions/CocoStudio/Armature/display/CCSkin.h b/include/extensions/CocoStudio/Armature/display/CCSkin.h new file mode 100644 index 0000000..488472f --- /dev/null +++ b/include/extensions/CocoStudio/Armature/display/CCSkin.h @@ -0,0 +1,67 @@ +/**************************************************************************** +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. +****************************************************************************/ + +#ifndef __CCSKIN_H__ +#define __CCSKIN_H__ + +#include "../utils/CCArmatureDefine.h" +#include "../CCBone.h" + +NS_CC_EXT_BEGIN +/** + * @lua NA + */ +class CCSkin : public CCSprite +{ +public: + static CCSkin *create(); + static CCSkin *createWithSpriteFrameName(const char *pszSpriteFrameName); + static CCSkin *create(const char *pszFileName); +public: + /** + * @js ctor + */ + CCSkin(); + + bool initWithSpriteFrameName(const char *pszSpriteFrameName); + bool initWithFile(const char *pszFilename); + + void updateArmatureTransform(); + void updateTransform(); + + CCAffineTransform nodeToWorldTransform(); + CCAffineTransform nodeToWorldTransformAR(); + + CC_PROPERTY_PASS_BY_REF(CCBaseData, m_sSkinData, SkinData); + CC_PROPERTY(CCBone *, m_pBone, Bone); + +protected: + CCArmature *m_pArmature; + CCAffineTransform m_tSkinTransform; + CC_SYNTHESIZE_READONLY(std::string, m_strDisplayName, DisplayName) +}; + +NS_CC_EXT_END + +#endif /*__CCSKIN_H__*/ diff --git a/include/extensions/CocoStudio/Armature/external_tool/sigslot.h b/include/extensions/CocoStudio/Armature/external_tool/sigslot.h new file mode 100644 index 0000000..ef08d34 --- /dev/null +++ b/include/extensions/CocoStudio/Armature/external_tool/sigslot.h @@ -0,0 +1,2540 @@ +// sigslot.h: Signal/Slot classes +// +// Written by Sarah Thompson (sarah@telergy.com) 2002. +// +// License: Public domain. You are free to use this code however you like, with the proviso that +// the author takes on no responsibility or liability for any use. +// +// QUICK DOCUMENTATION +// +// (see also the full documentation at http://sigslot.sourceforge.net/) +// +// #define switches +// SIGSLOT_PURE_ISO - Define this to force ISO C++ compliance. This also disables +// all of the thread safety support on platforms where it is +// available. +// +// SIGSLOT_USE_POSIX_THREADS - Force use of Posix threads when using a C++ compiler other than +// gcc on a platform that supports Posix threads. (When using gcc, +// this is the default - use SIGSLOT_PURE_ISO to disable this if +// necessary) +// +// SIGSLOT_DEFAULT_MT_POLICY - Where thread support is enabled, this defaults to multi_threaded_global. +// Otherwise, the default is single_threaded. #define this yourself to +// override the default. In pure ISO mode, anything other than +// single_threaded will cause a compiler error. +// +// PLATFORM NOTES +// +// Win32 - On Win32, the WIN32 symbol must be #defined. Most mainstream +// compilers do this by default, but you may need to define it +// yourself if your build environment is less standard. This causes +// the Win32 thread support to be compiled in and used automatically. +// +// Unix/Linux/BSD, etc. - If you're using gcc, it is assumed that you have Posix threads +// available, so they are used automatically. You can override this +// (as under Windows) with the SIGSLOT_PURE_ISO switch. If you're using +// something other than gcc but still want to use Posix threads, you +// need to #define SIGSLOT_USE_POSIX_THREADS. +// +// ISO C++ - If none of the supported platforms are detected, or if +// SIGSLOT_PURE_ISO is defined, all multithreading support is turned off, +// along with any code that might cause a pure ISO C++ environment to +// complain. Before you ask, gcc -ansi -pedantic won't compile this +// library, but gcc -ansi is fine. Pedantic mode seems to throw a lot of +// errors that aren't really there. If you feel like investigating this, +// please contact the author. +// +// +// THREADING MODES +// +// single_threaded - Your program is assumed to be single threaded from the point of view +// of signal/slot usage (i.e. all objects using signals and slots are +// created and destroyed from a single thread). Behaviour if objects are +// destroyed concurrently is undefined (i.e. you'll get the occasional +// segmentation fault/memory exception). +// +// multi_threaded_global - Your program is assumed to be multi threaded. Objects using signals and +// slots can be safely created and destroyed from any thread, even when +// connections exist. In multi_threaded_global mode, this is achieved by a +// single global mutex (actually a critical section on Windows because they +// are faster). This option uses less OS resources, but results in more +// opportunities for contention, possibly resulting in more context switches +// than are strictly necessary. +// +// multi_threaded_local - Behaviour in this mode is essentially the same as multi_threaded_global, +// except that each signal, and each object that inherits has_slots, all +// have their own mutex/critical section. In practice, this means that +// mutex collisions (and hence context switches) only happen if they are +// absolutely essential. However, on some platforms, creating a lot of +// mutexes can slow down the whole OS, so use this option with care. +// +// USING THE LIBRARY +// +// See the full documentation at http://sigslot.sourceforge.net/ +// +// + +#ifndef SIGSLOT_H__ +#define SIGSLOT_H__ + +#include +#include + +#if defined(SIGSLOT_PURE_ISO) || (!defined(WIN32) && !defined(__GNUG__) && !defined(SIGSLOT_USE_POSIX_THREADS)) +# define _SIGSLOT_SINGLE_THREADED +#elif defined(WIN32) +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) +// TODO: CC_PLATFORM_WINRT/CC_PLATFORM_WP8 need to implement _SIGSLOT_HAS_WIN32_THREADS +# define _SIGSLOT_SINGLE_THREADED +#else +# define _SIGSLOT_HAS_WIN32_THREADS +#endif +# include +#elif defined(__GNUG__) || defined(SIGSLOT_USE_POSIX_THREADS) +# define _SIGSLOT_HAS_POSIX_THREADS +# include +#else +# define _SIGSLOT_SINGLE_THREADED +#endif + +#ifndef SIGSLOT_DEFAULT_MT_POLICY +# ifdef _SIGSLOT_SINGLE_THREADED +# define SIGSLOT_DEFAULT_MT_POLICY single_threaded +# else +# define SIGSLOT_DEFAULT_MT_POLICY multi_threaded_local +# endif +#endif + + +namespace sigslot { + + class single_threaded + { + public: + single_threaded() + { + ; + } + + virtual ~single_threaded() + { + ; + } + + virtual void lock() + { + ; + } + + virtual void unlock() + { + ; + } + }; + +#ifdef _SIGSLOT_HAS_WIN32_THREADS + // The multi threading policies only get compiled in if they are enabled. + class multi_threaded_global + { + public: + multi_threaded_global() + { + static bool isinitialised = false; + + if(!isinitialised) + { + InitializeCriticalSection(get_critsec()); + isinitialised = true; + } + } + + multi_threaded_global(const multi_threaded_global&) + { + ; + } + + virtual ~multi_threaded_global() + { + ; + } + + virtual void lock() + { + EnterCriticalSection(get_critsec()); + } + + virtual void unlock() + { + LeaveCriticalSection(get_critsec()); + } + + private: + CRITICAL_SECTION* get_critsec() + { + static CRITICAL_SECTION g_critsec; + return &g_critsec; + } + }; + + class multi_threaded_local + { + public: + multi_threaded_local() + { + InitializeCriticalSection(&m_critsec); + } + + multi_threaded_local(const multi_threaded_local&) + { + InitializeCriticalSection(&m_critsec); + } + + virtual ~multi_threaded_local() + { + DeleteCriticalSection(&m_critsec); + } + + virtual void lock() + { + EnterCriticalSection(&m_critsec); + } + + virtual void unlock() + { + LeaveCriticalSection(&m_critsec); + } + + private: + CRITICAL_SECTION m_critsec; + }; +#endif // _SIGSLOT_HAS_WIN32_THREADS + +#ifdef _SIGSLOT_HAS_POSIX_THREADS + // The multi threading policies only get compiled in if they are enabled. + class multi_threaded_global + { + public: + multi_threaded_global() + { + pthread_mutex_init(get_mutex(), NULL); + } + + multi_threaded_global(const multi_threaded_global&) + { + ; + } + + virtual ~multi_threaded_global() + { + ; + } + + virtual void lock() + { + pthread_mutex_lock(get_mutex()); + } + + virtual void unlock() + { + pthread_mutex_unlock(get_mutex()); + } + + private: + pthread_mutex_t* get_mutex() + { + static pthread_mutex_t g_mutex; + return &g_mutex; + } + }; + + class multi_threaded_local + { + public: + multi_threaded_local() + { + pthread_mutex_init(&m_mutex, NULL); + } + + multi_threaded_local(const multi_threaded_local&) + { + pthread_mutex_init(&m_mutex, NULL); + } + + virtual ~multi_threaded_local() + { + pthread_mutex_destroy(&m_mutex); + } + + virtual void lock() + { + pthread_mutex_lock(&m_mutex); + } + + virtual void unlock() + { + pthread_mutex_unlock(&m_mutex); + } + + private: + pthread_mutex_t m_mutex; + }; +#endif // _SIGSLOT_HAS_POSIX_THREADS + + template + class lock_block + { + public: + mt_policy *m_mutex; + + lock_block(mt_policy *mtx) + : m_mutex(mtx) + { + m_mutex->lock(); + } + + ~lock_block() + { + m_mutex->unlock(); + } + }; + + template + class has_slots; + + template + class _connection_base0 + { + public: + virtual has_slots* getdest() const = 0; + virtual void emit() = 0; + virtual _connection_base0* clone() = 0; + virtual _connection_base0* duplicate(has_slots* pnewdest) = 0; + }; + + template + class _connection_base1 + { + public: + virtual has_slots* getdest() const = 0; + virtual void emit(arg1_type) = 0; + virtual _connection_base1* clone() = 0; + virtual _connection_base1* duplicate(has_slots* pnewdest) = 0; + }; + + template + class _connection_base2 + { + public: + virtual has_slots* getdest() const = 0; + virtual void emit(arg1_type, arg2_type) = 0; + virtual _connection_base2* clone() = 0; + virtual _connection_base2* duplicate(has_slots* pnewdest) = 0; + }; + + template + class _connection_base3 + { + public: + virtual has_slots* getdest() const = 0; + virtual void emit(arg1_type, arg2_type, arg3_type) = 0; + virtual _connection_base3* clone() = 0; + virtual _connection_base3* duplicate(has_slots* pnewdest) = 0; + }; + + template + class _connection_base4 + { + public: + virtual has_slots* getdest() const = 0; + virtual void emit(arg1_type, arg2_type, arg3_type, arg4_type) = 0; + virtual _connection_base4* clone() = 0; + virtual _connection_base4* duplicate(has_slots* pnewdest) = 0; + }; + + template + class _connection_base5 + { + public: + virtual has_slots* getdest() const = 0; + virtual void emit(arg1_type, arg2_type, arg3_type, arg4_type, + arg5_type) = 0; + virtual _connection_base5* clone() = 0; + virtual _connection_base5* duplicate(has_slots* pnewdest) = 0; + }; + + template + class _connection_base6 + { + public: + virtual has_slots* getdest() const = 0; + virtual void emit(arg1_type, arg2_type, arg3_type, arg4_type, arg5_type, + arg6_type) = 0; + virtual _connection_base6* clone() = 0; + virtual _connection_base6* duplicate(has_slots* pnewdest) = 0; + }; + + template + class _connection_base7 + { + public: + virtual has_slots* getdest() const = 0; + virtual void emit(arg1_type, arg2_type, arg3_type, arg4_type, arg5_type, + arg6_type, arg7_type) = 0; + virtual _connection_base7* clone() = 0; + virtual _connection_base7* duplicate(has_slots* pnewdest) = 0; + }; + + template + class _connection_base8 + { + public: + virtual has_slots* getdest() const = 0; + virtual void emit(arg1_type, arg2_type, arg3_type, arg4_type, arg5_type, + arg6_type, arg7_type, arg8_type) = 0; + virtual _connection_base8* clone() = 0; + virtual _connection_base8* duplicate(has_slots* pnewdest) = 0; + }; + + template + class _signal_base : public mt_policy + { + public: + virtual void slot_disconnect(has_slots* pslot) = 0; + virtual void slot_duplicate(const has_slots* poldslot, has_slots* pnewslot) = 0; + }; + + template + class has_slots : public mt_policy + { + private: + typedef std::set<_signal_base *> sender_set; + typedef typename sender_set::const_iterator const_iterator; + + public: + has_slots() + { + ; + } + + has_slots(const has_slots& hs) + : mt_policy(hs) + { + lock_block lock(this); + const_iterator it = hs.m_senders.begin(); + const_iterator itEnd = hs.m_senders.end(); + + while(it != itEnd) + { + (*it)->slot_duplicate(&hs, this); + m_senders.insert(*it); + ++it; + } + } + + void signal_connect(_signal_base* sender) + { + lock_block lock(this); + m_senders.insert(sender); + } + + void signal_disconnect(_signal_base* sender) + { + lock_block lock(this); + m_senders.erase(sender); + } + + virtual ~has_slots() + { + disconnect_all(); + } + + void disconnect_all() + { + lock_block lock(this); + const_iterator it = m_senders.begin(); + const_iterator itEnd = m_senders.end(); + + while(it != itEnd) + { + (*it)->slot_disconnect(this); + ++it; + } + + m_senders.erase(m_senders.begin(), m_senders.end()); + } + + private: + sender_set m_senders; + }; + + template + class _signal_base0 : public _signal_base + { + public: + typedef std::list<_connection_base0 *> connections_list; + + _signal_base0() + { + ; + } + + _signal_base0(const _signal_base0& s) + : _signal_base(s) + { + lock_block lock(this); + typename connections_list::const_iterator it = s.m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = s.m_connected_slots.end(); + + while(it != itEnd) + { + (*it)->getdest()->signal_connect(this); + m_connected_slots.push_back((*it)->clone()); + + ++it; + } + } + + ~_signal_base0() + { + disconnect_all(); + } + + void disconnect_all() + { + lock_block lock(this); + typename connections_list::const_iterator it = m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + (*it)->getdest()->signal_disconnect(this); + delete *it; + + ++it; + } + + m_connected_slots.erase(m_connected_slots.begin(), m_connected_slots.end()); + } + + void disconnect(has_slots* pclass) + { + lock_block lock(this); + typename connections_list::iterator it = m_connected_slots.begin(); + typename connections_list::iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + if((*it)->getdest() == pclass) + { + delete *it; + m_connected_slots.erase(it); + pclass->signal_disconnect(this); + return; + } + + ++it; + } + } + + void slot_disconnect(has_slots* pslot) + { + lock_block lock(this); + typename connections_list::iterator it = m_connected_slots.begin(); + typename connections_list::iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + typename connections_list::iterator itNext = it; + ++itNext; + + if((*it)->getdest() == pslot) + { + delete *it; + m_connected_slots.erase(it); + } + + it = itNext; + } + } + + void slot_duplicate(const has_slots* oldtarget, has_slots* newtarget) + { + lock_block lock(this); + typename connections_list::iterator it = m_connected_slots.begin(); + typename connections_list::iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + if((*it)->getdest() == oldtarget) + { + m_connected_slots.push_back((*it)->duplicate(newtarget)); + } + + ++it; + } + } + + protected: + connections_list m_connected_slots; + }; + + template + class _signal_base1 : public _signal_base + { + public: + typedef std::list<_connection_base1 *> connections_list; + + _signal_base1() + { + ; + } + + _signal_base1(const _signal_base1& s) + : _signal_base(s) + { + lock_block lock(this); + typename connections_list::const_iterator it = s.m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = s.m_connected_slots.end(); + + while(it != itEnd) + { + (*it)->getdest()->signal_connect(this); + m_connected_slots.push_back((*it)->clone()); + + ++it; + } + } + + void slot_duplicate(const has_slots* oldtarget, has_slots* newtarget) + { + lock_block lock(this); + typename connections_list::iterator it = m_connected_slots.begin(); + typename connections_list::iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + if((*it)->getdest() == oldtarget) + { + m_connected_slots.push_back((*it)->duplicate(newtarget)); + } + + ++it; + } + } + + ~_signal_base1() + { + disconnect_all(); + } + + void disconnect_all() + { + lock_block lock(this); + typename connections_list::const_iterator it = m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + (*it)->getdest()->signal_disconnect(this); + delete *it; + + ++it; + } + + m_connected_slots.erase(m_connected_slots.begin(), m_connected_slots.end()); + } + + void disconnect(has_slots* pclass) + { + lock_block lock(this); + typename connections_list::iterator it = m_connected_slots.begin(); + typename connections_list::iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + if((*it)->getdest() == pclass) + { + delete *it; + m_connected_slots.erase(it); + pclass->signal_disconnect(this); + return; + } + + ++it; + } + } + + void slot_disconnect(has_slots* pslot) + { + lock_block lock(this); + typename connections_list::iterator it = m_connected_slots.begin(); + typename connections_list::iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + typename connections_list::iterator itNext = it; + ++itNext; + + if((*it)->getdest() == pslot) + { + delete *it; + m_connected_slots.erase(it); + } + + it = itNext; + } + } + + + protected: + connections_list m_connected_slots; + }; + + template + class _signal_base2 : public _signal_base + { + public: + typedef std::list<_connection_base2 *> + connections_list; + + _signal_base2() + { + ; + } + + _signal_base2(const _signal_base2& s) + : _signal_base(s) + { + lock_block lock(this); + typename connections_list::const_iterator it = s.m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = s.m_connected_slots.end(); + + while(it != itEnd) + { + (*it)->getdest()->signal_connect(this); + m_connected_slots.push_back((*it)->clone()); + + ++it; + } + } + + void slot_duplicate(const has_slots* oldtarget, has_slots* newtarget) + { + lock_block lock(this); + typename connections_list::iterator it = m_connected_slots.begin(); + typename connections_list::iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + if((*it)->getdest() == oldtarget) + { + m_connected_slots.push_back((*it)->duplicate(newtarget)); + } + + ++it; + } + } + + ~_signal_base2() + { + disconnect_all(); + } + + void disconnect_all() + { + lock_block lock(this); + typename connections_list::const_iterator it = m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + (*it)->getdest()->signal_disconnect(this); + delete *it; + + ++it; + } + + m_connected_slots.erase(m_connected_slots.begin(), m_connected_slots.end()); + } + + void disconnect(has_slots* pclass) + { + lock_block lock(this); + typename connections_list::iterator it = m_connected_slots.begin(); + typename connections_list::iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + if((*it)->getdest() == pclass) + { + delete *it; + m_connected_slots.erase(it); + pclass->signal_disconnect(this); + return; + } + + ++it; + } + } + + void slot_disconnect(has_slots* pslot) + { + lock_block lock(this); + typename connections_list::iterator it = m_connected_slots.begin(); + typename connections_list::iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + typename connections_list::iterator itNext = it; + ++itNext; + + if((*it)->getdest() == pslot) + { + delete *it; + m_connected_slots.erase(it); + } + + it = itNext; + } + } + + protected: + connections_list m_connected_slots; + }; + + template + class _signal_base3 : public _signal_base + { + public: + typedef std::list<_connection_base3 *> + connections_list; + + _signal_base3() + { + ; + } + + _signal_base3(const _signal_base3& s) + : _signal_base(s) + { + lock_block lock(this); + typename connections_list::const_iterator it = s.m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = s.m_connected_slots.end(); + + while(it != itEnd) + { + (*it)->getdest()->signal_connect(this); + m_connected_slots.push_back((*it)->clone()); + + ++it; + } + } + + void slot_duplicate(const has_slots* oldtarget, has_slots* newtarget) + { + lock_block lock(this); + typename connections_list::iterator it = m_connected_slots.begin(); + typename connections_list::iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + if((*it)->getdest() == oldtarget) + { + m_connected_slots.push_back((*it)->duplicate(newtarget)); + } + + ++it; + } + } + + ~_signal_base3() + { + disconnect_all(); + } + + void disconnect_all() + { + lock_block lock(this); + typename connections_list::const_iterator it = m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + (*it)->getdest()->signal_disconnect(this); + delete *it; + + ++it; + } + + m_connected_slots.erase(m_connected_slots.begin(), m_connected_slots.end()); + } + + void disconnect(has_slots* pclass) + { + lock_block lock(this); + typename connections_list::iterator it = m_connected_slots.begin(); + typename connections_list::iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + if((*it)->getdest() == pclass) + { + delete *it; + m_connected_slots.erase(it); + pclass->signal_disconnect(this); + return; + } + + ++it; + } + } + + void slot_disconnect(has_slots* pslot) + { + lock_block lock(this); + typename connections_list::iterator it = m_connected_slots.begin(); + typename connections_list::iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + typename connections_list::iterator itNext = it; + ++itNext; + + if((*it)->getdest() == pslot) + { + delete *it; + m_connected_slots.erase(it); + } + + it = itNext; + } + } + + protected: + connections_list m_connected_slots; + }; + + template + class _signal_base4 : public _signal_base + { + public: + typedef std::list<_connection_base4 *> connections_list; + + _signal_base4() + { + ; + } + + _signal_base4(const _signal_base4& s) + : _signal_base(s) + { + lock_block lock(this); + typename connections_list::const_iterator it = s.m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = s.m_connected_slots.end(); + + while(it != itEnd) + { + (*it)->getdest()->signal_connect(this); + m_connected_slots.push_back((*it)->clone()); + + ++it; + } + } + + void slot_duplicate(const has_slots* oldtarget, has_slots* newtarget) + { + lock_block lock(this); + typename connections_list::iterator it = m_connected_slots.begin(); + typename connections_list::iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + if((*it)->getdest() == oldtarget) + { + m_connected_slots.push_back((*it)->duplicate(newtarget)); + } + + ++it; + } + } + + ~_signal_base4() + { + disconnect_all(); + } + + void disconnect_all() + { + lock_block lock(this); + typename connections_list::const_iterator it = m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + (*it)->getdest()->signal_disconnect(this); + delete *it; + + ++it; + } + + m_connected_slots.erase(m_connected_slots.begin(), m_connected_slots.end()); + } + + void disconnect(has_slots* pclass) + { + lock_block lock(this); + typename connections_list::iterator it = m_connected_slots.begin(); + typename connections_list::iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + if((*it)->getdest() == pclass) + { + delete *it; + m_connected_slots.erase(it); + pclass->signal_disconnect(this); + return; + } + + ++it; + } + } + + void slot_disconnect(has_slots* pslot) + { + lock_block lock(this); + typename connections_list::iterator it = m_connected_slots.begin(); + typename connections_list::iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + typename connections_list::iterator itNext = it; + ++itNext; + + if((*it)->getdest() == pslot) + { + delete *it; + m_connected_slots.erase(it); + } + + it = itNext; + } + } + + protected: + connections_list m_connected_slots; + }; + + template + class _signal_base5 : public _signal_base + { + public: + typedef std::list<_connection_base5 *> connections_list; + + _signal_base5() + { + ; + } + + _signal_base5(const _signal_base5& s) + : _signal_base(s) + { + lock_block lock(this); + typename connections_list::const_iterator it = s.m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = s.m_connected_slots.end(); + + while(it != itEnd) + { + (*it)->getdest()->signal_connect(this); + m_connected_slots.push_back((*it)->clone()); + + ++it; + } + } + + void slot_duplicate(const has_slots* oldtarget, has_slots* newtarget) + { + lock_block lock(this); + typename connections_list::iterator it = m_connected_slots.begin(); + typename connections_list::iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + if((*it)->getdest() == oldtarget) + { + m_connected_slots.push_back((*it)->duplicate(newtarget)); + } + + ++it; + } + } + + ~_signal_base5() + { + disconnect_all(); + } + + void disconnect_all() + { + lock_block lock(this); + typename connections_list::const_iterator it = m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + (*it)->getdest()->signal_disconnect(this); + delete *it; + + ++it; + } + + m_connected_slots.erase(m_connected_slots.begin(), m_connected_slots.end()); + } + + void disconnect(has_slots* pclass) + { + lock_block lock(this); + typename connections_list::iterator it = m_connected_slots.begin(); + typename connections_list::iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + if((*it)->getdest() == pclass) + { + delete *it; + m_connected_slots.erase(it); + pclass->signal_disconnect(this); + return; + } + + ++it; + } + } + + void slot_disconnect(has_slots* pslot) + { + lock_block lock(this); + typename connections_list::iterator it = m_connected_slots.begin(); + typename connections_list::iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + typename connections_list::iterator itNext = it; + ++itNext; + + if((*it)->getdest() == pslot) + { + delete *it; + m_connected_slots.erase(it); + } + + it = itNext; + } + } + + protected: + connections_list m_connected_slots; + }; + + template + class _signal_base6 : public _signal_base + { + public: + typedef std::list<_connection_base6 *> connections_list; + + _signal_base6() + { + ; + } + + _signal_base6(const _signal_base6& s) + : _signal_base(s) + { + lock_block lock(this); + typename connections_list::const_iterator it = s.m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = s.m_connected_slots.end(); + + while(it != itEnd) + { + (*it)->getdest()->signal_connect(this); + m_connected_slots.push_back((*it)->clone()); + + ++it; + } + } + + void slot_duplicate(const has_slots* oldtarget, has_slots* newtarget) + { + lock_block lock(this); + typename connections_list::iterator it = m_connected_slots.begin(); + typename connections_list::iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + if((*it)->getdest() == oldtarget) + { + m_connected_slots.push_back((*it)->duplicate(newtarget)); + } + + ++it; + } + } + + ~_signal_base6() + { + disconnect_all(); + } + + void disconnect_all() + { + lock_block lock(this); + typename connections_list::const_iterator it = m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + (*it)->getdest()->signal_disconnect(this); + delete *it; + + ++it; + } + + m_connected_slots.erase(m_connected_slots.begin(), m_connected_slots.end()); + } + + void disconnect(has_slots* pclass) + { + lock_block lock(this); + typename connections_list::iterator it = m_connected_slots.begin(); + typename connections_list::iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + if((*it)->getdest() == pclass) + { + delete *it; + m_connected_slots.erase(it); + pclass->signal_disconnect(this); + return; + } + + ++it; + } + } + + void slot_disconnect(has_slots* pslot) + { + lock_block lock(this); + typename connections_list::iterator it = m_connected_slots.begin(); + typename connections_list::iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + typename connections_list::iterator itNext = it; + ++itNext; + + if((*it)->getdest() == pslot) + { + delete *it; + m_connected_slots.erase(it); + } + + it = itNext; + } + } + + protected: + connections_list m_connected_slots; + }; + + template + class _signal_base7 : public _signal_base + { + public: + typedef std::list<_connection_base7 *> connections_list; + + _signal_base7() + { + ; + } + + _signal_base7(const _signal_base7& s) + : _signal_base(s) + { + lock_block lock(this); + typename connections_list::const_iterator it = s.m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = s.m_connected_slots.end(); + + while(it != itEnd) + { + (*it)->getdest()->signal_connect(this); + m_connected_slots.push_back((*it)->clone()); + + ++it; + } + } + + void slot_duplicate(const has_slots* oldtarget, has_slots* newtarget) + { + lock_block lock(this); + typename connections_list::iterator it = m_connected_slots.begin(); + typename connections_list::iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + if((*it)->getdest() == oldtarget) + { + m_connected_slots.push_back((*it)->duplicate(newtarget)); + } + + ++it; + } + } + + ~_signal_base7() + { + disconnect_all(); + } + + void disconnect_all() + { + lock_block lock(this); + typename connections_list::const_iterator it = m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + (*it)->getdest()->signal_disconnect(this); + delete *it; + + ++it; + } + + m_connected_slots.erase(m_connected_slots.begin(), m_connected_slots.end()); + } + + void disconnect(has_slots* pclass) + { + lock_block lock(this); + typename connections_list::iterator it = m_connected_slots.begin(); + typename connections_list::iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + if((*it)->getdest() == pclass) + { + delete *it; + m_connected_slots.erase(it); + pclass->signal_disconnect(this); + return; + } + + ++it; + } + } + + void slot_disconnect(has_slots* pslot) + { + lock_block lock(this); + typename connections_list::iterator it = m_connected_slots.begin(); + typename connections_list::iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + typename connections_list::iterator itNext = it; + ++itNext; + + if((*it)->getdest() == pslot) + { + delete *it; + m_connected_slots.erase(it); + } + + it = itNext; + } + } + + protected: + connections_list m_connected_slots; + }; + + template + class _signal_base8 : public _signal_base + { + public: + typedef std::list<_connection_base8 *> + connections_list; + + _signal_base8() + { + ; + } + + _signal_base8(const _signal_base8& s) + : _signal_base(s) + { + lock_block lock(this); + typename connections_list::const_iterator it = s.m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = s.m_connected_slots.end(); + + while(it != itEnd) + { + (*it)->getdest()->signal_connect(this); + m_connected_slots.push_back((*it)->clone()); + + ++it; + } + } + + void slot_duplicate(const has_slots* oldtarget, has_slots* newtarget) + { + lock_block lock(this); + typename connections_list::iterator it = m_connected_slots.begin(); + typename connections_list::iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + if((*it)->getdest() == oldtarget) + { + m_connected_slots.push_back((*it)->duplicate(newtarget)); + } + + ++it; + } + } + + ~_signal_base8() + { + disconnect_all(); + } + + void disconnect_all() + { + lock_block lock(this); + typename connections_list::const_iterator it = m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + (*it)->getdest()->signal_disconnect(this); + delete *it; + + ++it; + } + + m_connected_slots.erase(m_connected_slots.begin(), m_connected_slots.end()); + } + + void disconnect(has_slots* pclass) + { + lock_block lock(this); + typename connections_list::iterator it = m_connected_slots.begin(); + typename connections_list::iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + if((*it)->getdest() == pclass) + { + delete *it; + m_connected_slots.erase(it); + pclass->signal_disconnect(this); + return; + } + + ++it; + } + } + + void slot_disconnect(has_slots* pslot) + { + lock_block lock(this); + typename connections_list::iterator it = m_connected_slots.begin(); + typename connections_list::iterator itEnd = m_connected_slots.end(); + + while(it != itEnd) + { + typename connections_list::iterator itNext = it; + ++itNext; + + if((*it)->getdest() == pslot) + { + delete *it; + m_connected_slots.erase(it); + } + + it = itNext; + } + } + + protected: + connections_list m_connected_slots; + }; + + + template + class _connection0 : public _connection_base0 + { + public: + _connection0() + { + m_pobject = NULL; + m_pmemfun = NULL; + } + + _connection0(dest_type* pobject, void (dest_type::*pmemfun)()) + { + m_pobject = pobject; + m_pmemfun = pmemfun; + } + + virtual _connection_base0* clone() + { + return new _connection0(*this); + } + + virtual _connection_base0* duplicate(has_slots* pnewdest) + { + return new _connection0((dest_type *)pnewdest, m_pmemfun); + } + + virtual void emit() + { + (m_pobject->*m_pmemfun)(); + } + + virtual has_slots* getdest() const + { + return m_pobject; + } + + private: + dest_type* m_pobject; + void (dest_type::* m_pmemfun)(); + }; + + template + class _connection1 : public _connection_base1 + { + public: + _connection1() + { + m_pobject = NULL; + m_pmemfun = NULL; + } + + _connection1(dest_type* pobject, void (dest_type::*pmemfun)(arg1_type)) + { + m_pobject = pobject; + m_pmemfun = pmemfun; + } + + virtual _connection_base1* clone() + { + return new _connection1(*this); + } + + virtual _connection_base1* duplicate(has_slots* pnewdest) + { + return new _connection1((dest_type *)pnewdest, m_pmemfun); + } + + virtual void emit(arg1_type a1) + { + (m_pobject->*m_pmemfun)(a1); + } + + virtual has_slots* getdest() const + { + return m_pobject; + } + + private: + dest_type* m_pobject; + void (dest_type::* m_pmemfun)(arg1_type); + }; + + template + class _connection2 : public _connection_base2 + { + public: + _connection2() + { + m_pobject = NULL; + m_pmemfun = NULL; + } + + _connection2(dest_type* pobject, void (dest_type::*pmemfun)(arg1_type, + arg2_type)) + { + m_pobject = pobject; + m_pmemfun = pmemfun; + } + + virtual _connection_base2* clone() + { + return new _connection2(*this); + } + + virtual _connection_base2* duplicate(has_slots* pnewdest) + { + return new _connection2((dest_type *)pnewdest, m_pmemfun); + } + + virtual void emit(arg1_type a1, arg2_type a2) + { + (m_pobject->*m_pmemfun)(a1, a2); + } + + virtual has_slots* getdest() const + { + return m_pobject; + } + + private: + dest_type* m_pobject; + void (dest_type::* m_pmemfun)(arg1_type, arg2_type); + }; + + template + class _connection3 : public _connection_base3 + { + public: + _connection3() + { + m_pobject = NULL; + m_pmemfun = NULL; + } + + _connection3(dest_type* pobject, void (dest_type::*pmemfun)(arg1_type, + arg2_type, arg3_type)) + { + m_pobject = pobject; + m_pmemfun = pmemfun; + } + + virtual _connection_base3* clone() + { + return new _connection3(*this); + } + + virtual _connection_base3* duplicate(has_slots* pnewdest) + { + return new _connection3((dest_type *)pnewdest, m_pmemfun); + } + + virtual void emit(arg1_type a1, arg2_type a2, arg3_type a3) + { + (m_pobject->*m_pmemfun)(a1, a2, a3); + } + + virtual has_slots* getdest() const + { + return m_pobject; + } + + private: + dest_type* m_pobject; + void (dest_type::* m_pmemfun)(arg1_type, arg2_type, arg3_type); + }; + + template + class _connection4 : public _connection_base4 + { + public: + _connection4() + { + m_pobject = NULL; + m_pmemfun = NULL; + } + + _connection4(dest_type* pobject, void (dest_type::*pmemfun)(arg1_type, + arg2_type, arg3_type, arg4_type)) + { + m_pobject = pobject; + m_pmemfun = pmemfun; + } + + virtual _connection_base4* clone() + { + return new _connection4(*this); + } + + virtual _connection_base4* duplicate(has_slots* pnewdest) + { + return new _connection4((dest_type *)pnewdest, m_pmemfun); + } + + virtual void emit(arg1_type a1, arg2_type a2, arg3_type a3, + arg4_type a4) + { + (m_pobject->*m_pmemfun)(a1, a2, a3, a4); + } + + virtual has_slots* getdest() const + { + return m_pobject; + } + + private: + dest_type* m_pobject; + void (dest_type::* m_pmemfun)(arg1_type, arg2_type, arg3_type, + arg4_type); + }; + + template + class _connection5 : public _connection_base5 + { + public: + _connection5() + { + m_pobject = NULL; + m_pmemfun = NULL; + } + + _connection5(dest_type* pobject, void (dest_type::*pmemfun)(arg1_type, + arg2_type, arg3_type, arg4_type, arg5_type)) + { + m_pobject = pobject; + m_pmemfun = pmemfun; + } + + virtual _connection_base5* clone() + { + return new _connection5(*this); + } + + virtual _connection_base5* duplicate(has_slots* pnewdest) + { + return new _connection5((dest_type *)pnewdest, m_pmemfun); + } + + virtual void emit(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4, + arg5_type a5) + { + (m_pobject->*m_pmemfun)(a1, a2, a3, a4, a5); + } + + virtual has_slots* getdest() const + { + return m_pobject; + } + + private: + dest_type* m_pobject; + void (dest_type::* m_pmemfun)(arg1_type, arg2_type, arg3_type, arg4_type, + arg5_type); + }; + + template + class _connection6 : public _connection_base6 + { + public: + _connection6() + { + m_pobject = NULL; + m_pmemfun = NULL; + } + + _connection6(dest_type* pobject, void (dest_type::*pmemfun)(arg1_type, + arg2_type, arg3_type, arg4_type, arg5_type, arg6_type)) + { + m_pobject = pobject; + m_pmemfun = pmemfun; + } + + virtual _connection_base6* clone() + { + return new _connection6(*this); + } + + virtual _connection_base6* duplicate(has_slots* pnewdest) + { + return new _connection6((dest_type *)pnewdest, m_pmemfun); + } + + virtual void emit(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4, + arg5_type a5, arg6_type a6) + { + (m_pobject->*m_pmemfun)(a1, a2, a3, a4, a5, a6); + } + + virtual has_slots* getdest() const + { + return m_pobject; + } + + private: + dest_type* m_pobject; + void (dest_type::* m_pmemfun)(arg1_type, arg2_type, arg3_type, arg4_type, + arg5_type, arg6_type); + }; + + template + class _connection7 : public _connection_base7 + { + public: + _connection7() + { + m_pobject = NULL; + m_pmemfun = NULL; + } + + _connection7(dest_type* pobject, void (dest_type::*pmemfun)(arg1_type, + arg2_type, arg3_type, arg4_type, arg5_type, arg6_type, arg7_type)) + { + m_pobject = pobject; + m_pmemfun = pmemfun; + } + + virtual _connection_base7* clone() + { + return new _connection7(*this); + } + + virtual _connection_base7* duplicate(has_slots* pnewdest) + { + return new _connection7((dest_type *)pnewdest, m_pmemfun); + } + + virtual void emit(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4, + arg5_type a5, arg6_type a6, arg7_type a7) + { + (m_pobject->*m_pmemfun)(a1, a2, a3, a4, a5, a6, a7); + } + + virtual has_slots* getdest() const + { + return m_pobject; + } + + private: + dest_type* m_pobject; + void (dest_type::* m_pmemfun)(arg1_type, arg2_type, arg3_type, arg4_type, + arg5_type, arg6_type, arg7_type); + }; + + template + class _connection8 : public _connection_base8 + { + public: + _connection8() + { + m_pobject = NULL; + m_pmemfun = NULL; + } + + _connection8(dest_type* pobject, void (dest_type::*pmemfun)(arg1_type, + arg2_type, arg3_type, arg4_type, arg5_type, arg6_type, + arg7_type, arg8_type)) + { + m_pobject = pobject; + m_pmemfun = pmemfun; + } + + virtual _connection_base8* clone() + { + return new _connection8(*this); + } + + virtual _connection_base8* duplicate(has_slots* pnewdest) + { + return new _connection8((dest_type *)pnewdest, m_pmemfun); + } + + virtual void emit(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4, + arg5_type a5, arg6_type a6, arg7_type a7, arg8_type a8) + { + (m_pobject->*m_pmemfun)(a1, a2, a3, a4, a5, a6, a7, a8); + } + + virtual has_slots* getdest() const + { + return m_pobject; + } + + private: + dest_type* m_pobject; + void (dest_type::* m_pmemfun)(arg1_type, arg2_type, arg3_type, arg4_type, + arg5_type, arg6_type, arg7_type, arg8_type); + }; + + template + class signal0 : public _signal_base0 + { + public: + typedef std::list<_connection_base0 *> connections_list; + signal0() + { + ; + } + + signal0(const signal0& s) + : _signal_base0(s) + { + ; + } + + + template + void connect(desttype* pclass, void (desttype::*pmemfun)()) + { + lock_block lock(this); + _connection0* conn = + new _connection0(pclass, pmemfun); + + _signal_base0::m_connected_slots.push_back(conn); + pclass->signal_connect(this); + } + + void emit() + { + lock_block lock(this); + typename connections_list::const_iterator itNext, it = _signal_base0::m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = _signal_base0::m_connected_slots.end(); + + while(it != itEnd) + { + itNext = it; + ++itNext; + + (*it)->emit(); + + it = itNext; + } + } + + void operator()() + { + lock_block lock(this); + typename connections_list::const_iterator itNext, it = _signal_base0::m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = _signal_base0::m_connected_slots.end(); + + while(it != itEnd) + { + itNext = it; + ++itNext; + + (*it)->emit(); + + it = itNext; + } + } + + }; + + template + class signal1 : public _signal_base1 + { + public: + typedef std::list<_connection_base1 *> connections_list; + typedef _signal_base1 signal_base; + signal1() + { + ; + } + + signal1(const signal1& s) + : _signal_base1(s) + { + ; + } + + template + void connect(desttype* pclass, void (desttype::*pmemfun)(arg1_type)) + { + lock_block lock(this); + _connection1* conn = + new _connection1(pclass, pmemfun); + signal_base::m_connected_slots.push_back(conn); + pclass->signal_connect(this); + } + + void emit(arg1_type a1) + { + lock_block lock(this); + typename connections_list::const_iterator itNext, it = signal_base::m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = signal_base::m_connected_slots.end(); + + while(it != itEnd) + { + itNext = it; + ++itNext; + + (*it)->emit(a1); + + it = itNext; + } + } + + void operator()(arg1_type a1) + { + lock_block lock(this); + typename connections_list::const_iterator itNext, it = signal_base::m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = signal_base::m_connected_slots.end(); + + while(it != itEnd) + { + itNext = it; + ++itNext; + + (*it)->emit(a1); + + it = itNext; + } + } + }; + + template + class signal2 : public _signal_base2 + { + public: + typedef std::list<_connection_base2 *> + connections_list; + typedef _signal_base2 signal_base; + signal2() + { + ; + } + + signal2(const signal2& s) + : _signal_base2(s) + { + ; + } + + template + void connect(desttype* pclass, void (desttype::*pmemfun)(arg1_type, + arg2_type)) + { + lock_block lock(this); + _connection2* conn = new + _connection2(pclass, pmemfun); + signal_base::m_connected_slots.push_back(conn); + pclass->signal_connect(this); + } + + void emit(arg1_type a1, arg2_type a2) + { + lock_block lock(this); + typename connections_list::const_iterator itNext, it = signal_base::m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = signal_base::m_connected_slots.end(); + + while(it != itEnd) + { + itNext = it; + ++itNext; + + (*it)->emit(a1, a2); + + it = itNext; + } + } + + void operator()(arg1_type a1, arg2_type a2) + { + lock_block lock(this); + typename connections_list::const_iterator itNext, it = signal_base::m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = signal_base::m_connected_slots.end(); + + while(it != itEnd) + { + itNext = it; + ++itNext; + + (*it)->emit(a1, a2); + + it = itNext; + } + } + }; + + template + class signal3 : public _signal_base3 + { + public: + typedef std::list<_connection_base3 *> + connections_list; + typedef _signal_base3 signal_base; + signal3() + { + ; + } + + ~signal3() + { + + } + + signal3(const signal3& s) + : _signal_base3(s) + { + ; + } + + template + void connect(desttype* pclass, void (desttype::*pmemfun)(arg1_type, + arg2_type, arg3_type)) + { + lock_block lock(this); + _connection3* conn = + new _connection3(pclass, + pmemfun); + signal_base::m_connected_slots.push_back(conn); + pclass->signal_connect(this); + } + + void emit(arg1_type a1, arg2_type a2, arg3_type a3) + { + lock_block lock(this); + typename connections_list::const_iterator itNext, it = signal_base::m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = signal_base::m_connected_slots.end(); + + while(it != itEnd) + { + itNext = it; + ++itNext; + + (*it)->emit(a1, a2, a3); + + it = itNext; + } + } + + void operator()(arg1_type a1, arg2_type a2, arg3_type a3) + { + lock_block lock(this); + typename connections_list::const_iterator itNext, it = signal_base::m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = signal_base::m_connected_slots.end(); + + while(it != itEnd) + { + itNext = it; + ++itNext; + + (*it)->emit(a1, a2, a3); + + it = itNext; + } + } + }; + + template + class signal4 : public _signal_base4 + { + public: + typedef std::list<_connection_base4 *> connections_list; + typedef _signal_base4 signal_base; + signal4() + { + ; + } + + signal4(const signal4& s) + : _signal_base4(s) + { + ; + } + + template + void connect(desttype* pclass, void (desttype::*pmemfun)(arg1_type, + arg2_type, arg3_type, arg4_type)) + { + lock_block lock(this); + _connection4* + conn = new _connection4(pclass, pmemfun); + signal_base::m_connected_slots.push_back(conn); + pclass->signal_connect(this); + } + + void emit(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4) + { + lock_block lock(this); + typename connections_list::const_iterator itNext, it = signal_base::m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = signal_base::m_connected_slots.end(); + + while(it != itEnd) + { + itNext = it; + ++itNext; + + (*it)->emit(a1, a2, a3, a4); + + it = itNext; + } + } + + void operator()(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4) + { + lock_block lock(this); + typename connections_list::const_iterator itNext, it = signal_base::m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = signal_base::m_connected_slots.end(); + + while(it != itEnd) + { + itNext = it; + ++itNext; + + (*it)->emit(a1, a2, a3, a4); + + it = itNext; + } + } + }; + + template + class signal5 : public _signal_base5 + { + public: + typedef std::list<_connection_base5 *> connections_list; + typedef _signal_base5 signal_base; + signal5() + { + ; + } + + signal5(const signal5& s) + : _signal_base5(s) + { + ; + } + + template + void connect(desttype* pclass, void (desttype::*pmemfun)(arg1_type, + arg2_type, arg3_type, arg4_type, arg5_type)) + { + lock_block lock(this); + _connection5* conn = new _connection5(pclass, pmemfun); + signal_base::m_connected_slots.push_back(conn); + pclass->signal_connect(this); + } + + void emit(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4, + arg5_type a5) + { + lock_block lock(this); + typename connections_list::const_iterator itNext, it = signal_base::m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = signal_base::m_connected_slots.end(); + + while(it != itEnd) + { + itNext = it; + ++itNext; + + (*it)->emit(a1, a2, a3, a4, a5); + + it = itNext; + } + } + + void operator()(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4, + arg5_type a5) + { + lock_block lock(this); + typename connections_list::const_iterator itNext, it = signal_base::m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = signal_base::m_connected_slots.end(); + + while(it != itEnd) + { + itNext = it; + ++itNext; + + (*it)->emit(a1, a2, a3, a4, a5); + + it = itNext; + } + } + }; + + + template + class signal6 : public _signal_base6 + { + public: + typedef std::list<_connection_base6 *> connections_list; + typedef _signal_base6 signal_base; + signal6() + { + ; + } + + signal6(const signal6& s) + : _signal_base6(s) + { + ; + } + + template + void connect(desttype* pclass, void (desttype::*pmemfun)(arg1_type, + arg2_type, arg3_type, arg4_type, arg5_type, arg6_type)) + { + lock_block lock(this); + _connection6* conn = + new _connection6(pclass, pmemfun); + signal_base::m_connected_slots.push_back(conn); + pclass->signal_connect(this); + } + + void emit(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4, + arg5_type a5, arg6_type a6) + { + lock_block lock(this); + typename connections_list::const_iterator itNext, it = signal_base::m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = signal_base::m_connected_slots.end(); + + while(it != itEnd) + { + itNext = it; + ++itNext; + + (*it)->emit(a1, a2, a3, a4, a5, a6); + + it = itNext; + } + } + + void operator()(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4, + arg5_type a5, arg6_type a6) + { + lock_block lock(this); + typename connections_list::const_iterator itNext, it = signal_base::m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = signal_base::m_connected_slots.end(); + + while(it != itEnd) + { + itNext = it; + ++itNext; + + (*it)->emit(a1, a2, a3, a4, a5, a6); + + it = itNext; + } + } + }; + + template + class signal7 : public _signal_base7 + { + public: + typedef std::list<_connection_base7 *> connections_list; + typedef _signal_base7 signal_base; + signal7() + { + ; + } + + signal7(const signal7& s) + : _signal_base7(s) + { + ; + } + + template + void connect(desttype* pclass, void (desttype::*pmemfun)(arg1_type, + arg2_type, arg3_type, arg4_type, arg5_type, arg6_type, + arg7_type)) + { + lock_block lock(this); + _connection7* conn = + new _connection7(pclass, pmemfun); + signal_base::m_connected_slots.push_back(conn); + pclass->signal_connect(this); + } + + void emit(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4, + arg5_type a5, arg6_type a6, arg7_type a7) + { + lock_block lock(this); + typename connections_list::const_iterator itNext, it = signal_base::m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = signal_base::m_connected_slots.end(); + + while(it != itEnd) + { + itNext = it; + ++itNext; + + (*it)->emit(a1, a2, a3, a4, a5, a6, a7); + + it = itNext; + } + } + + void operator()(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4, + arg5_type a5, arg6_type a6, arg7_type a7) + { + lock_block lock(this); + typename connections_list::const_iterator itNext, it = signal_base::m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = signal_base::m_connected_slots.end(); + + while(it != itEnd) + { + itNext = it; + ++itNext; + + (*it)->emit(a1, a2, a3, a4, a5, a6, a7); + + it = itNext; + } + } + }; + + template + class signal8 : public _signal_base8 + { + public: + typedef std::list<_connection_base8 *> + connections_list; + typedef _signal_base8 signal_base; + signal8() + { + ; + } + + signal8(const signal8& s) + : _signal_base8(s) + { + ; + } + + template + void connect(desttype* pclass, void (desttype::*pmemfun)(arg1_type, + arg2_type, arg3_type, arg4_type, arg5_type, arg6_type, + arg7_type, arg8_type)) + { + lock_block lock(this); + _connection8* conn = + new _connection8(pclass, pmemfun); + signal_base::m_connected_slots.push_back(conn); + pclass->signal_connect(this); + } + + void emit(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4, + arg5_type a5, arg6_type a6, arg7_type a7, arg8_type a8) + { + lock_block lock(this); + typename connections_list::const_iterator itNext, it = signal_base::m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = signal_base::m_connected_slots.end(); + + while(it != itEnd) + { + itNext = it; + ++itNext; + + (*it)->emit(a1, a2, a3, a4, a5, a6, a7, a8); + + it = itNext; + } + } + + void operator()(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4, + arg5_type a5, arg6_type a6, arg7_type a7, arg8_type a8) + { + lock_block lock(this); + typename connections_list::const_iterator itNext, it = signal_base::m_connected_slots.begin(); + typename connections_list::const_iterator itEnd = signal_base::m_connected_slots.end(); + + while(it != itEnd) + { + itNext = it; + ++itNext; + + (*it)->emit(a1, a2, a3, a4, a5, a6, a7, a8); + + it = itNext; + } + } + }; + +}; // namespace sigslot + +#endif // SIGSLOT_H__ + diff --git a/include/extensions/CocoStudio/Armature/physics/CCColliderDetector.h b/include/extensions/CocoStudio/Armature/physics/CCColliderDetector.h new file mode 100644 index 0000000..4c7ffe2 --- /dev/null +++ b/include/extensions/CocoStudio/Armature/physics/CCColliderDetector.h @@ -0,0 +1,160 @@ +/**************************************************************************** +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. +****************************************************************************/ + +#ifndef __CCCOLLIDERDETECTOR_H__ +#define __CCCOLLIDERDETECTOR_H__ + +#include "../utils/CCArmatureDefine.h" +#include "../datas/CCDatas.h" + +#ifndef PT_RATIO +#define PT_RATIO 32 +#endif + +#if ENABLE_PHYSICS_CHIPMUNK_DETECT +struct cpBody; +struct cpShape; +#elif ENABLE_PHYSICS_BOX2D_DETECT +class b2Body; +class b2Fixture; +struct b2Filter; +#endif + + +NS_CC_EXT_BEGIN + +class CCBone; +/** + * @js NA + * @lua NA + */ +class CCColliderFilter +{ +public: + ~CCColliderFilter() { } + +#if ENABLE_PHYSICS_BOX2D_DETECT +public: + CCColliderFilter(unsigned short categoryBits = 0x0001, unsigned short maskBits = 0xFFFF, signed short groupIndex = 0); + void updateShape(b2Fixture *fixture); +protected: + CC_SYNTHESIZE(unsigned short, m_CategoryBits, CategoryBits); + CC_SYNTHESIZE(unsigned short, m_MaskBits, MaskBits); + CC_SYNTHESIZE(signed short, m_GroupIndex, GroupIndex); +#elif ENABLE_PHYSICS_CHIPMUNK_DETECT +public: + CCColliderFilter(uintptr_t collisionType = 0, uintptr_t group = 0); + void updateShape(cpShape *shape); +protected: + CC_SYNTHESIZE(uintptr_t, m_CollisionType, CollisionType); + CC_SYNTHESIZE(uintptr_t, m_Group, Group); +#endif +}; + +/** +* @js NA +* @lua NA +*/ +class ColliderBody : public CCObject +{ +public: +#if ENABLE_PHYSICS_BOX2D_DETECT + CC_SYNTHESIZE(b2Fixture *, m_pFixture, B2Fixture) +#elif ENABLE_PHYSICS_CHIPMUNK_DETECT + CC_SYNTHESIZE(cpShape *, m_pShape, Shape) +#elif ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX + CC_SYNTHESIZE_READONLY(CCArray *, m_pCalculatedVertexList, CalculatedVertexList); +#endif + +public: + ColliderBody(CCContourData *contourData); + ~ColliderBody(); + + inline CCContourData *getContourData() { return m_pContourData; } + +#if ENABLE_PHYSICS_BOX2D_DETECT || ENABLE_PHYSICS_CHIPMUNK_DETECT + void setColliderFilter(CCColliderFilter *filter); + CCColliderFilter *getColliderFilter(); +private: + CCColliderFilter *m_pFilter; +#endif + +private: + CCContourData *m_pContourData; +}; + +/* + * @brief ContourSprite used to draw the contour of the display + * @js NA + * @lua NA + */ +class CCColliderDetector : public CCObject +{ +public: + static CCColliderDetector *create(); + static CCColliderDetector *create(CCBone *bone); +public: + CCColliderDetector(); + ~CCColliderDetector(void); + + virtual bool init(); + virtual bool init(CCBone *bone); + + void addContourData(CCContourData *contourData); + void addContourDataList(CCArray *contourDataList); + + void removeContourData(CCContourData *contourData); + void removeAll(); + + void updateTransform(CCAffineTransform &t); + + void setActive(bool active); + bool getActive(); + + CCArray *getColliderBodyList(); + +#if ENABLE_PHYSICS_BOX2D_DETECT || ENABLE_PHYSICS_CHIPMUNK_DETECT + virtual void setColliderFilter(CCColliderFilter *filter); + virtual CCColliderFilter *getColliderFilter(); +protected: + CCColliderFilter *m_pFilter; +#endif +protected: + CCArray *m_pColliderBodyList; + + CC_SYNTHESIZE(CCBone *, m_pBone, Bone); + +#if ENABLE_PHYSICS_BOX2D_DETECT + CC_PROPERTY(b2Body *, m_pBody, Body); +#elif ENABLE_PHYSICS_CHIPMUNK_DETECT + CC_PROPERTY(cpBody *, m_pBody, Body); +#endif + +protected: + bool m_bActive; +}; + +NS_CC_EXT_END + +#endif /*__CCCOLLIDERDETECTOR_H__*/ diff --git a/include/extensions/CocoStudio/Armature/utils/CCArmatureDataManager.h b/include/extensions/CocoStudio/Armature/utils/CCArmatureDataManager.h new file mode 100644 index 0000000..b0050eb --- /dev/null +++ b/include/extensions/CocoStudio/Armature/utils/CCArmatureDataManager.h @@ -0,0 +1,203 @@ +/**************************************************************************** +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. +****************************************************************************/ + +#ifndef __CCARMATUREDATAMANAGER_H__ +#define __CCARMATUREDATAMANAGER_H__ + +#include "CCArmatureDefine.h" +#include "../datas/CCDatas.h" + + +NS_CC_EXT_BEGIN + +struct CCRelativeData +{ + std::vector plistFiles; + std::vector armatures; + std::vector animations; + std::vector textures; +}; + +/** + * @brief format and manage armature configuration and armature animation + * @lua NA + */ +class CCArmatureDataManager : public CCObject +{ +public: + /** + * @js getInstance + */ + static CCArmatureDataManager *sharedArmatureDataManager(); + + static void purge(); +private: + CCArmatureDataManager(void); + ~CCArmatureDataManager(void); + +public: + + /** + * Init CCArmatureDataManager + */ + virtual bool init(); + + + + /** + * Add armature data + * @param id The id of the armature data + * @param armatureData CCArmatureData * + */ + void addArmatureData(const char *id, CCArmatureData *armatureData, const char *configFilePath = ""); + + /** + * @brief get armature data + * @param id the id of the armature data you want to get + * @return CCArmatureData * + */ + CCArmatureData *getArmatureData(const char *id); + + /** + * @brief remove armature data + * @param id the id of the armature data you want to get + */ + void removeArmatureData(const char *id); + + /** + * @brief add animation data + * @param id the id of the animation data + * @return CCAnimationData * + */ + void addAnimationData(const char *id, CCAnimationData *animationData, const char *configFilePath = ""); + + /** + * @brief get animation data from m_pAnimationDatas(CCDictionary) + * @param id the id of the animation data you want to get + * @return CCAnimationData * + */ + CCAnimationData *getAnimationData(const char *id); + + /** + * @brief remove animation data + * @param id the id of the animation data + */ + void removeAnimationData(const char *id); + + /** + * @brief add texture data + * @param id the id of the texture data + * @return CCTextureData * + */ + void addTextureData(const char *id, CCTextureData *textureData, const char *configFilePath = ""); + + /** + * @brief get texture data + * @param id the id of the texture data you want to get + * @return CCTextureData * + */ + CCTextureData *getTextureData(const char *id); + + /** + * @brief remove texture data + * @param id the id of the texture data you want to get + */ + void removeTextureData(const char *id); + + /** + * @brief Add ArmatureFileInfo, it is managed by CCArmatureDataManager. + */ + void addArmatureFileInfo(const char *configFilePath); + + /** + * @brief Add ArmatureFileInfo, it is managed by CCArmatureDataManager. + * It will load data in a new thread + */ + void addArmatureFileInfoAsync(const char *configFilePath, CCObject *target, SEL_SCHEDULE selector); + + /** + * @brief Add ArmatureFileInfo, it is managed by CCArmatureDataManager. + */ + void addArmatureFileInfo(const char *imagePath, const char *plistPath, const char *configFilePath); + + /** + * @brief Add ArmatureFileInfo, it is managed by CCArmatureDataManager. + * It will load data in a new thread + */ + void addArmatureFileInfoAsync(const char *imagePath, const char *plistPath, const char *configFilePath, CCObject *target, SEL_SCHEDULE selector); + + + virtual void removeArmatureFileInfo(const char *configFilePath); + + + /** + * @brief Add sprite frame to CCSpriteFrameCache, it will save display name and it's relative image name + */ + void addSpriteFrameFromFile(const char *plistPath, const char *imagePath, const char *configFilePath = ""); + + + /** + * @brief Juge whether or not need auto load sprite file + */ + bool isAutoLoadSpriteFile(); + + + CCDictionary *getArmatureDatas() const; + CCDictionary *getAnimationDatas() const; + CCDictionary *getTextureDatas() const; + +protected: + void addRelativeData(const char* configFilePath); + CCRelativeData *getRelativeData(const char* configFilePath); +private: + /** + * @brief save amature datas + * @key std::string + * @value CCArmatureData * + */ + CCDictionary *m_pArmarureDatas; + + /** + * @brief save animation datas + * @key std::string + * @value CCAnimationData * + */ + CCDictionary *m_pAnimationDatas; + + /** + * @brief save texture datas + * @key std::string + * @value CCTextureData * + */ + CCDictionary *m_pTextureDatas; + + bool m_bAutoLoadSpriteFile; + + std::map m_sRelativeDatas; +}; + + +NS_CC_EXT_END + +#endif/*__CCARMATUREDATAMANAGER_H__*/ diff --git a/include/extensions/CocoStudio/Armature/utils/CCArmatureDefine.h b/include/extensions/CocoStudio/Armature/utils/CCArmatureDefine.h new file mode 100644 index 0000000..a64eb39 --- /dev/null +++ b/include/extensions/CocoStudio/Armature/utils/CCArmatureDefine.h @@ -0,0 +1,71 @@ +/**************************************************************************** +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. +****************************************************************************/ + +#ifndef __CCARMATUREDEFINE_H__ +#define __CCARMATUREDEFINE_H__ + + +#include "cocos2d.h" +#include "ExtensionMacros.h" + +#define VERSION_COMBINED 0.30f +#define VERSION_CHANGE_ROTATION_RANGE 1.0f +#define VERSION_COLOR_READING 1.1f + +#ifndef AUTO_ADD_SPRITE_FRAME_NAME_PREFIX +#define AUTO_ADD_SPRITE_FRAME_NAME_PREFIX 0 +#endif // !AUTO_ADD_SPRITE_FRAME_NAME_PREFIX + + +#define PHYSICS_TYPE 3 + +#if PHYSICS_TYPE == 1 +#define ENABLE_PHYSICS_BOX2D_DETECT 1 +#define ENABLE_PHYSICS_CHIPMUNK_DETECT 0 +#define ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX 0 +#elif PHYSICS_TYPE == 2 +#define ENABLE_PHYSICS_BOX2D_DETECT 0 +#define ENABLE_PHYSICS_CHIPMUNK_DETECT 1 +#define ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX 0 +#elif PHYSICS_TYPE == 3 +#define ENABLE_PHYSICS_BOX2D_DETECT 0 +#define ENABLE_PHYSICS_CHIPMUNK_DETECT 0 +#define ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX 1 +#else +#define ENABLE_PHYSICS_BOX2D_DETECT 0 +#define ENABLE_PHYSICS_CHIPMUNK_DETECT 0 +#define ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX 0 +#endif + + +#define CS_RETURN_IF(cond) if (cond) return +#define CS_RETURN_NULL_IF(cond) if (cond) return NULL; + +NS_CC_EXT_BEGIN + +const char *armatureVersion(); + +NS_CC_EXT_END + +#endif /*__CCARMATUREDEFINE_H__*/ diff --git a/include/extensions/CocoStudio/Armature/utils/CCDataReaderHelper.h b/include/extensions/CocoStudio/Armature/utils/CCDataReaderHelper.h new file mode 100644 index 0000000..163a677 --- /dev/null +++ b/include/extensions/CocoStudio/Armature/utils/CCDataReaderHelper.h @@ -0,0 +1,133 @@ +/**************************************************************************** +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. +****************************************************************************/ + +#ifndef __CCDATAREADERHELPER_H__ +#define __CCDATAREADERHELPER_H__ + +#include "CCArmatureDefine.h" +#include "../datas/CCDatas.h" +#include "../CCArmature.h" + +#include "../../Json/DictionaryHelper.h" +#include "../../Json/rapidjson/document.h" + +namespace tinyxml2 +{ + class XMLElement; +} + +NS_CC_EXT_BEGIN + +typedef struct _DataInfo DataInfo; +/** +* @js NA +* @lua NA +*/ +class CCDataReaderHelper : CCObject +{ +public: + static CCDataReaderHelper *sharedDataReaderHelper(); + + /** + * Scale the position data, used for multiresolution adapter + * It won't effect the data already read. + */ + static void setPositionReadScale(float scale); + static float getPositionReadScale(); + + static void purge(); + +public: + ~CCDataReaderHelper(); + + void addDataFromFile(const char *filePath); + void addDataFromFileAsync(const char *imagePath, const char *plistPath, const char *filePath, CCObject *target, SEL_SCHEDULE selector); + + void addDataAsyncCallBack(float dt); + + void removeConfigFile(const char *configFile); +public: + + /** + * Translate XML export from Dragon CCBone flash tool to datas, and save them. + * When you add a new xml, the data already saved will be keeped. + * + * @param xmlPath The cache of the xml + */ + static void addDataFromCache(const char *pFileContent, DataInfo *dataInfo = NULL); + + + + /** + * Decode CCArmature Datas from xml export from Dragon CCBone flash tool + */ + static CCArmatureData *decodeArmature(tinyxml2::XMLElement *armatureXML, DataInfo *dataInfo); + static CCBoneData *decodeBone(tinyxml2::XMLElement *boneXML, tinyxml2::XMLElement *parentXML, DataInfo *dataInfo); + static CCDisplayData *decodeBoneDisplay(tinyxml2::XMLElement *displayXML, DataInfo *dataInfo); + + + /** + * Decode CCArmatureAnimation Datas from xml export from Dragon CCBone flash tool + */ + static CCAnimationData *decodeAnimation(tinyxml2::XMLElement *animationXML, DataInfo *dataInfo); + static CCMovementData *decodeMovement(tinyxml2::XMLElement *movementXML, CCArmatureData *armatureData, DataInfo *dataInfo); + static CCMovementBoneData *decodeMovementBone(tinyxml2::XMLElement *movBoneXml, tinyxml2::XMLElement *parentXml, CCBoneData *boneData, DataInfo *dataInfo); + static CCFrameData *decodeFrame(tinyxml2::XMLElement *frameXML, tinyxml2::XMLElement *parentFrameXml, CCBoneData *boneData, DataInfo *dataInfo); + + + /** + * Decode Texture Datas from xml export from Dragon CCBone flash tool + */ + static CCTextureData *decodeTexture(tinyxml2::XMLElement *textureXML, DataInfo *dataInfo); + + /** + * Decode Contour Datas from xml export from Dragon CCBone flash tool + */ + static CCContourData *decodeContour(tinyxml2::XMLElement *contourXML, DataInfo *dataInfo); + +public: + static void addDataFromJsonCache(const char *fileContent, DataInfo *dataInfo = NULL); + + static CCArmatureData *decodeArmature(const rapidjson::Value &json, DataInfo *dataInfo); + static CCBoneData *decodeBone(const rapidjson::Value &json, DataInfo *dataInfo); + static CCDisplayData *decodeBoneDisplay(const rapidjson::Value &json, DataInfo *dataInfo); + static CCAnimationData *decodeAnimation(const rapidjson::Value &json, DataInfo *dataInfo); + static CCMovementData *decodeMovement(const rapidjson::Value &json, DataInfo *dataInfo); + + static CCMovementBoneData *decodeMovementBone(const rapidjson::Value &json, DataInfo *dataInfo); + static CCFrameData *decodeFrame(const rapidjson::Value &json, DataInfo *dataInfo); + + static CCTextureData *decodeTexture(const rapidjson::Value &json); + static CCContourData *decodeContour(const rapidjson::Value &json); + + static void decodeNode(CCBaseData *node, const rapidjson::Value &json, DataInfo *dataInfo); +private: + static std::vector s_arrConfigFileList; + + static CCDataReaderHelper *s_DataReaderHelper; +}; + +NS_CC_EXT_END + +#endif /*__CCDATAREADERHELPER_H__*/ diff --git a/include/extensions/CocoStudio/Armature/utils/CCSpriteFrameCacheHelper.h b/include/extensions/CocoStudio/Armature/utils/CCSpriteFrameCacheHelper.h new file mode 100644 index 0000000..29f598a --- /dev/null +++ b/include/extensions/CocoStudio/Armature/utils/CCSpriteFrameCacheHelper.h @@ -0,0 +1,60 @@ +/**************************************************************************** +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. +****************************************************************************/ +#ifndef __CCSPRITEFRAMECACHEHELPER_H__ +#define __CCSPRITEFRAMECACHEHELPER_H__ + +#include "CCArmatureDefine.h" +#include + +using namespace std; + +NS_CC_EXT_BEGIN +/** +* @js NA +* @lua NA +*/ +class CCSpriteFrameCacheHelper +{ +public: + static CCSpriteFrameCacheHelper *sharedSpriteFrameCacheHelper(); + + static void purge(); +public: + + /** + * @brief Add sprite frame to CCSpriteFrameCache, it will save display name and it's relative image name + */ + void addSpriteFrameFromFile(const char *plistPath, const char *imagePath); + + +private: + CCSpriteFrameCacheHelper(); + ~CCSpriteFrameCacheHelper(); + + static CCSpriteFrameCacheHelper *s_SpriteFrameCacheHelper; +}; + +NS_CC_EXT_END + +#endif /*__CCSPRITEFRAMECACHEHELPER_H__*/ diff --git a/include/extensions/CocoStudio/Armature/utils/CCTransformHelp.h b/include/extensions/CocoStudio/Armature/utils/CCTransformHelp.h new file mode 100644 index 0000000..8a3e0ef --- /dev/null +++ b/include/extensions/CocoStudio/Armature/utils/CCTransformHelp.h @@ -0,0 +1,64 @@ +/**************************************************************************** +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. +****************************************************************************/ + +#ifndef __CCTRANSFORMHELP_H__ +#define __CCTRANSFORMHELP_H__ + +#include "CCArmatureDefine.h" +#include "../datas/CCDatas.h" + +NS_CC_EXT_BEGIN + +/* + * use to calculate the matrix of node from parent node + * @js NA + * @lua NA + */ +class CCTransformHelp +{ +public: + CCTransformHelp(); + + static void transformFromParent(CCBaseData &node, const CCBaseData &parentNode); + static void transformToParent(CCBaseData &node, const CCBaseData &parentNode); + + static void transformFromParentWithoutScale(CCBaseData &node, const CCBaseData &parentNode); + static void transformToParentWithoutScale(CCBaseData &node, const CCBaseData &parentNode); + + static void nodeToMatrix(const CCBaseData &_node, CCAffineTransform &_matrix); + static void matrixToNode(const CCAffineTransform &_matrix, CCBaseData &_node); + + static void nodeConcat(CCBaseData &target, CCBaseData &source); + static void nodeSub(CCBaseData &target, CCBaseData &source); +public: + static CCAffineTransform helpMatrix1; + static CCAffineTransform helpMatrix2; + + static CCPoint helpPoint1; + static CCPoint helpPoint2; +}; + +NS_CC_EXT_END + +#endif /*__CCTRANSFORMHELP_H__*/ diff --git a/include/extensions/CocoStudio/Armature/utils/CCTweenFunction.h b/include/extensions/CocoStudio/Armature/utils/CCTweenFunction.h new file mode 100644 index 0000000..6a12553 --- /dev/null +++ b/include/extensions/CocoStudio/Armature/utils/CCTweenFunction.h @@ -0,0 +1,141 @@ +/**************************************************************************** +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. +****************************************************************************/ + +#ifndef __CCTWEENFUNCTION_H__ +#define __CCTWEENFUNCTION_H__ + + +#include "CCArmatureDefine.h" +#include + +NS_CC_EXT_BEGIN + +enum CCTweenType +{ + CUSTOM_EASING = -1, + + Linear, + + Sine_EaseIn, + Sine_EaseOut, + Sine_EaseInOut, + + + Quad_EaseIn, + Quad_EaseOut, + Quad_EaseInOut, + + Cubic_EaseIn, + Cubic_EaseOut, + Cubic_EaseInOut, + + Quart_EaseIn, + Quart_EaseOut, + Quart_EaseInOut, + + Quint_EaseIn, + Quint_EaseOut, + Quint_EaseInOut, + + Expo_EaseIn, + Expo_EaseOut, + Expo_EaseInOut, + + Circ_EaseIn, + Circ_EaseOut, + Circ_EaseInOut, + + Elastic_EaseIn, + Elastic_EaseOut, + Elastic_EaseInOut, + + Back_EaseIn, + Back_EaseOut, + Back_EaseInOut, + + Bounce_EaseIn, + Bounce_EaseOut, + Bounce_EaseInOut, + + TWEEN_EASING_MAX = 10000 +}; +/** +* @js NA +* @lua NA +*/ +class CCTweenFunction +{ +public: + + static float tweenTo(float time, CCTweenType type, float *easingParam); + + static float linear(float time); + + static float sineEaseIn(float time); + static float sineEaseOut(float time); + static float sineEaseInOut(float time); + + static float quadEaseIn(float time); + static float quadEaseOut(float time); + static float quadEaseInOut(float time); + + static float cubicEaseIn(float time); + static float cubicEaseOut(float time); + static float cubicEaseInOut(float time); + + static float quartEaseIn(float time); + static float quartEaseOut(float time); + static float quartEaseInOut(float time); + + static float quintEaseIn(float time); + static float quintEaseOut(float time); + static float quintEaseInOut(float time); + + static float expoEaseIn(float time); + static float expoEaseOut(float time); + static float expoEaseInOut(float time); + + static float circEaseIn(float time); + static float circEaseOut(float time); + static float circEaseInOut(float time); + + static float elasticEaseIn(float time, float *easingParam); + static float elasticEaseOut(float time, float *easingParam); + static float elasticEaseInOut(float time, float *easingParam); + + static float backEaseIn(float time); + static float backEaseOut(float time); + static float backEaseInOut(float time); + + static float bounceEaseIn(float time); + static float bounceEaseOut(float time); + static float bounceEaseInOut(float time); + + static float customEase(float time, float *easingParam); +}; + + +NS_CC_EXT_END + +#endif /*__CCTWEENFUNCTION_H__*/ diff --git a/include/extensions/CocoStudio/Armature/utils/CCUtilMath.h b/include/extensions/CocoStudio/Armature/utils/CCUtilMath.h new file mode 100644 index 0000000..68f41d6 --- /dev/null +++ b/include/extensions/CocoStudio/Armature/utils/CCUtilMath.h @@ -0,0 +1,55 @@ +/**************************************************************************** +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. +****************************************************************************/ + +#ifndef __CCUTILMATH_H__ +#define __CCUTILMATH_H__ + +#include "CCArmatureDefine.h" +#include + +NS_CC_EXT_BEGIN + +#define CC_DOUBLE_PI (M_PI*2) + +#define CC_HALF_PI (M_PI * 0.5f) + + +//! hit test function +bool isSpriteContainPoint(CCSprite *sprite, CCPoint point); +bool isSpriteContainPoint(CCSprite *sprite, CCPoint point, CCPoint &outPoint); + +#define CC_SPRITE_CONTAIN_POINT(sprite, point) isSpriteContainPoint((sprite), (point)) +#define CC_SPRITE_CONTAIN_POINT_WITH_RETURN(sprite, point, outPoint) isSpriteContainPoint((sprite), (point), outPoint) + + +//! motion curve function +CCPoint bezierTo(float t, CCPoint &point1, CCPoint &point2, CCPoint &point3); +CCPoint bezierTo(float t, CCPoint &point1, CCPoint &point2, CCPoint &point3, CCPoint &point4); + +CCPoint circleTo(float t, CCPoint ¢er, float radius, float fromRadian, float radianDif); + + +NS_CC_EXT_END + +#endif /*__CCUTILMATH_H__*/ diff --git a/include/extensions/CocoStudio/Components/CCComAttribute.h b/include/extensions/CocoStudio/Components/CCComAttribute.h new file mode 100644 index 0000000..babbba1 --- /dev/null +++ b/include/extensions/CocoStudio/Components/CCComAttribute.h @@ -0,0 +1,70 @@ +/**************************************************************************** +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. +****************************************************************************/ + +#ifndef __CC_EXTENTIONS_CCCOMATTRIBUTE_H__ +#define __CC_EXTENTIONS_CCCOMATTRIBUTE_H__ + +#include "CCComBase.h" + +NS_CC_EXT_BEGIN +/** + * @lua NA + */ +class CCComAttribute : public cocos2d::CCComponent +{ + DECLARE_CLASS_COMPONENT_INFO +protected: + /** + * @js ctor + */ + CCComAttribute(void); + /** + * @js NA + */ + virtual ~CCComAttribute(void); + +public: + virtual bool init(); + static CCComAttribute* create(void); + virtual bool serialize(void* r); + + void setInt(const char *key, int value); + void setFloat(const char *key, float value); + void setBool(const char *key, bool value); + void setCString(const char *key, const char *value); + + int getInt(const char *key, int def = 0) const; + float getFloat(const char *key, float def = 0.0f) const; + bool getBool(const char *key, bool def = false) const; + const char* getCString(const char *key, const char *def = NULL) const; + + bool parse(const std::string &jsonPath); +private: + cocos2d::CCDictionary *_dict; + rapidjson::Document _doc; +}; + +NS_CC_EXT_END + +#endif // __FUNDATION__CCCOMPONENT_H__ diff --git a/include/extensions/CocoStudio/Components/CCComAudio.h b/include/extensions/CocoStudio/Components/CCComAudio.h new file mode 100644 index 0000000..303a51a --- /dev/null +++ b/include/extensions/CocoStudio/Components/CCComAudio.h @@ -0,0 +1,90 @@ +/**************************************************************************** +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. +****************************************************************************/ + +#ifndef __CC_EXTENTIONS_CCCOMAUDIO_H__ +#define __CC_EXTENTIONS_CCCOMAUDIO_H__ + +#include "CCComBase.h" + +NS_CC_EXT_BEGIN +/** + * @lua NA + */ +class CCComAudio : public cocos2d::CCComponent +{ + DECLARE_CLASS_COMPONENT_INFO +protected: + CCComAudio(void); + virtual ~CCComAudio(void); + +public: + virtual bool init(); + virtual void onEnter(); + virtual void onExit(); + virtual bool isEnabled() const; + virtual void setEnabled(bool b); + virtual bool serialize(void* r); + + static CCComAudio* create(void); + +public: + void end(); + void preloadBackgroundMusic(const char* pszFilePath); + void playBackgroundMusic(const char* pszFilePath, bool bLoop); + void playBackgroundMusic(const char* pszFilePath); + void playBackgroundMusic(); + void stopBackgroundMusic(bool bReleaseData); + void stopBackgroundMusic(); + void pauseBackgroundMusic(); + void resumeBackgroundMusic(); + void rewindBackgroundMusic(); + bool willPlayBackgroundMusic(); + bool isBackgroundMusicPlaying(); + float getBackgroundMusicVolume(); + void setBackgroundMusicVolume(float volume); + float getEffectsVolume(); + void setEffectsVolume(float volume); + unsigned int playEffect(const char* pszFilePath, bool bLoop); + unsigned int playEffect(const char* pszFilePath); + unsigned int playEffect(); + void pauseEffect(unsigned int nSoundId); + void pauseAllEffects(); + void resumeEffect(unsigned int nSoundId); + void resumeAllEffects(); + void stopEffect(unsigned int nSoundId); + void stopAllEffects(); + void preloadEffect(const char* pszFilePath); + void unloadEffect(const char* pszFilePath); + void setFile(const char* pszFilePath); + const char* getFile(); + void setLoop(bool bLoop); + bool isLoop(); +private: + std::string m_strFilePath; + bool m_bLoop; +}; + +NS_CC_EXT_END + +#endif // __FUNDATION__CCCOMPONENT_H__ diff --git a/include/extensions/CocoStudio/Components/CCComBase.h b/include/extensions/CocoStudio/Components/CCComBase.h new file mode 100644 index 0000000..cc1b227 --- /dev/null +++ b/include/extensions/CocoStudio/Components/CCComBase.h @@ -0,0 +1,51 @@ +/**************************************************************************** +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. +****************************************************************************/ + +#ifndef __CC_EXTENTIONS_CCCOMBASE_H__ +#define __CC_EXTENTIONS_CCCOMBASE_H__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" +#include "../Trigger/ObjectFactory.h" +#include "../Json/DictionaryHelper.h" +#include + + +#define DECLARE_CLASS_COMPONENT_INFO \ + public: \ + static cocos2d::extension::ObjectFactory::TInfo Type; \ + static cocos2d::CCObject* createInstance(void); \ + +#define IMPLEMENT_CLASS_COMPONENT_INFO(className) \ + cocos2d::CCObject* className::createInstance(void) \ + { \ + return className::create(); \ + } \ + cocos2d::extension::ObjectFactory::TInfo className::Type(#className, &className::createInstance); \ + +#define CREATE_CLASS_COMPONENT_INFO(className) \ + cocos2d::extension::ObjectFactory::TInfo(#className, &className::createInstance) + + +#endif diff --git a/include/extensions/CocoStudio/Components/CCComController.h b/include/extensions/CocoStudio/Components/CCComController.h new file mode 100644 index 0000000..1b3c845 --- /dev/null +++ b/include/extensions/CocoStudio/Components/CCComController.h @@ -0,0 +1,59 @@ +/**************************************************************************** +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. +****************************************************************************/ + +#ifndef __CC_EXTENTIONS_CCCOMCONTROLLER_H__ +#define __CC_EXTENTIONS_CCCOMCONTROLLER_H__ + +#include "CCComBase.h" +#include "CCInputDelegate.h" + +NS_CC_EXT_BEGIN +/** + * @lua NA + */ +class CCComController : public cocos2d::CCComponent, public CCInputDelegate +{ + DECLARE_CLASS_COMPONENT_INFO +public: + /** + * @js ctor + */ + CCComController(void); + /** + * @js NA + */ + virtual ~CCComController(void); + virtual bool init(); + virtual void onEnter(); + virtual void onExit(); + virtual void update(float delta); + virtual bool isEnabled() const; + virtual void setEnabled(bool b); + + static CCComController* create(void); +}; + +NS_CC_EXT_END + +#endif // __FUNDATION__CCCOMPONENT_H__ diff --git a/include/extensions/CocoStudio/Components/CCComRender.h b/include/extensions/CocoStudio/Components/CCComRender.h new file mode 100644 index 0000000..b2fb6eb --- /dev/null +++ b/include/extensions/CocoStudio/Components/CCComRender.h @@ -0,0 +1,66 @@ +/**************************************************************************** +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. +****************************************************************************/ + +#ifndef __CC_EXTENTIONS_CCCOMRENDER_H__ +#define __CC_EXTENTIONS_CCCOMRENDER_H__ + +#include "CCComBase.h" + +NS_CC_EXT_BEGIN + +/** + * @lua NA + */ +class CCComRender : public cocos2d::CCComponent +{ + DECLARE_CLASS_COMPONENT_INFO +public: + /** + * @js ctor + */ + CCComRender(void); + CCComRender(cocos2d::CCNode *node, const char *comName); + /** + * @js NA + */ + virtual ~CCComRender(void); + +public: + virtual void onEnter(); + virtual void onExit(); + virtual bool serialize(void* r); + virtual cocos2d::CCNode* getNode(); + virtual void setNode(cocos2d::CCNode *pNode); + + static CCComRender* create(cocos2d::CCNode *pNode, const char *comName); + static CCComRender* create(void); +private: + bool readJson(const char *pszFileName, rapidjson::Document &doc); +private: + cocos2d::CCNode *m_pRender; +}; + +NS_CC_EXT_END + +#endif // __FUNDATION__CCCOMPONENT_H__ diff --git a/include/extensions/CocoStudio/Components/CCInputDelegate.h b/include/extensions/CocoStudio/Components/CCInputDelegate.h new file mode 100644 index 0000000..4be3b76 --- /dev/null +++ b/include/extensions/CocoStudio/Components/CCInputDelegate.h @@ -0,0 +1,83 @@ +/**************************************************************************** +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. +****************************************************************************/ + +#ifndef __CC_EXTENTIONS_CCINPUTDELEGATE_H__ +#define __CC_EXTENTIONS_CCINPUTDELEGATE_H__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" + +NS_CC_EXT_BEGIN +/** + * @lua NA + */ +class CCInputDelegate : public CCTouchDelegate, public CCAccelerometerDelegate, public CCKeypadDelegate +{ +protected: + CCInputDelegate(void); + virtual ~CCInputDelegate(void); + +public: + virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent); + virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent); + virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent); + virtual void ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent); + + virtual void ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent); + virtual void ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent); + virtual void ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent); + virtual void ccTouchesCancelled(CCSet *pTouches, CCEvent *pEvent); + /** + * @js NA + */ + virtual void didAccelerate(CCAcceleration* pAccelerationValue); +public: + virtual bool isTouchEnabled(); + virtual void setTouchEnabled(bool value); + + virtual bool isAccelerometerEnabled(); + virtual void setAccelerometerEnabled(bool value); + + virtual bool isKeypadEnabled(); + virtual void setKeypadEnabled(bool value); + + virtual void setTouchMode(ccTouchesMode mode); + virtual int getTouchMode(); + + virtual void setTouchPriority(int priority); + virtual int getTouchPriority(); + +protected: + bool m_bTouchEnabled; + bool m_bAccelerometerEnabled; + bool m_bKeypadEnabled; + +private: + int m_nTouchPriority; + ccTouchesMode m_eTouchMode; +}; + +NS_CC_EXT_END + +#endif // __FUNDATION__CCCOMPONENT_H__ diff --git a/include/extensions/CocoStudio/GUI/BaseClasses/UIWidget.h b/include/extensions/CocoStudio/GUI/BaseClasses/UIWidget.h new file mode 100644 index 0000000..b9559f7 --- /dev/null +++ b/include/extensions/CocoStudio/GUI/BaseClasses/UIWidget.h @@ -0,0 +1,730 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +#ifndef __UIWIDGET_H__ +#define __UIWIDGET_H__ + +#include "cocos2d.h" +#include "../Layouts/UILayoutDefine.h" +#include "../Layouts/UILayoutParameter.h" +#include "../System/GUIDefine.h" + +NS_CC_BEGIN + +namespace ui { + +typedef enum +{ + BRIGHT_NONE = -1, + BRIGHT_NORMAL, + BRIGHT_HIGHLIGHT +}BrightStyle; + +typedef enum +{ + WidgetTypeWidget, //control + WidgetTypeContainer //container +}WidgetType; + +typedef enum +{ + UI_TEX_TYPE_LOCAL, + UI_TEX_TYPE_PLIST +}TextureResType; + +typedef enum +{ + TOUCH_EVENT_BEGAN, + TOUCH_EVENT_MOVED, + TOUCH_EVENT_ENDED, + TOUCH_EVENT_CANCELED +}TouchEventType; + +typedef enum +{ + SIZE_ABSOLUTE, + SIZE_PERCENT +}SizeType; + +typedef enum +{ + POSITION_ABSOLUTE, + POSITION_PERCENT +}PositionType; + +typedef void (CCObject::*SEL_TouchEvent)(CCObject*,TouchEventType); +#define toucheventselector(_SELECTOR) (SEL_TouchEvent)(&_SELECTOR) +/** +* @js NA +* @lua NA +*/ +class Widget : public CCNode +{ +public: + /** + * Default constructor + */ + Widget(void); + + /** + * Default destructor + */ + virtual ~Widget(); + + /** + * Allocates and initializes a widget. + */ + static Widget* create(); + + /** + * Sets whether the widget is enabled + * + * Highest control of widget. + * The default value is true, a widget is default to enabled + * + * @param enabled true if the widget is enabled, widget may be touched and visible, false if the widget is disabled, widget cannot be touched and hidden. + */ + virtual void setEnabled(bool enabled); + + /** + * Determines if the widget is enabled + * + * @return true if the widget is enabled, false if the widget is disabled. + */ + bool isEnabled() const; + + /** + * Sets whether the widget is bright + * + * The default value is true, a widget is default to bright + * + * @param visible true if the widget is bright, false if the widget is dark. + */ + void setBright(bool bright); + + /** + * Determines if the widget is bright + * + * @return true if the widget is bright, false if the widget is dark. + */ + bool isBright() const; + + /** + * Sets whether the widget is touch enabled + * + * The default value is false, a widget is default to touch disabled + * + * @param visible true if the widget is touch enabled, false if the widget is touch disabled. + */ + virtual void setTouchEnabled(bool enabled); + + /** + * To set the bright style of widget. + * + * @see BrightStyle + * + * @param style BRIGHT_NORMAL the widget is normal state, BRIGHT_HIGHLIGHT the widget is height light state. + */ + void setBrightStyle(BrightStyle style); + + /** + * Determines if the widget is touch enabled + * + * @return true if the widget is touch enabled, false if the widget is touch disabled. + */ + bool isTouchEnabled() const; + + /** + * Determines if the widget is on focused + * + * @return true if the widget is on focused, false if the widget is not on focused. + */ + bool isFocused() const; + + /** + * Sets whether the widget is on focused + * + * The default value is false, a widget is default to not on focused + * + * @param fucosed true if the widget is on focused, false if the widget is not on focused. + */ + void setFocused(bool fucosed); + + /** + * Gets the left boundary position of this widget. + * + * @return The left boundary position of this widget. + */ + float getLeftInParent(); + + /** + * Gets the bottom boundary position of this widget. + * + * @return The bottom boundary position of this widget. + */ + float getBottomInParent(); + + /** + * Gets the right boundary position of this widget. + * + * @return The right boundary position of this widget. + */ + float getRightInParent(); + + /** + * Gets the top boundary position of this widget. + * + * @return The top boundary position of this widget. + */ + float getTopInParent(); + + /** + * Adds a child to the container with z-order as 0. + * + * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. + * + * @param child A child node + */ + virtual void addChild(CCNode * child); + /** + * Adds a child to the container with a z-order + * + * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. + * + * @param child A child node + * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) + */ + virtual void addChild(CCNode * child, int zOrder); + /** + * Adds a child to the container with z order and tag + * + * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. + * + * @param child A child node + * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) + * @param tag A interger to identify the node easily. Please refer to setTag(int) + */ + virtual void addChild(CCNode* child, int zOrder, int tag); + /** + * Gets a child from the container with its tag + * + * @param tag An identifier to find the child node. + * + * @return a Node object whose tag equals to the input parameter + */ + virtual CCNode * getChildByTag(int tag); + + virtual void sortAllChildren(); + /** + * Return an array of children + * + * Composing a "tree" structure is a very important feature of Node + * Here's a sample code of traversing children array: + @code + Node* node = NULL; + CCARRAY_FOREACH(parent->getChildren(), node) + { + node->setPosition(0,0); + } + @endcode + * This sample code traverses all children nodes, and set their position to (0,0) + * + * @return An array of children + */ + virtual CCArray* getChildren(); + + /** + * Get the amount of children. + * + * @return The amount of children. + */ + virtual unsigned int getChildrenCount() const; + + /** + * Removes this node itself from its parent node with a cleanup. + * If the node orphan, then nothing happens. + * @see `removeFromParentAndCleanup(bool)` + */ + virtual void removeFromParent(); + /** + * Removes this node itself from its parent node. + * If the node orphan, then nothing happens. + * @param cleanup true if all actions and callbacks on this node should be removed, false otherwise. + * @js removeFromParent + * @lua removeFromParent + */ + virtual void removeFromParentAndCleanup(bool cleanup); + + virtual void removeChild(CCNode* child); + + /** + * Removes a child from the container. It will also cleanup all running actions depending on the cleanup parameter. + * + * @param child The child node which will be removed. + * @param cleanup true if all running actions and callbacks on the child node will be cleanup, false otherwise. + */ + virtual void removeChild(CCNode* child, bool cleanup); + + /** + * Removes a child from the container by tag value. It will also cleanup all running actions depending on the cleanup parameter + * + * @param tag An interger number that identifies a child node + * @param cleanup true if all running actions and callbacks on the child node will be cleanup, false otherwise. + */ + virtual void removeChildByTag(int tag, bool cleanup); + /** + * Removes all children from the container with a cleanup. + * + * @see `removeAllChildrenWithCleanup(bool)` + */ + virtual void removeAllChildren(); + /** + * Removes all children from the container, and do a cleanup to all running actions depending on the cleanup parameter. + * + * @param cleanup true if all running actions on all children nodes should be cleanup, false oterwise. + * @js removeAllChildren + * @lua removeAllChildren + */ + virtual void removeAllChildrenWithCleanup(bool cleanup); + + /** + * Gets a child from the container with its name + * + * @param name An key to find the child widget. + * + * @return a Widget object whose name equals to the input parameter + */ + virtual Widget* getChildByName(const char* name); + + virtual void addNode(CCNode* node); + + virtual void addNode(CCNode * node, int zOrder); + + virtual void addNode(CCNode* node, int zOrder, int tag); + + virtual CCNode * getNodeByTag(int tag); + + virtual CCArray* getNodes(); + + virtual void removeNode(CCNode* node); + + virtual void removeNodeByTag(int tag); + + virtual void removeAllNodes(); + + virtual void visit(); + + /** + * Sets the touch event target/selector of the menu item + */ + void addTouchEventListener(CCObject* target,SEL_TouchEvent selector); + + + //cocos2d property + + /** + * Changes the position (x,y) of the widget in OpenGL coordinates + * + * Usually we use p(x,y) to compose Point object. + * The original point (0,0) is at the left-bottom corner of screen. + * + * @param position The position (x,y) of the widget in OpenGL coordinates + */ + void setPosition(const CCPoint &pos); + + /** + * Changes the position (x,y) of the widget in OpenGL coordinates + * + * Usually we use p(x,y) to compose Point object. + * The original point (0,0) is at the left-bottom corner of screen. + * + * @param percent The percent (x,y) of the widget in OpenGL coordinates + */ + void setPositionPercent(const CCPoint &percent); + + /** + * Gets the percent (x,y) of the widget in OpenGL coordinates + * + * @see setPosition(const Point&) + * + * @return The percent (x,y) of the widget in OpenGL coordinates + */ + const CCPoint& getPositionPercent(); + + /** + * Changes the position type of the widget + * + * @see PositionType + * + * @param type the position type of widget + */ + void setPositionType(PositionType type); + + /** + * Gets the position type of the widget + * + * @see PositionType + * + * @return type the position type of widget + */ + PositionType getPositionType() const; + + /** + * Sets whether the widget should be flipped horizontally or not. + * + * @param bFlipX true if the widget should be flipped horizaontally, false otherwise. + */ + virtual void setFlipX(bool flipX); + + /** + * Returns the flag which indicates whether the widget is flipped horizontally or not. + * + * It only flips the texture of the widget, and not the texture of the widget's children. + * Also, flipping the texture doesn't alter the anchorPoint. + * If you want to flip the anchorPoint too, and/or to flip the children too use: + * widget->setScaleX(sprite->getScaleX() * -1); + * + * @return true if the widget is flipped horizaontally, false otherwise. + */ + virtual bool isFlipX(){return _flippedX;}; + + /** + * Sets whether the widget should be flipped vertically or not. + * + * @param bFlipY true if the widget should be flipped vertically, flase otherwise. + */ + virtual void setFlipY(bool flipY); + + /** + * Return the flag which indicates whether the widget is flipped vertically or not. + * + * It only flips the texture of the widget, and not the texture of the widget's children. + * Also, flipping the texture doesn't alter the anchorPoint. + * If you want to flip the anchorPoint too, and/or to flip the children too use: + * widget->setScaleY(widget->getScaleY() * -1); + * + * @return true if the widget is flipped vertically, flase otherwise. + */ + virtual bool isFlipY(){return _flippedY;}; + + virtual void setColor(const ccColor3B& color); + + virtual void setOpacity(GLubyte opacity); + + const ccColor3B& getColor(){return _color;}; + + GLubyte getOpacity(){return _opacity;}; + + /** + * A call back function when widget lost of focus. + */ + void didNotSelectSelf(); + + /* + * Checks a point if in parent's area. + * + * @param point + * + * @return true if the point is in parent's area, flase otherwise. + */ + bool clippingParentAreaContainPoint(const CCPoint &pt); + + /* + * Sends the touch event to widget's parent + */ + virtual void checkChildInfo(int handleState,Widget* sender,const CCPoint &touchPoint); + + /* + * Gets the touch began point of widget when widget is selected. + * + * @return the touch began point. + */ + const CCPoint& getTouchStartPos(); + + /* + * Gets the touch move point of widget when widget is selected. + * + * @return the touch move point. + */ + const CCPoint& getTouchMovePos(); + + /* + * Gets the touch end point of widget when widget is selected. + * + * @return the touch end point. + */ + const CCPoint& getTouchEndPos(); + + /** + * Changes the name that is used to identify the widget easily. + * + * @param A const char* that indentifies the widget. + */ + void setName(const char* name); + + /** + * Returns a name that is used to identify the widget easily. + * + * You can set tags to widget then identify them easily. + * + * @return A const char* that identifies the widget. + */ + const char* getName() const; + + /** + * Returns a type that is widget's type + * + * @see WidgetType + * + * @return A WidgetType + */ + WidgetType getWidgetType() const; + + /** + * Changes the size that is widget's size + * + * @param size that is widget's size + */ + virtual void setSize(const CCSize &size); + + /** + * Changes the percent that is widget's percent size + * + * @param percent that is widget's percent size + */ + virtual void setSizePercent(const CCPoint &percent); + + /** + * Changes the size type of widget. + * + * @see SizeType + * + * @param type that is widget's size type + */ + void setSizeType(SizeType type); + + /** + * Gets the size type of widget. + * + * @see SizeType + * + * @param type that is widget's size type + */ + SizeType getSizeType() const; + + /** + * Returns size of widget + * + * @return size + */ + const CCSize& getSize() const; + + virtual const CCSize& getLayoutSize() {return _size;}; + + /** + * Returns size percent of widget + * + * @return size percent + */ + const CCPoint& getSizePercent() const; + + const CCSize& getCustomSize() const; + + /** + * Checks a point if is in widget's space + * + * @param point + * + * @return true if the point is in widget's space, flase otherwise. + */ + virtual bool hitTest(const CCPoint &pt); + + virtual bool onTouchBegan(CCTouch *touch, CCEvent *unused_event); + virtual void onTouchMoved(CCTouch *touch, CCEvent *unused_event); + virtual void onTouchEnded(CCTouch *touch, CCEvent *unused_event); + virtual void onTouchCancelled(CCTouch *touch, CCEvent *unused_event); + + /** + * Sets a LayoutParameter to widget. + * + * @see LayoutParameter + * + * @param LayoutParameter pointer + * + * @param type Relative or Linear + */ + void setLayoutParameter(LayoutParameter* parameter); + + /** + * Gets LayoutParameter of widget. + * + * @see LayoutParameter + * + * @param type Relative or Linear + * + * @return LayoutParameter + */ + LayoutParameter* getLayoutParameter(LayoutParameterType type); + + /** + * Ignore the widget size + * + * @param ignore, true that widget will ignore it's size, use texture size, false otherwise. Default value is true. + */ + virtual void ignoreContentAdaptWithSize(bool ignore); + + /** + * Gets the widget if is ignore it's size. + * + * @param ignore, true that widget will ignore it's size, use texture size, false otherwise. Default value is true. + */ + bool isIgnoreContentAdaptWithSize() const; + + /** + * Gets world position of widget. + * + * @return world position of widget. + */ + CCPoint getWorldPosition(); + + /** + * Gets the Virtual Renderer of widget. + * + * For example, a button's Virtual Renderer is it's texture renderer. + * + * @return Node pointer. + */ + virtual CCNode* getVirtualRenderer(); + + /** + * Gets the content size of widget. + * + * Content size is widget's texture size. + */ + virtual const CCSize& getContentSize() const; + + /** + * Returns the "class name" of widget. + */ + virtual std::string getDescription() const; + + Widget* clone(); + + virtual void onEnter(); + virtual void onExit(); + + void updateSizeAndPosition(); + + void updateSizeAndPosition(const CCSize& parentSize); + + /*temp action*/ + void setActionTag(int tag); + int getActionTag(); +protected: + //call back function called when size changed. + virtual void onSizeChanged(); + + //initializes state of widget. + virtual bool init(); + + //initializes renderer of widget. + virtual void initRenderer(){}; + + //call back function called widget's state changed to normal. + virtual void onPressStateChangedToNormal(); + + //call back function called widget's state changed to selected. + virtual void onPressStateChangedToPressed(); + + //call back function called widget's state changed to dark. + virtual void onPressStateChangedToDisabled(); + void pushDownEvent(); + void moveEvent(); + void releaseUpEvent(); + void cancelUpEvent(); + void updateAnchorPoint(); + virtual void updateTextureColor(){}; + virtual void updateTextureOpacity(){}; + virtual void updateTextureRGBA(){}; + virtual void updateFlippedX(){}; + virtual void updateFlippedY(){}; + void updateColorToRenderer(CCNode* renderer); + void updateOpacityToRenderer(CCNode* renderer); + void updateRGBAToRenderer(CCNode* renderer); + void copyProperties(Widget* model); + virtual Widget* createCloneInstance(); + virtual void copySpecialProperties(Widget* model); + virtual void copyClonedWidgetChildren(Widget* model); + Widget* getWidgetParent(); +protected: + bool _enabled; ///< Highest control of widget + bool _bright; ///< is this widget bright + bool _touchEnabled; ///< is this widget touch endabled + bool _touchPassedEnabled; ///< is the touch event should be passed + bool _focus; ///< is the widget on focus + BrightStyle _brightStyle; ///< bright style + CCPoint _touchStartPos; ///< touch began point + CCPoint _touchMovePos; ///< touch moved point + CCPoint _touchEndPos; ///< touch ended point + + CCObject* _touchEventListener; + SEL_TouchEvent _touchEventSelector; + + + + std::string _name; + WidgetType _widgetType; + int _actionTag; + CCSize _size; + CCSize _customSize; + bool _ignoreSize; + bool _affectByClipping; + SizeType _sizeType; + CCPoint _sizePercent; + PositionType _positionType; + CCPoint _positionPercent; + bool _reorderWidgetChildDirty; + bool _hitted; + CCArray* _widgetChildren; + CCDictionary* _layoutParameterDictionary; + + CCArray* _nodes; + + ccColor3B _color; + GLubyte _opacity; + + bool _flippedX; + bool _flippedY; + + friend class TouchGroup; +}; +} + +namespace gui = ui; + +NS_CC_END + + + +#endif /* defined(__Widget__) */ diff --git a/include/extensions/CocoStudio/GUI/Layouts/UILayout.h b/include/extensions/CocoStudio/GUI/Layouts/UILayout.h new file mode 100644 index 0000000..33b7650 --- /dev/null +++ b/include/extensions/CocoStudio/GUI/Layouts/UILayout.h @@ -0,0 +1,316 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +#ifndef __LAYOUT_H__ +#define __LAYOUT_H__ + +#include "../BaseClasses/UIWidget.h" + +NS_CC_BEGIN + +namespace ui { + +typedef enum +{ + LAYOUT_COLOR_NONE, + LAYOUT_COLOR_SOLID, + LAYOUT_COLOR_GRADIENT +}LayoutBackGroundColorType; + +typedef enum +{ + LAYOUT_ABSOLUTE, + LAYOUT_LINEAR_VERTICAL, + LAYOUT_LINEAR_HORIZONTAL, + LAYOUT_RELATIVE +}LayoutType; + +typedef enum { + LAYOUT_CLIPPING_STENCIL, + LAYOUT_CLIPPING_SCISSOR +}LayoutClippingType; + +/** + * @js NA + * @lua NA + */ +class Layout : public Widget +{ + + DECLARE_CLASS_GUI_INFO + +public: + /** + * Default constructor + */ + Layout(); + + /** + * Default destructor + */ + virtual ~Layout(); + + /** + * Allocates and initializes a layout. + */ + static Layout* create(); + + //background + /** + * Sets a background image for layout + * + * @param fileName image file path. + * + * @param texType @see TextureResType. UI_TEX_TYPE_LOCAL means local file, UI_TEX_TYPE_PLIST means sprite frame. + */ + void setBackGroundImage(const char* fileName,TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Sets a background image capinsets for layout, if the background image is a scale9 render. + * + * @param capinsets of background image. + * + */ + void setBackGroundImageCapInsets(const CCRect& capInsets); + + const CCRect& getBackGroundImageCapInsets(); + + /** + * Sets Color Type for layout. + * + * @param type @see LayoutBackGroundColorType. + */ + void setBackGroundColorType(LayoutBackGroundColorType type); + + LayoutBackGroundColorType getBackGroundColorType(); + + /** + * Sets background iamge use scale9 renderer. + * + * @param enabled true that use scale9 renderer, false otherwise. + */ + void setBackGroundImageScale9Enabled(bool enabled); + + bool isBackGroundImageScale9Enabled(); + + /** + * Sets background color for layout, if color type is LAYOUT_COLOR_SOLID + * + * @param color + */ + void setBackGroundColor(const ccColor3B &color); + + const ccColor3B& getBackGroundColor(); + + /** + * Sets background color for layout, if color type is LAYOUT_COLOR_GRADIENT + * + * @param start color + * + * @param end color + */ + void setBackGroundColor(const ccColor3B &startColor, const ccColor3B &endColor); + + const ccColor3B& getBackGroundStartColor(); + + const ccColor3B& getBackGroundEndColor(); + + /** + * Sets background opacity layout. + * + * @param opacity + */ + void setBackGroundColorOpacity(GLubyte opacity); + + GLubyte getBackGroundColorOpacity(); + + /** + * Sets background color vector for layout, if color type is LAYOUT_COLOR_GRADIENT + * + * @param vector + */ + void setBackGroundColorVector(const CCPoint &vector); + + const CCPoint& getBackGroundColorVector(); + + void setBackGroundImageColor(const ccColor3B& color); + + void setBackGroundImageOpacity(GLubyte opacity); + + const ccColor3B& getBackGroundImageColor(); + + GLubyte getBackGroundImageOpacity(); + + /** + * Remove the background image of layout. + */ + void removeBackGroundImage(); + + /** + * Gets background image texture size. + * + * @return background image texture size. + */ + const CCSize& getBackGroundImageTextureSize() const; + + /** + * Changes if layout can clip it's content and child. + * + * If you really need this, please enable it. But it would reduce the rendering efficiency. + * + * @param clipping enabled. + */ + virtual void setClippingEnabled(bool enabled); + + void setClippingType(LayoutClippingType type); + + LayoutClippingType getClippingType(); + + /** + * Gets if layout is clipping enabled. + * + * @return if layout is clipping enabled. + */ + virtual bool isClippingEnabled(); + + /** + * Returns the "class name" of widget. + */ + virtual std::string getDescription() const; + + /** + * Sets LayoutType. + * + * @see LayoutType + * + * @param LayoutType + */ + virtual void setLayoutType(LayoutType type); + + /** + * Gets LayoutType. + * + * @see LayoutType + * + * @return LayoutType + */ + virtual LayoutType getLayoutType() const; + + virtual void addChild(CCNode * child); + /** + * Adds a child to the container with a z-order + * + * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. + * + * @param child A child node + * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) + */ + virtual void addChild(CCNode * child, int zOrder); + /** + * Adds a child to the container with z order and tag + * + * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. + * + * @param child A child node + * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) + * @param tag A interger to identify the node easily. Please refer to setTag(int) + */ + virtual void addChild(CCNode* child, int zOrder, int tag); + + virtual void removeChild(CCNode* child); + + virtual void removeChild(CCNode* widget, bool cleanup); + + virtual void removeAllChildren(); + + virtual void removeAllChildrenWithCleanup(bool cleanup); + + virtual void visit(); + + virtual void sortAllChildren(); + + void requestDoLayout(); + + virtual void onEnter(); + virtual void onExit(); + + virtual bool hitTest(const CCPoint &pt); +protected: + //override "init" method of widget. + virtual bool init(); + + //override "onSizeChanged" method of widget. + virtual void onSizeChanged(); + + //init background image renderer. + void addBackGroundImage(); + + void supplyTheLayoutParameterLackToChild(Widget* child); + virtual Widget* createCloneInstance(); + virtual void copySpecialProperties(Widget* model); + virtual void copyClonedWidgetChildren(Widget* model); + + void stencilClippingVisit(); + void scissorClippingVisit(); + + void setStencilClippingSize(const CCSize& size); + const CCRect& getClippingRect(); + virtual void doLayout(); + void updateBackGroundImageColor(); + void updateBackGroundImageOpacity(); + void updateBackGroundImageRGBA(); +protected: + bool _clippingEnabled; + + //background + bool _backGroundScale9Enabled; + CCNode* _backGroundImage; + std::string _backGroundImageFileName; + CCRect _backGroundImageCapInsets; + LayoutBackGroundColorType _colorType; + TextureResType _bgImageTexType; + CCLayerColor* _colorRender; + CCLayerGradient* _gradientRender; + ccColor3B _cColor; + ccColor3B _gStartColor; + ccColor3B _gEndColor; + CCPoint _alongVector; + GLubyte _cOpacity; + CCSize _backGroundImageTextureSize; + LayoutType _layoutType; + LayoutClippingType _clippingType; + CCDrawNode* _clippingStencil; + bool _handleScissor; + bool _scissorRectDirty; + CCRect _clippingRect; + Layout* _clippingParent; + bool _doLayoutDirty; + bool _clippingRectDirty; + ccColor3B _backGroundImageColor; + GLubyte _backGroundImageOpacity; +}; + +} +NS_CC_END +#endif /* defined(__Layout__) */ diff --git a/include/extensions/CocoStudio/GUI/Layouts/UILayoutDefine.h b/include/extensions/CocoStudio/GUI/Layouts/UILayoutDefine.h new file mode 100644 index 0000000..772e94b --- /dev/null +++ b/include/extensions/CocoStudio/GUI/Layouts/UILayoutDefine.h @@ -0,0 +1,96 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +#ifndef __UILAYOUTDEFINE_H__ +#define __UILAYOUTDEFINE_H__ + +#include "cocos2d.h" + +NS_CC_BEGIN + +namespace ui { +/** +* @js NA +* @lua NA +*/ +class Margin +{ +public: + float left; + float top; + float right; + float bottom; + +public: + Margin(); + Margin(float l, float t, float r, float b); + Margin(const Margin& other); + Margin& operator= (const Margin& other); + void setMargin(float l, float t, float r, float b); + bool equals(const Margin& target) const; +}; + +const Margin MarginZero = Margin(); + +typedef enum +{ + LINEAR_GRAVITY_NONE, + LINEAR_GRAVITY_LEFT, + LINEAR_GRAVITY_TOP, + LINEAR_GRAVITY_RIGHT, + LINEAR_GRAVITY_BOTTOM, + LINEAR_GRAVITY_CENTER_VERTICAL, + LINEAR_GRAVITY_CENTER_HORIZONTAL +}LinearGravity; + +typedef enum +{ + RELATIVE_ALIGN_NONE, + RELATIVE_ALIGN_PARENT_TOP_LEFT, + RELATIVE_ALIGN_PARENT_TOP_CENTER_HORIZONTAL, + RELATIVE_ALIGN_PARENT_TOP_RIGHT, + RELATIVE_ALIGN_PARENT_LEFT_CENTER_VERTICAL, + RELATIVE_CENTER_IN_PARENT, + RELATIVE_ALIGN_PARENT_RIGHT_CENTER_VERTICAL, + RELATIVE_ALIGN_PARENT_LEFT_BOTTOM, + RELATIVE_ALIGN_PARENT_BOTTOM_CENTER_HORIZONTAL, + RELATIVE_ALIGN_PARENT_RIGHT_BOTTOM, + + RELATIVE_LOCATION_ABOVE_LEFTALIGN, + RELATIVE_LOCATION_ABOVE_CENTER, + RELATIVE_LOCATION_ABOVE_RIGHTALIGN, + RELATIVE_LOCATION_LEFT_OF_TOPALIGN, + RELATIVE_LOCATION_LEFT_OF_CENTER, + RELATIVE_LOCATION_LEFT_OF_BOTTOMALIGN, + RELATIVE_LOCATION_RIGHT_OF_TOPALIGN, + RELATIVE_LOCATION_RIGHT_OF_CENTER, + RELATIVE_LOCATION_RIGHT_OF_BOTTOMALIGN, + RELATIVE_LOCATION_BELOW_LEFTALIGN, + RELATIVE_LOCATION_BELOW_CENTER, + RELATIVE_LOCATION_BELOW_RIGHTALIGN +}RelativeAlign; + +} +NS_CC_END +#endif /* defined(__UILayoutDefine__) */ diff --git a/include/extensions/CocoStudio/GUI/Layouts/UILayoutParameter.h b/include/extensions/CocoStudio/GUI/Layouts/UILayoutParameter.h new file mode 100644 index 0000000..552a0b0 --- /dev/null +++ b/include/extensions/CocoStudio/GUI/Layouts/UILayoutParameter.h @@ -0,0 +1,226 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +#ifndef __LAYOUTPARMETER_H__ +#define __LAYOUTPARMETER_H__ + +#include "UILayoutDefine.h" + +NS_CC_BEGIN + +namespace ui { + +typedef enum +{ + LAYOUT_PARAMETER_NONE, + LAYOUT_PARAMETER_LINEAR, + LAYOUT_PARAMETER_RELATIVE +}LayoutParameterType; +/** +* @js NA +* @lua NA +*/ +class LayoutParameter : public CCObject +{ +public: + /** + * Default constructor + */ + LayoutParameter() : _margin(Margin()){_layoutParameterType = LAYOUT_PARAMETER_NONE;}; + + /** + * Default destructor + */ + virtual ~LayoutParameter(){}; + + /** + * Allocates and initializes. + * @return A initialized LayoutParameter which is marked as "autorelease". + */ + static LayoutParameter* create(); + + /** + * Sets Margin parameter for LayoutParameter. + * + * @see Margin + * + * @param margin + */ + void setMargin(const Margin& margin); + + /** + * Gets Margin parameter of LayoutParameter. + * + * @see Margin + * + * @return const Margin& + */ + const Margin& getMargin() const; + + /** + * Gets LayoutParameterType of LayoutParameter. + * + * @see LayoutParameterType + * + * @return LayoutParameterType + */ + LayoutParameterType getLayoutType() const; + + LayoutParameter* clone(); + virtual LayoutParameter* createCloneInstance(); + virtual void copyProperties(LayoutParameter* model); +protected: + Margin _margin; + LayoutParameterType _layoutParameterType; +}; +/** +* @js NA +* @lua NA +*/ +class LinearLayoutParameter : public LayoutParameter +{ +public: + /** + * Default constructor + */ + LinearLayoutParameter() : _linearGravity(LINEAR_GRAVITY_NONE){_layoutParameterType = LAYOUT_PARAMETER_LINEAR;}; + + /** + * Default destructor + */ + virtual ~LinearLayoutParameter(){}; + + /** + * Allocates and initializes. + * @return A initialized LayoutParameter which is marked as "autorelease". + */ + static LinearLayoutParameter* create(); + + /** + * Sets LinearGravity parameter for LayoutParameter. + * + * @see LinearGravity + * + * @param LinearGravity + */ + void setGravity(LinearGravity gravity); + + /** + * Gets LinearGravity parameter for LayoutParameter. + * + * @see LinearGravity + * + * @return LinearGravity + */ + LinearGravity getGravity() const; + virtual LayoutParameter* createCloneInstance(); + virtual void copyProperties(LayoutParameter* model); +protected: + LinearGravity _linearGravity; +}; +/** +* @js NA +* @lua NA +*/ + +class RelativeLayoutParameter : public LayoutParameter +{ +public: + /** + * Default constructor + */ + RelativeLayoutParameter() : _relativeAlign(RELATIVE_ALIGN_NONE),_relativeWidgetName(""),_relativeLayoutName(""),_put(false){_layoutParameterType = LAYOUT_PARAMETER_RELATIVE;}; + + /** + * Default destructor + */ + virtual ~RelativeLayoutParameter(){}; + + /** + * Allocates and initializes. + * @return A initialized LayoutParameter which is marked as "autorelease". + */ + static RelativeLayoutParameter* create(); + + /** + * Sets RelativeAlign parameter for LayoutParameter. + * + * @see RelativeAlign + * + * @param RelativeAlign + */ + void setAlign(RelativeAlign align); + + /** + * Gets RelativeAlign parameter for LayoutParameter. + * + * @see RelativeAlign + * + * @return RelativeAlign + */ + RelativeAlign getAlign() const; + + /** + * Sets a key for LayoutParameter. Witch widget named this is relative to. + * + * @param name + */ + void setRelativeToWidgetName(const char* name); + + /** + * Gets the key of LayoutParameter. Witch widget named this is relative to. + * + * @return name + */ + const char* getRelativeToWidgetName() const; + + /** + * Sets a name in Relative Layout for LayoutParameter. + * + * @param name + */ + void setRelativeName(const char* name); + + /** + * Gets a name in Relative Layout of LayoutParameter. + * + * @return name + */ + const char* getRelativeName() const; + + virtual LayoutParameter* createCloneInstance(); + virtual void copyProperties(LayoutParameter* model); +protected: + RelativeAlign _relativeAlign; + std::string _relativeWidgetName; + std::string _relativeLayoutName; + bool _put; + friend class Layout; +}; + +} + +NS_CC_END + +#endif /* defined(__LayoutParameter__) */ diff --git a/include/extensions/CocoStudio/GUI/System/CocosGUI.h b/include/extensions/CocoStudio/GUI/System/CocosGUI.h new file mode 100644 index 0000000..6d71d19 --- /dev/null +++ b/include/extensions/CocoStudio/GUI/System/CocosGUI.h @@ -0,0 +1,55 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +#ifndef __COCOSGUI_H__ +#define __COCOSGUI_H__ + + +#include "../BaseClasses/UIWidget.h" +#include "../Layouts/UILayout.h" +#include "../UIWidgets/UIButton.h" +#include "../UIWidgets/UICheckBox.h" +#include "../UIWidgets/UIImageView.h" +#include "../UIWidgets/UILabel.h" +#include "../UIWidgets/UILabelAtlas.h" +#include "../UIWidgets/UILoadingBar.h" +#include "../UIWidgets/ScrollWidget/UIScrollView.h" +#include "../UIWidgets/UISlider.h" +#include "../UIWidgets/UITextField.h" +#include "../UIWidgets/ScrollWidget/UIListView.h" +#include "../UIWidgets/UILabelBMFont.h" +#include "../UIWidgets/ScrollWidget/UIPageView.h" +#include "UIHelper.h" +#include "../../Reader/GUIReader.h" +#include "UITouchGroup.h" +#include "../UIWidgets/Compatible/CompatibleClasses.h" +#include "../UIWidgets/UIRichText.h" + +//NS_CC_EXT_BEGIN + +const char* CocosGUIVersion(); + +//NS_CC_EXT_END + +#endif /* defined(__CocosGUITest__Cocos__) */ diff --git a/include/extensions/CocoStudio/GUI/System/GUIDefine.h b/include/extensions/CocoStudio/GUI/System/GUIDefine.h new file mode 100644 index 0000000..c2bbbe5 --- /dev/null +++ b/include/extensions/CocoStudio/GUI/System/GUIDefine.h @@ -0,0 +1,75 @@ +/**************************************************************************** + Copyright (c) 2014 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __TestCpp__GUIDefine__ +#define __TestCpp__GUIDefine__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" +#include +#include "../../Trigger/ObjectFactory.h" + +#ifdef __apple__ +#pragma mark - +#pragma mark Widget macro +#pragma mark - +#endif + +#define DECLARE_CLASS_GUI_INFO \ + public: \ + static cocos2d::extension::ObjectFactory::TInfo Type; \ + static cocos2d::CCObject* createInstance(void); \ + +#define IMPLEMENT_CLASS_GUI_INFO(className) \ + cocos2d::CCObject* className::createInstance(void) \ + { \ + return className::create(); \ + } \ + cocos2d::extension::ObjectFactory::TInfo className::Type(#className, &className::createInstance); \ + +#define CREATE_CLASS_GUI_INFO(className) \ + cocos2d::extension::ObjectFactory::TInfo(#className, &className::createInstance) + +#ifdef __apple__ +#pragma mark - +#pragma mark Reader macro +#pragma mark - +#endif + +#define DECLARE_CLASS_WIDGET_READER_INFO \ +public: \ + static cocos2d::extension::ObjectFactory::TInfo Type; \ + static cocos2d::CCObject* createInstance(void); \ + +#define IMPLEMENT_CLASS_WIDGET_READER_INFO(className) \ + cocos2d::CCObject* className::createInstance(void) \ + { \ + return className::getInstance(); \ + } \ + cocos2d::extension::ObjectFactory::TInfo className::Type(#className, &className::createInstance); \ + +#define CREATE_CLASS_WIDGET_READER_INFO(className) \ + cocos2d::extension::ObjectFactory::TInfo(#className, &className::createInstance) + +#endif /* defined(__TestCpp__GUIDefine__) */ diff --git a/include/extensions/CocoStudio/GUI/System/UIHelper.h b/include/extensions/CocoStudio/GUI/System/UIHelper.h new file mode 100644 index 0000000..d050e43 --- /dev/null +++ b/include/extensions/CocoStudio/GUI/System/UIHelper.h @@ -0,0 +1,81 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +#ifndef __UIHELPER_H__ +#define __UIHELPER_H__ + +NS_CC_BEGIN + +namespace ui { + +/** +* @js NA +* @lua NA +*/ +class UIHelper +{ +public: + /** + * Finds a widget whose tag equals to param tag from root widget. + * + * @param root widget which will be seeked. + * + * @tag tag value. + * + * @return finded result. + */ + static Widget* seekWidgetByTag(Widget* root, int tag); + + /** + * Finds a widget whose name equals to param name from root widget. + * + * @param root widget which will be seeked. + * + * @name name value. + * + * @return finded result. + */ + static Widget* seekWidgetByName(Widget* root, const char* name); + + /** + * Finds a widget whose name equals to param name from root widget. + * + * RelativeLayout will call this method to find the widget witch is needed. + * + * @param root widget which will be seeked. + * + * @name name value. + * + * @return finded result. + */ + static Widget* seekWidgetByRelativeName(Widget* root, const char* name); + + /*temp action*/ + static Widget* seekActionWidgetByActionTag(Widget* root, int tag); +}; +} + +NS_CC_END + +#endif /* defined(__CocoGUI__UISystem__) */ diff --git a/include/extensions/CocoStudio/GUI/System/UITouchGroup.h b/include/extensions/CocoStudio/GUI/System/UITouchGroup.h new file mode 100644 index 0000000..62b0ca1 --- /dev/null +++ b/include/extensions/CocoStudio/GUI/System/UITouchGroup.h @@ -0,0 +1,132 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + + +#ifndef __UILAYER_H__ +#define __UILAYER_H__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" +#include "../BaseClasses/UIWidget.h" + +NS_CC_BEGIN + +namespace ui { + +/** + * @lua NA + */ +class TouchGroup : public CCLayer +{ + +public: + /** + * Default constructor + * @js ctor + */ + TouchGroup(); + + /** + * Default destructor + * @js NA + */ + virtual ~TouchGroup(); + + /** + * Allocates and initializes a widget. + */ + static TouchGroup *create(void); + + //initializes state of uilayer. + virtual bool init(); + + virtual void onEnter(); + virtual void onExit(); + virtual void onEnterTransitionDidFinish(); + + virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent); + virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent); + virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent); + virtual void ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent); + + /** + * Add a widget to UILayer, for drawing. + * + * @param widget. + */ + void addWidget(Widget* widget); + + /** + * Remove a widget from UILayer. + * + * @param widget. + * + * @param cleanup true if all running actions on all children widgets should be cleanup, false otherwise. + */ + void removeWidget(Widget* widget); + + /** + * Finds a widget whose tag is equal tag param from widget tree. + * + * @param tag. + */ + Widget* getWidgetByTag(int tag); + + /** + * Seek a widget whose name is equal name param from widget tree. + * + * @param name. + */ + Widget* getWidgetByName(const char* name); + + /** + * Remove and clean up all of UILayer's widget. + */ + virtual void clear(); + + /** + * Gets root widget of UILayer. + * + * @return UIRootWidget, "UIRootWidget" is the root widget of UILayer. + */ + Widget* getRootWidget(); +protected: + bool checkEventWidget(CCTouch* touch, CCEvent *pEvent); + bool checkTouchEvent(Widget* root, CCTouch* touch, CCEvent* pEvent); +protected: + Widget* m_pRootWidget; + CCPoint touchBeganedPoint; + CCPoint touchMovedPoint; + CCPoint touchEndedPoint; + CCPoint touchCanceledPoint; + CCArray* m_pSelectedWidgets; +}; + +} + +NS_CC_END + + + +#endif /* defined(__UILAYER_H__) */ diff --git a/include/extensions/CocoStudio/GUI/UIWidgets/Compatible/CompatibleClasses.h b/include/extensions/CocoStudio/GUI/UIWidgets/Compatible/CompatibleClasses.h new file mode 100644 index 0000000..6b33df4 --- /dev/null +++ b/include/extensions/CocoStudio/GUI/UIWidgets/Compatible/CompatibleClasses.h @@ -0,0 +1,58 @@ + +#ifndef __COMPATIBLECLASSES_H__ +#define __COMPATIBLECLASSES_H__ + +#include "cocos2d.h" +#include "../../BaseClasses/UIWidget.h" +#include "../UIButton.h" +#include "../UICheckBox.h" +#include "../UIImageView.h" +#include "../UILabel.h" +#include "../UILabelAtlas.h" +#include "../UILabelBMFont.h" +#include "../UILoadingBar.h" +#include "../UISlider.h" +#include "../UITextField.h" +#include "../../Layouts/UILayout.h" +#include "../ScrollWidget/UIListView.h" +#include "../ScrollWidget/UIPageView.h" +#include "../ScrollWidget/UIScrollView.h" + +//class type define +NS_CC_BEGIN +// +namespace ui { + +typedef cocos2d::ui::Layout UIPanel; +typedef cocos2d::ui::Layout UILayout; +typedef cocos2d::ui::Widget UIWidget; + +typedef cocos2d::ui::LayoutParameter UILayoutParameter; +typedef cocos2d::ui::Margin UIMargin; + +typedef cocos2d::ui::ListView UIListView; +typedef cocos2d::ui::PageView UIPageView; +typedef cocos2d::ui::ScrollView UIDragPanel; +typedef cocos2d::ui::ScrollView UIScrollView; +typedef cocos2d::ui::Button UIButton; +typedef cocos2d::ui::Button UITextButton; +typedef cocos2d::ui::CheckBox UICheckBox; +typedef cocos2d::ui::ImageView UIImageView; +typedef cocos2d::ui::Label UILabel; +typedef cocos2d::ui::LabelAtlas UILabelAtlas; +typedef cocos2d::ui::LabelBMFont UILabelBMFont; +typedef cocos2d::ui::LoadingBar UILoadingBar; +typedef cocos2d::ui::Slider UISlider; +typedef cocos2d::ui::TextField UITextField; +typedef cocos2d::ui::TouchGroup UILayer; + +typedef cocos2d::ui::LinearGravity UILinearGravity; +typedef cocos2d::ui::RelativeAlign UIRelativeAlign; +typedef cocos2d::ui::LayoutParameter UILayoutParameter; +typedef cocos2d::ui::LinearLayoutParameter UILinearLayoutParameter; +typedef cocos2d::ui::RelativeLayoutParameter UIRelativeLayoutParameter; +} +NS_CC_END + + +#endif /* defined(__CompatibleClasses__) */ diff --git a/include/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIListView.h b/include/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIListView.h new file mode 100644 index 0000000..0c90e1c --- /dev/null +++ b/include/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIListView.h @@ -0,0 +1,215 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + + +#ifndef __UILISTVIEW_H__ +#define __UILISTVIEW_H__ + +#include "UIScrollView.h" + +NS_CC_BEGIN + +namespace ui{ + +typedef enum +{ + LISTVIEW_GRAVITY_LEFT, + LISTVIEW_GRAVITY_RIGHT, + LISTVIEW_GRAVITY_CENTER_HORIZONTAL, + + LISTVIEW_GRAVITY_TOP, + LISTVIEW_GRAVITY_BOTTOM, + LISTVIEW_GRAVITY_CENTER_VERTICAL, +}ListViewGravity; + +typedef enum +{ + LISTVIEW_ONSELECTEDITEM_START, + LISTVIEW_ONSELECTEDITEM_END +}ListViewEventType; + +typedef void (CCObject::*SEL_ListViewEvent)(CCObject*,ListViewEventType); +#define listvieweventselector(_SELECTOR) (SEL_ListViewEvent)(&_SELECTOR) + +class ListView : public ScrollView +{ + + DECLARE_CLASS_GUI_INFO + +public: + + /** + * Default constructor + */ + ListView(); + + /** + * Default destructor + */ + virtual ~ListView(); + + /** + * Allocates and initializes. + */ + static ListView* create(); + + /** + * Sets a item model for listview + * + * A model will be cloned for adding default item. + * + * @param model item model for listview + */ + void setItemModel(Widget* model); + + /** + * Push back a default item(create by a cloned model) into listview. + */ + void pushBackDefaultItem(); + + /** + * Insert a default item(create by a cloned model) into listview. + */ + void insertDefaultItem(int index); + + /** + * Push back custom item into listview. + */ + void pushBackCustomItem(Widget* item); + + /** + * Insert custom item into listview. + */ + void insertCustomItem(Widget* item, int index); + + /** + * Removes the last item of listview. + */ + void removeLastItem(); + + /** + * Removes a item whose index is same as the parameter. + * + * @param index of item. + */ + void removeItem(int index); + + void removeAllItems(); + + /** + * Returns a item whose index is same as the parameter. + * + * @param index of item. + * + * @return the item widget. + */ + Widget* getItem(unsigned int index); + + /** + * Returns the item container. + */ + CCArray* getItems(); + + /** + * Returns the index of item. + * + * @param item the item which need to be checked. + * + * @return the index of item. + */ + unsigned int getIndex(Widget* item) const; + + /** + * Changes the gravity of listview. + * @see ListViewGravity + */ + void setGravity(ListViewGravity gravity); + + /** + * Changes the margin between each item. + * + * @param margin + */ + void setItemsMargin(float margin); + + float getItemsMargin(); + + virtual void sortAllChildren(); + + int getCurSelectedIndex() const; + + void addEventListenerListView(CCObject* target, SEL_ListViewEvent selector); + + /** + * Changes scroll direction of scrollview. + * + * @see SCROLLVIEW_DIR SCROLLVIEW_DIR_VERTICAL means vertical scroll, SCROLLVIEW_DIR_HORIZONTAL means horizontal scroll + * + * @param SCROLLVIEW_DIR + */ + virtual void setDirection(SCROLLVIEW_DIR dir); + + virtual std::string getDescription() const; + + void requestRefreshView(); + + void refreshView(); +protected: + virtual void addChild(CCNode* child) {ScrollView::addChild(child);}; + virtual void addChild(CCNode * child, int zOrder) {ScrollView::addChild(child, zOrder);}; + virtual void addChild(CCNode* child, int zOrder, int tag) {ScrollView::addChild(child, zOrder, tag);}; + virtual void removeChild(CCNode* widget) {ScrollView::removeChild(widget);}; + virtual void removeChild(CCNode* widget, bool cleanup) {ScrollView::removeChild(widget, cleanup);}; + + virtual void removeAllChildren() {ScrollView::removeAllChildren();}; + virtual void removeAllChildrenWithCleanup(bool cleanup) {ScrollView::removeAllChildrenWithCleanup(cleanup);}; + virtual CCArray* getChildren() {return ScrollView::getChildren();}; + virtual unsigned int getChildrenCount() const {return ScrollView::getChildrenCount();}; + virtual CCNode * getChildByTag(int tag) {return ScrollView::getChildByTag(tag);}; + virtual Widget* getChildByName(const char* name) {return ScrollView::getChildByName(name);}; + virtual bool init(); + void updateInnerContainerSize(); + void remedyLayoutParameter(Widget* item); + virtual void onSizeChanged(); + virtual Widget* createCloneInstance(); + virtual void copySpecialProperties(Widget* model); + virtual void copyClonedWidgetChildren(Widget* model); + void selectedItemEvent(int state); + virtual void interceptTouchEvent(int handleState,Widget* sender,const CCPoint &touchPoint); +protected: + + Widget* _model; + ListViewGravity _gravity; + float _itemsMargin; + CCObject* _listViewEventListener; + SEL_ListViewEvent _listViewEventSelector; + int _curSelectedIndex; + bool _refreshViewDirty; + CCArray* _items; +}; + +} +NS_CC_END + +#endif /* defined(__ListView__) */ diff --git a/include/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIPageView.h b/include/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIPageView.h new file mode 100644 index 0000000..54a00e8 --- /dev/null +++ b/include/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIPageView.h @@ -0,0 +1,221 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +#ifndef __UIPAGEVIEW_H__ +#define __UIPAGEVIEW_H__ + +#include "../../Layouts/UILayout.h" +#include "UIScrollInterface.h" + +NS_CC_BEGIN + +namespace ui { + +typedef enum +{ + PAGEVIEW_EVENT_TURNING, +}PageViewEventType; + +typedef void (CCObject::*SEL_PageViewEvent)(CCObject*, PageViewEventType); +#define pagevieweventselector(_SELECTOR)(SEL_PageViewEvent)(&_SELECTOR) + +typedef enum { + PAGEVIEW_TOUCHLEFT, + PAGEVIEW_TOUCHRIGHT +}PVTouchDir; + +class PageView : public Layout , public UIScrollInterface +{ + + DECLARE_CLASS_GUI_INFO + +public: + /** + * Default constructor + */ + PageView(); + + /** + * Default destructor + */ + virtual ~PageView(); + + /** + * Allocates and initializes. + */ + static PageView* create(); + + /** + * Add a widget to a page of pageview. + * + * @param widget widget to be added to pageview. + * + * @param pageIdx index of page. + * + * @param forceCreate if force create and there is no page exsit, pageview would create a default page for adding widget. + */ + void addWidgetToPage(Widget* widget, int pageIdx, bool forceCreate); + + /** + * Push back a page to pageview. + * + * @param page page to be added to pageview. + */ + void addPage(Layout* page); + + /** + * Inert a page to pageview. + * + * @param page page to be added to pageview. + */ + void insertPage(Layout* page, int idx); + + /** + * Remove a page of pageview. + * + * @param page page which will be removed. + */ + void removePage(Layout* page); + + /** + * Remove a page at index of pageview. + * + * @param index index of page. + */ + void removePageAtIndex(int index); + + void removeAllPages(); + + /** + * scroll pageview to index. + * + * @param idx index of page. + */ + void scrollToPage(int idx); + + /** + * Gets current page index. + * + * @return current page index. + */ + int getCurPageIndex() const; + + CCArray* getPages(); + + Layout* getPage(int index); + + // event + void addEventListenerPageView(CCObject *target, SEL_PageViewEvent selector); + + + + + virtual bool onTouchBegan(CCTouch *touch, CCEvent *unusedEvent); + virtual void onTouchMoved(CCTouch *touch, CCEvent *unusedEvent); + virtual void onTouchEnded(CCTouch *touch, CCEvent *unusedEvent); + virtual void onTouchCancelled(CCTouch *touch, CCEvent *unusedEvent); + + //override "update" method of widget. + virtual void update(float dt); + /** + * Sets LayoutType. + * + * @see LayoutType + * + * @param LayoutType + */ + virtual void setLayoutType(LayoutType type){}; + + /** + * Gets LayoutType. + * + * @see LayoutType + * + * @return LayoutType + */ + virtual LayoutType getLayoutType() const {return LAYOUT_ABSOLUTE;}; + + /** + * Returns the "class name" of widget. + */ + virtual std::string getDescription() const; + + virtual void onEnter(); +protected: + virtual void addChild(CCNode * child); + virtual void addChild(CCNode * child, int zOrder); + virtual void addChild(CCNode* child, int zOrder, int tag); + virtual void removeChild(CCNode* widget); + virtual void removeChild(CCNode* widget, bool cleanup); + virtual void removeAllChildren(); + virtual void removeAllChildrenWithCleanup(bool cleanup); + virtual CCArray* getChildren(){return Widget::getChildren();}; + virtual unsigned int getChildrenCount() const {return Widget::getChildrenCount();}; + virtual CCNode * getChildByTag(int tag) {return Widget::getChildByTag(tag);}; + virtual Widget* getChildByName(const char* name) {return Widget::getChildByName(name);}; + virtual bool init(); + Layout* createPage(); + float getPositionXByIndex(int idx); + void updateBoundaryPages(); + virtual void handlePressLogic(const CCPoint &touchPoint); + virtual void handleMoveLogic(const CCPoint &touchPoint); + virtual void handleReleaseLogic(const CCPoint &touchPoint); + virtual void interceptTouchEvent(int handleState, Widget* sender, const CCPoint &touchPoint); + virtual void checkChildInfo(int handleState, Widget* sender, const CCPoint &touchPoint); + virtual bool scrollPages(float touchOffset); + void movePages(float offset); + void pageTurningEvent(); + void updateChildrenSize(); + void updateChildrenPosition(); + virtual void onSizeChanged(); + virtual Widget* createCloneInstance(); + virtual void copySpecialProperties(Widget* model); + virtual void copyClonedWidgetChildren(Widget* model); + virtual void setClippingEnabled(bool enabled) {Layout::setClippingEnabled(enabled);}; + virtual void doLayout() {if (!_doLayoutDirty){return;} _doLayoutDirty = false;}; +protected: + int _curPageIdx; + CCArray* _pages; + PVTouchDir _touchMoveDir; + float _touchStartLocation; + float _touchMoveStartLocation; + CCPoint _movePagePoint; + Widget* _leftChild; + Widget* _rightChild; + float _leftBoundary; + float _rightBoundary; + bool _isAutoScrolling; + float _autoScrollDistance; + float _autoScrollSpeed; + int _autoScrollDir; + float _childFocusCancelOffset; + CCObject* _pageViewEventListener; + SEL_PageViewEvent _pageViewEventSelector; + +}; + +} +NS_CC_END + +#endif /* defined(__PageView__) */ diff --git a/include/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIScrollInterface.h b/include/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIScrollInterface.h new file mode 100644 index 0000000..2a70f17 --- /dev/null +++ b/include/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIScrollInterface.h @@ -0,0 +1,49 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +#ifndef __UISCROLLDELEGATE_H__ +#define __UISCROLLDELEGATE_H__ + +#include "../../BaseClasses/UIWidget.h" + +NS_CC_BEGIN + +namespace ui { + +class UIScrollInterface +{ +public: + virtual ~UIScrollInterface() {} + +protected: + virtual void handlePressLogic(const CCPoint &touchPoint) = 0; + virtual void handleMoveLogic(const CCPoint &touchPoint) = 0; + virtual void handleReleaseLogic(const CCPoint &touchPoint) = 0; + virtual void interceptTouchEvent(int handleState, Widget* sender, const CCPoint &touchPoint) = 0; +}; + +} +NS_CC_END + +#endif /* defined(__UIScrollDelegate__) */ diff --git a/include/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIScrollView.h b/include/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIScrollView.h new file mode 100644 index 0000000..728fcf5 --- /dev/null +++ b/include/extensions/CocoStudio/GUI/UIWidgets/ScrollWidget/UIScrollView.h @@ -0,0 +1,442 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +#ifndef __UISCROLLVIEW_H__ +#define __UISCROLLVIEW_H__ + +#include "../../Layouts/UILayout.h" +#include "UIScrollInterface.h" + +NS_CC_BEGIN + +namespace ui { + +class ScrollInnerContainer : public Layout +{ +public: + ScrollInnerContainer(); + virtual ~ScrollInnerContainer(); + static ScrollInnerContainer* create(); + virtual const CCSize& getLayoutSize(); +protected: +}; + +enum SCROLLVIEW_DIR +{ + SCROLLVIEW_DIR_NONE, + SCROLLVIEW_DIR_VERTICAL, + SCROLLVIEW_DIR_HORIZONTAL, + SCROLLVIEW_DIR_BOTH +}; + +typedef enum +{ + SCROLLVIEW_EVENT_SCROLL_TO_TOP, + SCROLLVIEW_EVENT_SCROLL_TO_BOTTOM, + SCROLLVIEW_EVENT_SCROLL_TO_LEFT, + SCROLLVIEW_EVENT_SCROLL_TO_RIGHT, + SCROLLVIEW_EVENT_SCROLLING, + SCROLLVIEW_EVENT_BOUNCE_TOP, + SCROLLVIEW_EVENT_BOUNCE_BOTTOM, + SCROLLVIEW_EVENT_BOUNCE_LEFT, + SCROLLVIEW_EVENT_BOUNCE_RIGHT +}ScrollviewEventType; + +typedef void (CCObject::*SEL_ScrollViewEvent)(CCObject*, ScrollviewEventType); +#define scrollvieweventselector(_SELECTOR) (SEL_ScrollViewEvent)(&_SELECTOR) + + +class ScrollView : public Layout , public UIScrollInterface +{ + + DECLARE_CLASS_GUI_INFO + +public: + /** + * Default constructor + */ + ScrollView(); + + /** + * Default destructor + */ + virtual ~ScrollView(); + + /** + * Allocates and initializes. + */ + static ScrollView* create(); + + /** + * Changes scroll direction of scrollview. + * + * @see SCROLLVIEW_DIR SCROLLVIEW_DIR_VERTICAL means vertical scroll, SCROLLVIEW_DIR_HORIZONTAL means horizontal scroll + * + * @param SCROLLVIEW_DIR + */ + virtual void setDirection(SCROLLVIEW_DIR dir); + + /** + * Gets scroll direction of scrollview. + * + * @see SCROLLVIEW_DIR SCROLLVIEW_DIR_VERTICAL means vertical scroll, SCROLLVIEW_DIR_HORIZONTAL means horizontal scroll + * + * @return SCROLLVIEW_DIR + */ + SCROLLVIEW_DIR getDirection(); + + /** + * Gets inner container of scrollview. + * + * Inner container is the container of scrollview's children. + * + * @return inner container. + */ + Layout* getInnerContainer(); + + /** + * Scroll inner container to bottom boundary of scrollview. + */ + void scrollToBottom(float time, bool attenuated); + + /** + * Scroll inner container to top boundary of scrollview. + */ + void scrollToTop(float time, bool attenuated); + + /** + * Scroll inner container to left boundary of scrollview. + */ + void scrollToLeft(float time, bool attenuated); + + /** + * Scroll inner container to right boundary of scrollview. + */ + void scrollToRight(float time, bool attenuated); + + /** + * Scroll inner container to top and left boundary of scrollview. + */ + void scrollToTopLeft(float time, bool attenuated); + + /** + * Scroll inner container to top and right boundary of scrollview. + */ + void scrollToTopRight(float time, bool attenuated); + + /** + * Scroll inner container to bottom and left boundary of scrollview. + */ + void scrollToBottomLeft(float time, bool attenuated); + + /** + * Scroll inner container to bottom and right boundary of scrollview. + */ + void scrollToBottomRight(float time, bool attenuated); + + /** + * Scroll inner container to vertical percent position of scrollview. + */ + void scrollToPercentVertical(float percent, float time, bool attenuated); + + /** + * Scroll inner container to horizontal percent position of scrollview. + */ + void scrollToPercentHorizontal(float percent, float time, bool attenuated); + + /** + * Scroll inner container to both direction percent position of scrollview. + */ + void scrollToPercentBothDirection(const CCPoint& percent, float time, bool attenuated); + + /** + * Move inner container to bottom boundary of scrollview. + */ + void jumpToBottom(); + + /** + * Move inner container to top boundary of scrollview. + */ + void jumpToTop(); + + /** + * Move inner container to left boundary of scrollview. + */ + void jumpToLeft(); + + /** + * Move inner container to right boundary of scrollview. + */ + void jumpToRight(); + + /** + * Move inner container to top and left boundary of scrollview. + */ + void jumpToTopLeft(); + + /** + * Move inner container to top and right boundary of scrollview. + */ + void jumpToTopRight(); + + /** + * Move inner container to bottom and left boundary of scrollview. + */ + void jumpToBottomLeft(); + + /** + * Move inner container to bottom and right boundary of scrollview. + */ + void jumpToBottomRight(); + + /** + * Move inner container to vertical percent position of scrollview. + */ + void jumpToPercentVertical(float percent); + + /** + * Move inner container to horizontal percent position of scrollview. + */ + void jumpToPercentHorizontal(float percent); + + /** + * Move inner container to both direction percent position of scrollview. + */ + void jumpToPercentBothDirection(const CCPoint& percent); + + /** + * Changes inner container size of scrollview. + * + * Inner container size must be larger than or equal scrollview's size. + * + * @param inner container size. + */ + void setInnerContainerSize(const CCSize &size); + + /** + * Gets inner container size of scrollview. + * + * Inner container size must be larger than or equal scrollview's size. + * + * @return inner container size. + */ + const CCSize& getInnerContainerSize() const; + + /** + * Add call back function called scrollview event triggered + */ + void addEventListenerScrollView(CCObject* target, SEL_ScrollViewEvent selector); + + virtual void addChild(CCNode * child); + /** + * Adds a child to the container with a z-order + * + * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. + * + * @param child A child node + * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) + */ + virtual void addChild(CCNode * child, int zOrder); + /** + * Adds a child to the container with z order and tag + * + * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. + * + * @param child A child node + * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) + * @param tag A interger to identify the node easily. Please refer to setTag(int) + */ + virtual void addChild(CCNode* child, int zOrder, int tag); + + //override "removeAllChildrenAndCleanUp" method of widget. + virtual void removeAllChildren(); + + virtual void removeAllChildrenWithCleanup(bool cleanup); + + virtual void removeChild(CCNode* child); + + //override "removeChild" method of widget. + virtual void removeChild(CCNode* child, bool cleaup); + + //override "getChildren" method of widget. + virtual CCArray* getChildren(); + + virtual unsigned int getChildrenCount() const; + + virtual CCNode * getChildByTag(int tag); + + virtual Widget* getChildByName(const char* name); + + virtual void addNode(CCNode* node); + + virtual void addNode(CCNode * node, int zOrder); + + virtual void addNode(CCNode* node, int zOrder, int tag); + + virtual CCNode * getNodeByTag(int tag); + + virtual void removeNodeByTag(int tag); + + virtual CCArray* getNodes(); + + virtual void removeNode(CCNode* node); + + virtual void removeAllNodes(); + + + virtual bool onTouchBegan(CCTouch *touch, CCEvent *unusedEvent); + virtual void onTouchMoved(CCTouch *touch, CCEvent *unusedEvent); + virtual void onTouchEnded(CCTouch *touch, CCEvent *unusedEvent); + virtual void onTouchCancelled(CCTouch *touch, CCEvent *unusedEvent); + + virtual void update(float dt); + + void setBounceEnabled(bool enabled); + + bool isBounceEnabled() const; + + void setInertiaScrollEnabled(bool enabled); + + bool isInertiaScrollEnabled() const; + + /** + * Sets LayoutType. + * + * @see LayoutType + * + * @param LayoutType + */ + virtual void setLayoutType(LayoutType type); + + /** + * Gets LayoutType. + * + * @see LayoutType + * + * @return LayoutType + */ + virtual LayoutType getLayoutType() const; + + /** + * Returns the "class name" of widget. + */ + virtual std::string getDescription() const; + + virtual void onEnter(); +protected: + virtual bool init(); + virtual void initRenderer(); + void moveChildren(float offsetX, float offsetY); + void autoScrollChildren(float dt); + void bounceChildren(float dt); + void checkBounceBoundary(); + bool checkNeedBounce(); + void startAutoScrollChildrenWithOriginalSpeed(const CCPoint& dir, float v, bool attenuated, float acceleration); + void startAutoScrollChildrenWithDestination(const CCPoint& des, float time, bool attenuated); + void jumpToDestination(const CCPoint& des); + void stopAutoScrollChildren(); + void startBounceChildren(float v); + void stopBounceChildren(); + bool checkCustomScrollDestination(float* touchOffsetX, float* touchOffsetY); + virtual bool scrollChildren(float touchOffsetX, float touchOffsetY); + bool bounceScrollChildren(float touchOffsetX, float touchOffsetY); + void startRecordSlidAction(); + virtual void endRecordSlidAction(); + virtual void handlePressLogic(const CCPoint &touchPoint); + virtual void handleMoveLogic(const CCPoint &touchPoint); + virtual void handleReleaseLogic(const CCPoint &touchPoint); + virtual void interceptTouchEvent(int handleState,Widget* sender,const CCPoint &touchPoint); + virtual void checkChildInfo(int handleState,Widget* sender,const CCPoint &touchPoint); + void recordSlidTime(float dt); + void scrollToTopEvent(); + void scrollToBottomEvent(); + void scrollToLeftEvent(); + void scrollToRightEvent(); + void scrollingEvent(); + void bounceTopEvent(); + void bounceBottomEvent(); + void bounceLeftEvent(); + void bounceRightEvent(); + virtual void onSizeChanged(); + virtual Widget* createCloneInstance(); + virtual void copySpecialProperties(Widget* model); + virtual void copyClonedWidgetChildren(Widget* model); + virtual void setClippingEnabled(bool able) {Layout::setClippingEnabled(able);}; + virtual void doLayout(); +protected: + ScrollInnerContainer* _innerContainer; + + SCROLLVIEW_DIR _direction; + + CCPoint _touchBeganPoint; + CCPoint _touchMovedPoint; + CCPoint _touchEndedPoint; + CCPoint _touchMovingPoint; + CCPoint _autoScrollDir; + + float _topBoundary; + float _bottomBoundary; + float _leftBoundary; + float _rightBoundary; + + float _bounceTopBoundary; + float _bounceBottomBoundary; + float _bounceLeftBoundary; + float _bounceRightBoundary; + + + bool _autoScroll; + float _autoScrollAddUpTime; + + float _autoScrollOriginalSpeed; + float _autoScrollAcceleration; + bool _isAutoScrollSpeedAttenuated; + bool _needCheckAutoScrollDestination; + CCPoint _autoScrollDestination; + + bool _bePressed; + float _slidTime; + CCPoint _moveChildPoint; + float _childFocusCancelOffset; + + bool _leftBounceNeeded; + bool _topBounceNeeded; + bool _rightBounceNeeded; + bool _bottomBounceNeeded; + + bool _bounceEnabled; + bool _bouncing; + CCPoint _bounceDir; + float _bounceOriginalSpeed; + bool _inertiaScrollEnabled; + + + + CCObject* _scrollViewEventListener; + SEL_ScrollViewEvent _scrollViewEventSelector; +}; + +} +NS_CC_END +#endif /* defined(__CocoGUI__ScrollView__) */ diff --git a/include/extensions/CocoStudio/GUI/UIWidgets/UIButton.h b/include/extensions/CocoStudio/GUI/UIWidgets/UIButton.h new file mode 100644 index 0000000..bb5a2c0 --- /dev/null +++ b/include/extensions/CocoStudio/GUI/UIWidgets/UIButton.h @@ -0,0 +1,225 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +#ifndef __UIBUTTON_H__ +#define __UIBUTTON_H__ + +#include "../BaseClasses/UIWidget.h" + +NS_CC_BEGIN + +namespace ui{ + +/** +* @js NA +* @lua NA +*/ +class Button : public Widget +{ + DECLARE_CLASS_GUI_INFO + +public: + /** + * Default constructor + */ + Button(); + + /** + * Default destructor + */ + virtual ~Button(); + + /** + * Allocates and initializes. + */ + static Button* create(); + + /** + * Load textures for button. + * + * @param normal normal state texture. + * + * @param selected selected state texture. + * + * @param disabled dark state texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadTextures(const char* normal,const char* selected,const char* disabled,TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Load normal state texture for button. + * + * @param normal normal state texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadTextureNormal(const char* normal, TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Load selected state texture for button. + * + * @param selected selected state texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadTexturePressed(const char* selected, TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Load dark state texture for button. + * + * @param disabled dark state texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadTextureDisabled(const char* disabled, TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Sets capinsets for button, if button is using scale9 renderer. + * + * @param capInsets capinsets for button + */ + void setCapInsets(const CCRect &capInsets); + + /** + * Sets capinsets for button, if button is using scale9 renderer. + * + * @param capInsets capinsets for button + */ + void setCapInsetsNormalRenderer(const CCRect &capInsets); + + const CCRect& getCapInsetNormalRenderer(); + + /** + * Sets capinsets for button, if button is using scale9 renderer. + * + * @param capInsets capinsets for button + */ + void setCapInsetsPressedRenderer(const CCRect &capInsets); + + const CCRect& getCapInsetPressedRenderer(); + + /** + * Sets capinsets for button, if button is using scale9 renderer. + * + * @param capInsets capinsets for button + */ + void setCapInsetsDisabledRenderer(const CCRect &capInsets); + + const CCRect& getCapInsetDisabledRenderer(); + + //override "setAnchorPoint" of widget. + virtual void setAnchorPoint(const CCPoint &pt); + + /** + * Sets if button is using scale9 renderer. + * + * @param true that using scale9 renderer, false otherwise. + */ + virtual void setScale9Enabled(bool able); + + bool isScale9Enabled(); + + /** + * Changes if button can be clicked zoom effect. + * + * @param true that can be clicked zoom effect, false otherwise. + */ + void setPressedActionEnabled(bool enabled); + + //override "ignoreContentAdaptWithSize" method of widget. + virtual void ignoreContentAdaptWithSize(bool ignore); + + //override "getContentSize" method of widget. + virtual const CCSize& getContentSize() const; + + //override "getVirtualRenderer" method of widget. + virtual CCNode* getVirtualRenderer(); + + /** + * Returns the "class name" of widget. + */ + virtual std::string getDescription() const; + + void setTitleText(const std::string& text); + const char* getTitleText() const; + void setTitleColor(const ccColor3B& color); + const ccColor3B& getTitleColor() const; + void setTitleFontSize(float size); + float getTitleFontSize() const; + void setTitleFontName(const char* fontName); + const char* getTitleFontName() const; + +protected: + virtual bool init(); + virtual void initRenderer(); + virtual void onPressStateChangedToNormal(); + virtual void onPressStateChangedToPressed(); + virtual void onPressStateChangedToDisabled(); + virtual void onSizeChanged(); + virtual void updateTextureColor(); + virtual void updateTextureOpacity(); + virtual void updateTextureRGBA(); + virtual void updateFlippedX(); + virtual void updateFlippedY(); + void normalTextureScaleChangedWithSize(); + void pressedTextureScaleChangedWithSize(); + void disabledTextureScaleChangedWithSize(); + virtual Widget* createCloneInstance(); + virtual void copySpecialProperties(Widget* model); +protected: + CCNode* _buttonNormalRenderer; + CCNode* _buttonClickedRenderer; + CCNode* _buttonDisableRenderer; + CCLabelTTF* _titleRenderer; + std::string _normalFileName; + std::string _clickedFileName; + std::string _disabledFileName; + bool _prevIgnoreSize; + bool _scale9Enabled; + CCRect _capInsetsNormal; + CCRect _capInsetsPressed; + CCRect _capInsetsDisabled; + TextureResType _normalTexType; + TextureResType _pressedTexType; + TextureResType _disabledTexType; + CCSize _normalTextureSize; + CCSize _pressedTextureSize; + CCSize _disabledTextureSize; + bool _pressedActionEnabled; + ccColor3B _titleColor; + float _normalTextureScaleXInSize; + float _normalTextureScaleYInSize; + float _pressedTextureScaleXInSize; + float _pressedTextureScaleYInSize; + bool _normalTextureLoaded; + bool _pressedTextureLoaded; + bool _disabledTextureLoaded; +}; + +} + +NS_CC_END + +#endif /* defined(__CocoGUI__Button__) */ diff --git a/include/extensions/CocoStudio/GUI/UIWidgets/UICheckBox.h b/include/extensions/CocoStudio/GUI/UIWidgets/UICheckBox.h new file mode 100644 index 0000000..81c5549 --- /dev/null +++ b/include/extensions/CocoStudio/GUI/UIWidgets/UICheckBox.h @@ -0,0 +1,210 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +#ifndef __UICHECKBOX_H__ +#define __UICHECKBOX_H__ + +#include "../BaseClasses/UIWidget.h" + +NS_CC_BEGIN + +namespace ui { + +typedef enum +{ + CHECKBOX_STATE_EVENT_SELECTED, + CHECKBOX_STATE_EVENT_UNSELECTED +}CheckBoxEventType; + +typedef void (CCObject::*SEL_SelectedStateEvent)(CCObject*,CheckBoxEventType); +#define checkboxselectedeventselector(_SELECTOR) (SEL_SelectedStateEvent)(&_SELECTOR) + +/** +* @js NA +* @lua NA +*/ +class CheckBox : public Widget +{ + DECLARE_CLASS_GUI_INFO + +public: + /** + * Default constructor + */ + CheckBox(); + + /** + * Default destructor + */ + virtual ~CheckBox(); + + /** + * Allocates and initializes. + */ + static CheckBox* create(); + + /** + * Load textures for checkbox. + * + * @param backGround backGround texture. + * + * @param backGroundSelected backGround selected state texture. + * + * @param cross cross texture. + * + * @param frontCrossDisabled cross dark state texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadTextures(const char* backGround,const char* backGroundSelected,const char* cross,const char* backGroundDisabled,const char* frontCrossDisabled,TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Load backGround texture for checkbox. + * + * @param backGround backGround texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadTextureBackGround(const char* backGround,TextureResType type = UI_TEX_TYPE_LOCAL); + + /** + * Load backGroundSelected texture for checkbox. + * + * @param backGroundSelected backGround selected state texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadTextureBackGroundSelected(const char* backGroundSelected,TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Load cross texture for checkbox. + * + * @param cross cross texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadTextureFrontCross(const char* cross,TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Load backGroundDisabled texture for checkbox. + * + * @param backGroundDisabled backGroundDisabled texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadTextureBackGroundDisabled(const char* backGroundDisabled,TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Load frontCrossDisabled texture for checkbox. + * + * @param frontCrossDisabled frontCrossDisabled texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadTextureFrontCrossDisabled(const char* frontCrossDisabled,TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Sets selcted state for checkbox. + * + * @param selected true that checkbox is selected, false otherwise. + */ + void setSelectedState(bool selected); + + /** + * Gets selcted state of checkbox. + * + * @return selected true that checkbox is selected, false otherwise. + */ + bool getSelectedState(); + + //override "setAnchorPoint" method of widget. + virtual void setAnchorPoint(const CCPoint &pt); + + //add a call back function would called when checkbox is selected or unselected. + void addEventListenerCheckBox(CCObject* target,SEL_SelectedStateEvent selector); + + //override "onTouchEnded" method of widget. + virtual void onTouchEnded(CCTouch *touch, CCEvent *unused_event); + + //override "getContentSize" method of widget. + virtual const CCSize& getContentSize() const; + + //override "getVirtualRenderer" method of widget. + virtual CCNode* getVirtualRenderer(); + + /** + * Returns the "class name" of widget. + */ + virtual std::string getDescription() const; + +protected: + virtual bool init(); + virtual void initRenderer(); + virtual void onPressStateChangedToNormal(); + virtual void onPressStateChangedToPressed(); + virtual void onPressStateChangedToDisabled(); + void selectedEvent(); + void unSelectedEvent(); + virtual void onSizeChanged(); + virtual void updateTextureColor(); + virtual void updateTextureOpacity(); + virtual void updateTextureRGBA(); + virtual void updateFlippedX(); + virtual void updateFlippedY(); + void backGroundTextureScaleChangedWithSize(); + void backGroundSelectedTextureScaleChangedWithSize(); + void frontCrossTextureScaleChangedWithSize(); + void backGroundDisabledTextureScaleChangedWithSize(); + void frontCrossDisabledTextureScaleChangedWithSize(); + virtual Widget* createCloneInstance(); + virtual void copySpecialProperties(Widget* model); +protected: + CCSprite* _backGroundBoxRenderer; + CCSprite* _backGroundSelectedBoxRenderer; + CCSprite* _frontCrossRenderer; + CCSprite* _backGroundBoxDisabledRenderer; + CCSprite* _frontCrossDisabledRenderer; + bool _isSelected; + + CCObject* _checkBoxEventListener; + SEL_SelectedStateEvent _checkBoxEventSelector; + + TextureResType _backGroundTexType; + TextureResType _backGroundSelectedTexType; + TextureResType _frontCrossTexType; + TextureResType _backGroundDisabledTexType; + TextureResType _frontCrossDisabledTexType; + + std::string _backGroundFileName; + std::string _backGroundSelectedFileName; + std::string _frontCrossFileName; + std::string _backGroundDisabledFileName; + std::string _frontCrossDisabledFileName; +}; + +} + +NS_CC_END + +#endif /* defined(__CocoGUI__CheckBox__) */ diff --git a/include/extensions/CocoStudio/GUI/UIWidgets/UIImageView.h b/include/extensions/CocoStudio/GUI/UIWidgets/UIImageView.h new file mode 100644 index 0000000..c5e2dbb --- /dev/null +++ b/include/extensions/CocoStudio/GUI/UIWidgets/UIImageView.h @@ -0,0 +1,129 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +#ifndef __UIIMAGEVIEW_H__ +#define __UIIMAGEVIEW_H__ + +#include "../BaseClasses/UIWidget.h" + +NS_CC_BEGIN + +namespace ui { + +/** +* @js NA +* @lua NA +*/ +class ImageView : public Widget +{ + DECLARE_CLASS_GUI_INFO + +public: + /** + * Default constructor + */ + ImageView(); + + /** + * Default destructor + */ + virtual ~ImageView(); + + /** + * Allocates and initializes. + */ + static ImageView* create(); + + /** + * Load texture for imageview. + * + * @param fileName file name of texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadTexture(const char* fileName,TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Updates the texture rect of the ImageView in points. + * It will call setTextureRect:rotated:untrimmedSize with rotated = NO, and utrimmedSize = rect.size. + */ + void setTextureRect(const CCRect& rect); + + /** + * Sets if imageview is using scale9 renderer. + * + * @param true that using scale9 renderer, false otherwise. + */ + void setScale9Enabled(bool able); + + bool isScale9Enabled(); + + /** + * Sets capinsets for imageview, if imageview is using scale9 renderer. + * + * @param capInsets capinsets for imageview + */ + void setCapInsets(const CCRect &capInsets); + + const CCRect& getCapInsets(); + + //override "setAnchorPoint" method of widget. + virtual void setAnchorPoint(const CCPoint &pt); + + //override "ignoreContentAdaptWithSize" method of widget. + virtual void ignoreContentAdaptWithSize(bool ignore); + + /** + * Returns the "class name" of widget. + */ + virtual std::string getDescription() const; + + virtual const CCSize& getContentSize() const; + virtual CCNode* getVirtualRenderer(); +protected: + virtual void initRenderer(); + virtual void onSizeChanged(); + virtual void updateTextureColor(); + virtual void updateTextureOpacity(); + virtual void updateTextureRGBA(); + virtual void updateFlippedX(); + virtual void updateFlippedY(); + void imageTextureScaleChangedWithSize(); + virtual Widget* createCloneInstance(); + virtual void copySpecialProperties(Widget* model); +protected: + bool _scale9Enabled; + bool _prevIgnoreSize; + CCRect _capInsets; + CCNode* _imageRenderer; + std::string _textureFile; + TextureResType _imageTexType; + CCSize _imageTextureSize; +}; + +} + +NS_CC_END + +#endif /* defined(__CocoGUI__ImageView__) */ diff --git a/include/extensions/CocoStudio/GUI/UIWidgets/UILabel.h b/include/extensions/CocoStudio/GUI/UIWidgets/UILabel.h new file mode 100644 index 0000000..c31d7fa --- /dev/null +++ b/include/extensions/CocoStudio/GUI/UIWidgets/UILabel.h @@ -0,0 +1,164 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +#ifndef __UILABEL_H__ +#define __UILABEL_H__ + +#include "../BaseClasses/UIWidget.h" + +NS_CC_BEGIN + +namespace ui { + +/** +* @js NA +* @lua NA +*/ +class Label : public Widget +{ + DECLARE_CLASS_GUI_INFO + +public: + /** + * Default constructor + */ + Label(); + + /** + * Default destructor + */ + virtual ~Label(); + + /** + * Allocates and initializes. + */ + static Label* create(); + + /** + * Changes the string value of label. + * + * @param text string value. + */ + void setText(const std::string& text); + + /** + * Gets the string value of label. + * + * @return text string value. + */ + const char* getStringValue(); + + /** + * Gets the string length of label. + * + * @return string length. + */ + int getStringLength(); + + /** + * Sets the font size of label. + * + * @param font size. + */ + void setFontSize(int size); + + int getFontSize(); + + /** + * Sets the font name of label. + * + * @param font name. + */ + void setFontName(const std::string& name); + + const char* getFontName(); + /** + * Sets the touch scale enabled of label. + * + * @param touch scale enabled of label. + */ + void setTouchScaleChangeEnabled(bool enabled); + + /** + * Gets the touch scale enabled of label. + * + * @return touch scale enabled of label. + */ + bool isTouchScaleChangeEnabled(); + + //override "setAnchorPoint" method of widget. + virtual void setAnchorPoint(const CCPoint &pt); + + //override "getContentSize" method of widget. + virtual const CCSize& getContentSize() const; + + //override "getVirtualRenderer" method of widget. + virtual CCNode* getVirtualRenderer(); + + /** + * Returns the "class name" of widget. + */ + virtual std::string getDescription() const; + + void setTextAreaSize(const CCSize &size); + + CCSize getTextAreaSize(); + + void setTextHorizontalAlignment(CCTextAlignment alignment); + + CCTextAlignment getTextHorizontalAlignment(); + + void setTextVerticalAlignment(CCVerticalTextAlignment alignment); + + CCVerticalTextAlignment getTextVerticalAlignment(); +protected: + virtual bool init(); + virtual void initRenderer(); + virtual void onPressStateChangedToNormal(); + virtual void onPressStateChangedToPressed(); + virtual void onPressStateChangedToDisabled(); + virtual void onSizeChanged(); + virtual void updateTextureColor(); + virtual void updateTextureOpacity(); + virtual void updateTextureRGBA(); + virtual void updateFlippedX(); + virtual void updateFlippedY(); + void labelScaleChangedWithSize(); + virtual Widget* createCloneInstance(); + virtual void copySpecialProperties(Widget* model); +protected: + bool _touchScaleChangeEnabled; + float _normalScaleValueX; + float _normalScaleValueY; + std::string _fontName; + int _fontSize; + float _onSelectedScaleOffset; + CCLabelTTF* _labelRenderer; +}; + +} + +NS_CC_END + +#endif /* defined(__CocoGUI__Label__) */ diff --git a/include/extensions/CocoStudio/GUI/UIWidgets/UILabelAtlas.h b/include/extensions/CocoStudio/GUI/UIWidgets/UILabelAtlas.h new file mode 100644 index 0000000..2150cfc --- /dev/null +++ b/include/extensions/CocoStudio/GUI/UIWidgets/UILabelAtlas.h @@ -0,0 +1,128 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +#ifndef __UILABELATLAS_H__ +#define __UILABELATLAS_H__ + +#include "../BaseClasses/UIWidget.h" + +NS_CC_BEGIN + +namespace ui { + +/** + * @js NA + * @lua NA + */ +class UICCLabelAtlas : public CCLabelAtlas +{ +public: + /** + * Default constructor + */ + UICCLabelAtlas(); + + /** + * Default destructor + */ + virtual ~UICCLabelAtlas(); + + /** + * Allocates and initializes. + */ + static UICCLabelAtlas* create(); + void setProperty(const std::string& string, const std::string& charMapFile, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap); + void setProperty(const std::string& string, CCTexture2D *texture, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharMap); + virtual void updateDisplayedOpacity(GLubyte opacity); + virtual void draw(void); +}; +/** + * @js NA + * @lua NA + */ +class LabelAtlas : public Widget +{ + DECLARE_CLASS_GUI_INFO + +public: + /** + * Default constructor + */ + LabelAtlas(); + + /** + * Default destructor + */ + virtual ~LabelAtlas(); + + /** + * Allocates and initializes. + */ + static LabelAtlas* create(); + + /** initializes the LabelAtlas with a string, a char map file(the atlas), the width and height of each element and the starting char of the atlas */ + void setProperty(const std::string& stringValue,const std::string& charMapFile, int itemWidth, int itemHeight, const std::string& startCharMap); + + //set string value for labelatlas. + void setStringValue(const std::string& value); + + //get string value for labelatlas. + const char* getStringValue() const; + + //override "setAnchorPoint" method of widget. + virtual void setAnchorPoint(const CCPoint &pt); + + //override "getContentSize" method of widget. + virtual const CCSize& getContentSize() const; + + //override "getVirtualRenderer" method of widget. + virtual CCNode* getVirtualRenderer(); + + /** + * Returns the "class name" of widget. + */ + virtual std::string getDescription() const; + +protected: + virtual void initRenderer(); + virtual void onSizeChanged(); + virtual void updateTextureColor(); + virtual void updateTextureOpacity(); + virtual void updateTextureRGBA(); + void labelAtlasScaleChangedWithSize(); + virtual Widget* createCloneInstance(); + virtual void copySpecialProperties(Widget* model); +protected: + UICCLabelAtlas* _labelAtlasRenderer; + std::string _stringValue; + std::string _charMapFileName; + int _itemWidth; + int _itemHeight; + std::string _startCharMap; +}; + +} +NS_CC_END + +#endif /* defined(__CocoGUI__LabelAtlas__) */ diff --git a/include/extensions/CocoStudio/GUI/UIWidgets/UILabelBMFont.h b/include/extensions/CocoStudio/GUI/UIWidgets/UILabelBMFont.h new file mode 100644 index 0000000..39af54f --- /dev/null +++ b/include/extensions/CocoStudio/GUI/UIWidgets/UILabelBMFont.h @@ -0,0 +1,92 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +#ifndef __UILABELBMFONT_H__ +#define __UILABELBMFONT_H__ + +#include "../BaseClasses/UIWidget.h" + +NS_CC_BEGIN + +namespace ui { + +/** +* @js NA +* @lua NA +*/ +class LabelBMFont : public Widget +{ + DECLARE_CLASS_GUI_INFO + +public: + /** + * Default constructor + */ + LabelBMFont(); + + /** + * Default destructor + */ + virtual ~LabelBMFont(); + + /** + * Allocates and initializes. + */ + static LabelBMFont* create(); + + /** init a bitmap font atlas with an initial string and the FNT file */ + void setFntFile(const char* fileName); + + /** set string value for labelbmfont*/ + void setText(const char* value); + + /** get string value for labelbmfont*/ + const char* getStringValue(); + virtual void setAnchorPoint(const CCPoint &pt); + virtual const CCSize& getContentSize() const; + virtual CCNode* getVirtualRenderer(); + /** + * Returns the "class name" of widget. + */ + virtual std::string getDescription() const; +protected: + virtual void initRenderer(); + virtual void onSizeChanged(); + virtual void updateTextureColor(); + virtual void updateTextureOpacity(); + virtual void updateTextureRGBA(); + void labelBMFontScaleChangedWithSize(); + virtual Widget* createCloneInstance(); + virtual void copySpecialProperties(Widget* model); +protected: + cocos2d::CCLabelBMFont* _labelBMFontRenderer; + bool _fntFileHasInit; + std::string _fntFileName; + std::string _stringValue; +}; + +} +NS_CC_END + +#endif /* defined(__LabelBMFont__) */ diff --git a/include/extensions/CocoStudio/GUI/UIWidgets/UILoadingBar.h b/include/extensions/CocoStudio/GUI/UIWidgets/UILoadingBar.h new file mode 100644 index 0000000..100af27 --- /dev/null +++ b/include/extensions/CocoStudio/GUI/UIWidgets/UILoadingBar.h @@ -0,0 +1,161 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +#ifndef __UILOADINGBAR_H__ +#define __UILOADINGBAR_H__ + +#include "../BaseClasses/UIWidget.h" + +NS_CC_BEGIN + +namespace ui { + +typedef enum +{ + LoadingBarTypeLeft, + LoadingBarTypeRight +}LoadingBarType; +/** +* @js NA +* @lua NA +*/ +class LoadingBar : public Widget +{ + + DECLARE_CLASS_GUI_INFO + +public: + /** + * Default constructor + */ + LoadingBar(); + + /** + * Default destructor + */ + virtual ~LoadingBar(); + + /** + * Allocates and initializes. + */ + static LoadingBar* create(); + + /** + * Changes the progress direction of loadingbar. + * + * @see LoadingBarType LoadingBarTypeLeft means progress left to right, LoadingBarTypeRight otherwise. + * + * @param LoadingBarType + */ + void setDirection(LoadingBarType dir); + + /** + * Gets the progress direction of loadingbar. + * + * @see LoadingBarType LoadingBarTypeLeft means progress left to right, LoadingBarTypeRight otherwise. + * + * @param LoadingBarType + */ + int getDirection(); + + /** + * Load texture for loadingbar. + * + * @param fileName file name of texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadTexture(const char* texture,TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Changes the progress direction of loadingbar. + * + * @param percent percent value from 1 to 100. + */ + void setPercent(int percent); + + /** + * Gets the progress direction of loadingbar. + * + * @return percent percent value from 1 to 100. + */ + int getPercent(); + + /** + * Sets if loadingbar is using scale9 renderer. + * + * @param true that using scale9 renderer, false otherwise. + */ + void setScale9Enabled(bool enabled); + + bool isScale9Enabled(); + + /** + * Sets capinsets for loadingbar, if loadingbar is using scale9 renderer. + * + * @param capInsets capinsets for loadingbar + */ + void setCapInsets(const CCRect &capInsets); + + const CCRect& getCapInsets(); + + //override "ignoreContentAdaptWithSize" method of widget. + virtual void ignoreContentAdaptWithSize(bool ignore); + + //override "getContentSize" method of widget. + virtual const CCSize& getContentSize() const; + + //override "getVirtualRenderer" method of widget. + virtual CCNode* getVirtualRenderer(); + + /** + * Returns the "class name" of widget. + */ + virtual std::string getDescription() const; +protected: + virtual void initRenderer(); + virtual void onSizeChanged(); + virtual void updateTextureColor(); + virtual void updateTextureOpacity(); + virtual void updateTextureRGBA(); + void setScale9Scale(); + void barRendererScaleChangedWithSize(); + virtual Widget* createCloneInstance(); + virtual void copySpecialProperties(Widget* model); +protected: + LoadingBarType _barType; + int _percent; + float _totalLength; + CCNode* _barRenderer; + TextureResType _renderBarTexType; + CCSize _barRendererTextureSize; + bool _scale9Enabled; + bool _prevIgnoreSize; + CCRect _capInsets; + std::string _textureFile; +}; + +} +NS_CC_END +#endif /* defined(__CocoGUI__LoadingBar__) */ diff --git a/include/extensions/CocoStudio/GUI/UIWidgets/UIRichText.h b/include/extensions/CocoStudio/GUI/UIWidgets/UIRichText.h new file mode 100644 index 0000000..8645a78 --- /dev/null +++ b/include/extensions/CocoStudio/GUI/UIWidgets/UIRichText.h @@ -0,0 +1,133 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +#ifndef __UIRICHTEXT_H__ +#define __UIRICHTEXT_H__ + +#include "../BaseClasses/UIWidget.h" + +NS_CC_BEGIN + +namespace ui { + +typedef enum { + RICH_TEXT, + RICH_IMAGE, + RICH_CUSTOM +}RichElementType; + +class RichElement : public CCObject +{ +public: + RichElement(){}; + virtual ~RichElement(){}; + virtual bool init(int tag, const ccColor3B& color, GLubyte opacity); +protected: + RichElementType _type; + int _tag; + ccColor3B _color; + GLubyte _opacity; + friend class RichText; +}; + +class RichElementText : public RichElement +{ +public: + RichElementText(){_type = RICH_TEXT;}; + virtual ~RichElementText(){}; + virtual bool init(int tag, const ccColor3B& color, GLubyte opacity, const char* text, const char* fontName, float fontSize); + static RichElementText* create(int tag, const ccColor3B& color, GLubyte opacity, const char* text, const char* fontName, float fontSize); +protected: + std::string _text; + std::string _fontName; + float _fontSize; + friend class RichText; + +}; + +class RichElementImage : public RichElement +{ +public: + RichElementImage(){_type = RICH_IMAGE;}; + virtual ~RichElementImage(){}; + virtual bool init(int tag, const ccColor3B& color, GLubyte opacity, const char* filePath); + static RichElementImage* create(int tag, const ccColor3B& color, GLubyte opacity, const char* filePath); +protected: + std::string _filePath; + CCRect _textureRect; + int _textureType; + friend class RichText; +}; + +class RichElementCustomNode : public RichElement +{ +public: + RichElementCustomNode(){_type = RICH_CUSTOM;}; + virtual ~RichElementCustomNode(){CC_SAFE_RELEASE(_customNode);}; + virtual bool init(int tag, const ccColor3B& color, GLubyte opacity, CCNode* customNode); + static RichElementCustomNode* create(int tag, const ccColor3B& color, GLubyte opacity, CCNode* customNode); +protected: + CCNode* _customNode; + friend class RichText; +}; + +class RichText : public Widget +{ +public: + RichText(); + virtual ~RichText(); + static RichText* create(); + void insertElement(RichElement* element, int index); + void pushBackElement(RichElement* element); + void removeElement(int index); + void removeElement(RichElement* element); + virtual void visit(); + void setVerticalSpace(float space); + virtual void setAnchorPoint(const CCPoint &pt); + virtual const CCSize& getContentSize() const; + void formatText(); + virtual void ignoreContentAdaptWithSize(bool ignore); +protected: + virtual bool init(); + virtual void initRenderer(); + void pushToContainer(CCNode* renderer); + void handleTextRenderer(const char* text, const char* fontName, float fontSize, const ccColor3B& color, GLubyte opacity); + void handleImageRenderer(const char* fileParh, const ccColor3B& color, GLubyte opacity); + void handleCustomRenderer(CCNode* renderer); + void formarRenderers(); + void addNewLine(); +protected: + bool _formatTextDirty; + CCArray* _richElements; + std::vector _elementRenders; + float _leftSpaceWidth; + float _verticalSpace; + CCNode* _elementRenderersContainer; +}; + +} + +NS_CC_END + +#endif /* defined(__UIRichText__) */ diff --git a/include/extensions/CocoStudio/GUI/UIWidgets/UISlider.h b/include/extensions/CocoStudio/GUI/UIWidgets/UISlider.h new file mode 100644 index 0000000..21195ca --- /dev/null +++ b/include/extensions/CocoStudio/GUI/UIWidgets/UISlider.h @@ -0,0 +1,249 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +#ifndef __UISLIDER_H__ +#define __UISLIDER_H__ + +#include "../BaseClasses/UIWidget.h" + +NS_CC_BEGIN + +namespace ui { + +typedef enum +{ + SLIDER_PERCENTCHANGED +}SliderEventType; + +typedef void (CCObject::*SEL_SlidPercentChangedEvent)(CCObject*,SliderEventType); +#define sliderpercentchangedselector(_SELECTOR) (SEL_SlidPercentChangedEvent)(&_SELECTOR) + +/** +* @js NA +* @lua NA +*/ +class Slider : public Widget +{ + + DECLARE_CLASS_GUI_INFO + +public: + /** + * Default constructor + */ + Slider(); + + /** + * Default destructor + */ + virtual ~Slider(); + + /** + * Allocates and initializes. + */ + static Slider* create(); + + /** + * Load texture for slider bar. + * + * @param fileName file name of texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadBarTexture(const char* fileName,TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Sets if slider is using scale9 renderer. + * + * @param true that using scale9 renderer, false otherwise. + */ + void setScale9Enabled(bool able); + + bool isScale9Enabled(); + + /** + * Sets capinsets for slider, if slider is using scale9 renderer. + * + * @param capInsets capinsets for slider + */ + void setCapInsets(const CCRect &capInsets); + + /** + * Sets capinsets for slider, if slider is using scale9 renderer. + * + * @param capInsets capinsets for slider + */ + void setCapInsetsBarRenderer(const CCRect &capInsets); + + const CCRect& getCapInsetBarRenderer(); + + /** + * Sets capinsets for slider, if slider is using scale9 renderer. + * + * @param capInsets capinsets for slider + */ + void setCapInsetProgressBarRebderer(const CCRect &capInsets); + + const CCRect& getCapInsetProgressBarRebderer(); + + /** + * Load textures for slider ball. + * + * @param slider ball normal normal state texture. + * + * @param slider ball selected selected state texture. + * + * @param slider ball disabled dark state texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadSlidBallTextures(const char* normal,const char* pressed,const char* disabled,TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Load normal state texture for slider ball. + * + * @param normal normal state texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadSlidBallTextureNormal(const char* normal,TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Load selected state texture for slider ball. + * + * @param selected selected state texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadSlidBallTexturePressed(const char* pressed,TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Load dark state texture for slider ball. + * + * @param disabled dark state texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadSlidBallTextureDisabled(const char* disabled,TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Load dark state texture for slider progress bar. + * + * @param fileName file path of texture. + * + * @param texType @see UI_TEX_TYPE_LOCAL + */ + void loadProgressBarTexture(const char* fileName, TextureResType texType = UI_TEX_TYPE_LOCAL); + + /** + * Changes the progress direction of slider. + * + * @param percent percent value from 1 to 100. + */ + void setPercent(int percent); + + /** + * Gets the progress direction of slider. + * + * @return percent percent value from 1 to 100. + */ + int getPercent(); + + /** + * Add call back function called when slider's percent has changed to slider. + */ + void addEventListenerSlider(CCObject* target,SEL_SlidPercentChangedEvent selector); + + virtual bool onTouchBegan(CCTouch *touch, CCEvent *unused_event); + virtual void onTouchMoved(CCTouch *touch, CCEvent *unused_event); + virtual void onTouchEnded(CCTouch *touch, CCEvent *unused_event); + virtual void onTouchCancelled(CCTouch *touch, CCEvent *unused_event); + + //override "getContentSize" method of widget. + virtual const CCSize& getContentSize() const; + + //override "getVirtualRenderer" method of widget. + virtual CCNode* getVirtualRenderer(); + + //override "ignoreContentAdaptWithSize" method of widget. + virtual void ignoreContentAdaptWithSize(bool ignore); + + /** + * Returns the "class name" of widget. + */ + virtual std::string getDescription() const; + +protected: + virtual bool init(); + virtual void initRenderer(); + float getPercentWithBallPos(float location); + void percentChangedEvent(); + virtual void onPressStateChangedToNormal(); + virtual void onPressStateChangedToPressed(); + virtual void onPressStateChangedToDisabled(); + virtual void onSizeChanged(); + virtual void updateTextureColor(); + virtual void updateTextureOpacity(); + virtual void updateTextureRGBA(); + void barRendererScaleChangedWithSize(); + void progressBarRendererScaleChangedWithSize(); + virtual Widget* createCloneInstance(); + virtual void copySpecialProperties(Widget* model); +protected: + CCNode* _barRenderer; + CCNode* _progressBarRenderer; + CCSize _progressBarTextureSize; + + CCSprite* _slidBallNormalRenderer; + CCSprite* _slidBallPressedRenderer; + CCSprite* _slidBallDisabledRenderer; + CCNode* _slidBallRenderer; + + float _barLength; + int _percent; + + bool _scale9Enabled; + bool _prevIgnoreSize; + std::string _textureFile; + std::string _progressBarTextureFile; + std::string _slidBallNormalTextureFile; + std::string _slidBallPressedTextureFile; + std::string _slidBallDisabledTextureFile; + + CCRect _capInsetsBarRenderer; + CCRect _capInsetsProgressBarRenderer; + + CCObject* _sliderEventListener; + SEL_SlidPercentChangedEvent _sliderEventSelector; + TextureResType _barTexType; + TextureResType _progressBarTexType; + TextureResType _ballNTexType; + TextureResType _ballPTexType; + TextureResType _ballDTexType; +}; + +} +NS_CC_END + +#endif /* defined(__CocoGUI__Slider__) */ diff --git a/include/extensions/CocoStudio/GUI/UIWidgets/UITextField.h b/include/extensions/CocoStudio/GUI/UIWidgets/UITextField.h new file mode 100644 index 0000000..d2c0c90 --- /dev/null +++ b/include/extensions/CocoStudio/GUI/UIWidgets/UITextField.h @@ -0,0 +1,195 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +#ifndef __UITEXTFIELD_H__ +#define __UITEXTFIELD_H__ + +#include "../BaseClasses/UIWidget.h" + +NS_CC_BEGIN + +namespace ui { + +/** + * @js NA + * @lua NA + */ +class UICCTextField: public CCTextFieldTTF, public CCTextFieldDelegate +{ +public: + UICCTextField(); + ~UICCTextField(); + + virtual void onEnter(); + + // static + static UICCTextField* create(const char *placeholder, const char *fontName, float fontSize); + + // CCTextFieldDelegate + virtual bool onTextFieldAttachWithIME(CCTextFieldTTF *pSender); + virtual bool onTextFieldDetachWithIME(CCTextFieldTTF * pSender); + virtual bool onTextFieldInsertText(CCTextFieldTTF * pSender, const char * text, int nLen); + virtual bool onTextFieldDeleteBackward(CCTextFieldTTF * pSender, const char * delText, int nLen); + + void insertText(const char* text, int len); + void deleteBackward(); + + void openIME(); + void closeIME(); + + void setMaxLengthEnabled(bool enable); + bool isMaxLengthEnabled(); + void setMaxLength(int length); + int getMaxLength(); + int getCharCount(); + void setPasswordEnabled(bool enable); + bool isPasswordEnabled(); + void setPasswordStyleText(const char* styleText); + void setPasswordText(const char* text); + void setAttachWithIME(bool attach); + bool getAttachWithIME(); + void setDetachWithIME(bool detach); + bool getDetachWithIME(); + void setInsertText(bool insert); + bool getInsertText(); + void setDeleteBackward(bool deleteBackward); + bool getDeleteBackward(); +protected: + bool _maxLengthEnabled; + int _maxLength; + bool _passwordEnabled; + std::string _passwordStyleText; + bool _attachWithIME; + bool _detachWithIME; + bool _insertText; + bool _deleteBackward; +}; + +typedef enum +{ + TEXTFIELD_EVENT_ATTACH_WITH_IME, + TEXTFIELD_EVENT_DETACH_WITH_IME, + TEXTFIELD_EVENT_INSERT_TEXT, + TEXTFIELD_EVENT_DELETE_BACKWARD, +}TextFiledEventType; + +typedef void (CCObject::*SEL_TextFieldEvent)(CCObject*, TextFiledEventType); +#define textfieldeventselector(_SELECTOR) (SEL_TextFieldEvent)(&_SELECTOR) + +/** class UITextField : public Widget +* @js NA +* @lua NA +*/ +class TextField : public Widget +{ + + DECLARE_CLASS_GUI_INFO + +public: + TextField(); + virtual ~TextField(); + static TextField* create(); + void setTouchSize(const CCSize &size); + CCSize getTouchSize(); + void setTouchAreaEnabled(bool enable); + virtual bool hitTest(const CCPoint &pt); + void setText(const std::string& text); + void setPlaceHolder(const std::string& value); + const char* getPlaceHolder(); + void setFontSize(int size); + int getFontSize(); + void setFontName(const std::string& name); + const char* getFontName(); + virtual void didNotSelectSelf(); + const char* getStringValue(); + virtual bool onTouchBegan(CCTouch *touch, CCEvent *unused_event); + void setMaxLengthEnabled(bool enable); + bool isMaxLengthEnabled(); + void setMaxLength(int length); + int getMaxLength(); + void setPasswordEnabled(bool enable); + bool isPasswordEnabled(); + void setPasswordStyleText(const char* styleText); + const char* getPasswordStyleText(); + virtual void update(float dt); + bool getAttachWithIME(); + void setAttachWithIME(bool attach); + bool getDetachWithIME(); + void setDetachWithIME(bool detach); + bool getInsertText(); + void setInsertText(bool insertText); + bool getDeleteBackward(); + void setDeleteBackward(bool deleteBackward); + void addEventListenerTextField(CCObject* target, SEL_TextFieldEvent selecor); + + virtual void setAnchorPoint(const CCPoint &pt); + + /** + * Returns the "class name" of widget. + */ + virtual std::string getDescription() const; + + virtual const CCSize& getContentSize() const; + virtual CCNode* getVirtualRenderer(); + void attachWithIME(); + virtual void onEnter(); + + void setTextAreaSize(const CCSize &size); + void setTextHorizontalAlignment(CCTextAlignment alignment); + void setTextVerticalAlignment(CCVerticalTextAlignment alignment); + /*=*/ + +protected: + virtual bool init(); + virtual void initRenderer(); + // event + void attachWithIMEEvent(); + void detachWithIMEEvent(); + void insertTextEvent(); + void deleteBackwardEvent(); + virtual void onSizeChanged(); + virtual void updateTextureColor(); + virtual void updateTextureOpacity(); + virtual void updateTextureRGBA(); + void textfieldRendererScaleChangedWithSize(); + virtual Widget* createCloneInstance(); + virtual void copySpecialProperties(Widget* model); +protected: + UICCTextField* _textFieldRenderer; + + float _touchWidth; + float _touchHeight; + bool _useTouchArea; + + CCObject* _textFieldEventListener; + SEL_TextFieldEvent _textFieldEventSelector; + + std::string _passwordStyleText; +}; + +} + +NS_CC_END + +#endif /* defined(__TextField__) */ diff --git a/include/extensions/CocoStudio/Json/DictionaryHelper.h b/include/extensions/CocoStudio/Json/DictionaryHelper.h new file mode 100644 index 0000000..6fd94f8 --- /dev/null +++ b/include/extensions/CocoStudio/Json/DictionaryHelper.h @@ -0,0 +1,81 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +#ifndef __DICTIONARYHELPER_H__ +#define __DICTIONARYHELPER_H__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" +#include "rapidjson/document.h" + +#define DICTOOL DictionaryHelper::shareHelper() + +NS_CC_EXT_BEGIN +/** +* @js NA +* @lua NA +*/ +class DictionaryHelper +{ +public: + DictionaryHelper(); + ~DictionaryHelper(); + static DictionaryHelper* shareHelper(); + static void purgeDictionaryHelper(); + cocos2d::CCDictionary* getSubDictionary(cocos2d::CCDictionary* root,const char* key); + int getIntValue(cocos2d::CCDictionary* root,const char* key); + float getFloatValue(cocos2d::CCDictionary* root,const char* key); + const char* getStringValue(cocos2d::CCDictionary* root,const char* key); + bool getBooleanValue(cocos2d::CCDictionary* root,const char* key); + cocos2d::CCArray* getArrayValue(cocos2d::CCDictionary* root,const char* key); + cocos2d::CCObject* checkObjectExist(cocos2d::CCDictionary* root,const char* key); + int objectToIntValue(cocos2d::CCObject* obj); + float objectToFloatValue(cocos2d::CCObject* obj); + const char* objectToStringValue(cocos2d::CCObject* obj); + bool objectToBooleanValue(cocos2d::CCObject* obj); + cocos2d::CCArray* objectToCCArray(cocos2d::CCObject* obj); + + const rapidjson::Value& getSubDictionary_json(const rapidjson::Value &root, const char* key); + const rapidjson::Value& getSubDictionary_json(const rapidjson::Value &root, const char* key, int idx); + const rapidjson::Value& getSubDictionary_json(const rapidjson::Value &root, int idx); + + int getIntValue_json(const rapidjson::Value& root, const char* key, int def = 0); + float getFloatValue_json(const rapidjson::Value& root,const char* key, float def = 0.0f); + bool getBooleanValue_json(const rapidjson::Value& root,const char* key, bool def = false); + const char* getStringValue_json(const rapidjson::Value& root,const char* key, const char *def = NULL); + int getArrayCount_json(const rapidjson::Value& root,const char* key, int def = 0); + + int getIntValueFromArray_json(const rapidjson::Value& root,const char* arrayKey,int idx, int def = 0); + float getFloatValueFromArray_json(const rapidjson::Value& root,const char* arrayKey,int idx, float def = 0.0f); + bool getBoolValueFromArray_json(const rapidjson::Value& root,const char* arrayKey,int idx, bool def = false); + const char* getStringValueFromArray_json(const rapidjson::Value& root,const char* arrayKey,int idx, const char *def = NULL); + const rapidjson::Value &getDictionaryFromArray_json(const rapidjson::Value &root, const char* key,int idx); + bool checkObjectExist_json(const rapidjson::Value &root); + bool checkObjectExist_json(const rapidjson::Value &root, const char* key); + bool checkObjectExist_json(const rapidjson::Value &root, int index); +}; + +NS_CC_EXT_END + +#endif /* defined(__CocoGUI__DictionaryHelper__) */ diff --git a/include/extensions/CocoStudio/Json/rapidjson/document.h b/include/extensions/CocoStudio/Json/rapidjson/document.h new file mode 100644 index 0000000..c70e618 --- /dev/null +++ b/include/extensions/CocoStudio/Json/rapidjson/document.h @@ -0,0 +1,821 @@ +#ifndef RAPIDJSON_DOCUMENT_H_ +#define RAPIDJSON_DOCUMENT_H_ + +#include "reader.h" +#include "internal/strfunc.h" +#include // placement new + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4127) // conditional expression is constant +#endif + +namespace rapidjson { + +/////////////////////////////////////////////////////////////////////////////// +// GenericValue + +//! Represents a JSON value. Use Value for UTF8 encoding and default allocator. +/*! + A JSON value can be one of 7 types. This class is a variant type supporting + these types. + + Use the Value if UTF8 and default allocator + + \tparam Encoding Encoding of the value. (Even non-string values need to have the same encoding in a document) + \tparam Allocator Allocator type for allocating memory of object, array and string. +*/ +#pragma pack (push, 4) +template > +class GenericValue { +public: + //! Name-value pair in an object. + struct Member { + GenericValue name; //!< name of member (must be a string) + GenericValue value; //!< value of member. + }; + + typedef Encoding EncodingType; //!< Encoding type from template parameter. + typedef Allocator AllocatorType; //!< Allocator type from template parameter. + typedef typename Encoding::Ch Ch; //!< Character type derived from Encoding. + typedef Member* MemberIterator; //!< Member iterator for iterating in object. + typedef const Member* ConstMemberIterator; //!< Constant member iterator for iterating in object. + typedef GenericValue* ValueIterator; //!< Value iterator for iterating in array. + typedef const GenericValue* ConstValueIterator; //!< Constant value iterator for iterating in array. + + //!@name Constructors and destructor. + //@{ + + //! Default constructor creates a null value. + GenericValue() : flags_(kNullFlag) {} + + //! Copy constructor is not permitted. +private: + GenericValue(const GenericValue& rhs); + +public: + + //! Constructor with JSON value type. + /*! This creates a Value of specified type with default content. + \param type Type of the value. + \note Default content for number is zero. + */ + GenericValue(Type type) { + static const unsigned defaultFlags[7] = { + kNullFlag, kFalseFlag, kTrueFlag, kObjectFlag, kArrayFlag, kConstStringFlag, + kNumberFlag | kIntFlag | kUintFlag | kInt64Flag | kUint64Flag | kDoubleFlag + }; + RAPIDJSON_ASSERT(type <= kNumberType); + flags_ = defaultFlags[type]; + memset(&data_, 0, sizeof(data_)); + } + + //! Constructor for boolean value. + GenericValue(bool b) : flags_(b ? kTrueFlag : kFalseFlag) {} + + //! Constructor for int value. + GenericValue(int i) : flags_(kNumberIntFlag) { + data_.n.i64 = i; + if (i >= 0) + flags_ |= kUintFlag | kUint64Flag; + } + + //! Constructor for unsigned value. + GenericValue(unsigned u) : flags_(kNumberUintFlag) { + data_.n.u64 = u; + if (!(u & 0x80000000)) + flags_ |= kIntFlag | kInt64Flag; + } + + //! Constructor for int64_t value. + GenericValue(int64_t i64) : flags_(kNumberInt64Flag) { + data_.n.i64 = i64; + if (i64 >= 0) { + flags_ |= kNumberUint64Flag; + if (!(i64 & 0xFFFFFFFF00000000LL)) + flags_ |= kUintFlag; + if (!(i64 & 0xFFFFFFFF80000000LL)) + flags_ |= kIntFlag; + } + else if (i64 >= -2147483648LL) + flags_ |= kIntFlag; + } + + //! Constructor for uint64_t value. + GenericValue(uint64_t u64) : flags_(kNumberUint64Flag) { + data_.n.u64 = u64; + if (!(u64 & 0x8000000000000000ULL)) + flags_ |= kInt64Flag; + if (!(u64 & 0xFFFFFFFF00000000ULL)) + flags_ |= kUintFlag; + if (!(u64 & 0xFFFFFFFF80000000ULL)) + flags_ |= kIntFlag; + } + + //! Constructor for double value. + GenericValue(double d) : flags_(kNumberDoubleFlag) { data_.n.d = d; } + + //! Constructor for constant string (i.e. do not make a copy of string) + GenericValue(const Ch* s, SizeType length) { + RAPIDJSON_ASSERT(s != NULL); + flags_ = kConstStringFlag; + data_.s.str = s; + data_.s.length = length; + } + + //! Constructor for constant string (i.e. do not make a copy of string) + GenericValue(const Ch* s) { SetStringRaw(s, internal::StrLen(s)); } + + //! Constructor for copy-string (i.e. do make a copy of string) + GenericValue(const Ch* s, SizeType length, Allocator& allocator) { SetStringRaw(s, length, allocator); } + + //! Constructor for copy-string (i.e. do make a copy of string) + GenericValue(const Ch*s, Allocator& allocator) { SetStringRaw(s, internal::StrLen(s), allocator); } + + //! Destructor. + /*! Need to destruct elements of array, members of object, or copy-string. + */ + ~GenericValue() { + if (Allocator::kNeedFree) { // Shortcut by Allocator's trait + switch(flags_) { + case kArrayFlag: + for (GenericValue* v = data_.a.elements; v != data_.a.elements + data_.a.size; ++v) + v->~GenericValue(); + Allocator::Free(data_.a.elements); + break; + + case kObjectFlag: + for (Member* m = data_.o.members; m != data_.o.members + data_.o.size; ++m) { + m->name.~GenericValue(); + m->value.~GenericValue(); + } + Allocator::Free(data_.o.members); + break; + + case kCopyStringFlag: + Allocator::Free(const_cast(data_.s.str)); + break; + } + } + } + + //@} + + //!@name Assignment operators + //@{ + + //! Assignment with move semantics. + /*! \param rhs Source of the assignment. It will become a null value after assignment. + */ + GenericValue& operator=(GenericValue& rhs) { + RAPIDJSON_ASSERT(this != &rhs); + this->~GenericValue(); + memcpy(this, &rhs, sizeof(GenericValue)); + rhs.flags_ = kNullFlag; + return *this; + } + + //! Assignment with primitive types. + /*! \tparam T Either Type, int, unsigned, int64_t, uint64_t, const Ch* + \param value The value to be assigned. + */ + template + GenericValue& operator=(T value) { + this->~GenericValue(); + new (this) GenericValue(value); + return *this; + } + //@} + + //!@name Type + //@{ + + Type GetType() const { return static_cast(flags_ & kTypeMask); } + bool IsNull() const { return flags_ == kNullFlag; } + bool IsFalse() const { return flags_ == kFalseFlag; } + bool IsTrue() const { return flags_ == kTrueFlag; } + bool IsBool() const { return (flags_ & kBoolFlag) != 0; } + bool IsObject() const { return flags_ == kObjectFlag; } + bool IsArray() const { return flags_ == kArrayFlag; } + bool IsNumber() const { return (flags_ & kNumberFlag) != 0; } + bool IsInt() const { return (flags_ & kIntFlag) != 0; } + bool IsUint() const { return (flags_ & kUintFlag) != 0; } + bool IsInt64() const { return (flags_ & kInt64Flag) != 0; } + bool IsUint64() const { return (flags_ & kUint64Flag) != 0; } + bool IsDouble() const { return (flags_ & kDoubleFlag) != 0; } + bool IsString() const { return (flags_ & kStringFlag) != 0; } + + //@} + + //!@name Null + //@{ + + GenericValue& SetNull() { this->~GenericValue(); new (this) GenericValue(); return *this; } + + //@} + + //!@name Bool + //@{ + + bool GetBool() const { RAPIDJSON_ASSERT(IsBool()); return flags_ == kTrueFlag; } + GenericValue& SetBool(bool b) { this->~GenericValue(); new (this) GenericValue(b); return *this; } + + //@} + + //!@name Object + //@{ + + //! Set this value as an empty object. + GenericValue& SetObject() { this->~GenericValue(); new (this) GenericValue(kObjectType); return *this; } + + //! Get the value associated with the object's name. + GenericValue& operator[](const Ch* name) { + if (Member* member = FindMember(name)) + return member->value; + else { + static GenericValue NullValue; + return NullValue; + } + } + const GenericValue& operator[](const Ch* name) const { return const_cast(*this)[name]; } + + //! Member iterators. + ConstMemberIterator MemberonBegin() const { RAPIDJSON_ASSERT(IsObject()); return data_.o.members; } + ConstMemberIterator MemberonEnd() const { RAPIDJSON_ASSERT(IsObject()); return data_.o.members + data_.o.size; } + MemberIterator MemberonBegin() { RAPIDJSON_ASSERT(IsObject()); return data_.o.members; } + MemberIterator MemberonEnd() { RAPIDJSON_ASSERT(IsObject()); return data_.o.members + data_.o.size; } + + //! Check whether a member exists in the object. + bool HasMember(const Ch* name) const { return FindMember(name) != 0; } + + //! Add a member (name-value pair) to the object. + /*! \param name A string value as name of member. + \param value Value of any type. + \param allocator Allocator for reallocating memory. + \return The value itself for fluent API. + \note The ownership of name and value will be transfered to this object if success. + */ + GenericValue& AddMember(GenericValue& name, GenericValue& value, Allocator& allocator) { + RAPIDJSON_ASSERT(IsObject()); + RAPIDJSON_ASSERT(name.IsString()); + Object& o = data_.o; + if (o.size >= o.capacity) { + if (o.capacity == 0) { + o.capacity = kDefaultObjectCapacity; + o.members = (Member*)allocator.Malloc(o.capacity * sizeof(Member)); + } + else { + SizeType oldCapacity = o.capacity; + o.capacity *= 2; + o.members = (Member*)allocator.Realloc(o.members, oldCapacity * sizeof(Member), o.capacity * sizeof(Member)); + } + } + o.members[o.size].name.RawAssign(name); + o.members[o.size].value.RawAssign(value); + o.size++; + return *this; + } + + GenericValue& AddMember(const Ch* name, Allocator& nameAllocator, GenericValue& value, Allocator& allocator) { + GenericValue n(name, internal::StrLen(name), nameAllocator); + return AddMember(n, value, allocator); + } + + GenericValue& AddMember(const Ch* name, GenericValue& value, Allocator& allocator) { + GenericValue n(name, internal::StrLen(name)); + return AddMember(n, value, allocator); + } + + template + GenericValue& AddMember(const Ch* name, T value, Allocator& allocator) { + GenericValue n(name, internal::StrLen(name)); + GenericValue v(value); + return AddMember(n, v, allocator); + } + + //! Remove a member in object by its name. + /*! \param name Name of member to be removed. + \return Whether the member existed. + \note Removing member is implemented by moving the last member. So the ordering of members is changed. + */ + bool RemoveMember(const Ch* name) { + RAPIDJSON_ASSERT(IsObject()); + if (Member* m = FindMember(name)) { + RAPIDJSON_ASSERT(data_.o.size > 0); + RAPIDJSON_ASSERT(data_.o.members != 0); + + Member* last = data_.o.members + (data_.o.size - 1); + if (data_.o.size > 1 && m != last) { + // Move the last one to this place + m->name = last->name; + m->value = last->value; + } + else { + // Only one left, just destroy + m->name.~GenericValue(); + m->value.~GenericValue(); + } + --data_.o.size; + return true; + } + return false; + } + + //@} + + //!@name Array + //@{ + + //! Set this value as an empty array. + GenericValue& SetArray() { this->~GenericValue(); new (this) GenericValue(kArrayType); return *this; } + + //! Get the number of elements in array. + SizeType Size() const { RAPIDJSON_ASSERT(IsArray()); return data_.a.size; } + + //! Get the capacity of array. + SizeType Capacity() const { RAPIDJSON_ASSERT(IsArray()); return data_.a.capacity; } + + //! Check whether the array is empty. + bool Empty() const { RAPIDJSON_ASSERT(IsArray()); return data_.a.size == 0; } + + //! Remove all elements in the array. + /*! This function do not deallocate memory in the array, i.e. the capacity is unchanged. + */ + void Clear() { + RAPIDJSON_ASSERT(IsArray()); + for (SizeType i = 0; i < data_.a.size; ++i) + data_.a.elements[i].~GenericValue(); + data_.a.size = 0; + } + + //! Get an element from array by index. + /*! \param index Zero-based index of element. + \note +\code +Value a(kArrayType); +a.PushBack(123); +int x = a[0].GetInt(); // Error: operator[ is ambiguous, as 0 also mean a null pointer of const char* type. +int y = a[SizeType(0)].GetInt(); // Cast to SizeType will work. +int z = a[0u].GetInt(); // This works too. +\endcode + */ + GenericValue& operator[](SizeType index) { + RAPIDJSON_ASSERT(IsArray()); + RAPIDJSON_ASSERT(index < data_.a.size); + return data_.a.elements[index]; + } + const GenericValue& operator[](SizeType index) const { return const_cast(*this)[index]; } + + //! Element iterator + ValueIterator onBegin() { RAPIDJSON_ASSERT(IsArray()); return data_.a.elements; } + ValueIterator onEnd() { RAPIDJSON_ASSERT(IsArray()); return data_.a.elements + data_.a.size; } + ConstValueIterator onBegin() const { return const_cast(*this).onBegin(); } + ConstValueIterator onEnd() const { return const_cast(*this).onEnd(); } + + //! Request the array to have enough capacity to store elements. + /*! \param newCapacity The capacity that the array at least need to have. + \param allocator The allocator for allocating memory. It must be the same one use previously. + \return The value itself for fluent API. + */ + GenericValue& Reserve(SizeType newCapacity, Allocator &allocator) { + RAPIDJSON_ASSERT(IsArray()); + if (newCapacity > data_.a.capacity) { + data_.a.elements = (GenericValue*)allocator.Realloc(data_.a.elements, data_.a.capacity * sizeof(GenericValue), newCapacity * sizeof(GenericValue)); + data_.a.capacity = newCapacity; + } + return *this; + } + + //! Append a value at the end of the array. + /*! \param value The value to be appended. + \param allocator The allocator for allocating memory. It must be the same one use previously. + \return The value itself for fluent API. + \note The ownership of the value will be transfered to this object if success. + \note If the number of elements to be appended is known, calls Reserve() once first may be more efficient. + */ + GenericValue& PushBack(GenericValue& value, Allocator& allocator) { + RAPIDJSON_ASSERT(IsArray()); + if (data_.a.size >= data_.a.capacity) + Reserve(data_.a.capacity == 0 ? kDefaultArrayCapacity : data_.a.capacity * 2, allocator); + data_.a.elements[data_.a.size++].RawAssign(value); + return *this; + } + + template + GenericValue& PushBack(T value, Allocator& allocator) { + GenericValue v(value); + return PushBack(v, allocator); + } + + //! Remove the last element in the array. + GenericValue& PopBack() { + RAPIDJSON_ASSERT(IsArray()); + RAPIDJSON_ASSERT(!Empty()); + data_.a.elements[--data_.a.size].~GenericValue(); + return *this; + } + //@} + + //!@name Number + //@{ + + int GetInt() const { RAPIDJSON_ASSERT(flags_ & kIntFlag); return data_.n.i.i; } + unsigned GetUint() const { RAPIDJSON_ASSERT(flags_ & kUintFlag); return data_.n.u.u; } + int64_t GetInt64() const { RAPIDJSON_ASSERT(flags_ & kInt64Flag); return data_.n.i64; } + uint64_t GetUint64() const { RAPIDJSON_ASSERT(flags_ & kUint64Flag); return data_.n.u64; } + + double GetDouble() const { + RAPIDJSON_ASSERT(IsNumber()); + if ((flags_ & kDoubleFlag) != 0) return data_.n.d; // exact type, no conversion. + if ((flags_ & kIntFlag) != 0) return data_.n.i.i; // int -> double + if ((flags_ & kUintFlag) != 0) return data_.n.u.u; // unsigned -> double + if ((flags_ & kInt64Flag) != 0) return (double)data_.n.i64; // int64_t -> double (may lose precision) + RAPIDJSON_ASSERT((flags_ & kUint64Flag) != 0); return (double)data_.n.u64; // uint64_t -> double (may lose precision) + } + + GenericValue& SetInt(int i) { this->~GenericValue(); new (this) GenericValue(i); return *this; } + GenericValue& SetUint(unsigned u) { this->~GenericValue(); new (this) GenericValue(u); return *this; } + GenericValue& SetInt64(int64_t i64) { this->~GenericValue(); new (this) GenericValue(i64); return *this; } + GenericValue& SetUint64(uint64_t u64) { this->~GenericValue(); new (this) GenericValue(u64); return *this; } + GenericValue& SetDouble(double d) { this->~GenericValue(); new (this) GenericValue(d); return *this; } + + //@} + + //!@name String + //@{ + + const Ch* GetString() const { RAPIDJSON_ASSERT(IsString()); return data_.s.str; } + + //! Get the length of string. + /*! Since rapidjson permits "\u0000" in the json string, strlen(v.GetString()) may not equal to v.GetStringLength(). + */ + SizeType GetStringLength() const { RAPIDJSON_ASSERT(IsString()); return data_.s.length; } + + //! Set this value as a string without copying source string. + /*! This version has better performance with supplied length, and also support string containing null character. + \param s source string pointer. + \param length The length of source string, excluding the trailing null terminator. + \return The value itself for fluent API. + */ + GenericValue& SetString(const Ch* s, SizeType length) { this->~GenericValue(); SetStringRaw(s, length); return *this; } + + //! Set this value as a string without copying source string. + /*! \param s source string pointer. + \return The value itself for fluent API. + */ + GenericValue& SetString(const Ch* s) { return SetString(s, internal::StrLen(s)); } + + //! Set this value as a string by copying from source string. + /*! This version has better performance with supplied length, and also support string containing null character. + \param s source string. + \param length The length of source string, excluding the trailing null terminator. + \param allocator Allocator for allocating copied buffer. Commonly use document.GetAllocator(). + \return The value itself for fluent API. + */ + GenericValue& SetString(const Ch* s, SizeType length, Allocator& allocator) { this->~GenericValue(); SetStringRaw(s, length, allocator); return *this; } + + //! Set this value as a string by copying from source string. + /*! \param s source string. + \param allocator Allocator for allocating copied buffer. Commonly use document.GetAllocator(). + \return The value itself for fluent API. + */ + GenericValue& SetString(const Ch* s, Allocator& allocator) { SetString(s, internal::StrLen(s), allocator); return *this; } + + //@} + + //! Generate events of this value to a Handler. + /*! This function adopts the GoF visitor pattern. + Typical usage is to output this JSON value as JSON text via Writer, which is a Handler. + It can also be used to deep clone this value via GenericDocument, which is also a Handler. + \tparam Handler type of handler. + \param handler An object implementing concept Handler. + */ + template + const GenericValue& Accept(Handler& handler) const { + switch(GetType()) { + case kNullType: handler.Null(); break; + case kFalseType: handler.Bool(false); break; + case kTrueType: handler.Bool(true); break; + + case kObjectType: + handler.StartObject(); + for (Member* m = data_.o.members; m != data_.o.members + data_.o.size; ++m) { + handler.String(m->name.data_.s.str, m->name.data_.s.length, false); + m->value.Accept(handler); + } + handler.EndObject(data_.o.size); + break; + + case kArrayType: + handler.StartArray(); + for (GenericValue* v = data_.a.elements; v != data_.a.elements + data_.a.size; ++v) + v->Accept(handler); + handler.EndArray(data_.a.size); + break; + + case kStringType: + handler.String(data_.s.str, data_.s.length, false); + break; + + case kNumberType: + if (IsInt()) handler.Int(data_.n.i.i); + else if (IsUint()) handler.Uint(data_.n.u.u); + else if (IsInt64()) handler.Int64(data_.n.i64); + else if (IsUint64()) handler.Uint64(data_.n.u64); + else handler.Double(data_.n.d); + break; + } + return *this; + } + +private: + template + friend class GenericDocument; + + enum { + kBoolFlag = 0x100, + kNumberFlag = 0x200, + kIntFlag = 0x400, + kUintFlag = 0x800, + kInt64Flag = 0x1000, + kUint64Flag = 0x2000, + kDoubleFlag = 0x4000, + kStringFlag = 0x100000, + kCopyFlag = 0x200000, + + // Initial flags of different types. + kNullFlag = kNullType, + kTrueFlag = kTrueType | kBoolFlag, + kFalseFlag = kFalseType | kBoolFlag, + kNumberIntFlag = kNumberType | kNumberFlag | kIntFlag | kInt64Flag, + kNumberUintFlag = kNumberType | kNumberFlag | kUintFlag | kUint64Flag | kInt64Flag, + kNumberInt64Flag = kNumberType | kNumberFlag | kInt64Flag, + kNumberUint64Flag = kNumberType | kNumberFlag | kUint64Flag, + kNumberDoubleFlag = kNumberType | kNumberFlag | kDoubleFlag, + kConstStringFlag = kStringType | kStringFlag, + kCopyStringFlag = kStringType | kStringFlag | kCopyFlag, + kObjectFlag = kObjectType, + kArrayFlag = kArrayType, + + kTypeMask = 0xFF // bitwise-and with mask of 0xFF can be optimized by compiler + }; + + static const SizeType kDefaultArrayCapacity = 16; + static const SizeType kDefaultObjectCapacity = 16; + + struct String { + const Ch* str; + SizeType length; + unsigned hashcode; //!< reserved + }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode + + // By using proper binary layout, retrieval of different integer types do not need conversions. + union Number { +#if RAPIDJSON_ENDIAN == RAPIDJSON_LITTLEENDIAN + struct I { + int i; + char padding[4]; + }i; + struct U { + unsigned u; + char padding2[4]; + }u; +#else + struct I { + char padding[4]; + int i; + }i; + struct U { + char padding2[4]; + unsigned u; + }u; +#endif + int64_t i64; + uint64_t u64; + double d; + }; // 8 bytes + + struct Object { + Member* members; + SizeType size; + SizeType capacity; + }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode + + struct Array { + GenericValue* elements; + SizeType size; + SizeType capacity; + }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode + + union Data { + String s; + Number n; + Object o; + Array a; + }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode + + //! Find member by name. + Member* FindMember(const Ch* name) { + RAPIDJSON_ASSERT(name); + RAPIDJSON_ASSERT(IsObject()); + + SizeType length = internal::StrLen(name); + + Object& o = data_.o; + for (Member* member = o.members; member != data_.o.members + data_.o.size; ++member) + if (length == member->name.data_.s.length && memcmp(member->name.data_.s.str, name, length * sizeof(Ch)) == 0) + return member; + + return 0; + } + const Member* FindMember(const Ch* name) const { return const_cast(*this).FindMember(name); } + + // Initialize this value as array with initial data, without calling destructor. + void SetArrayRaw(GenericValue* values, SizeType count, Allocator& alloctaor) { + flags_ = kArrayFlag; + data_.a.elements = (GenericValue*)alloctaor.Malloc(count * sizeof(GenericValue)); + memcpy(data_.a.elements, values, count * sizeof(GenericValue)); + data_.a.size = data_.a.capacity = count; + } + + //! Initialize this value as object with initial data, without calling destructor. + void SetObjectRaw(Member* members, SizeType count, Allocator& alloctaor) { + flags_ = kObjectFlag; + data_.o.members = (Member*)alloctaor.Malloc(count * sizeof(Member)); + memcpy(data_.o.members, members, count * sizeof(Member)); + data_.o.size = data_.o.capacity = count; + } + + //! Initialize this value as constant string, without calling destructor. + void SetStringRaw(const Ch* s, SizeType length) { + RAPIDJSON_ASSERT(s != NULL); + flags_ = kConstStringFlag; + data_.s.str = s; + data_.s.length = length; + } + + //! Initialize this value as copy string with initial data, without calling destructor. + void SetStringRaw(const Ch* s, SizeType length, Allocator& allocator) { + RAPIDJSON_ASSERT(s != NULL); + flags_ = kCopyStringFlag; + data_.s.str = (Ch *)allocator.Malloc((length + 1) * sizeof(Ch)); + data_.s.length = length; + memcpy(const_cast(data_.s.str), s, length * sizeof(Ch)); + const_cast(data_.s.str)[length] = '\0'; + } + + //! Assignment without calling destructor + void RawAssign(GenericValue& rhs) { + memcpy(this, &rhs, sizeof(GenericValue)); + rhs.flags_ = kNullFlag; + } + + Data data_; + unsigned flags_; +}; +#pragma pack (pop) + +//! Value with UTF8 encoding. +typedef GenericValue > Value; + +/////////////////////////////////////////////////////////////////////////////// +// GenericDocument + +//! A document for parsing JSON text as DOM. +/*! + \implements Handler + \tparam Encoding encoding for both parsing and string storage. + \tparam Alloactor allocator for allocating memory for the DOM, and the stack during parsing. +*/ +template > +class GenericDocument : public GenericValue { +public: + typedef typename Encoding::Ch Ch; //!< Character type derived from Encoding. + typedef GenericValue ValueType; //!< Value type of the document. + typedef Allocator AllocatorType; //!< Allocator type from template parameter. + + //! Constructor + /*! \param allocator Optional allocator for allocating stack memory. + \param stackCapacity Initial capacity of stack in bytes. + */ + GenericDocument(Allocator* allocator = 0, size_t stackCapacity = kDefaultStackCapacity) : stack_(allocator, stackCapacity), parseError_(0), errorOffset_(0) {} + + //! Parse JSON text from an input stream. + /*! \tparam parseFlags Combination of ParseFlag. + \param stream Input stream to be parsed. + \return The document itself for fluent API. + */ + template + GenericDocument& ParseStream(Stream& stream) { + ValueType::SetNull(); // Remove existing root if exist + GenericReader reader; + if (reader.template Parse(stream, *this)) { + RAPIDJSON_ASSERT(stack_.GetSize() == sizeof(ValueType)); // Got one and only one root object + this->RawAssign(*stack_.template Pop(1)); // Add this-> to prevent issue 13. + parseError_ = 0; + errorOffset_ = 0; + } + else { + parseError_ = reader.GetParseError(); + errorOffset_ = reader.GetErrorOffset(); + ClearStack(); + } + return *this; + } + + //! Parse JSON text from a mutable string. + /*! \tparam parseFlags Combination of ParseFlag. + \param str Mutable zero-terminated string to be parsed. + \return The document itself for fluent API. + */ + template + GenericDocument& ParseInsitu(Ch* str) { + GenericInsituStringStream s(str); + return ParseStream(s); + } + + //! Parse JSON text from a read-only string. + /*! \tparam parseFlags Combination of ParseFlag (must not contain kParseInsituFlag). + \param str Read-only zero-terminated string to be parsed. + */ + template + GenericDocument& Parse(const Ch* str) { + RAPIDJSON_ASSERT(!(parseFlags & kParseInsituFlag)); + GenericStringStream s(str); + return ParseStream(s); + } + + //! Whether a parse error was occured in the last parsing. + bool HasParseError() const { return parseError_ != 0; } + + //! Get the message of parsing error. + const char* GetParseError() const { return parseError_; } + + //! Get the offset in character of the parsing error. + size_t GetErrorOffset() const { return errorOffset_; } + + //! Get the allocator of this document. + Allocator& GetAllocator() { return stack_.GetAllocator(); } + + //! Get the capacity of stack in bytes. + size_t GetStackCapacity() const { return stack_.GetCapacity(); } + +private: + // Prohibit assignment + GenericDocument& operator=(const GenericDocument&); + + friend class GenericReader; // for Reader to call the following private handler functions + + // Implementation of Handler + void Null() { new (stack_.template Push()) ValueType(); } + void Bool(bool b) { new (stack_.template Push()) ValueType(b); } + void Int(int i) { new (stack_.template Push()) ValueType(i); } + void Uint(unsigned i) { new (stack_.template Push()) ValueType(i); } + void Int64(int64_t i) { new (stack_.template Push()) ValueType(i); } + void Uint64(uint64_t i) { new (stack_.template Push()) ValueType(i); } + void Double(double d) { new (stack_.template Push()) ValueType(d); } + + void String(const Ch* str, SizeType length, bool copy) { + if (copy) + new (stack_.template Push()) ValueType(str, length, GetAllocator()); + else + new (stack_.template Push()) ValueType(str, length); + } + + void StartObject() { new (stack_.template Push()) ValueType(kObjectType); } + + void EndObject(SizeType memberCount) { + typename ValueType::Member* members = stack_.template Pop(memberCount); + stack_.template Top()->SetObjectRaw(members, (SizeType)memberCount, GetAllocator()); + } + + void StartArray() { new (stack_.template Push()) ValueType(kArrayType); } + + void EndArray(SizeType elementCount) { + ValueType* elements = stack_.template Pop(elementCount); + stack_.template Top()->SetArrayRaw(elements, elementCount, GetAllocator()); + } + + void ClearStack() { + if (Allocator::kNeedFree) + while (stack_.GetSize() > 0) // Here assumes all elements in stack array are GenericValue (Member is actually 2 GenericValue objects) + (stack_.template Pop(1))->~ValueType(); + else + stack_.Clear(); + } + + static const size_t kDefaultStackCapacity = 1024; + internal::Stack stack_; + const char* parseError_; + size_t errorOffset_; +}; + +typedef GenericDocument > Document; + +} // namespace rapidjson + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +#endif // RAPIDJSON_DOCUMENT_H_ diff --git a/include/extensions/CocoStudio/Json/rapidjson/filestream.h b/include/extensions/CocoStudio/Json/rapidjson/filestream.h new file mode 100644 index 0000000..8858949 --- /dev/null +++ b/include/extensions/CocoStudio/Json/rapidjson/filestream.h @@ -0,0 +1,46 @@ +#ifndef RAPIDJSON_FILESTREAM_H_ +#define RAPIDJSON_FILESTREAM_H_ + +#include + +namespace rapidjson { + +//! Wrapper of C file stream for input or output. +/*! + This simple wrapper does not check the validity of the stream. + \implements Stream +*/ +class FileStream { +public: + typedef char Ch; //!< Character type. Only support char. + + FileStream(FILE* fp) : fp_(fp), count_(0) { Read(); } + char Peek() const { return current_; } + char Take() { char c = current_; Read(); return c; } + size_t Tell() const { return count_; } + void Put(char c) { fputc(c, fp_); } + + // Not implemented + char* PutBegin() { return 0; } + size_t PutEnd(char*) { return 0; } + +private: + void Read() { + RAPIDJSON_ASSERT(fp_ != 0); + int c = fgetc(fp_); + if (c != EOF) { + current_ = (char)c; + count_++; + } + else + current_ = '\0'; + } + + FILE* fp_; + char current_; + size_t count_; +}; + +} // namespace rapidjson + +#endif // RAPIDJSON_FILESTREAM_H_ diff --git a/include/extensions/CocoStudio/Json/rapidjson/internal/pow10.h b/include/extensions/CocoStudio/Json/rapidjson/internal/pow10.h new file mode 100644 index 0000000..bf3a9af --- /dev/null +++ b/include/extensions/CocoStudio/Json/rapidjson/internal/pow10.h @@ -0,0 +1,54 @@ +#ifndef RAPIDJSON_POW10_ +#define RAPIDJSON_POW10_ + +namespace rapidjson { +namespace internal { + +//! Computes integer powers of 10 in double (10.0^n). +/*! This function uses lookup table for fast and accurate results. + \param n positive/negative exponent. Must <= 308. + \return 10.0^n +*/ +inline double Pow10(int n) { + static const double e[] = { // 1e-308...1e308: 617 * 8 bytes = 4936 bytes + 1e-308,1e-307,1e-306,1e-305,1e-304,1e-303,1e-302,1e-301,1e-300, + 1e-299,1e-298,1e-297,1e-296,1e-295,1e-294,1e-293,1e-292,1e-291,1e-290,1e-289,1e-288,1e-287,1e-286,1e-285,1e-284,1e-283,1e-282,1e-281,1e-280, + 1e-279,1e-278,1e-277,1e-276,1e-275,1e-274,1e-273,1e-272,1e-271,1e-270,1e-269,1e-268,1e-267,1e-266,1e-265,1e-264,1e-263,1e-262,1e-261,1e-260, + 1e-259,1e-258,1e-257,1e-256,1e-255,1e-254,1e-253,1e-252,1e-251,1e-250,1e-249,1e-248,1e-247,1e-246,1e-245,1e-244,1e-243,1e-242,1e-241,1e-240, + 1e-239,1e-238,1e-237,1e-236,1e-235,1e-234,1e-233,1e-232,1e-231,1e-230,1e-229,1e-228,1e-227,1e-226,1e-225,1e-224,1e-223,1e-222,1e-221,1e-220, + 1e-219,1e-218,1e-217,1e-216,1e-215,1e-214,1e-213,1e-212,1e-211,1e-210,1e-209,1e-208,1e-207,1e-206,1e-205,1e-204,1e-203,1e-202,1e-201,1e-200, + 1e-199,1e-198,1e-197,1e-196,1e-195,1e-194,1e-193,1e-192,1e-191,1e-190,1e-189,1e-188,1e-187,1e-186,1e-185,1e-184,1e-183,1e-182,1e-181,1e-180, + 1e-179,1e-178,1e-177,1e-176,1e-175,1e-174,1e-173,1e-172,1e-171,1e-170,1e-169,1e-168,1e-167,1e-166,1e-165,1e-164,1e-163,1e-162,1e-161,1e-160, + 1e-159,1e-158,1e-157,1e-156,1e-155,1e-154,1e-153,1e-152,1e-151,1e-150,1e-149,1e-148,1e-147,1e-146,1e-145,1e-144,1e-143,1e-142,1e-141,1e-140, + 1e-139,1e-138,1e-137,1e-136,1e-135,1e-134,1e-133,1e-132,1e-131,1e-130,1e-129,1e-128,1e-127,1e-126,1e-125,1e-124,1e-123,1e-122,1e-121,1e-120, + 1e-119,1e-118,1e-117,1e-116,1e-115,1e-114,1e-113,1e-112,1e-111,1e-110,1e-109,1e-108,1e-107,1e-106,1e-105,1e-104,1e-103,1e-102,1e-101,1e-100, + 1e-99, 1e-98, 1e-97, 1e-96, 1e-95, 1e-94, 1e-93, 1e-92, 1e-91, 1e-90, 1e-89, 1e-88, 1e-87, 1e-86, 1e-85, 1e-84, 1e-83, 1e-82, 1e-81, 1e-80, + 1e-79, 1e-78, 1e-77, 1e-76, 1e-75, 1e-74, 1e-73, 1e-72, 1e-71, 1e-70, 1e-69, 1e-68, 1e-67, 1e-66, 1e-65, 1e-64, 1e-63, 1e-62, 1e-61, 1e-60, + 1e-59, 1e-58, 1e-57, 1e-56, 1e-55, 1e-54, 1e-53, 1e-52, 1e-51, 1e-50, 1e-49, 1e-48, 1e-47, 1e-46, 1e-45, 1e-44, 1e-43, 1e-42, 1e-41, 1e-40, + 1e-39, 1e-38, 1e-37, 1e-36, 1e-35, 1e-34, 1e-33, 1e-32, 1e-31, 1e-30, 1e-29, 1e-28, 1e-27, 1e-26, 1e-25, 1e-24, 1e-23, 1e-22, 1e-21, 1e-20, + 1e-19, 1e-18, 1e-17, 1e-16, 1e-15, 1e-14, 1e-13, 1e-12, 1e-11, 1e-10, 1e-9, 1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1e+0, + 1e+1, 1e+2, 1e+3, 1e+4, 1e+5, 1e+6, 1e+7, 1e+8, 1e+9, 1e+10, 1e+11, 1e+12, 1e+13, 1e+14, 1e+15, 1e+16, 1e+17, 1e+18, 1e+19, 1e+20, + 1e+21, 1e+22, 1e+23, 1e+24, 1e+25, 1e+26, 1e+27, 1e+28, 1e+29, 1e+30, 1e+31, 1e+32, 1e+33, 1e+34, 1e+35, 1e+36, 1e+37, 1e+38, 1e+39, 1e+40, + 1e+41, 1e+42, 1e+43, 1e+44, 1e+45, 1e+46, 1e+47, 1e+48, 1e+49, 1e+50, 1e+51, 1e+52, 1e+53, 1e+54, 1e+55, 1e+56, 1e+57, 1e+58, 1e+59, 1e+60, + 1e+61, 1e+62, 1e+63, 1e+64, 1e+65, 1e+66, 1e+67, 1e+68, 1e+69, 1e+70, 1e+71, 1e+72, 1e+73, 1e+74, 1e+75, 1e+76, 1e+77, 1e+78, 1e+79, 1e+80, + 1e+81, 1e+82, 1e+83, 1e+84, 1e+85, 1e+86, 1e+87, 1e+88, 1e+89, 1e+90, 1e+91, 1e+92, 1e+93, 1e+94, 1e+95, 1e+96, 1e+97, 1e+98, 1e+99, 1e+100, + 1e+101,1e+102,1e+103,1e+104,1e+105,1e+106,1e+107,1e+108,1e+109,1e+110,1e+111,1e+112,1e+113,1e+114,1e+115,1e+116,1e+117,1e+118,1e+119,1e+120, + 1e+121,1e+122,1e+123,1e+124,1e+125,1e+126,1e+127,1e+128,1e+129,1e+130,1e+131,1e+132,1e+133,1e+134,1e+135,1e+136,1e+137,1e+138,1e+139,1e+140, + 1e+141,1e+142,1e+143,1e+144,1e+145,1e+146,1e+147,1e+148,1e+149,1e+150,1e+151,1e+152,1e+153,1e+154,1e+155,1e+156,1e+157,1e+158,1e+159,1e+160, + 1e+161,1e+162,1e+163,1e+164,1e+165,1e+166,1e+167,1e+168,1e+169,1e+170,1e+171,1e+172,1e+173,1e+174,1e+175,1e+176,1e+177,1e+178,1e+179,1e+180, + 1e+181,1e+182,1e+183,1e+184,1e+185,1e+186,1e+187,1e+188,1e+189,1e+190,1e+191,1e+192,1e+193,1e+194,1e+195,1e+196,1e+197,1e+198,1e+199,1e+200, + 1e+201,1e+202,1e+203,1e+204,1e+205,1e+206,1e+207,1e+208,1e+209,1e+210,1e+211,1e+212,1e+213,1e+214,1e+215,1e+216,1e+217,1e+218,1e+219,1e+220, + 1e+221,1e+222,1e+223,1e+224,1e+225,1e+226,1e+227,1e+228,1e+229,1e+230,1e+231,1e+232,1e+233,1e+234,1e+235,1e+236,1e+237,1e+238,1e+239,1e+240, + 1e+241,1e+242,1e+243,1e+244,1e+245,1e+246,1e+247,1e+248,1e+249,1e+250,1e+251,1e+252,1e+253,1e+254,1e+255,1e+256,1e+257,1e+258,1e+259,1e+260, + 1e+261,1e+262,1e+263,1e+264,1e+265,1e+266,1e+267,1e+268,1e+269,1e+270,1e+271,1e+272,1e+273,1e+274,1e+275,1e+276,1e+277,1e+278,1e+279,1e+280, + 1e+281,1e+282,1e+283,1e+284,1e+285,1e+286,1e+287,1e+288,1e+289,1e+290,1e+291,1e+292,1e+293,1e+294,1e+295,1e+296,1e+297,1e+298,1e+299,1e+300, + 1e+301,1e+302,1e+303,1e+304,1e+305,1e+306,1e+307,1e+308 + }; + RAPIDJSON_ASSERT(n <= 308); + return n < -308 ? 0.0 : e[n + 308]; +} + +} // namespace internal +} // namespace rapidjson + +#endif // RAPIDJSON_POW10_ diff --git a/include/extensions/CocoStudio/Json/rapidjson/internal/stack.h b/include/extensions/CocoStudio/Json/rapidjson/internal/stack.h new file mode 100644 index 0000000..966893b --- /dev/null +++ b/include/extensions/CocoStudio/Json/rapidjson/internal/stack.h @@ -0,0 +1,82 @@ +#ifndef RAPIDJSON_INTERNAL_STACK_H_ +#define RAPIDJSON_INTERNAL_STACK_H_ + +namespace rapidjson { +namespace internal { + +/////////////////////////////////////////////////////////////////////////////// +// Stack + +//! A type-unsafe stack for storing different types of data. +/*! \tparam Allocator Allocator for allocating stack memory. +*/ +template +class Stack { +public: + Stack(Allocator* allocator, size_t stack_capacity) : allocator_(allocator), own_allocator_(0), stack_(0), stack_top_(0), stack_end_(0), stack_capacity_(stack_capacity) { + RAPIDJSON_ASSERT(stack_capacity_ > 0); + if (!allocator_) + own_allocator_ = allocator_ = new Allocator(); + stack_top_ = stack_ = (char*)allocator_->Malloc(stack_capacity_); + stack_end_ = stack_ + stack_capacity_; + } + + ~Stack() { + Allocator::Free(stack_); + delete own_allocator_; // Only delete if it is owned by the stack + } + + void Clear() { /*stack_top_ = 0;*/ stack_top_ = stack_; } + + template + T* Push(size_t count = 1) { + // Expand the stack if needed + if (stack_top_ + sizeof(T) * count >= stack_end_) { + size_t new_capacity = stack_capacity_ * 2; + size_t size = GetSize(); + size_t new_size = GetSize() + sizeof(T) * count; + if (new_capacity < new_size) + new_capacity = new_size; + stack_ = (char*)allocator_->Realloc(stack_, stack_capacity_, new_capacity); + stack_capacity_ = new_capacity; + stack_top_ = stack_ + size; + stack_end_ = stack_ + stack_capacity_; + } + T* ret = (T*)stack_top_; + stack_top_ += sizeof(T) * count; + return ret; + } + + template + T* Pop(size_t count) { + RAPIDJSON_ASSERT(GetSize() >= count * sizeof(T)); + stack_top_ -= count * sizeof(T); + return (T*)stack_top_; + } + + template + T* Top() { + RAPIDJSON_ASSERT(GetSize() >= sizeof(T)); + return (T*)(stack_top_ - sizeof(T)); + } + + template + T* Bottom() { return (T*)stack_; } + + Allocator& GetAllocator() { return *allocator_; } + size_t GetSize() const { return stack_top_ - stack_; } + size_t GetCapacity() const { return stack_capacity_; } + +private: + Allocator* allocator_; + Allocator* own_allocator_; + char *stack_; + char *stack_top_; + char *stack_end_; + size_t stack_capacity_; +}; + +} // namespace internal +} // namespace rapidjson + +#endif // RAPIDJSON_STACK_H_ diff --git a/include/extensions/CocoStudio/Json/rapidjson/internal/strfunc.h b/include/extensions/CocoStudio/Json/rapidjson/internal/strfunc.h new file mode 100644 index 0000000..bbf444f --- /dev/null +++ b/include/extensions/CocoStudio/Json/rapidjson/internal/strfunc.h @@ -0,0 +1,24 @@ +#ifndef RAPIDJSON_INTERNAL_STRFUNC_H_ +#define RAPIDJSON_INTERNAL_STRFUNC_H_ + +namespace rapidjson { +namespace internal { + +//! Custom strlen() which works on different character types. +/*! \tparam Ch Character type (e.g. char, wchar_t, short) + \param s Null-terminated input string. + \return Number of characters in the string. + \note This has the same semantics as strlen(), the return value is not number of Unicode codepoints. +*/ +template +inline SizeType StrLen(const Ch* s) { + const Ch* p = s; + while (*p != '\0') + ++p; + return SizeType(p - s); +} + +} // namespace internal +} // namespace rapidjson + +#endif // RAPIDJSON_INTERNAL_STRFUNC_H_ diff --git a/include/extensions/CocoStudio/Json/rapidjson/prettywriter.h b/include/extensions/CocoStudio/Json/rapidjson/prettywriter.h new file mode 100644 index 0000000..238ff5f --- /dev/null +++ b/include/extensions/CocoStudio/Json/rapidjson/prettywriter.h @@ -0,0 +1,156 @@ +#ifndef RAPIDJSON_PRETTYWRITER_H_ +#define RAPIDJSON_PRETTYWRITER_H_ + +#include "writer.h" + +namespace rapidjson { + +//! Writer with indentation and spacing. +/*! + \tparam Stream Type of ouptut stream. + \tparam Encoding Encoding of both source strings and output. + \tparam Allocator Type of allocator for allocating memory of stack. +*/ +template, typename Allocator = MemoryPoolAllocator<> > +class PrettyWriter : public Writer { +public: + typedef Writer Base; + typedef typename Base::Ch Ch; + + //! Constructor + /*! \param stream Output stream. + \param allocator User supplied allocator. If it is null, it will create a private one. + \param levelDepth Initial capacity of + */ + PrettyWriter(Stream& stream, Allocator* allocator = 0, size_t levelDepth = Base::kDefaultLevelDepth) : + Base(stream, allocator, levelDepth), indentChar_(' '), indentCharCount_(4) {} + + //! Set custom indentation. + /*! \param indentChar Character for indentation. Must be whitespace character (' ', '\t', '\n', '\r'). + \param indentCharCount Number of indent characters for each indentation level. + \note The default indentation is 4 spaces. + */ + PrettyWriter& SetIndent(Ch indentChar, unsigned indentCharCount) { + RAPIDJSON_ASSERT(indentChar == ' ' || indentChar == '\t' || indentChar == '\n' || indentChar == '\r'); + indentChar_ = indentChar; + indentCharCount_ = indentCharCount; + return *this; + } + + //@name Implementation of Handler. + //@{ + + PrettyWriter& Null() { PrettyPrefix(kNullType); Base::WriteNull(); return *this; } + PrettyWriter& Bool(bool b) { PrettyPrefix(b ? kTrueType : kFalseType); Base::WriteBool(b); return *this; } + PrettyWriter& Int(int i) { PrettyPrefix(kNumberType); Base::WriteInt(i); return *this; } + PrettyWriter& Uint(unsigned u) { PrettyPrefix(kNumberType); Base::WriteUint(u); return *this; } + PrettyWriter& Int64(int64_t i64) { PrettyPrefix(kNumberType); Base::WriteInt64(i64); return *this; } + PrettyWriter& Uint64(uint64_t u64) { PrettyPrefix(kNumberType); Base::WriteUint64(u64); return *this; } + PrettyWriter& Double(double d) { PrettyPrefix(kNumberType); Base::WriteDouble(d); return *this; } + + PrettyWriter& String(const Ch* str, SizeType length, bool copy = false) { + (void)copy; + PrettyPrefix(kStringType); + Base::WriteString(str, length); + return *this; + } + + PrettyWriter& StartObject() { + PrettyPrefix(kObjectType); + new (Base::level_stack_.template Push()) typename Base::Level(false); + Base::WriteStartObject(); + return *this; + } + + PrettyWriter& EndObject(SizeType memberCount = 0) { + (void)memberCount; + RAPIDJSON_ASSERT(Base::level_stack_.GetSize() >= sizeof(typename Base::Level)); + RAPIDJSON_ASSERT(!Base::level_stack_.template Top()->inArray); + bool empty = Base::level_stack_.template Pop(1)->valueCount == 0; + + if (!empty) { + Base::stream_.Put('\n'); + WriteIndent(); + } + Base::WriteEndObject(); + return *this; + } + + PrettyWriter& StartArray() { + PrettyPrefix(kArrayType); + new (Base::level_stack_.template Push()) typename Base::Level(true); + Base::WriteStartArray(); + return *this; + } + + PrettyWriter& EndArray(SizeType memberCount = 0) { + (void)memberCount; + RAPIDJSON_ASSERT(Base::level_stack_.GetSize() >= sizeof(typename Base::Level)); + RAPIDJSON_ASSERT(Base::level_stack_.template Top()->inArray); + bool empty = Base::level_stack_.template Pop(1)->valueCount == 0; + + if (!empty) { + Base::stream_.Put('\n'); + WriteIndent(); + } + Base::WriteEndArray(); + return *this; + } + + //@} + + //! Simpler but slower overload. + PrettyWriter& String(const Ch* str) { return String(str, internal::StrLen(str)); } + +protected: + void PrettyPrefix(Type type) { + (void)type; + if (Base::level_stack_.GetSize() != 0) { // this value is not at root + typename Base::Level* level = Base::level_stack_.template Top(); + + if (level->inArray) { + if (level->valueCount > 0) { + Base::stream_.Put(','); // add comma if it is not the first element in array + Base::stream_.Put('\n'); + } + else + Base::stream_.Put('\n'); + WriteIndent(); + } + else { // in object + if (level->valueCount > 0) { + if (level->valueCount % 2 == 0) { + Base::stream_.Put(','); + Base::stream_.Put('\n'); + } + else { + Base::stream_.Put(':'); + Base::stream_.Put(' '); + } + } + else + Base::stream_.Put('\n'); + + if (level->valueCount % 2 == 0) + WriteIndent(); + } + if (!level->inArray && level->valueCount % 2 == 0) + RAPIDJSON_ASSERT(type == kStringType); // if it's in object, then even number should be a name + level->valueCount++; + } + else + RAPIDJSON_ASSERT(type == kObjectType || type == kArrayType); + } + + void WriteIndent() { + size_t count = (Base::level_stack_.GetSize() / sizeof(typename Base::Level)) * indentCharCount_; + PutN(Base::stream_, indentChar_, count); + } + + Ch indentChar_; + unsigned indentCharCount_; +}; + +} // namespace rapidjson + +#endif // RAPIDJSON_RAPIDJSON_H_ diff --git a/include/extensions/CocoStudio/Json/rapidjson/rapidjson.h b/include/extensions/CocoStudio/Json/rapidjson/rapidjson.h new file mode 100644 index 0000000..7acb2aa --- /dev/null +++ b/include/extensions/CocoStudio/Json/rapidjson/rapidjson.h @@ -0,0 +1,525 @@ +#ifndef RAPIDJSON_RAPIDJSON_H_ +#define RAPIDJSON_RAPIDJSON_H_ + +// Copyright (c) 2011-2012 Milo Yip (miloyip@gmail.com) +// Version 0.11 + +#include // malloc(), realloc(), free() +#include // memcpy() + +/////////////////////////////////////////////////////////////////////////////// +// RAPIDJSON_NO_INT64DEFINE + +// Here defines int64_t and uint64_t types in global namespace. +// If user have their own definition, can define RAPIDJSON_NO_INT64DEFINE to disable this. +#ifndef RAPIDJSON_NO_INT64DEFINE +#ifdef _MSC_VER +typedef __int64 int64_t; +typedef unsigned __int64 uint64_t; +#else +#include +#endif +#endif // RAPIDJSON_NO_INT64TYPEDEF + +/////////////////////////////////////////////////////////////////////////////// +// RAPIDJSON_ENDIAN +#define RAPIDJSON_LITTLEENDIAN 0 //!< Little endian machine +#define RAPIDJSON_BIGENDIAN 1 //!< Big endian machine + +//! Endianness of the machine. +/*! GCC provided macro for detecting endianness of the target machine. But other + compilers may not have this. User can define RAPIDJSON_ENDIAN to either + RAPIDJSON_LITTLEENDIAN or RAPIDJSON_BIGENDIAN. +*/ +#ifndef RAPIDJSON_ENDIAN +#ifdef __BYTE_ORDER__ +#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ +#define RAPIDJSON_ENDIAN RAPIDJSON_LITTLEENDIAN +#else +#define RAPIDJSON_ENDIAN RAPIDJSON_BIGENDIAN +#endif // __BYTE_ORDER__ +#else +#define RAPIDJSON_ENDIAN RAPIDJSON_LITTLEENDIAN // Assumes little endian otherwise. +#endif +#endif // RAPIDJSON_ENDIAN + +/////////////////////////////////////////////////////////////////////////////// +// RAPIDJSON_SSE2/RAPIDJSON_SSE42/RAPIDJSON_SIMD + +// Enable SSE2 optimization. +//#define RAPIDJSON_SSE2 + +// Enable SSE4.2 optimization. +//#define RAPIDJSON_SSE42 + +#if defined(RAPIDJSON_SSE2) || defined(RAPIDJSON_SSE42) +#define RAPIDJSON_SIMD +#endif + +/////////////////////////////////////////////////////////////////////////////// +// RAPIDJSON_NO_SIZETYPEDEFINE + +#ifndef RAPIDJSON_NO_SIZETYPEDEFINE +namespace rapidjson { +//! Use 32-bit array/string indices even for 64-bit platform, instead of using size_t. +/*! User may override the SizeType by defining RAPIDJSON_NO_SIZETYPEDEFINE. +*/ +typedef unsigned SizeType; +} // namespace rapidjson +#endif + +/////////////////////////////////////////////////////////////////////////////// +// RAPIDJSON_ASSERT + +//! Assertion. +/*! By default, rapidjson uses C assert() for assertion. + User can override it by defining RAPIDJSON_ASSERT(x) macro. +*/ +#ifndef RAPIDJSON_ASSERT +#include +#define RAPIDJSON_ASSERT(x) assert(x) +#endif // RAPIDJSON_ASSERT + +/////////////////////////////////////////////////////////////////////////////// +// Helpers + +#define RAPIDJSON_MULTILINEMACRO_BEGIN do { +#define RAPIDJSON_MULTILINEMACRO_END \ +} while((void)0, 0) + +namespace rapidjson { + +/////////////////////////////////////////////////////////////////////////////// +// Allocator + +/*! \class rapidjson::Allocator + \brief Concept for allocating, resizing and freeing memory block. + + Note that Malloc() and Realloc() are non-static but Free() is static. + + So if an allocator need to support Free(), it needs to put its pointer in + the header of memory block. + +\code +concept Allocator { + static const bool kNeedFree; //!< Whether this allocator needs to call Free(). + + // Allocate a memory block. + // \param size of the memory block in bytes. + // \returns pointer to the memory block. + void* Malloc(size_t size); + + // Resize a memory block. + // \param originalPtr The pointer to current memory block. Null pointer is permitted. + // \param originalSize The current size in bytes. (Design issue: since some allocator may not book-keep this, explicitly pass to it can save memory.) + // \param newSize the new size in bytes. + void* Realloc(void* originalPtr, size_t originalSize, size_t newSize); + + // Free a memory block. + // \param pointer to the memory block. Null pointer is permitted. + static void Free(void *ptr); +}; +\endcode +*/ + +/////////////////////////////////////////////////////////////////////////////// +// CrtAllocator + +//! C-runtime library allocator. +/*! This class is just wrapper for standard C library memory routines. + \implements Allocator +*/ +class CrtAllocator { +public: + static const bool kNeedFree = true; + void* Malloc(size_t size) { return malloc(size); } + void* Realloc(void* originalPtr, size_t originalSize, size_t newSize) { (void)originalSize; return realloc(originalPtr, newSize); } + static void Free(void *ptr) { free(ptr); } +}; + +/////////////////////////////////////////////////////////////////////////////// +// MemoryPoolAllocator + +//! Default memory allocator used by the parser and DOM. +/*! This allocator allocate memory blocks from pre-allocated memory chunks. + + It does not free memory blocks. And Realloc() only allocate new memory. + + The memory chunks are allocated by BaseAllocator, which is CrtAllocator by default. + + User may also supply a buffer as the first chunk. + + If the user-buffer is full then additional chunks are allocated by BaseAllocator. + + The user-buffer is not deallocated by this allocator. + + \tparam BaseAllocator the allocator type for allocating memory chunks. Default is CrtAllocator. + \implements Allocator +*/ +template +class MemoryPoolAllocator { +public: + static const bool kNeedFree = false; //!< Tell users that no need to call Free() with this allocator. (concept Allocator) + + //! Constructor with chunkSize. + /*! \param chunkSize The size of memory chunk. The default is kDefaultChunkSize. + \param baseAllocator The allocator for allocating memory chunks. + */ + MemoryPoolAllocator(size_t chunkSize = kDefaultChunkCapacity, BaseAllocator* baseAllocator = 0) : + chunkHead_(0), chunk_capacity_(chunkSize), userBuffer_(0), baseAllocator_(baseAllocator), ownBaseAllocator_(0) + { + if (!baseAllocator_) + ownBaseAllocator_ = baseAllocator_ = new BaseAllocator(); + AddChunk(chunk_capacity_); + } + + //! Constructor with user-supplied buffer. + /*! The user buffer will be used firstly. When it is full, memory pool allocates new chunk with chunk size. + + The user buffer will not be deallocated when this allocator is destructed. + + \param buffer User supplied buffer. + \param size Size of the buffer in bytes. It must at least larger than sizeof(ChunkHeader). + \param chunkSize The size of memory chunk. The default is kDefaultChunkSize. + \param baseAllocator The allocator for allocating memory chunks. + */ + MemoryPoolAllocator(char *buffer, size_t size, size_t chunkSize = kDefaultChunkCapacity, BaseAllocator* baseAllocator = 0) : + chunkHead_(0), chunk_capacity_(chunkSize), userBuffer_(buffer), baseAllocator_(baseAllocator), ownBaseAllocator_(0) + { + RAPIDJSON_ASSERT(buffer != 0); + RAPIDJSON_ASSERT(size > sizeof(ChunkHeader)); + chunkHead_ = (ChunkHeader*)buffer; + chunkHead_->capacity = size - sizeof(ChunkHeader); + chunkHead_->size = 0; + chunkHead_->next = 0; + } + + //! Destructor. + /*! This deallocates all memory chunks, excluding the user-supplied buffer. + */ + ~MemoryPoolAllocator() { + Clear(); + delete ownBaseAllocator_; + } + + //! Deallocates all memory chunks, excluding the user-supplied buffer. + void Clear() { + while(chunkHead_ != 0 && chunkHead_ != (ChunkHeader *)userBuffer_) { + ChunkHeader* next = chunkHead_->next; + baseAllocator_->Free(chunkHead_); + chunkHead_ = next; + } + } + + //! Computes the total capacity of allocated memory chunks. + /*! \return total capacity in bytes. + */ + size_t Capacity() { + size_t capacity = 0; + for (ChunkHeader* c = chunkHead_; c != 0; c = c->next) + capacity += c->capacity; + return capacity; + } + + //! Computes the memory blocks allocated. + /*! \return total used bytes. + */ + size_t Size() { + size_t size = 0; + for (ChunkHeader* c = chunkHead_; c != 0; c = c->next) + size += c->size; + return size; + } + + //! Allocates a memory block. (concept Allocator) + void* Malloc(size_t size) { + size = (size + 3) & ~3; // Force aligning size to 4 + + if (chunkHead_->size + size > chunkHead_->capacity) + AddChunk(chunk_capacity_ > size ? chunk_capacity_ : size); + + char *buffer = (char *)(chunkHead_ + 1) + chunkHead_->size; + RAPIDJSON_ASSERT(((uintptr_t)buffer & 3) == 0); // returned buffer is aligned to 4 + chunkHead_->size += size; + + return buffer; + } + + //! Resizes a memory block (concept Allocator) + void* Realloc(void* originalPtr, size_t originalSize, size_t newSize) { + if (originalPtr == 0) + return Malloc(newSize); + + // Do not shrink if new size is smaller than original + if (originalSize >= newSize) + return originalPtr; + + // Simply expand it if it is the last allocation and there is sufficient space + if (originalPtr == (char *)(chunkHead_ + 1) + chunkHead_->size - originalSize) { + size_t increment = newSize - originalSize; + increment = (increment + 3) & ~3; // Force aligning size to 4 + if (chunkHead_->size + increment <= chunkHead_->capacity) { + chunkHead_->size += increment; + RAPIDJSON_ASSERT(((uintptr_t)originalPtr & 3) == 0); // returned buffer is aligned to 4 + return originalPtr; + } + } + + // Realloc process: allocate and copy memory, do not free original buffer. + void* newBuffer = Malloc(newSize); + RAPIDJSON_ASSERT(newBuffer != 0); // Do not handle out-of-memory explicitly. + return memcpy(newBuffer, originalPtr, originalSize); + } + + //! Frees a memory block (concept Allocator) + static void Free(void *) {} // Do nothing + +private: + //! Creates a new chunk. + /*! \param capacity Capacity of the chunk in bytes. + */ + void AddChunk(size_t capacity) { + ChunkHeader* chunk = (ChunkHeader*)baseAllocator_->Malloc(sizeof(ChunkHeader) + capacity); + chunk->capacity = capacity; + chunk->size = 0; + chunk->next = chunkHead_; + chunkHead_ = chunk; + } + + static const int kDefaultChunkCapacity = 64 * 1024; //!< Default chunk capacity. + + //! Chunk header for perpending to each chunk. + /*! Chunks are stored as a singly linked list. + */ + struct ChunkHeader { + size_t capacity; //!< Capacity of the chunk in bytes (excluding the header itself). + size_t size; //!< Current size of allocated memory in bytes. + ChunkHeader *next; //!< Next chunk in the linked list. + }; + + ChunkHeader *chunkHead_; //!< Head of the chunk linked-list. Only the head chunk serves allocation. + size_t chunk_capacity_; //!< The minimum capacity of chunk when they are allocated. + char *userBuffer_; //!< User supplied buffer. + BaseAllocator* baseAllocator_; //!< base allocator for allocating memory chunks. + BaseAllocator* ownBaseAllocator_; //!< base allocator created by this object. +}; + +/////////////////////////////////////////////////////////////////////////////// +// Encoding + +/*! \class rapidjson::Encoding + \brief Concept for encoding of Unicode characters. + +\code +concept Encoding { + typename Ch; //! Type of character. + + //! \brief Encode a Unicode codepoint to a buffer. + //! \param buffer pointer to destination buffer to store the result. It should have sufficient size of encoding one character. + //! \param codepoint An unicode codepoint, ranging from 0x0 to 0x10FFFF inclusively. + //! \returns the pointer to the next character after the encoded data. + static Ch* Encode(Ch *buffer, unsigned codepoint); +}; +\endcode +*/ + +/////////////////////////////////////////////////////////////////////////////// +// UTF8 + +//! UTF-8 encoding. +/*! http://en.wikipedia.org/wiki/UTF-8 + \tparam CharType Type for storing 8-bit UTF-8 data. Default is char. + \implements Encoding +*/ +template +struct UTF8 { + typedef CharType Ch; + + static Ch* Encode(Ch *buffer, unsigned codepoint) { + if (codepoint <= 0x7F) + *buffer++ = codepoint & 0xFF; + else if (codepoint <= 0x7FF) { + *buffer++ = 0xC0 | ((codepoint >> 6) & 0xFF); + *buffer++ = 0x80 | ((codepoint & 0x3F)); + } + else if (codepoint <= 0xFFFF) { + *buffer++ = 0xE0 | ((codepoint >> 12) & 0xFF); + *buffer++ = 0x80 | ((codepoint >> 6) & 0x3F); + *buffer++ = 0x80 | (codepoint & 0x3F); + } + else { + RAPIDJSON_ASSERT(codepoint <= 0x10FFFF); + *buffer++ = 0xF0 | ((codepoint >> 18) & 0xFF); + *buffer++ = 0x80 | ((codepoint >> 12) & 0x3F); + *buffer++ = 0x80 | ((codepoint >> 6) & 0x3F); + *buffer++ = 0x80 | (codepoint & 0x3F); + } + return buffer; + } +}; + +/////////////////////////////////////////////////////////////////////////////// +// UTF16 + +//! UTF-16 encoding. +/*! http://en.wikipedia.org/wiki/UTF-16 + \tparam CharType Type for storing 16-bit UTF-16 data. Default is wchar_t. C++11 may use char16_t instead. + \implements Encoding +*/ +template +struct UTF16 { + typedef CharType Ch; + + static Ch* Encode(Ch* buffer, unsigned codepoint) { + if (codepoint <= 0xFFFF) { + RAPIDJSON_ASSERT(codepoint < 0xD800 || codepoint > 0xDFFF); // Code point itself cannot be surrogate pair + *buffer++ = static_cast(codepoint); + } + else { + RAPIDJSON_ASSERT(codepoint <= 0x10FFFF); + unsigned v = codepoint - 0x10000; + *buffer++ = static_cast((v >> 10) + 0xD800); + *buffer++ = (v & 0x3FF) + 0xDC00; + } + return buffer; + } +}; + +/////////////////////////////////////////////////////////////////////////////// +// UTF32 + +//! UTF-32 encoding. +/*! http://en.wikipedia.org/wiki/UTF-32 + \tparam Ch Type for storing 32-bit UTF-32 data. Default is unsigned. C++11 may use char32_t instead. + \implements Encoding +*/ +template +struct UTF32 { + typedef CharType Ch; + + static Ch *Encode(Ch* buffer, unsigned codepoint) { + RAPIDJSON_ASSERT(codepoint <= 0x10FFFF); + *buffer++ = codepoint; + return buffer; + } +}; + +/////////////////////////////////////////////////////////////////////////////// +// Stream + +/*! \class rapidjson::Stream + \brief Concept for reading and writing characters. + + For read-only stream, no need to implement PutBegin(), Put() and PutEnd(). + + For write-only stream, only need to implement Put(). + +\code +concept Stream { + typename Ch; //!< Character type of the stream. + + //! Read the current character from stream without moving the read cursor. + Ch Peek() const; + + //! Read the current character from stream and moving the read cursor to next character. + Ch Take(); + + //! Get the current read cursor. + //! \return Number of characters read from start. + size_t Tell(); + + //! Begin writing operation at the current read pointer. + //! \return The begin writer pointer. + Ch* PutBegin(); + + //! Write a character. + void Put(Ch c); + + //! End the writing operation. + //! \param begin The begin write pointer returned by PutBegin(). + //! \return Number of characters written. + size_t PutEnd(Ch* begin); +} +\endcode +*/ + +//! Put N copies of a character to a stream. +template +inline void PutN(Stream& stream, Ch c, size_t n) { + for (size_t i = 0; i < n; i++) + stream.Put(c); +} + +/////////////////////////////////////////////////////////////////////////////// +// StringStream + +//! Read-only string stream. +/*! \implements Stream +*/ +template +struct GenericStringStream { + typedef typename Encoding::Ch Ch; + + GenericStringStream(const Ch *src) : src_(src), head_(src) {} + + Ch Peek() const { return *src_; } + Ch Take() { return *src_++; } + size_t Tell() const { return src_ - head_; } + + Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; } + void Put(Ch) { RAPIDJSON_ASSERT(false); } + size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; } + + const Ch* src_; //!< Current read position. + const Ch* head_; //!< Original head of the string. +}; + +typedef GenericStringStream > StringStream; + +/////////////////////////////////////////////////////////////////////////////// +// InsituStringStream + +//! A read-write string stream. +/*! This string stream is particularly designed for in-situ parsing. + \implements Stream +*/ +template +struct GenericInsituStringStream { + typedef typename Encoding::Ch Ch; + + GenericInsituStringStream(Ch *src) : src_(src), dst_(0), head_(src) {} + + // Read + Ch Peek() { return *src_; } + Ch Take() { return *src_++; } + size_t Tell() { return src_ - head_; } + + // Write + Ch* PutBegin() { return dst_ = src_; } + void Put(Ch c) { RAPIDJSON_ASSERT(dst_ != 0); *dst_++ = c; } + size_t PutEnd(Ch* begin) { return dst_ - begin; } + + Ch* src_; + Ch* dst_; + Ch* head_; +}; + +typedef GenericInsituStringStream > InsituStringStream; + +/////////////////////////////////////////////////////////////////////////////// +// Type + +//! Type of JSON value +enum Type { + kNullType = 0, //!< null + kFalseType = 1, //!< false + kTrueType = 2, //!< true + kObjectType = 3, //!< object + kArrayType = 4, //!< array + kStringType = 5, //!< string + kNumberType = 6, //!< number +}; + +} // namespace rapidjson + +#endif // RAPIDJSON_RAPIDJSON_H_ diff --git a/include/extensions/CocoStudio/Json/rapidjson/reader.h b/include/extensions/CocoStudio/Json/rapidjson/reader.h new file mode 100644 index 0000000..b87486b --- /dev/null +++ b/include/extensions/CocoStudio/Json/rapidjson/reader.h @@ -0,0 +1,683 @@ +#ifndef RAPIDJSON_READER_H_ +#define RAPIDJSON_READER_H_ + +// Copyright (c) 2011 Milo Yip (miloyip@gmail.com) +// Version 0.1 + +#include "rapidjson.h" +#include "internal/pow10.h" +#include "internal/stack.h" +#include + +#ifdef RAPIDJSON_SSE42 +#include +#elif defined(RAPIDJSON_SSE2) +#include +#endif + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4127) // conditional expression is constant +#endif + +#ifndef RAPIDJSON_PARSE_ERROR +#define RAPIDJSON_PARSE_ERROR(msg, offset) \ + RAPIDJSON_MULTILINEMACRO_BEGIN \ + parseError_ = msg; \ + errorOffset_ = offset; \ + longjmp(jmpbuf_, 1); \ + RAPIDJSON_MULTILINEMACRO_END +#endif + +namespace rapidjson { + +/////////////////////////////////////////////////////////////////////////////// +// ParseFlag + +//! Combination of parseFlags +enum ParseFlag { + kParseDefaultFlags = 0, //!< Default parse flags. Non-destructive parsing. Text strings are decoded into allocated buffer. + kParseInsituFlag = 1 //!< In-situ(destructive) parsing. +}; + +/////////////////////////////////////////////////////////////////////////////// +// Handler + +/*! \class rapidjson::Handler + \brief Concept for receiving events from GenericReader upon parsing. +\code +concept Handler { + typename Ch; + + void Null(); + void Bool(bool b); + void Int(int i); + void Uint(unsigned i); + void Int64(int64_t i); + void Uint64(uint64_t i); + void Double(double d); + void String(const Ch* str, SizeType length, bool copy); + void StartObject(); + void EndObject(SizeType memberCount); + void StartArray(); + void EndArray(SizeType elementCount); +}; +\endcode +*/ +/////////////////////////////////////////////////////////////////////////////// +// BaseReaderHandler + +//! Default implementation of Handler. +/*! This can be used as base class of any reader handler. + \implements Handler +*/ +template > +struct BaseReaderHandler { + typedef typename Encoding::Ch Ch; + + void Default() {} + void Null() { Default(); } + void Bool(bool) { Default(); } + void Int(int) { Default(); } + void Uint(unsigned) { Default(); } + void Int64(int64_t) { Default(); } + void Uint64(uint64_t) { Default(); } + void Double(double) { Default(); } + void String(const Ch*, SizeType, bool) { Default(); } + void StartObject() { Default(); } + void EndObject(SizeType) { Default(); } + void StartArray() { Default(); } + void EndArray(SizeType) { Default(); } +}; + +/////////////////////////////////////////////////////////////////////////////// +// SkipWhitespace + +//! Skip the JSON white spaces in a stream. +/*! \param stream A input stream for skipping white spaces. + \note This function has SSE2/SSE4.2 specialization. +*/ +template +void SkipWhitespace(Stream& stream) { + Stream s = stream; // Use a local copy for optimization + while (s.Peek() == ' ' || s.Peek() == '\n' || s.Peek() == '\r' || s.Peek() == '\t') + s.Take(); + stream = s; +} + +#ifdef RAPIDJSON_SSE42 +//! Skip whitespace with SSE 4.2 pcmpistrm instruction, testing 16 8-byte characters at once. +inline const char *SkipWhitespace_SIMD(const char* p) { + static const char whitespace[16] = " \n\r\t"; + __m128i w = _mm_loadu_si128((const __m128i *)&whitespace[0]); + + for (;;) { + __m128i s = _mm_loadu_si128((const __m128i *)p); + unsigned r = _mm_cvtsi128_si32(_mm_cmpistrm(w, s, _SIDD_UBYTE_OPS | _SIDD_CMP_EQUAL_ANY | _SIDD_BIT_MASK | _SIDD_NEGATIVE_POLARITY)); + if (r == 0) // all 16 characters are whitespace + p += 16; + else { // some of characters may be non-whitespace +#ifdef _MSC_VER // Find the index of first non-whitespace + unsigned long offset; + if (_BitScanForward(&offset, r)) + return p + offset; +#else + if (r != 0) + return p + __builtin_ffs(r) - 1; +#endif + } + } +} + +#elif defined(RAPIDJSON_SSE2) + +//! Skip whitespace with SSE2 instructions, testing 16 8-byte characters at once. +inline const char *SkipWhitespace_SIMD(const char* p) { + static const char whitespaces[4][17] = { + " ", + "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r", + "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"}; + + __m128i w0 = _mm_loadu_si128((const __m128i *)&whitespaces[0][0]); + __m128i w1 = _mm_loadu_si128((const __m128i *)&whitespaces[1][0]); + __m128i w2 = _mm_loadu_si128((const __m128i *)&whitespaces[2][0]); + __m128i w3 = _mm_loadu_si128((const __m128i *)&whitespaces[3][0]); + + for (;;) { + __m128i s = _mm_loadu_si128((const __m128i *)p); + __m128i x = _mm_cmpeq_epi8(s, w0); + x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w1)); + x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w2)); + x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w3)); + unsigned short r = ~_mm_movemask_epi8(x); + if (r == 0) // all 16 characters are whitespace + p += 16; + else { // some of characters may be non-whitespace +#ifdef _MSC_VER // Find the index of first non-whitespace + unsigned long offset; + if (_BitScanForward(&offset, r)) + return p + offset; +#else + if (r != 0) + return p + __builtin_ffs(r) - 1; +#endif + } + } +} + +#endif // RAPIDJSON_SSE2 + +#ifdef RAPIDJSON_SIMD +//! Template function specialization for InsituStringStream +template<> inline void SkipWhitespace(InsituStringStream& stream) { + stream.src_ = const_cast(SkipWhitespace_SIMD(stream.src_)); +} + +//! Template function specialization for StringStream +template<> inline void SkipWhitespace(StringStream& stream) { + stream.src_ = SkipWhitespace_SIMD(stream.src_); +} +#endif // RAPIDJSON_SIMD + +/////////////////////////////////////////////////////////////////////////////// +// GenericReader + +//! SAX-style JSON parser. Use Reader for UTF8 encoding and default allocator. +/*! GenericReader parses JSON text from a stream, and send events synchronously to an + object implementing Handler concept. + + It needs to allocate a stack for storing a single decoded string during + non-destructive parsing. + + For in-situ parsing, the decoded string is directly written to the source + text string, no temporary buffer is required. + + A GenericReader object can be reused for parsing multiple JSON text. + + \tparam Encoding Encoding of both the stream and the parse output. + \tparam Allocator Allocator type for stack. +*/ +template > +class GenericReader { +public: + typedef typename Encoding::Ch Ch; + + //! Constructor. + /*! \param allocator Optional allocator for allocating stack memory. (Only use for non-destructive parsing) + \param stackCapacity stack capacity in bytes for storing a single decoded string. (Only use for non-destructive parsing) + */ + GenericReader(Allocator* allocator = 0, size_t stackCapacity = kDefaultStackCapacity) : stack_(allocator, stackCapacity), parseError_(0), errorOffset_(0) {} + + //! Parse JSON text. + /*! \tparam parseFlags Combination of ParseFlag. + \tparam Stream Type of input stream. + \tparam Handler Type of handler which must implement Handler concept. + \param stream Input stream to be parsed. + \param handler The handler to receive events. + \return Whether the parsing is successful. + */ + template + bool Parse(Stream& stream, Handler& handler) { + parseError_ = 0; + errorOffset_ = 0; + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4611) // interaction between '_setjmp' and C++ object destruction is non-portable +#endif + if (setjmp(jmpbuf_)) { +#ifdef _MSC_VER +#pragma warning(pop) +#endif + stack_.Clear(); + return false; + } + + SkipWhitespace(stream); + + if (stream.Peek() == '\0') + RAPIDJSON_PARSE_ERROR("Text only contains white space(s)", stream.Tell()); + else { + switch (stream.Peek()) { + case '{': ParseObject(stream, handler); break; + case '[': ParseArray(stream, handler); break; + default: RAPIDJSON_PARSE_ERROR("Expect either an object or array at root", stream.Tell()); + } + SkipWhitespace(stream); + + if (stream.Peek() != '\0') + RAPIDJSON_PARSE_ERROR("Nothing should follow the root object or array.", stream.Tell()); + } + + return true; + } + + bool HasParseError() const { return parseError_ != 0; } + const char* GetParseError() const { return parseError_; } + size_t GetErrorOffset() const { return errorOffset_; } + +private: + // Parse object: { string : value, ... } + template + void ParseObject(Stream& stream, Handler& handler) { + RAPIDJSON_ASSERT(stream.Peek() == '{'); + stream.Take(); // Skip '{' + handler.StartObject(); + SkipWhitespace(stream); + + if (stream.Peek() == '}') { + stream.Take(); + handler.EndObject(0); // empty object + return; + } + + for (SizeType memberCount = 0;;) { + if (stream.Peek() != '"') { + RAPIDJSON_PARSE_ERROR("Name of an object member must be a string", stream.Tell()); + break; + } + + ParseString(stream, handler); + SkipWhitespace(stream); + + if (stream.Take() != ':') { + RAPIDJSON_PARSE_ERROR("There must be a colon after the name of object member", stream.Tell()); + break; + } + SkipWhitespace(stream); + + ParseValue(stream, handler); + SkipWhitespace(stream); + + ++memberCount; + + switch(stream.Take()) { + case ',': SkipWhitespace(stream); break; + case '}': handler.EndObject(memberCount); return; + default: RAPIDJSON_PARSE_ERROR("Must be a comma or '}' after an object member", stream.Tell()); + } + } + } + + // Parse array: [ value, ... ] + template + void ParseArray(Stream& stream, Handler& handler) { + RAPIDJSON_ASSERT(stream.Peek() == '['); + stream.Take(); // Skip '[' + handler.StartArray(); + SkipWhitespace(stream); + + if (stream.Peek() == ']') { + stream.Take(); + handler.EndArray(0); // empty array + return; + } + + for (SizeType elementCount = 0;;) { + ParseValue(stream, handler); + ++elementCount; + SkipWhitespace(stream); + + switch (stream.Take()) { + case ',': SkipWhitespace(stream); break; + case ']': handler.EndArray(elementCount); return; + default: RAPIDJSON_PARSE_ERROR("Must be a comma or ']' after an array element.", stream.Tell()); + } + } + } + + template + void ParseNull(Stream& stream, Handler& handler) { + RAPIDJSON_ASSERT(stream.Peek() == 'n'); + stream.Take(); + + if (stream.Take() == 'u' && stream.Take() == 'l' && stream.Take() == 'l') + handler.Null(); + else + RAPIDJSON_PARSE_ERROR("Invalid value", stream.Tell() - 1); + } + + template + void ParseTrue(Stream& stream, Handler& handler) { + RAPIDJSON_ASSERT(stream.Peek() == 't'); + stream.Take(); + + if (stream.Take() == 'r' && stream.Take() == 'u' && stream.Take() == 'e') + handler.Bool(true); + else + RAPIDJSON_PARSE_ERROR("Invalid value", stream.Tell()); + } + + template + void ParseFalse(Stream& stream, Handler& handler) { + RAPIDJSON_ASSERT(stream.Peek() == 'f'); + stream.Take(); + + if (stream.Take() == 'a' && stream.Take() == 'l' && stream.Take() == 's' && stream.Take() == 'e') + handler.Bool(false); + else + RAPIDJSON_PARSE_ERROR("Invalid value", stream.Tell() - 1); + } + + // Helper function to parse four hexidecimal digits in \uXXXX in ParseString(). + template + unsigned ParseHex4(Stream& stream) { + Stream s = stream; // Use a local copy for optimization + unsigned codepoint = 0; + for (int i = 0; i < 4; i++) { + Ch c = s.Take(); + codepoint <<= 4; + codepoint += c; + if (c >= '0' && c <= '9') + codepoint -= '0'; + else if (c >= 'A' && c <= 'F') + codepoint -= 'A' - 10; + else if (c >= 'a' && c <= 'f') + codepoint -= 'a' - 10; + else + RAPIDJSON_PARSE_ERROR("Incorrect hex digit after \\u escape", s.Tell() - 1); + } + stream = s; // Restore stream + return codepoint; + } + + // Parse string, handling the prefix and suffix double quotes and escaping. + template + void ParseString(Stream& stream, Handler& handler) { +#define Z16 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 + static const Ch escape[256] = { + Z16, Z16, 0, 0,'\"', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,'/', + Z16, Z16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,'\\', 0, 0, 0, + 0, 0,'\b', 0, 0, 0,'\f', 0, 0, 0, 0, 0, 0, 0,'\n', 0, + 0, 0,'\r', 0,'\t', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16 + }; +#undef Z16 + + Stream s = stream; // Use a local copy for optimization + RAPIDJSON_ASSERT(s.Peek() == '\"'); + s.Take(); // Skip '\"' + Ch *head; + SizeType len; + if (parseFlags & kParseInsituFlag) + head = s.PutBegin(); + else + len = 0; + +#define RAPIDJSON_PUT(x) \ + do { \ + if (parseFlags & kParseInsituFlag) \ + s.Put(x); \ + else { \ + *stack_.template Push() = x; \ + ++len; \ + } \ + } while(false) + + for (;;) { + Ch c = s.Take(); + if (c == '\\') { // Escape + Ch e = s.Take(); + if ((sizeof(Ch) == 1 || e < 256) && escape[(unsigned char)e]) + RAPIDJSON_PUT(escape[(unsigned char)e]); + else if (e == 'u') { // Unicode + unsigned codepoint = ParseHex4(s); + if (codepoint >= 0xD800 && codepoint <= 0xDBFF) { // Handle UTF-16 surrogate pair + if (s.Take() != '\\' || s.Take() != 'u') { + RAPIDJSON_PARSE_ERROR("Missing the second \\u in surrogate pair", s.Tell() - 2); + return; + } + unsigned codepoint2 = ParseHex4(s); + if (codepoint2 < 0xDC00 || codepoint2 > 0xDFFF) { + RAPIDJSON_PARSE_ERROR("The second \\u in surrogate pair is invalid", s.Tell() - 2); + return; + } + codepoint = (((codepoint - 0xD800) << 10) | (codepoint2 - 0xDC00)) + 0x10000; + } + + Ch buffer[4]; + SizeType count = SizeType(Encoding::Encode(buffer, codepoint) - &buffer[0]); + + if (parseFlags & kParseInsituFlag) + for (SizeType i = 0; i < count; i++) + s.Put(buffer[i]); + else { + memcpy(stack_.template Push(count), buffer, count * sizeof(Ch)); + len += count; + } + } + else { + RAPIDJSON_PARSE_ERROR("Unknown escape character", stream.Tell() - 1); + return; + } + } + else if (c == '"') { // Closing double quote + if (parseFlags & kParseInsituFlag) { + size_t length = s.PutEnd(head); + RAPIDJSON_ASSERT(length <= 0xFFFFFFFF); + RAPIDJSON_PUT('\0'); // null-terminate the string + handler.String(head, SizeType(length), false); + } + else { + RAPIDJSON_PUT('\0'); + handler.String(stack_.template Pop(len), len - 1, true); + } + stream = s; // restore stream + return; + } + else if (c == '\0') { + RAPIDJSON_PARSE_ERROR("lacks ending quotation before the end of string", stream.Tell() - 1); + return; + } + else if ((unsigned)c < 0x20) { // RFC 4627: unescaped = %x20-21 / %x23-5B / %x5D-10FFFF + RAPIDJSON_PARSE_ERROR("Incorrect unescaped character in string", stream.Tell() - 1); + return; + } + else + RAPIDJSON_PUT(c); // Normal character, just copy + } +#undef RAPIDJSON_PUT + } + + template + void ParseNumber(Stream& stream, Handler& handler) { + Stream s = stream; // Local copy for optimization + // Parse minus + bool minus = false; + if (s.Peek() == '-') { + minus = true; + s.Take(); + } + + // Parse int: zero / ( digit1-9 *DIGIT ) + unsigned i; + bool try64bit = false; + if (s.Peek() == '0') { + i = 0; + s.Take(); + } + else if (s.Peek() >= '1' && s.Peek() <= '9') { + i = s.Take() - '0'; + + if (minus) + while (s.Peek() >= '0' && s.Peek() <= '9') { + if (i >= 214748364) { // 2^31 = 2147483648 + if (i != 214748364 || s.Peek() > '8') { + try64bit = true; + break; + } + } + i = i * 10 + (s.Take() - '0'); + } + else + while (s.Peek() >= '0' && s.Peek() <= '9') { + if (i >= 429496729) { // 2^32 - 1 = 4294967295 + if (i != 429496729 || s.Peek() > '5') { + try64bit = true; + break; + } + } + i = i * 10 + (s.Take() - '0'); + } + } + else { + RAPIDJSON_PARSE_ERROR("Expect a value here.", stream.Tell()); + return; + } + + // Parse 64bit int + uint64_t i64 = 0; + bool useDouble = false; + if (try64bit) { + i64 = i; + if (minus) + while (s.Peek() >= '0' && s.Peek() <= '9') { + if (i64 >= 922337203685477580uLL) // 2^63 = 9223372036854775808 + if (i64 != 922337203685477580uLL || s.Peek() > '8') { + useDouble = true; + break; + } + i64 = i64 * 10 + (s.Take() - '0'); + } + else + while (s.Peek() >= '0' && s.Peek() <= '9') { + if (i64 >= 1844674407370955161uLL) // 2^64 - 1 = 18446744073709551615 + if (i64 != 1844674407370955161uLL || s.Peek() > '5') { + useDouble = true; + break; + } + i64 = i64 * 10 + (s.Take() - '0'); + } + } + + // Force double for big integer + double d = 0.0; + if (useDouble) { + d = (double)i64; + while (s.Peek() >= '0' && s.Peek() <= '9') { + if (d >= 1E307) { + RAPIDJSON_PARSE_ERROR("Number too big to store in double", stream.Tell()); + return; + } + d = d * 10 + (s.Take() - '0'); + } + } + + // Parse frac = decimal-point 1*DIGIT + int expFrac = 0; + if (s.Peek() == '.') { + if (!useDouble) { + d = try64bit ? (double)i64 : (double)i; + useDouble = true; + } + s.Take(); + + if (s.Peek() >= '0' && s.Peek() <= '9') { + d = d * 10 + (s.Take() - '0'); + --expFrac; + } + else { + RAPIDJSON_PARSE_ERROR("At least one digit in fraction part", stream.Tell()); + return; + } + + while (s.Peek() >= '0' && s.Peek() <= '9') { + if (expFrac > -16) { + d = d * 10 + (s.Peek() - '0'); + --expFrac; + } + s.Take(); + } + } + + // Parse exp = e [ minus / plus ] 1*DIGIT + int exp = 0; + if (s.Peek() == 'e' || s.Peek() == 'E') { + if (!useDouble) { + d = try64bit ? (double)i64 : (double)i; + useDouble = true; + } + s.Take(); + + bool expMinus = false; + if (s.Peek() == '+') + s.Take(); + else if (s.Peek() == '-') { + s.Take(); + expMinus = true; + } + + if (s.Peek() >= '0' && s.Peek() <= '9') { + exp = s.Take() - '0'; + while (s.Peek() >= '0' && s.Peek() <= '9') { + exp = exp * 10 + (s.Take() - '0'); + if (exp > 308) { + RAPIDJSON_PARSE_ERROR("Number too big to store in double", stream.Tell()); + return; + } + } + } + else { + RAPIDJSON_PARSE_ERROR("At least one digit in exponent", s.Tell()); + return; + } + + if (expMinus) + exp = -exp; + } + + // Finish parsing, call event according to the type of number. + if (useDouble) { + d *= internal::Pow10(exp + expFrac); + handler.Double(minus ? -d : d); + } + else { + if (try64bit) { + if (minus) + handler.Int64(-(int64_t)i64); + else + handler.Uint64(i64); + } + else { + if (minus) + handler.Int(-(int)i); + else + handler.Uint(i); + } + } + + stream = s; // restore stream + } + + // Parse any JSON value + template + void ParseValue(Stream& stream, Handler& handler) { + switch (stream.Peek()) { + case 'n': ParseNull (stream, handler); break; + case 't': ParseTrue (stream, handler); break; + case 'f': ParseFalse (stream, handler); break; + case '"': ParseString(stream, handler); break; + case '{': ParseObject(stream, handler); break; + case '[': ParseArray (stream, handler); break; + default : ParseNumber(stream, handler); + } + } + + static const size_t kDefaultStackCapacity = 256; //!< Default stack capacity in bytes for storing a single decoded string. + internal::Stack stack_; //!< A stack for storing decoded string temporarily during non-destructive parsing. + jmp_buf jmpbuf_; //!< setjmp buffer for fast exit from nested parsing function calls. + const char* parseError_; + size_t errorOffset_; +}; // class GenericReader + +//! Reader with UTF8 encoding and default allocator. +typedef GenericReader > Reader; + +} // namespace rapidjson + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +#endif // RAPIDJSON_READER_H_ diff --git a/include/extensions/CocoStudio/Json/rapidjson/stringbuffer.h b/include/extensions/CocoStudio/Json/rapidjson/stringbuffer.h new file mode 100644 index 0000000..269ae10 --- /dev/null +++ b/include/extensions/CocoStudio/Json/rapidjson/stringbuffer.h @@ -0,0 +1,49 @@ +#ifndef RAPIDJSON_STRINGBUFFER_H_ +#define RAPIDJSON_STRINGBUFFER_H_ + +#include "rapidjson.h" +#include "internal/stack.h" + +namespace rapidjson { + +//! Represents an in-memory output stream. +/*! + \tparam Encoding Encoding of the stream. + \tparam Allocator type for allocating memory buffer. + \implements Stream +*/ +template +struct GenericStringBuffer { + typedef typename Encoding::Ch Ch; + + GenericStringBuffer(Allocator* allocator = 0, size_t capacity = kDefaultCapacity) : stack_(allocator, capacity) {} + + void Put(Ch c) { *stack_.template Push() = c; } + + void Clear() { stack_.Clear(); } + + const char* GetString() const { + // Push and pop a null terminator. This is safe. + *stack_.template Push() = '\0'; + stack_.template Pop(1); + + return stack_.template Bottom(); + } + + size_t Size() const { return stack_.GetSize(); } + + static const size_t kDefaultCapacity = 256; + mutable internal::Stack stack_; +}; + +typedef GenericStringBuffer > StringBuffer; + +//! Implement specialized version of PutN() with memset() for better performance. +template<> +inline void PutN(GenericStringBuffer >& stream, char c, size_t n) { + memset(stream.stack_.Push(n), c, n * sizeof(c)); +} + +} // namespace rapidjson + +#endif // RAPIDJSON_STRINGBUFFER_H_ diff --git a/include/extensions/CocoStudio/Json/rapidjson/writer.h b/include/extensions/CocoStudio/Json/rapidjson/writer.h new file mode 100644 index 0000000..d96f208 --- /dev/null +++ b/include/extensions/CocoStudio/Json/rapidjson/writer.h @@ -0,0 +1,241 @@ +#ifndef RAPIDJSON_WRITER_H_ +#define RAPIDJSON_WRITER_H_ + +#include "rapidjson.h" +#include "internal/stack.h" +#include "internal/strfunc.h" +#include // snprintf() or _sprintf_s() +#include // placement new + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4127) // conditional expression is constant +#endif + +namespace rapidjson { + +//! JSON writer +/*! Writer implements the concept Handler. + It generates JSON text by events to an output stream. + + User may programmatically calls the functions of a writer to generate JSON text. + + On the other side, a writer can also be passed to objects that generates events, + + for example Reader::Parse() and Document::Accept(). + + \tparam Stream Type of ouptut stream. + \tparam Encoding Encoding of both source strings and output. + \implements Handler +*/ +template, typename Allocator = MemoryPoolAllocator<> > +class Writer { +public: + typedef typename Encoding::Ch Ch; + + Writer(Stream& stream, Allocator* allocator = 0, size_t levelDepth = kDefaultLevelDepth) : + stream_(stream), level_stack_(allocator, levelDepth * sizeof(Level)) {} + + //@name Implementation of Handler + //@{ + Writer& Null() { Prefix(kNullType); WriteNull(); return *this; } + Writer& Bool(bool b) { Prefix(b ? kTrueType : kFalseType); WriteBool(b); return *this; } + Writer& Int(int i) { Prefix(kNumberType); WriteInt(i); return *this; } + Writer& Uint(unsigned u) { Prefix(kNumberType); WriteUint(u); return *this; } + Writer& Int64(int64_t i64) { Prefix(kNumberType); WriteInt64(i64); return *this; } + Writer& Uint64(uint64_t u64) { Prefix(kNumberType); WriteUint64(u64); return *this; } + Writer& Double(double d) { Prefix(kNumberType); WriteDouble(d); return *this; } + + Writer& String(const Ch* str, SizeType length, bool copy = false) { + (void)copy; + Prefix(kStringType); + WriteString(str, length); + return *this; + } + + Writer& StartObject() { + Prefix(kObjectType); + new (level_stack_.template Push()) Level(false); + WriteStartObject(); + return *this; + } + + Writer& EndObject(SizeType memberCount = 0) { + (void)memberCount; + RAPIDJSON_ASSERT(level_stack_.GetSize() >= sizeof(Level)); + RAPIDJSON_ASSERT(!level_stack_.template Top()->inArray); + level_stack_.template Pop(1); + WriteEndObject(); + return *this; + } + + Writer& StartArray() { + Prefix(kArrayType); + new (level_stack_.template Push()) Level(true); + WriteStartArray(); + return *this; + } + + Writer& EndArray(SizeType elementCount = 0) { + (void)elementCount; + RAPIDJSON_ASSERT(level_stack_.GetSize() >= sizeof(Level)); + RAPIDJSON_ASSERT(level_stack_.template Top()->inArray); + level_stack_.template Pop(1); + WriteEndArray(); + return *this; + } + //@} + + //! Simpler but slower overload. + Writer& String(const Ch* str) { return String(str, internal::StrLen(str)); } + +protected: + //! Information for each nested level + struct Level { + Level(bool inArray_) : inArray(inArray_), valueCount(0) {} + bool inArray; //!< true if in array, otherwise in object + size_t valueCount; //!< number of values in this level + }; + + static const size_t kDefaultLevelDepth = 32; + + void WriteNull() { + stream_.Put('n'); stream_.Put('u'); stream_.Put('l'); stream_.Put('l'); + } + + void WriteBool(bool b) { + if (b) { + stream_.Put('t'); stream_.Put('r'); stream_.Put('u'); stream_.Put('e'); + } + else { + stream_.Put('f'); stream_.Put('a'); stream_.Put('l'); stream_.Put('s'); stream_.Put('e'); + } + } + + void WriteInt(int i) { + if (i < 0) { + stream_.Put('-'); + i = -i; + } + WriteUint((unsigned)i); + } + + void WriteUint(unsigned u) { + char buffer[10]; + char *p = buffer; + do { + *p++ = (u % 10) + '0'; + u /= 10; + } while (u > 0); + + do { + --p; + stream_.Put(*p); + } while (p != buffer); + } + + void WriteInt64(int64_t i64) { + if (i64 < 0) { + stream_.Put('-'); + i64 = -i64; + } + WriteUint64((uint64_t)i64); + } + + void WriteUint64(uint64_t u64) { + char buffer[20]; + char *p = buffer; + do { + *p++ = char(u64 % 10) + '0'; + u64 /= 10; + } while (u64 > 0); + + do { + --p; + stream_.Put(*p); + } while (p != buffer); + } + + //! \todo Optimization with custom double-to-string converter. + void WriteDouble(double d) { + char buffer[100]; +#if _MSC_VER + int ret = sprintf_s(buffer, sizeof(buffer), "%g", d); +#else + int ret = snprintf(buffer, sizeof(buffer), "%g", d); +#endif + RAPIDJSON_ASSERT(ret >= 1); + for (int i = 0; i < ret; i++) + stream_.Put(buffer[i]); + } + + void WriteString(const Ch* str, SizeType length) { + static const char hexDigits[] = "0123456789ABCDEF"; + static const char escape[256] = { +#define Z16 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 + //0 1 2 3 4 5 6 7 8 9 A B C D E F + 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'b', 't', 'n', 'u', 'f', 'r', 'u', 'u', // 00 + 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', // 10 + 0, 0, '"', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20 + Z16, Z16, // 30~4F + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,'\\', 0, 0, 0, // 50 + Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16 // 60~FF +#undef Z16 + }; + + stream_.Put('\"'); + for (const Ch* p = str; p != str + length; ++p) { + if ((sizeof(Ch) == 1 || *p < 256) && escape[(unsigned char)*p]) { + stream_.Put('\\'); + stream_.Put(escape[(unsigned char)*p]); + if (escape[(unsigned char)*p] == 'u') { + stream_.Put('0'); + stream_.Put('0'); + stream_.Put(hexDigits[(*p) >> 4]); + stream_.Put(hexDigits[(*p) & 0xF]); + } + } + else + stream_.Put(*p); + } + stream_.Put('\"'); + } + + void WriteStartObject() { stream_.Put('{'); } + void WriteEndObject() { stream_.Put('}'); } + void WriteStartArray() { stream_.Put('['); } + void WriteEndArray() { stream_.Put(']'); } + + void Prefix(Type type) { + (void)type; + if (level_stack_.GetSize() != 0) { // this value is not at root + Level* level = level_stack_.template Top(); + if (level->valueCount > 0) { + if (level->inArray) + stream_.Put(','); // add comma if it is not the first element in array + else // in object + stream_.Put((level->valueCount % 2 == 0) ? ',' : ':'); + } + if (!level->inArray && level->valueCount % 2 == 0) + RAPIDJSON_ASSERT(type == kStringType); // if it's in object, then even number should be a name + level->valueCount++; + } + else + RAPIDJSON_ASSERT(type == kObjectType || type == kArrayType); + } + + Stream& stream_; + internal::Stack level_stack_; + +private: + // Prohibit assignment for VC C4512 warning + Writer& operator=(const Writer& w); +}; + +} // namespace rapidjson + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +#endif // RAPIDJSON_RAPIDJSON_H_ diff --git a/include/extensions/CocoStudio/Reader/GUIReader.h b/include/extensions/CocoStudio/Reader/GUIReader.h new file mode 100644 index 0000000..7330396 --- /dev/null +++ b/include/extensions/CocoStudio/Reader/GUIReader.h @@ -0,0 +1,185 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +#ifndef __CCSGUIREADER_H__ +#define __CCSGUIREADER_H__ + +#include "../GUI/BaseClasses/UIWidget.h" +#include "../Json/rapidjson/document.h" +#include "cocos-ext.h" +#include "WidgetReader/WidgetReaderProtocol.h" +#include "../Trigger/ObjectFactory.h" + +NS_CC_EXT_BEGIN + +typedef void (CCObject::*SEL_ParseEvent)(const std::string&, CCObject*, const rapidjson::Value&); +#define parseselector(_SELECTOR) (SEL_ParseEvent)(&_SELECTOR) + +#define kCCSVersion 1.0 +/** + * @js NA + * @lua NA + */ +class GUIReader : public CCObject +{ +public: + /** + * @js ctor + */ + GUIReader(); + /** + * @js NA + */ + ~GUIReader(); + /** + * @js getInstance + */ + static GUIReader* shareReader(); + /** + * @js pure + */ + static void purge(); + + cocos2d::ui::Widget* widgetFromJsonFile(const char* fileName); + int getVersionInteger(const char* str); + void storeFileDesignSize(const char* fileName, const cocos2d::CCSize &size); + const cocos2d::CCSize getFileDesignSize(const char* fileName) const; + + const std::string& getFilePath() const { return m_strFilePath; }; + + void registerTypeAndCallBack(const std::string& classType, + ObjectFactory::Instance ins, + CCObject* object, + SEL_ParseEvent callBack); +protected: + std::string m_strFilePath; + CCDictionary* _fileDesignSizes; + + typedef std::map ParseCallBackMap; + ParseCallBackMap _mapParseSelector; + typedef std::map ParseObjectMap; + ParseObjectMap _mapObject; + +public: + ParseCallBackMap getParseCallBackMap() { return _mapParseSelector; }; + ParseObjectMap getParseObjectMap() { return _mapObject; }; +}; + +class WidgetPropertiesReader : public CCObject +{ +public: + virtual cocos2d::ui::Widget* createWidget(const rapidjson::Value& dic, const char* fullPath, const char* fileName)=0; + virtual cocos2d::ui::Widget* widgetFromJsonDictionary(const rapidjson::Value& data) = 0; + virtual void setPropsForAllWidgetFromJsonDictionary(WidgetReaderProtocol* reader, cocos2d::ui::Widget* widget, const rapidjson::Value& options) = 0; + + virtual void setPropsForAllCustomWidgetFromJsonDictionary(const std::string& classType, + cocos2d::ui::Widget* widget, + const rapidjson::Value& customOptions) = 0; + +protected: + std::string m_strFilePath; +}; + + + +/** + * @js NA + * @lua NA + */ +class WidgetPropertiesReader0250 : public WidgetPropertiesReader +{ + + +public: + WidgetPropertiesReader0250(){}; + virtual ~WidgetPropertiesReader0250(){}; + + virtual cocos2d::ui::Widget* createWidget(const rapidjson::Value& dic, const char* fullPath, const char* fileName); + virtual cocos2d::ui::Widget* widgetFromJsonDictionary(const rapidjson::Value& dic); + virtual void setPropsForWidgetFromJsonDictionary(cocos2d::ui::Widget*widget,const rapidjson::Value& options); + + virtual void setColorPropsForWidgetFromJsonDictionary(cocos2d::ui::Widget*widget,const rapidjson::Value& options); + virtual void setPropsForButtonFromJsonDictionary(cocos2d::ui::Widget*widget,const rapidjson::Value& options); + virtual void setPropsForCheckBoxFromJsonDictionary(cocos2d::ui::Widget*widget,const rapidjson::Value& options); + virtual void setPropsForImageViewFromJsonDictionary(cocos2d::ui::Widget*widget,const rapidjson::Value& options); + virtual void setPropsForLabelFromJsonDictionary(cocos2d::ui::Widget*widget,const rapidjson::Value& options); + virtual void setPropsForLabelAtlasFromJsonDictionary(cocos2d::ui::Widget*widget,const rapidjson::Value& options); + virtual void setPropsForLabelBMFontFromJsonDictionary(cocos2d::ui::Widget*widget,const rapidjson::Value& options); + virtual void setPropsForLoadingBarFromJsonDictionary(cocos2d::ui::Widget*widget,const rapidjson::Value& options); + virtual void setPropsForSliderFromJsonDictionary(cocos2d::ui::Widget*widget,const rapidjson::Value& options); + virtual void setPropsForTextFieldFromJsonDictionary(cocos2d::ui::Widget*widget,const rapidjson::Value& options); + + virtual void setPropsForLayoutFromJsonDictionary(cocos2d::ui::Widget*widget,const rapidjson::Value& options); + virtual void setPropsForScrollViewFromJsonDictionary(cocos2d::ui::Widget*widget,const rapidjson::Value& options); + + virtual void setPropsForAllWidgetFromJsonDictionary(WidgetReaderProtocol* reader, cocos2d::ui::Widget* widget, const rapidjson::Value& options); + + virtual void setPropsForAllCustomWidgetFromJsonDictionary(const std::string& classType, + cocos2d::ui::Widget* widget, + const rapidjson::Value& customOptions); +}; + +/** + * @js NA + * @lua NA + */ +class WidgetPropertiesReader0300 : public WidgetPropertiesReader +{ + + +public: + WidgetPropertiesReader0300(){}; + virtual ~WidgetPropertiesReader0300(){}; + + virtual cocos2d::ui::Widget* createWidget(const rapidjson::Value& dic, const char* fullPath, const char* fileName); + virtual cocos2d::ui::Widget* widgetFromJsonDictionary(const rapidjson::Value& dic); + virtual void setPropsForWidgetFromJsonDictionary(cocos2d::ui::Widget*widget,const rapidjson::Value& options); + + virtual void setColorPropsForWidgetFromJsonDictionary(cocos2d::ui::Widget*widget,const rapidjson::Value& options); + virtual void setPropsForButtonFromJsonDictionary(cocos2d::ui::Widget*widget,const rapidjson::Value& options); + virtual void setPropsForCheckBoxFromJsonDictionary(cocos2d::ui::Widget*widget,const rapidjson::Value& options); + virtual void setPropsForImageViewFromJsonDictionary(cocos2d::ui::Widget*widget,const rapidjson::Value& options); + virtual void setPropsForLabelFromJsonDictionary(cocos2d::ui::Widget*widget,const rapidjson::Value& options); + virtual void setPropsForLabelAtlasFromJsonDictionary(cocos2d::ui::Widget*widget,const rapidjson::Value& options); + virtual void setPropsForLabelBMFontFromJsonDictionary(cocos2d::ui::Widget*widget,const rapidjson::Value& options); + virtual void setPropsForLoadingBarFromJsonDictionary(cocos2d::ui::Widget*widget,const rapidjson::Value& options); + virtual void setPropsForSliderFromJsonDictionary(cocos2d::ui::Widget*widget,const rapidjson::Value& options); + virtual void setPropsForTextFieldFromJsonDictionary(cocos2d::ui::Widget*widget,const rapidjson::Value& options); + + virtual void setPropsForLayoutFromJsonDictionary(cocos2d::ui::Widget*widget,const rapidjson::Value& options); + virtual void setPropsForPageViewFromJsonDictionary(cocos2d::ui::Widget*widget,const rapidjson::Value& options); + virtual void setPropsForScrollViewFromJsonDictionary(cocos2d::ui::Widget*widget,const rapidjson::Value& options); + virtual void setPropsForListViewFromJsonDictionary(cocos2d::ui::Widget* widget, const rapidjson::Value& options); + + virtual void setPropsForAllWidgetFromJsonDictionary(WidgetReaderProtocol* reader, cocos2d::ui::Widget* widget, const rapidjson::Value& options); + + virtual void setPropsForAllCustomWidgetFromJsonDictionary(const std::string& classType, + cocos2d::ui::Widget* widget, + const rapidjson::Value& customOptions); +}; + +NS_CC_EXT_END + + +#endif /* defined(__CCSGUIReader__) */ diff --git a/include/extensions/CocoStudio/Reader/SceneReader.h b/include/extensions/CocoStudio/Reader/SceneReader.h new file mode 100644 index 0000000..8558d54 --- /dev/null +++ b/include/extensions/CocoStudio/Reader/SceneReader.h @@ -0,0 +1,70 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +#ifndef __SceneReader_H__ +#define __SceneReader_H__ + +#include "cocos2d.h" +#include "cocos-ext.h" +#include "ExtensionMacros.h" + +NS_CC_EXT_BEGIN + + +typedef void (CCObject::*SEL_CallFuncOD)(CCObject*, void*); +#define callfuncOD_selector(_SELECTOR) (SEL_CallFuncOD)(&_SELECTOR) + +/** +* @js NA +* @lua NA +*/ +class SceneReader +{ +public: + SceneReader(void); + virtual ~SceneReader(void); + +public: + static SceneReader* sharedSceneReader(); + static void purge(); + static const char* sceneReaderVersion(); + cocos2d::CCNode* createNodeWithSceneFile(const char *pszFileName); + static void setTarget(CCObject *rec, SEL_CallFuncOD selector); + cocos2d::CCNode* getNodeByTag(int nTag); +private: + cocos2d::CCNode* createObject(const rapidjson::Value &root, cocos2d::CCNode* parent); + void setPropertyFromJsonDict(const rapidjson::Value &root, cocos2d::CCNode *node); + bool readJson(const char *pszFileName, rapidjson::Document &doc); + cocos2d::CCNode* nodeByTag(cocos2d::CCNode *pParent, int nTag); +private: + static SceneReader* _sharedReader; + static CCObject* _pListener; + static SEL_CallFuncOD _pfnSelector; + cocos2d::CCNode *_pNode; +}; + + +NS_CC_EXT_END + +#endif diff --git a/include/extensions/CocoStudio/Reader/WidgetReader/ButtonReader/ButtonReader.h b/include/extensions/CocoStudio/Reader/WidgetReader/ButtonReader/ButtonReader.h new file mode 100644 index 0000000..02b0a22 --- /dev/null +++ b/include/extensions/CocoStudio/Reader/WidgetReader/ButtonReader/ButtonReader.h @@ -0,0 +1,48 @@ +/**************************************************************************** + Copyright (c) 2014 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __TestCpp__ButtonReader__ +#define __TestCpp__ButtonReader__ + +#include "../WidgetReader.h" + +NS_CC_EXT_BEGIN + +class ButtonReader : public WidgetReader +{ +public: + DECLARE_CLASS_WIDGET_READER_INFO + + ButtonReader(); + virtual ~ButtonReader(); + + static ButtonReader* getInstance(); + static void purge(); + + virtual void setPropsFromJsonDictionary(ui::Widget* widget, const rapidjson::Value& options); +}; + +NS_CC_EXT_END + +#endif /* defined(__TestCpp__ButtonReader__) */ diff --git a/include/extensions/CocoStudio/Reader/WidgetReader/CheckBoxReader/CheckBoxReader.h b/include/extensions/CocoStudio/Reader/WidgetReader/CheckBoxReader/CheckBoxReader.h new file mode 100644 index 0000000..4a756b1 --- /dev/null +++ b/include/extensions/CocoStudio/Reader/WidgetReader/CheckBoxReader/CheckBoxReader.h @@ -0,0 +1,48 @@ +/**************************************************************************** + Copyright (c) 2014 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __TestCpp__CheckBoxReader__ +#define __TestCpp__CheckBoxReader__ + +#include "../WidgetReader.h" + +NS_CC_EXT_BEGIN + +class CheckBoxReader : public WidgetReader +{ +public: + DECLARE_CLASS_WIDGET_READER_INFO + + CheckBoxReader(); + virtual ~CheckBoxReader(); + + static CheckBoxReader* getInstance(); + static void purge(); + + virtual void setPropsFromJsonDictionary(ui::Widget* widget, const rapidjson::Value& options); +}; + +NS_CC_EXT_END + +#endif /* defined(__TestCpp__CheckBoxReader__) */ diff --git a/include/extensions/CocoStudio/Reader/WidgetReader/ImageViewReader/ImageViewReader.h b/include/extensions/CocoStudio/Reader/WidgetReader/ImageViewReader/ImageViewReader.h new file mode 100644 index 0000000..7db7cc3 --- /dev/null +++ b/include/extensions/CocoStudio/Reader/WidgetReader/ImageViewReader/ImageViewReader.h @@ -0,0 +1,48 @@ +/**************************************************************************** + Copyright (c) 2014 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __TestCpp__ImageViewReader__ +#define __TestCpp__ImageViewReader__ + +#include "../WidgetReader.h" + +NS_CC_EXT_BEGIN + +class ImageViewReader : public WidgetReader +{ +public: + DECLARE_CLASS_WIDGET_READER_INFO + + ImageViewReader(); + virtual ~ImageViewReader(); + + static ImageViewReader* getInstance(); + static void purge(); + + virtual void setPropsFromJsonDictionary(ui::Widget* widget, const rapidjson::Value& options); +}; + +NS_CC_EXT_END + +#endif /* defined(__TestCpp__ImageViewReader__) */ diff --git a/include/extensions/CocoStudio/Reader/WidgetReader/LabelAtlasReader/LabelAtlasReader.h b/include/extensions/CocoStudio/Reader/WidgetReader/LabelAtlasReader/LabelAtlasReader.h new file mode 100644 index 0000000..80d99fd --- /dev/null +++ b/include/extensions/CocoStudio/Reader/WidgetReader/LabelAtlasReader/LabelAtlasReader.h @@ -0,0 +1,47 @@ +/**************************************************************************** + Copyright (c) 2014 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __TestCpp__LabelAtlasReader__ +#define __TestCpp__LabelAtlasReader__ + +#include "../WidgetReader.h" + +NS_CC_EXT_BEGIN + +class LabelAtlasReader : public WidgetReader +{ +public: + DECLARE_CLASS_WIDGET_READER_INFO + + LabelAtlasReader(); + virtual ~LabelAtlasReader(); + + static LabelAtlasReader* getInstance(); + + virtual void setPropsFromJsonDictionary(ui::Widget* widget, const rapidjson::Value& options); +}; + +NS_CC_EXT_END + +#endif /* defined(__TestCpp__LabelAtlasReader__) */ diff --git a/include/extensions/CocoStudio/Reader/WidgetReader/LabelBMFontReader/LabelBMFontReader.h b/include/extensions/CocoStudio/Reader/WidgetReader/LabelBMFontReader/LabelBMFontReader.h new file mode 100644 index 0000000..4cbb76b --- /dev/null +++ b/include/extensions/CocoStudio/Reader/WidgetReader/LabelBMFontReader/LabelBMFontReader.h @@ -0,0 +1,48 @@ +/**************************************************************************** + Copyright (c) 2014 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __TestCpp__LabelBMFontReader__ +#define __TestCpp__LabelBMFontReader__ + +#include "../WidgetReader.h" + +NS_CC_EXT_BEGIN + +class LabelBMFontReader : public WidgetReader +{ +public: + DECLARE_CLASS_WIDGET_READER_INFO + + LabelBMFontReader(); + virtual ~LabelBMFontReader(); + + static LabelBMFontReader* getInstance(); + static void purge(); + + virtual void setPropsFromJsonDictionary(ui::Widget* widget, const rapidjson::Value& options); +}; + +NS_CC_EXT_END + +#endif /* defined(__TestCpp__LabelBMFontReader__) */ diff --git a/include/extensions/CocoStudio/Reader/WidgetReader/LabelReader/LabelReader.h b/include/extensions/CocoStudio/Reader/WidgetReader/LabelReader/LabelReader.h new file mode 100644 index 0000000..4269fed --- /dev/null +++ b/include/extensions/CocoStudio/Reader/WidgetReader/LabelReader/LabelReader.h @@ -0,0 +1,48 @@ +/**************************************************************************** + Copyright (c) 2014 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __TestCpp__LabelReader__ +#define __TestCpp__LabelReader__ + +#include "../WidgetReader.h" + +NS_CC_EXT_BEGIN + +class LabelReader : public WidgetReader +{ +public: + DECLARE_CLASS_WIDGET_READER_INFO + + LabelReader(); + virtual ~LabelReader(); + + static LabelReader* getInstance(); + static void purge(); + + virtual void setPropsFromJsonDictionary(ui::Widget* widget, const rapidjson::Value& options); +}; + +NS_CC_EXT_END + +#endif /* defined(__TestCpp__LabelReader__) */ diff --git a/include/extensions/CocoStudio/Reader/WidgetReader/LayoutReader/LayoutReader.h b/include/extensions/CocoStudio/Reader/WidgetReader/LayoutReader/LayoutReader.h new file mode 100644 index 0000000..69b3154 --- /dev/null +++ b/include/extensions/CocoStudio/Reader/WidgetReader/LayoutReader/LayoutReader.h @@ -0,0 +1,48 @@ +/**************************************************************************** + Copyright (c) 2014 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __TestCpp__LayoutReader__ +#define __TestCpp__LayoutReader__ + +#include "../WidgetReader.h" + +NS_CC_EXT_BEGIN + +class LayoutReader : public WidgetReader +{ +public: + DECLARE_CLASS_WIDGET_READER_INFO + + LayoutReader(); + virtual ~LayoutReader(); + + static LayoutReader* getInstance(); + static void purge(); + + virtual void setPropsFromJsonDictionary(ui::Widget* widget, const rapidjson::Value& options); +}; + +NS_CC_EXT_END + +#endif /* defined(__TestCpp__LayoutReader__) */ diff --git a/include/extensions/CocoStudio/Reader/WidgetReader/ListViewReader/ListViewReader.h b/include/extensions/CocoStudio/Reader/WidgetReader/ListViewReader/ListViewReader.h new file mode 100644 index 0000000..08f8299 --- /dev/null +++ b/include/extensions/CocoStudio/Reader/WidgetReader/ListViewReader/ListViewReader.h @@ -0,0 +1,48 @@ +/**************************************************************************** + Copyright (c) 2014 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __TestCpp__ListViewReader__ +#define __TestCpp__ListViewReader__ + +#include "../ScrollViewReader/ScrollViewReader.h" + +NS_CC_EXT_BEGIN + +class ListViewReader : public ScrollViewReader +{ +public: + DECLARE_CLASS_WIDGET_READER_INFO + + ListViewReader(); + virtual ~ListViewReader(); + + static ListViewReader* getInstance(); + static void purge(); + + virtual void setPropsFromJsonDictionary(ui::Widget* widget, const rapidjson::Value& options); +}; + +NS_CC_EXT_END + +#endif /* defined(__TestCpp__ListViewReader__) */ diff --git a/include/extensions/CocoStudio/Reader/WidgetReader/LoadingBarReader/LoadingBarReader.h b/include/extensions/CocoStudio/Reader/WidgetReader/LoadingBarReader/LoadingBarReader.h new file mode 100644 index 0000000..04ae627 --- /dev/null +++ b/include/extensions/CocoStudio/Reader/WidgetReader/LoadingBarReader/LoadingBarReader.h @@ -0,0 +1,48 @@ +/**************************************************************************** + Copyright (c) 2014 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __TestCpp__LoadingBarReader__ +#define __TestCpp__LoadingBarReader__ + +#include "../WidgetReader.h" + +NS_CC_EXT_BEGIN + +class LoadingBarReader : public WidgetReader +{ +public: + DECLARE_CLASS_WIDGET_READER_INFO + + LoadingBarReader(); + virtual ~LoadingBarReader(); + + static LoadingBarReader* getInstance(); + static void purge(); + + virtual void setPropsFromJsonDictionary(ui::Widget* widget, const rapidjson::Value& options); +}; + +NS_CC_EXT_END + +#endif /* defined(__TestCpp__LoadingBarReader__) */ diff --git a/include/extensions/CocoStudio/Reader/WidgetReader/PageViewReader/PageViewReader.h b/include/extensions/CocoStudio/Reader/WidgetReader/PageViewReader/PageViewReader.h new file mode 100644 index 0000000..75a764b --- /dev/null +++ b/include/extensions/CocoStudio/Reader/WidgetReader/PageViewReader/PageViewReader.h @@ -0,0 +1,48 @@ +/**************************************************************************** + Copyright (c) 2014 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __TestCpp__PageViewReader__ +#define __TestCpp__PageViewReader__ + +#include "../LayoutReader/LayoutReader.h" + +NS_CC_EXT_BEGIN + +class PageViewReader : public LayoutReader +{ +public: + DECLARE_CLASS_WIDGET_READER_INFO + + PageViewReader(); + virtual ~PageViewReader(); + + static PageViewReader* getInstance(); + static void purge(); + + virtual void setPropsFromJsonDictionary(ui::Widget* widget, const rapidjson::Value& options); +}; + +NS_CC_EXT_END + +#endif /* defined(__TestCpp__PageViewReader__) */ diff --git a/include/extensions/CocoStudio/Reader/WidgetReader/ScrollViewReader/ScrollViewReader.h b/include/extensions/CocoStudio/Reader/WidgetReader/ScrollViewReader/ScrollViewReader.h new file mode 100644 index 0000000..73fb024 --- /dev/null +++ b/include/extensions/CocoStudio/Reader/WidgetReader/ScrollViewReader/ScrollViewReader.h @@ -0,0 +1,48 @@ +/**************************************************************************** + Copyright (c) 2014 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __TestCpp__ScrollViewReader__ +#define __TestCpp__ScrollViewReader__ + +#include "../LayoutReader/LayoutReader.h" + +NS_CC_EXT_BEGIN + +class ScrollViewReader : public LayoutReader +{ +public: + DECLARE_CLASS_WIDGET_READER_INFO + + ScrollViewReader(); + virtual ~ScrollViewReader(); + + static ScrollViewReader* getInstance(); + static void purge(); + + virtual void setPropsFromJsonDictionary(ui::Widget* widget, const rapidjson::Value& options); +}; + +NS_CC_EXT_END + +#endif /* defined(__TestCpp__ScrollViewReader__) */ diff --git a/include/extensions/CocoStudio/Reader/WidgetReader/SliderReader/SliderReader.h b/include/extensions/CocoStudio/Reader/WidgetReader/SliderReader/SliderReader.h new file mode 100644 index 0000000..35dc936 --- /dev/null +++ b/include/extensions/CocoStudio/Reader/WidgetReader/SliderReader/SliderReader.h @@ -0,0 +1,48 @@ +/**************************************************************************** + Copyright (c) 2014 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __TestCpp__SliderReader__ +#define __TestCpp__SliderReader__ + +#include "../WidgetReader.h" + +NS_CC_EXT_BEGIN + +class SliderReader : public WidgetReader +{ +public: + DECLARE_CLASS_WIDGET_READER_INFO + + SliderReader(); + virtual ~SliderReader(); + + static SliderReader* getInstance(); + static void purge(); + + virtual void setPropsFromJsonDictionary(ui::Widget* widget, const rapidjson::Value& options); +}; + +NS_CC_EXT_END + +#endif /* defined(__TestCpp__SliderReader__) */ diff --git a/include/extensions/CocoStudio/Reader/WidgetReader/TextFieldReader/TextFieldReader.h b/include/extensions/CocoStudio/Reader/WidgetReader/TextFieldReader/TextFieldReader.h new file mode 100644 index 0000000..28fa6fd --- /dev/null +++ b/include/extensions/CocoStudio/Reader/WidgetReader/TextFieldReader/TextFieldReader.h @@ -0,0 +1,48 @@ +/**************************************************************************** + Copyright (c) 2014 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __TestCpp__TextFieldReader__ +#define __TestCpp__TextFieldReader__ + +#include "../WidgetReader.h" + +NS_CC_EXT_BEGIN + +class TextFieldReader : public WidgetReader +{ +public: + DECLARE_CLASS_WIDGET_READER_INFO + + TextFieldReader(); + virtual ~TextFieldReader(); + + static TextFieldReader* getInstance(); + static void purge(); + + virtual void setPropsFromJsonDictionary(ui::Widget* widget, const rapidjson::Value& options); +}; + +NS_CC_EXT_END + +#endif /* defined(__TestCpp__TextFieldReader__) */ diff --git a/include/extensions/CocoStudio/Reader/WidgetReader/WidgetReader.h b/include/extensions/CocoStudio/Reader/WidgetReader/WidgetReader.h new file mode 100644 index 0000000..df3ce84 --- /dev/null +++ b/include/extensions/CocoStudio/Reader/WidgetReader/WidgetReader.h @@ -0,0 +1,52 @@ +/**************************************************************************** + Copyright (c) 2014 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __TestCpp__WidgetReader__ +#define __TestCpp__WidgetReader__ + +#include "WidgetReaderProtocol.h" +#include "../GUIReader.h" +#include "../../GUI/System/GUIDefine.h" +#include "../../GUI/BaseClasses/UIWidget.h" + +NS_CC_EXT_BEGIN + +class WidgetReader : public CCObject, public WidgetReaderProtocol +{ +public: + DECLARE_CLASS_WIDGET_READER_INFO + + WidgetReader(); + virtual ~WidgetReader(); + + static WidgetReader* getInstance(); + static void purge(); + + virtual void setPropsFromJsonDictionary(ui::Widget* widget, const rapidjson::Value& options); + virtual void setColorPropsFromJsonDictionary(ui::Widget* widget, const rapidjson::Value& options); +}; + +NS_CC_EXT_END + +#endif /* defined(__TestCpp__WidgetReader__) */ diff --git a/include/extensions/CocoStudio/Reader/WidgetReader/WidgetReaderProtocol.h b/include/extensions/CocoStudio/Reader/WidgetReader/WidgetReaderProtocol.h new file mode 100644 index 0000000..ee7bb9f --- /dev/null +++ b/include/extensions/CocoStudio/Reader/WidgetReader/WidgetReaderProtocol.h @@ -0,0 +1,48 @@ +/**************************************************************************** + Copyright (c) 2014 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __TestCpp__WidgetReaderProtocol__ +#define __TestCpp__WidgetReaderProtocol__ + +#include "../../Json/DictionaryHelper.h" + +namespace cocos2d +{ + namespace ui + { + class Widget; + } +} + +NS_CC_EXT_BEGIN + +class WidgetReaderProtocol +{ +public: + virtual void setPropsFromJsonDictionary(ui::Widget* widget, const rapidjson::Value& options) = 0; +}; + +NS_CC_EXT_END + +#endif /* defined(__TestCpp__WidgetReaderProtocol__) */ diff --git a/include/extensions/CocoStudio/Trigger/ObjectFactory.h b/include/extensions/CocoStudio/Trigger/ObjectFactory.h new file mode 100644 index 0000000..3bda1e9 --- /dev/null +++ b/include/extensions/CocoStudio/Trigger/ObjectFactory.h @@ -0,0 +1,81 @@ +/**************************************************************************** +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. +****************************************************************************/ + +#ifndef __TRIGGERFACTORY_H__ +#define __TRIGGERFACTORY_H__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" +#include +#include + +namespace cocos2d +{ + namespace ui + { + class Widget; + } + namespace extension + { + class WidgetReaderProtocol; + } +} + + +NS_CC_EXT_BEGIN + +class ObjectFactory +{ +public: + typedef cocos2d::CCObject* (*Instance)(void); + struct TInfo + { + TInfo(void); + TInfo(const std::string& type, Instance ins = NULL); + TInfo(const TInfo &t); + ~TInfo(void); + TInfo& operator= (const TInfo &t); + std::string _class; + Instance _fun; + }; + typedef std::map FactoryMap; + ObjectFactory(void); + virtual ~ObjectFactory(void); + static ObjectFactory* getInstance(); + void destroyInstance(); + CCObject* createObject(std::string name); + CCComponent* createComponent(std::string name); + ui::Widget* createGUI(std::string name); + WidgetReaderProtocol* createWidgetReaderProtocol(std::string name); + void registerType(const TInfo &t); + void removeAll(); +private: + static ObjectFactory *_sharedFactory; + FactoryMap _typeMap; +}; + + +NS_CC_EXT_END + +#endif diff --git a/include/extensions/CocoStudio/Trigger/TriggerBase.h b/include/extensions/CocoStudio/Trigger/TriggerBase.h new file mode 100644 index 0000000..c9fa19f --- /dev/null +++ b/include/extensions/CocoStudio/Trigger/TriggerBase.h @@ -0,0 +1,54 @@ +/**************************************************************************** +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. +****************************************************************************/ + +#ifndef __TRIGGEREVENT_H__ +#define __TRIGGEREVENT_H__ + +#include "cocos2d.h" +#include "cocos-ext.h" +#include "ExtensionMacros.h" +#include "ObjectFactory.h" +#include "TriggerObj.h" +#include "TriggerMng.h" + +NS_CC_EXT_BEGIN + +#define DECLARE_CLASS_INFO \ + public: \ + static cocos2d::extension::ObjectFactory::TInfo Type; \ + static cocos2d::CCObject* createInstance(void); \ + +#define IMPLEMENT_CLASS_INFO(className) \ + cocos2d::CCObject* className::createInstance(void) \ + { \ + return new className; \ + } \ + cocos2d::extension::ObjectFactory::TInfo className::Type(#className, &className::createInstance); \ + + +void sendEvent(unsigned int event); + +NS_CC_EXT_END + +#endif diff --git a/include/extensions/CocoStudio/Trigger/TriggerMng.h b/include/extensions/CocoStudio/Trigger/TriggerMng.h new file mode 100644 index 0000000..df7904d --- /dev/null +++ b/include/extensions/CocoStudio/Trigger/TriggerMng.h @@ -0,0 +1,86 @@ +/**************************************************************************** +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. +****************************************************************************/ + +#ifndef __TRIGGERMNG_H__ +#define __TRIGGERMNG_H__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" +#include "../Json/DictionaryHelper.h" +#include "../Armature/CCArmature.h" + +NS_CC_EXT_BEGIN + +class TriggerObj; + +class ArmatureMovementDispatcher : public CCObject +{ +public: + ArmatureMovementDispatcher(void); + ~ArmatureMovementDispatcher(void); +public: + void addAnimationEventCallBack(CCObject*pTarget, SEL_MovementEventCallFunc mecf); + void removeAnnimationEventCallBack(CCObject*pTarget, SEL_MovementEventCallFunc mecf); + void animationEvent(cocos2d::extension::CCArmature *armature, cocos2d::extension::MovementEventType movementType, const char *movementID); + std::map *_mapEventAnimation; + +}; + +class TriggerMng +{ +public: + TriggerMng(void); + virtual ~TriggerMng(void); + +public: + static TriggerMng* getInstance(); + static const char* triggerMngVersion(); + void destroyInstance(); + +public: + void parse(const rapidjson::Value &root); + void removeAll(void); + CCArray* get(unsigned int event) const; + TriggerObj* getTriggerObj(unsigned int id) const; + bool add(unsigned int event, TriggerObj *pObj); + bool remove(unsigned int event); + bool remove(unsigned int event, TriggerObj *pObj); + bool removeTriggerObj(unsigned int id); + bool isEmpty(void) const; + void addArmatureMovementCallBack(CCArmature *pAr, CCObject *pTarget, SEL_MovementEventCallFunc mecf); + void removeArmatureMovementCallBack(CCArmature *pAr, CCObject *pTarget, SEL_MovementEventCallFunc mecf); + void removeArmatureAllMovementCallBack(CCArmature *pAr); + void removeAllArmatureMovementCallBack(); +private: + void alloc(void); +private: + CCDictionary *_eventTriggers; + static TriggerMng *_sharedTriggerMng; + CCDictionary *_triggerObjs; + std::map *_movementDispatches; +}; + +NS_CC_EXT_END + +#endif diff --git a/include/extensions/CocoStudio/Trigger/TriggerObj.h b/include/extensions/CocoStudio/Trigger/TriggerObj.h new file mode 100644 index 0000000..6cdafcc --- /dev/null +++ b/include/extensions/CocoStudio/Trigger/TriggerObj.h @@ -0,0 +1,89 @@ +/**************************************************************************** +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. +****************************************************************************/ + +#ifndef __TRIGGEROBJ_H__ +#define __TRIGGEROBJ_H__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" +#include "../Json/DictionaryHelper.h" +#include + +NS_CC_EXT_BEGIN + + +class BaseTriggerCondition : public CCObject +{ +protected: + BaseTriggerCondition(void); +public: + virtual ~BaseTriggerCondition(void); + virtual bool init(); + virtual bool detect(); + virtual void serialize(const rapidjson::Value &val); + virtual void removeAll(); +}; + +class BaseTriggerAction : public CCObject +{ +protected: + BaseTriggerAction(void); +public: + virtual ~BaseTriggerAction(void); + virtual bool init(); + virtual void done(); + virtual void serialize(const rapidjson::Value &val); + virtual void removeAll(); +}; + + +class TriggerObj : public CCObject +{ +public: + TriggerObj(void); + virtual ~TriggerObj(void); + virtual bool init(); + static TriggerObj* create(void); + + virtual bool detect(); + virtual void done(); + virtual void removeAll(); + virtual void serialize(const rapidjson::Value &val); + unsigned int getId(); + void setEnable(bool bEnable); + std::vector& getEvents(); + +private: + CCArray *_cons; + CCArray *_acts; + unsigned int _id; + bool _bEnable; + std::vector _vInt; +}; + +NS_CC_EXT_END + +#endif + + diff --git a/include/extensions/ExtensionMacros.h b/include/extensions/ExtensionMacros.h new file mode 100644 index 0000000..618a1f5 --- /dev/null +++ b/include/extensions/ExtensionMacros.h @@ -0,0 +1,34 @@ +/**************************************************************************** + Copyright (c) 2012 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __EXTENSIONMARCROS_H__ +#define __EXTENSIONMARCROS_H__ + +#define NS_CC_EXT_BEGIN namespace cocos2d { namespace extension { +#define NS_CC_EXT_END }} +#define USING_NS_CC_EXT using namespace cocos2d::extension + + +#endif /* __EXTENSIONMARCROS_H__ */ + diff --git a/include/extensions/GUI/CCControlExtension/CCControl.h b/include/extensions/GUI/CCControlExtension/CCControl.h new file mode 100644 index 0000000..b843504 --- /dev/null +++ b/include/extensions/GUI/CCControlExtension/CCControl.h @@ -0,0 +1,292 @@ +/* + * Copyright (c) 2012 cocos2d-x.org + * http://www.cocos2d-x.org + * + * Copyright 2011 Yannick Loriot. + * http://yannickloriot.com + * + * 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. + * + * Converted to c++ / cocos2d-x by Angus C + */ + + +#ifndef __CCCONTROL_H__ +#define __CCCONTROL_H__ + +#include "CCInvocation.h" +#include "CCControlUtils.h" +#include "cocos2d.h" + +NS_CC_EXT_BEGIN + +class CCInvocation; + +/** + * @addtogroup GUI + * @{ + * @addtogroup control_extension + * @{ + */ + +/** Number of kinds of control event. */ +#define kControlEventTotalNumber 9 + +/** Kinds of possible events for the control objects. */ +enum +{ + CCControlEventTouchDown = 1 << 0, // A touch-down event in the control. + CCControlEventTouchDragInside = 1 << 1, // An event where a finger is dragged inside the bounds of the control. + CCControlEventTouchDragOutside = 1 << 2, // An event where a finger is dragged just outside the bounds of the control. + CCControlEventTouchDragEnter = 1 << 3, // An event where a finger is dragged into the bounds of the control. + CCControlEventTouchDragExit = 1 << 4, // An event where a finger is dragged from within a control to outside its bounds. + CCControlEventTouchUpInside = 1 << 5, // A touch-up event in the control where the finger is inside the bounds of the control. + CCControlEventTouchUpOutside = 1 << 6, // A touch-up event in the control where the finger is outside the bounds of the control. + CCControlEventTouchCancel = 1 << 7, // A system event canceling the current touches for the control. + CCControlEventValueChanged = 1 << 8 // A touch dragging or otherwise manipulating a control, causing it to emit a series of different values. +}; +typedef unsigned int CCControlEvent; + +/** The possible state for a control. */ +enum +{ + CCControlStateNormal = 1 << 0, // The normal, or default state of a control¡ªthat is, enabled but neither selected nor highlighted. + CCControlStateHighlighted = 1 << 1, // Highlighted state of a control. A control enters this state when a touch down, drag inside or drag enter is performed. You can retrieve and set this value through the highlighted property. + CCControlStateDisabled = 1 << 2, // Disabled state of a control. This state indicates that the control is currently disabled. You can retrieve and set this value through the enabled property. + CCControlStateSelected = 1 << 3 // Selected state of a control. This state indicates that the control is currently selected. You can retrieve and set this value through the selected property. +}; +typedef unsigned int CCControlState; + +/* + * @class + * CCControl is inspired by the UIControl API class from the UIKit library of + * CocoaTouch. It provides a base class for control CCSprites such as CCButton + * or CCSlider that convey user intent to the application. + * + * The goal of CCControl is to define an interface and base implementation for + * preparing action messages and initially dispatching them to their targets when + * certain events occur. + * + * To use the CCControl you have to subclass it. + */ +class CCControl : public CCLayerRGBA +{ + + //CCRGBAProtocol + bool m_bIsOpacityModifyRGB; + + /** The current control state constant. */ + CC_SYNTHESIZE_READONLY(CCControlState, m_eState, State); + + /** True if all of the controls parents are visible */ +protected: + bool m_hasVisibleParents; + +public: + /** Tells whether the control is enabled. */ + virtual void setEnabled(bool bEnabled); + virtual bool isEnabled(); + /** A Boolean value that determines the control selected state. */ + virtual void setSelected(bool bSelected); + virtual bool isSelected(); + /** A Boolean value that determines whether the control is highlighted. */ + virtual void setHighlighted(bool bHighlighted); + virtual bool isHighlighted(); + bool hasVisibleParents(); + /** + * Updates the control layout using its current internal state. + */ + virtual void needsLayout(); + + virtual bool isOpacityModifyRGB(); + virtual void setOpacityModifyRGB(bool bOpacityModifyRGB); + +protected: + bool m_bEnabled; + bool m_bSelected; + bool m_bHighlighted; + + /** + * Table of connection between the CCControlEvents and their associated + * target-actions pairs. For each CCButtonEvents a list of NSInvocation + * (which contains the target-action pair) is linked. + */ + CCDictionary* m_pDispatchTable; + +public: + /** + * @js ctor + */ + CCControl(); + virtual bool init(void); + /** + * @js NA + * @lua NA + */ + virtual ~CCControl(); + + /** + * @js NA + * @lua NA + */ + virtual void onEnter(); + /** + * @js NA + * @lua NA + */ + virtual void onExit(); + virtual void registerWithTouchDispatcher(); + + /** + * Sends action messages for the given control events. + * + * @param controlEvents A bitmask whose set flags specify the control events for + * which action messages are sent. See "CCControlEvent" for bitmask constants. + */ + virtual void sendActionsForControlEvents(CCControlEvent controlEvents); + + /** + * Adds a target and action for a particular event (or events) to an internal + * dispatch table. + * The action message may optionnaly include the sender and the event as + * parameters, in that order. + * When you call this method, target is not retained. + * + * @param target The target object that is, the object to which the action + * message is sent. It cannot be nil. The target is not retained. + * @param action A selector identifying an action message. It cannot be NULL. + * @param controlEvents A bitmask specifying the control events for which the + * action message is sent. See "CCControlEvent" for bitmask constants. + */ + virtual void addTargetWithActionForControlEvents(CCObject* target, SEL_CCControlHandler action, CCControlEvent controlEvents); + + /** + * Removes a target and action for a particular event (or events) from an + * internal dispatch table. + * + * @param target The target object—that is, the object to which the action + * message is sent. Pass nil to remove all targets paired with action and the + * specified control events. + * @param action A selector identifying an action message. Pass NULL to remove + * all action messages paired with target. + * @param controlEvents A bitmask specifying the control events associated with + * target and action. See "CCControlEvent" for bitmask constants. + */ + virtual void removeTargetWithActionForControlEvents(CCObject* target, SEL_CCControlHandler action, CCControlEvent controlEvents); + + /** + * Returns a point corresponding to the touh location converted into the + * control space coordinates. + * @param touch A CCTouch object that represents a touch. + */ + virtual CCPoint getTouchLocation(CCTouch* touch); + + + /** + * Returns a boolean value that indicates whether a touch is inside the bounds + * of the receiver. The given touch must be relative to the world. + * + * @param touch A CCTouch object that represents a touch. + * + * @return YES whether a touch is inside the receiver¡¯s rect. + */ + virtual bool isTouchInside(CCTouch * touch); + + +protected: + /** + * Returns an CCInvocation object able to construct messages using a given + * target-action pair. (The invocation may optionnaly include the sender and + * the event as parameters, in that order) + * + * @param target The target object. + * @param action A selector identifying an action message. + * @param controlEvent A control events for which the action message is sent. + * See "CCControlEvent" for constants. + * + * @return an CCInvocation object able to construct messages using a given + * target-action pair. + */ + CCInvocation* invocationWithTargetAndActionForControlEvent(CCObject* target, SEL_CCControlHandler action, CCControlEvent controlEvent); + + + + /** + * Returns the CCInvocation list for the given control event. If the list does + * not exist, it'll create an empty array before returning it. + * + * @param controlEvent A control events for which the action message is sent. + * See "CCControlEvent" for constants. + * + * @return the CCInvocation list for the given control event. + */ + // + CCArray* dispatchListforControlEvent(CCControlEvent controlEvent); + /** + * Adds a target and action for a particular event to an internal dispatch + * table. + * The action message may optionnaly include the sender and the event as + * parameters, in that order. + * When you call this method, target is not retained. + * + * @param target The target object¡ªthat is, the object to which the action + * message is sent. It cannot be nil. The target is not retained. + * @param action A selector identifying an action message. It cannot be NULL. + * @param controlEvent A control event for which the action message is sent. + * See "CCControlEvent" for constants. + */ + void addTargetWithActionForControlEvent(CCObject* target, SEL_CCControlHandler action, CCControlEvent controlEvent); + + /** + * Removes a target and action for a particular event from an internal dispatch + * table. + * + * @param target The target object¡ªthat is, the object to which the action + * message is sent. Pass nil to remove all targets paired with action and the + * specified control events. + * @param action A selector identifying an action message. Pass NULL to remove + * all action messages paired with target. + * @param controlEvent A control event for which the action message is sent. + * See "CCControlEvent" for constants. + */ + void removeTargetWithActionForControlEvent(CCObject* target, SEL_CCControlHandler action, CCControlEvent controlEvent); + + static CCControl* create(); +public: + /** + * @js NA + */ + void addHandleOfControlEvent(int nFunID,CCControlEvent controlEvent); + /** + * @js NA + */ + void removeHandleOfControlEvent(CCControlEvent controlEvent); +private: + int getHandleOfControlEvent(CCControlEvent controlEvent); +private: + std::map m_mapHandleOfControlEvent; +}; + +// end of GUI group +/// @} +/// @} + +NS_CC_EXT_END + +#endif \ No newline at end of file diff --git a/include/extensions/GUI/CCControlExtension/CCControlButton.h b/include/extensions/GUI/CCControlExtension/CCControlButton.h new file mode 100644 index 0000000..046f87a --- /dev/null +++ b/include/extensions/GUI/CCControlExtension/CCControlButton.h @@ -0,0 +1,253 @@ +/* + * Copyright (c) 2012 cocos2d-x.org + * http://www.cocos2d-x.org + * + * Copyright 2011 Yannick Loriot. All rights reserved. + * http://yannickloriot.com + * + * 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. + * + * Converted to c++ / cocos2d-x by Angus C + */ + + +#ifndef __CCCONTROL_BUTTON_H__ +#define __CCCONTROL_BUTTON_H__ + +#include "CCControl.h" +#include "CCInvocation.h" +#include "CCScale9Sprite.h" + +NS_CC_EXT_BEGIN + +/* Define the button margin for Left/Right edge */ +#define CCControlButtonMarginLR 8 // px +/* Define the button margin for Top/Bottom edge */ +#define CCControlButtonMarginTB 2 // px + + +/** + * @addtogroup GUI + * @{ + * @addtogroup control_extension + * @{ + */ + +/** @class CCControlButton Button control for Cocos2D. */ +class CCControlButton : public CCControl +{ +public: + CCControlButton(); + virtual ~CCControlButton(); + virtual void needsLayout(void); + + virtual void setEnabled(bool enabled); + virtual void setSelected(bool enabled); + virtual void setHighlighted(bool enabled); +protected: + // CCRGBAProtocol + //bool m_bIsOpacityModifyRGB; + + /** The current title that is displayed on the button. */ + CC_SYNTHESIZE_READONLY(CCString*, m_currentTitle, CurrentTitle); + + /** The current color used to display the title. */ + CC_SYNTHESIZE_READONLY_PASS_BY_REF(ccColor3B, m_currentTitleColor, CurrentTitleColor); + + /** Adjust the background image. YES by default. If the property is set to NO, the + background will use the prefered size of the background image. */ + bool doesAdjustBackgroundImage(); + void setAdjustBackgroundImage(bool adjustBackgroundImage); + bool m_doesAdjustBackgroundImage; + + /** The current title label. */ + CC_SYNTHESIZE_RETAIN(CCNode*, m_titleLabel, TitleLabel); + + /** The current background sprite. */ + CC_SYNTHESIZE_RETAIN(CCScale9Sprite*, m_backgroundSprite, BackgroundSprite); + + /** The prefered size of the button, if label is larger it will be expanded. */ + CC_PROPERTY(CCSize, m_preferredSize, PreferredSize); + + /** Adjust the button zooming on touchdown. Default value is YES. */ + CC_PROPERTY(bool, m_zoomOnTouchDown, ZoomOnTouchDown); + + CC_PROPERTY(CCPoint, m_labelAnchorPoint, LabelAnchorPoint); + + /* Override setter to affect a background sprite too */ + virtual GLubyte getOpacity(void); + virtual void setOpacity(GLubyte var); + virtual const ccColor3B& getColor(void); + virtual void setColor(const ccColor3B&); + + /** Flag to know if the button is currently pushed. */ +protected: + bool m_isPushed; + bool m_bParentInited; +public: + bool isPushed() { return m_isPushed; } + + // + CC_SYNTHESIZE_RETAIN(CCDictionary*, m_titleDispatchTable, TitleDispatchTable); + // + CC_SYNTHESIZE_RETAIN(CCDictionary*, m_titleColorDispatchTable, TitleColorDispatchTable); + // + CC_SYNTHESIZE_RETAIN(CCDictionary*, m_titleLabelDispatchTable, TitleLabelDispatchTable); + // + CC_SYNTHESIZE_RETAIN(CCDictionary*, m_backgroundSpriteDispatchTable, BackgroundSpriteDispatchTable); + + /* Define the button margin for Top/Bottom edge */ + CC_SYNTHESIZE_READONLY(int, m_marginV, VerticalMargin); + /* Define the button margin for Left/Right edge */ + CC_SYNTHESIZE_READONLY(int, m_marginH, HorizontalOrigin); + //set the margins at once (so we only have to do one call of needsLayout) + virtual void setMargins(int marginH, int marginV); + + +public: + virtual bool init(); + virtual bool initWithLabelAndBackgroundSprite(CCNode* label, CCScale9Sprite* backgroundSprite); + + static CCControlButton* create(CCNode* label, CCScale9Sprite* backgroundSprite); + + virtual bool initWithTitleAndFontNameAndFontSize(std::string title, const char * fontName, float fontSize); + + static CCControlButton* create(std::string title, const char * fontName, float fontSize); + + virtual bool initWithBackgroundSprite(CCScale9Sprite* sprite); + + static CCControlButton* create(CCScale9Sprite* sprite); + + //events + virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent); + virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent); + virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent); + virtual void ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent); + + /** + * Returns the title used for a state. + * + * @param state The state that uses the title. Possible values are described in + * "CCControlState". + * + * @return The title for the specified state. + */ + virtual CCString* getTitleForState(CCControlState state); + + /** + * Sets the title string to use for the specified state. + * If a property is not specified for a state, the default is to use + * the CCButtonStateNormal value. + * + * @param title The title string to use for the specified state. + * @param state The state that uses the specified title. The values are described + * in "CCControlState". + */ + virtual void setTitleForState(CCString* title, CCControlState state); + + /** + * Returns the title color used for a state. + * + * @param state The state that uses the specified color. The values are described + * in "CCControlState". + * + * @return The color of the title for the specified state. + */ + + virtual const ccColor3B getTitleColorForState(CCControlState state); + + /** + * Sets the color of the title to use for the specified state. + * + * @param color The color of the title to use for the specified state. + * @param state The state that uses the specified color. The values are described + * in "CCControlState". + */ + virtual void setTitleColorForState(ccColor3B color, CCControlState state); + + /** + * Returns the title label used for a state. + * + * @param state The state that uses the title label. Possible values are described + * in "CCControlState". + */ + virtual CCNode* getTitleLabelForState(CCControlState state); + + /** + * Sets the title label to use for the specified state. + * If a property is not specified for a state, the default is to use + * the CCButtonStateNormal value. + * + * @param title The title label to use for the specified state. + * @param state The state that uses the specified title. The values are described + * in "CCControlState". + */ + virtual void setTitleLabelForState(CCNode* label, CCControlState state); + + virtual void setTitleTTFForState(const char * fntFile, CCControlState state); + virtual const char * getTitleTTFForState(CCControlState state); + + virtual void setTitleTTFSizeForState(float size, CCControlState state); + virtual float getTitleTTFSizeForState(CCControlState state); + + /** + * Sets the font of the label, changes the label to a CCLabelBMFont if neccessary. + * @param fntFile The name of the font to change to + * @param state The state that uses the specified fntFile. The values are described + * in "CCControlState". + */ + virtual void setTitleBMFontForState(const char * fntFile, CCControlState state); + virtual const char * getTitleBMFontForState(CCControlState state); + + /** + * Returns the background sprite used for a state. + * + * @param state The state that uses the background sprite. Possible values are + * described in "CCControlState". + */ + virtual CCScale9Sprite* getBackgroundSpriteForState(CCControlState state); + + /** + * Sets the background sprite to use for the specified button state. + * + * @param sprite The background sprite to use for the specified state. + * @param state The state that uses the specified image. The values are described + * in "CCControlState". + */ + virtual void setBackgroundSpriteForState(CCScale9Sprite* sprite, CCControlState state); + + /** + * Sets the background spriteFrame to use for the specified button state. + * + * @param spriteFrame The background spriteFrame to use for the specified state. + * @param state The state that uses the specified image. The values are described + * in "CCControlState". + */ + virtual void setBackgroundSpriteFrameForState(CCSpriteFrame * spriteFrame, CCControlState state); + + static CCControlButton* create(); +}; + +// end of GUI group +/// @} +/// @} + +NS_CC_EXT_END + +#endif \ No newline at end of file diff --git a/include/extensions/GUI/CCControlExtension/CCControlColourPicker.h b/include/extensions/GUI/CCControlExtension/CCControlColourPicker.h new file mode 100644 index 0000000..b9445f3 --- /dev/null +++ b/include/extensions/GUI/CCControlExtension/CCControlColourPicker.h @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2012 cocos2d-x.org + * http://www.cocos2d-x.org + * + * Copyright 2012 Stewart Hamilton-Arrandale. + * http://creativewax.co.uk + * + * Modified by Yannick Loriot. + * http://yannickloriot.com + * + * 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. + * + * Converted to c++ / cocos2d-x by Angus C + */ + +#ifndef __CCCONTROL_COLOUR_PICKER_H__ +#define __CCCONTROL_COLOUR_PICKER_H__ + + +#include "CCControl.h" +#include "CCControlUtils.h" +#include "CCControlHuePicker.h" +#include "CCControlSaturationBrightnessPicker.h" + +NS_CC_EXT_BEGIN + +/** + * @addtogroup GUI + * @{ + * @addtogroup control_extension + * @{ + */ + +class CCControlColourPicker: public CCControl +{ +public: + CCControlColourPicker(); + virtual ~CCControlColourPicker(); + virtual void setColor(const ccColor3B& colorValue); + virtual void setEnabled(bool bEnabled); +protected: + HSV m_hsv; + CC_SYNTHESIZE_RETAIN(CCControlSaturationBrightnessPicker*, m_colourPicker, colourPicker) + CC_SYNTHESIZE_RETAIN(CCControlHuePicker*, m_huePicker, HuePicker) + CC_SYNTHESIZE_RETAIN(CCSprite*, m_background, Background) + +public: + + static CCControlColourPicker* create(); + + virtual bool init(); + //virtual ~CCControlColourPicker(); + void hueSliderValueChanged(CCObject * sender, CCControlEvent controlEvent); + void colourSliderValueChanged(CCObject * sender, CCControlEvent controlEvent); + +protected: + void updateControlPicker(); + void updateHueAndControlPicker(); + virtual bool ccTouchBegan(CCTouch* touch, CCEvent* pEvent); + +}; + +// end of GUI group +/// @} +/// @} + +NS_CC_EXT_END + +#endif \ No newline at end of file diff --git a/include/extensions/GUI/CCControlExtension/CCControlExtensions.h b/include/extensions/GUI/CCControlExtension/CCControlExtensions.h new file mode 100644 index 0000000..1ae106f --- /dev/null +++ b/include/extensions/GUI/CCControlExtension/CCControlExtensions.h @@ -0,0 +1,37 @@ +/**************************************************************************** +Copyright (c) 2012 cocos2d-x.org + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ + +#ifndef __CCCONTROL_EXTENSIONS_H__ +#define __CCCONTROL_EXTENSIONS_H__ + +#include "CCScale9Sprite.h" +#include "CCControl.h" +#include "CCControlButton.h" +#include "CCControlColourPicker.h" +#include "CCControlPotentiometer.h" +#include "CCControlSlider.h" +#include "CCControlStepper.h" +#include "CCControlSwitch.h" + +#endif \ No newline at end of file diff --git a/include/extensions/GUI/CCControlExtension/CCControlHuePicker.h b/include/extensions/GUI/CCControlExtension/CCControlHuePicker.h new file mode 100644 index 0000000..9466894 --- /dev/null +++ b/include/extensions/GUI/CCControlExtension/CCControlHuePicker.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2012 cocos2d-x.org + * http://www.cocos2d-x.org + * + * Copyright 2012 Stewart Hamilton-Arrandale. + * http://creativewax.co.uk + * + * Modified by Yannick Loriot. + * http://yannickloriot.com + * + * 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. + * + * Converted to c++ / cocos2d-x by Angus C + */ + + +#ifndef __CCCONTROL_HUE_PICKER_H__ +#define __CCCONTROL_HUE_PICKER_H__ + +#include "CCControl.h" +#include "CCInvocation.h" + +NS_CC_EXT_BEGIN + +/** + * @addtogroup GUI + * @{ + * @addtogroup control_extension + * @{ + */ + +class CCControlHuePicker : public CCControl +{ + //maunally put in the setters + CC_SYNTHESIZE_READONLY(float, m_hue, Hue); + virtual void setHue(float val); + CC_SYNTHESIZE_READONLY(float, m_huePercentage, HuePercentage); + virtual void setHuePercentage(float val); + + + //not sure if these need to be there actually. I suppose someone might want to access the sprite? + CC_SYNTHESIZE_RETAIN(CCSprite*, m_background, Background); + CC_SYNTHESIZE_RETAIN(CCSprite*, m_slider, Slider); + CC_SYNTHESIZE_READONLY(CCPoint, m_startPos, StartPos); + +public: + CCControlHuePicker(); + virtual ~CCControlHuePicker(); + virtual bool initWithTargetAndPos(CCNode* target, CCPoint pos); + + static CCControlHuePicker* create(CCNode* target, CCPoint pos); + virtual void setEnabled(bool enabled); +protected: + void updateSliderPosition(CCPoint location); + bool checkSliderPosition(CCPoint location); + + virtual bool ccTouchBegan(CCTouch* touch, CCEvent* pEvent); + virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent); +}; + +// end of GUI group +/// @} +/// @} + +NS_CC_EXT_END + +#endif \ No newline at end of file diff --git a/include/extensions/GUI/CCControlExtension/CCControlPotentiometer.h b/include/extensions/GUI/CCControlExtension/CCControlPotentiometer.h new file mode 100644 index 0000000..98a6d4d --- /dev/null +++ b/include/extensions/GUI/CCControlExtension/CCControlPotentiometer.h @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2012 cocos2d-x.org + * http://www.cocos2d-x.org + * + * Copyright 2012 Yannick Loriot. All rights reserved. + * http://yannickloriot.com + * + * 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 __CCCONTROLPOTENTIOMETER_H__ +#define __CCCONTROLPOTENTIOMETER_H__ + +#include "CCControl.h" + +NS_CC_EXT_BEGIN + +/** + * @addtogroup GUI + * @{ + * @addtogroup control_extension + * @{ + */ + +/** @class CCControlPotentiometer Potentiometer control for Cocos2D. */ +class CCControlPotentiometer : public CCControl +{ +public: + CCControlPotentiometer(); + virtual ~CCControlPotentiometer(); + /** + * Creates potentiometer with a track filename and a progress filename. + */ + static CCControlPotentiometer* create(const char* backgroundFile, const char* progressFile, const char* thumbFile); + + /** + * Initializes a potentiometer with a track sprite and a progress bar. + * + * @param trackSprite CCSprite, that is used as a background. + * @param progressSprite CCProgressTimer, that is used as a progress bar. + */ + bool initWithTrackSprite_ProgressTimer_ThumbSprite(CCSprite* trackSprite, CCProgressTimer* progressTimer, CCSprite* thumbSprite); + void setValue(float value); + float getValue(); + + void setMinimumValue(float minimumValue); + float getMinimumValue(); + + void setMaximumValue(float maximumValue); + float getMaximumValue(); + + void setEnabled(bool enabled); + + virtual bool isTouchInside(CCTouch * touch); + + virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent); + virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent); + virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent); + +protected: + CC_SYNTHESIZE_RETAIN(CCSprite*, m_pThumbSprite, ThumbSprite) + CC_SYNTHESIZE_RETAIN(CCProgressTimer*, m_pProgressTimer, ProgressTimer) + CC_SYNTHESIZE(CCPoint, m_tPreviousLocation, PreviousLocation) + /** Contains the receiver’s current value. */ + float m_fValue; + /** Contains the minimum value of the receiver. + * The default value of this property is 0.0. */ + float m_fMinimumValue; + /** Contains the maximum value of the receiver. + * The default value of this property is 1.0. */ + float m_fMaximumValue; + /** Factorize the event dispath into these methods. */ + void potentiometerBegan(CCPoint location); + void potentiometerMoved(CCPoint location); + void potentiometerEnded(CCPoint location); + + /** Returns the distance between the point1 and point2. */ + float distanceBetweenPointAndPoint(CCPoint point1, CCPoint point2); + /** Returns the angle in degree between line1 and line2. */ + float angleInDegreesBetweenLineFromPoint_toPoint_toLineFromPoint_toPoint( + CCPoint beginLineA, + CCPoint endLineA, + CCPoint beginLineB, + CCPoint endLineB); + +}; + +// end of GUI group +/// @} +/// @} + +NS_CC_EXT_END + +#endif /* __CCCONTROLPOTENTIOMETER_H__ */ diff --git a/include/extensions/GUI/CCControlExtension/CCControlSaturationBrightnessPicker.h b/include/extensions/GUI/CCControlExtension/CCControlSaturationBrightnessPicker.h new file mode 100644 index 0000000..9e0a5de --- /dev/null +++ b/include/extensions/GUI/CCControlExtension/CCControlSaturationBrightnessPicker.h @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2012 cocos2d-x.org + * http://www.cocos2d-x.org + * + * Copyright 2012 Stewart Hamilton-Arrandale. + * http://creativewax.co.uk + * + * Modified by Yannick Loriot. + * http://yannickloriot.com + * + * 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. + * + * Converted to c++ / cocos2d-x by Angus C + */ + + +#ifndef __CCCONTROL_SATURATION_PICKER_H__ +#define __CCCONTROL_SATURATION_PICKER_H__ + +#include "CCControl.h" +#include "CCInvocation.h" + +NS_CC_EXT_BEGIN + +/** + * @addtogroup GUI + * @{ + * @addtogroup control_extension + * @{ + */ + +class CCControlSaturationBrightnessPicker : public CCControl +{ + /** Contains the receiver¡¯s current saturation value. */ + CC_SYNTHESIZE_READONLY(float, m_saturation, Saturation); + /** Contains the receiver¡¯s current brightness value. */ + CC_SYNTHESIZE_READONLY(float, m_brightness, Brightness); + + //not sure if these need to be there actually. I suppose someone might want to access the sprite? + CC_SYNTHESIZE_READONLY(CCSprite*, m_background, Background); + CC_SYNTHESIZE_READONLY(CCSprite*, m_overlay, Overlay); + CC_SYNTHESIZE_READONLY(CCSprite*, m_shadow, Shadow); + CC_SYNTHESIZE_READONLY(CCSprite*, m_slider, Slider); + CC_SYNTHESIZE_READONLY(CCPoint, m_startPos, StartPos); + +protected: + int boxPos; + int boxSize; + +public: + CCControlSaturationBrightnessPicker(); + virtual ~CCControlSaturationBrightnessPicker(); + virtual bool initWithTargetAndPos(CCNode* target, CCPoint pos); + + static CCControlSaturationBrightnessPicker* create(CCNode* target, CCPoint pos); + + virtual void setEnabled(bool enabled); + virtual void updateWithHSV(HSV hsv); + virtual void updateDraggerWithHSV(HSV hsv); + +protected: + void updateSliderPosition(CCPoint location); + bool checkSliderPosition(CCPoint location); + + virtual bool ccTouchBegan(CCTouch* touch, CCEvent* pEvent); + virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent); +}; + +// end of GUI group +/// @} +/// @} + +NS_CC_EXT_END + +#endif \ No newline at end of file diff --git a/include/extensions/GUI/CCControlExtension/CCControlSlider.h b/include/extensions/GUI/CCControlExtension/CCControlSlider.h new file mode 100644 index 0000000..446d2cf --- /dev/null +++ b/include/extensions/GUI/CCControlExtension/CCControlSlider.h @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2012 cocos2d-x.org + * http://www.cocos2d-x.org + * + * Copyright 2011 Yannick Loriot. All rights reserved. + * http://yannickloriot.com + * + * 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. + * + * Converted to c++ / cocos2d-x by Angus C + */ + + +#ifndef __CCCONTROL_SLIDER_H__ +#define __CCCONTROL_SLIDER_H__ + +#include "CCControl.h" +#include "CCInvocation.h" + +NS_CC_EXT_BEGIN + +/** + * @addtogroup GUI + * @{ + * @addtogroup control_extension + * @{ + */ + +class CCControlSlider: public CCControl +{ + //maunally put in the setters + /** Contains the receiver¡¯s current value. */ + CC_SYNTHESIZE_READONLY(float, m_value, Value); + virtual void setValue(float val); + /** Contains the minimum value of the receiver. + * The default value of this property is 0.0. */ + CC_SYNTHESIZE_READONLY(float, m_minimumValue, MinimumValue); + virtual void setMinimumValue(float val); + /** Contains the maximum value of the receiver. + * The default value of this property is 1.0. */ + CC_SYNTHESIZE_READONLY(float, m_maximumValue, MaximumValue); + virtual void setMaximumValue(float val); + virtual void setEnabled(bool enabled); + virtual bool isTouchInside(CCTouch * touch); + CCPoint locationFromTouch(CCTouch* touch); + + CC_SYNTHESIZE(float, m_minimumAllowedValue, MinimumAllowedValue); + CC_SYNTHESIZE(float, m_maximumAllowedValue, MaximumAllowedValue); + + // maybe this should be read-only + CC_SYNTHESIZE_RETAIN(CCSprite*, m_thumbSprite, ThumbSprite); + CC_SYNTHESIZE_RETAIN(CCSprite*, m_progressSprite, ProgressSprite); + CC_SYNTHESIZE_RETAIN(CCSprite*, m_backgroundSprite, BackgroundSprite); + +public: + CCControlSlider(); + virtual ~CCControlSlider(); + + /** + * Initializes a slider with a background sprite, a progress bar and a thumb + * item. + * + * @param backgroundSprite CCSprite, that is used as a background. + * @param progressSprite CCSprite, that is used as a progress bar. + * @param thumbItem CCSprite, that is used as a thumb. + */ + virtual bool initWithSprites(CCSprite * backgroundSprite, CCSprite* progressSprite, CCSprite* thumbSprite); + + /** + * Creates slider with a background filename, a progress filename and a + * thumb image filename. + */ + static CCControlSlider* create(const char* bgFile, const char* progressFile, const char* thumbFile); + + /** + * Creates a slider with a given background sprite and a progress bar and a + * thumb item. + * + * @see initWithBackgroundSprite:progressSprite:thumbMenuItem: + */ + static CCControlSlider* create(CCSprite * backgroundSprite, CCSprite* pogressSprite, CCSprite* thumbSprite); + + virtual void needsLayout(); +protected: + void sliderBegan(CCPoint location); + void sliderMoved(CCPoint location); + void sliderEnded(CCPoint location); + + virtual bool ccTouchBegan(CCTouch* touch, CCEvent* pEvent); + virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent); + virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent); + +/** Returns the value for the given location. */ + float valueForLocation(CCPoint location); +}; + +// end of GUI group +/// @} +/// @} + +NS_CC_EXT_END + +#endif \ No newline at end of file diff --git a/include/extensions/GUI/CCControlExtension/CCControlStepper.h b/include/extensions/GUI/CCControlExtension/CCControlStepper.h new file mode 100644 index 0000000..662cfc9 --- /dev/null +++ b/include/extensions/GUI/CCControlExtension/CCControlStepper.h @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2012 cocos2d-x.org + * http://www.cocos2d-x.org + * + * Copyright 2012 Yannick Loriot. All rights reserved. + * http://yannickloriot.com + * + * 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 __CCCONTROLSTEPPER_H__ +#define __CCCONTROLSTEPPER_H__ + +#include "CCControl.h" + +NS_CC_EXT_BEGIN + +/** + * @addtogroup GUI + * @{ + * @addtogroup control_extension + * @{ + */ + +typedef enum +{ + kCCControlStepperPartMinus, + kCCControlStepperPartPlus, + kCCControlStepperPartNone, +} CCControlStepperPart; + +class CCControlStepper : public CCControl +{ +public: + CCControlStepper(); + virtual ~CCControlStepper(); + + bool initWithMinusSpriteAndPlusSprite(CCSprite *minusSprite, CCSprite *plusSprite); + static CCControlStepper* create(CCSprite *minusSprite, CCSprite *plusSprite); + virtual void setWraps(bool wraps); + virtual void setMinimumValue(double minimumValue); + virtual void setMaximumValue(double maximumValue); + virtual void setValue(double value); + virtual double getValue(); + virtual void setStepValue(double stepValue); + /** Set the numeric value of the stepper. If send is true, the CCControlEventValueChanged is sent. */ + virtual void setValueWithSendingEvent(double value, bool send); + virtual bool isContinuous(); + void update(float dt); + + //events + virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent); + virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent); + virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent); + +protected: + // Weak links to children + CC_SYNTHESIZE_RETAIN(CCSprite*, m_pMinusSprite, MinusSprite) + CC_SYNTHESIZE_RETAIN(CCSprite*, m_pPlusSprite, PlusSprite) + CC_SYNTHESIZE_RETAIN(CCLabelTTF*, m_pMinusLabel, MinusLabel) + CC_SYNTHESIZE_RETAIN(CCLabelTTF*, m_pPlusLabel, PlusLabel) + + /** Update the layout of the stepper with the given touch location. */ + void updateLayoutUsingTouchLocation(CCPoint location); + + /** Start the autorepeat increment/decrement. */ + void startAutorepeat(); + + /** Stop the autorepeat. */ + void stopAutorepeat(); + + /** The numeric value of the stepper. */ + double m_dValue; + /** The continuous vs. noncontinuous state of the stepper. */ + bool m_bContinuous; + /** The automatic vs. nonautomatic repeat state of the stepper. */ + bool m_bAutorepeat; + /** The wrap vs. no-wrap state of the stepper. */ + bool m_bWraps; + /** The lowest possible numeric value for the stepper. */ + double m_dMinimumValue; + /** The highest possible numeric value for the stepper. */ + double m_dMaximumValue; + /** The step, or increment, value for the stepper. */ + double m_dStepValue; + bool m_bTouchInsideFlag; + CCControlStepperPart m_eTouchedPart; + int m_nAutorepeatCount; +}; + +// end of GUI group +/// @} +/// @} + +NS_CC_EXT_END + +#endif /* __CCCONTROLSTEPPER_H__ */ diff --git a/include/extensions/GUI/CCControlExtension/CCControlSwitch.h b/include/extensions/GUI/CCControlExtension/CCControlSwitch.h new file mode 100644 index 0000000..c2116f1 --- /dev/null +++ b/include/extensions/GUI/CCControlExtension/CCControlSwitch.h @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2012 cocos2d-x.org + * http://www.cocos2d-x.org + * + * Copyright 2012 Yannick Loriot. All rights reserved. + * http://yannickloriot.com + * + * 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 __CCCONTROLSWITCH_H__ +#define __CCCONTROLSWITCH_H__ + +#include "CCControl.h" + + +namespace cocos2d { class CCSprite; } +namespace cocos2d { class CCLabelTTF; } + +NS_CC_EXT_BEGIN + +class CCControlSwitchSprite; + +/** + * @addtogroup GUI + * @{ + * @addtogroup control_extension + * @{ + */ + +/** @class CCControlSwitch Switch control for Cocos2D. */ +class CCControlSwitch : public CCControl +{ +public: + CCControlSwitch(); + virtual ~CCControlSwitch(); + /** Initializes a switch with a mask sprite, on/off sprites for on/off states and a thumb sprite. */ + bool initWithMaskSprite(CCSprite *maskSprite, CCSprite * onSprite, CCSprite * offSprite, CCSprite * thumbSprite); + + /** Creates a switch with a mask sprite, on/off sprites for on/off states and a thumb sprite. */ + static CCControlSwitch* create(CCSprite *maskSprite, CCSprite * onSprite, CCSprite * offSprite, CCSprite * thumbSprite); + + + /** Initializes a switch with a mask sprite, on/off sprites for on/off states, a thumb sprite and an on/off labels. */ + bool initWithMaskSprite(CCSprite *maskSprite, CCSprite * onSprite, CCSprite * offSprite, CCSprite * thumbSprite, CCLabelTTF* onLabel, CCLabelTTF* offLabel); + + /** Creates a switch with a mask sprite, on/off sprites for on/off states, a thumb sprite and an on/off labels. */ + static CCControlSwitch* create(CCSprite *maskSprite, CCSprite * onSprite, CCSprite * offSprite, CCSprite * thumbSprite, CCLabelTTF* onLabel, CCLabelTTF* offLabel); + + + /** + * Set the state of the switch to On or Off, optionally animating the transition. + * + * @param isOn YES if the switch should be turned to the On position; NO if it + * should be turned to the Off position. If the switch is already in the + * designated position, nothing happens. + * @param animated YES to animate the "flipping" of the switch; otherwise NO. + */ + void setOn(bool isOn, bool animated); + void setOn(bool isOn); + bool isOn(void) { return m_bOn; } + bool hasMoved() { return m_bMoved; } + virtual void setEnabled(bool enabled); + + CCPoint locationFromTouch(CCTouch* touch); + //events + virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent); + virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent); + virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent); + virtual void ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent); + +protected: + /** Sprite which represents the view. */ + CCControlSwitchSprite* m_pSwitchSprite; + float m_fInitialTouchXPosition; + + bool m_bMoved; + /** A Boolean value that determines the off/on state of the switch. */ + bool m_bOn; +}; + +// end of GUI group +/// @} +/// @} + +NS_CC_EXT_END + +#endif /* __CCCONTROLSWITCH_H__ */ + diff --git a/include/extensions/GUI/CCControlExtension/CCControlUtils.h b/include/extensions/GUI/CCControlExtension/CCControlUtils.h new file mode 100644 index 0000000..b383629 --- /dev/null +++ b/include/extensions/GUI/CCControlExtension/CCControlUtils.h @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2012 cocos2d-x.org + * http://www.cocos2d-x.org + * + * + * Copyright 2012 Stewart Hamilton-Arrandale. + * http://creativewax.co.uk + * + * Modified by Yannick Loriot. + * http://yannickloriot.com + * + * 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. + * + * + * Converted to c++ / cocos2d-x by Angus C + */ + +#ifndef __CCCONTROL_UTILS_H__ +#define __CCCONTROL_UTILS_H__ + +#include "sprite_nodes/CCSprite.h" +#include "../../ExtensionMacros.h" + +NS_CC_EXT_BEGIN + +typedef struct +{ + double r; // percent + double g; // percent + double b; // percent + double a; // percent +} RGBA; + +typedef struct +{ + double h; // angle in degrees + double s; // percent + double v; // percent +} HSV; + +/** + * @addtogroup GUI + * @{ + * @addtogroup control_extension + * @{ + */ + +/**helper class to store ccColor3B's in mutable arrays + * @js NA + * @lua NA + **/ +class CCColor3bObject : public CCObject +{ +public: + ccColor3B value; + CCColor3bObject(ccColor3B s_value):value(s_value){} +}; + +class CCControlUtils +{ +public: + static CCSprite* addSpriteToTargetWithPosAndAnchor(const char* spriteName, CCNode * target, CCPoint pos, CCPoint anchor); + static HSV HSVfromRGB(RGBA value); + static RGBA RGBfromHSV(HSV value); + static CCRect CCRectUnion(const CCRect& src1, const CCRect& src2); +}; + +// end of GUI group +/// @} +/// @} + +NS_CC_EXT_END + +#endif \ No newline at end of file diff --git a/include/extensions/GUI/CCControlExtension/CCInvocation.h b/include/extensions/GUI/CCControlExtension/CCInvocation.h new file mode 100644 index 0000000..60f1741 --- /dev/null +++ b/include/extensions/GUI/CCControlExtension/CCInvocation.h @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2012 cocos2d-x.org + * http://www.cocos2d-x.org + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * + * Converted to c++ / cocos2d-x by Angus C + */ +/* + * + * Helper class to store targets and selectors (and eventually, params?) in the same CCMutableArray. Basically a very crude form of a NSInvocation + */ +#ifndef __CCINVOCATION_H__ +#define __CCINVOCATION_H__ + +#include "cocoa/CCObject.h" +#include "../../ExtensionMacros.h" + +NS_CC_EXT_BEGIN + +/** + * @addtogroup GUI + * @{ + * @addtogroup control_extension + * @{ + */ + +typedef unsigned int CCControlEvent; + +typedef void (CCObject::*SEL_CCControlHandler)(CCObject*, CCControlEvent); + +#define cccontrol_selector(_SELECTOR) (SEL_CCControlHandler)(&_SELECTOR) + +/** + * @js NA + * @lua NA + */ +class CCInvocation : public CCObject +{ + CC_SYNTHESIZE_READONLY(SEL_CCControlHandler, m_action, Action); + CC_SYNTHESIZE_READONLY(CCObject*, m_target, Target); + CC_SYNTHESIZE_READONLY(CCControlEvent, m_controlEvent, ControlEvent); + +public: + static CCInvocation* create(CCObject* target, SEL_CCControlHandler action, CCControlEvent controlEvent); + CCInvocation(CCObject* target, SEL_CCControlHandler action, CCControlEvent controlEvent); + + void invoke(CCObject* sender); +}; + +// end of GUI group +/// @} +/// @} + +NS_CC_EXT_END + +#endif \ No newline at end of file diff --git a/include/extensions/GUI/CCControlExtension/CCScale9Sprite.h b/include/extensions/GUI/CCControlExtension/CCScale9Sprite.h new file mode 100644 index 0000000..57e7c36 --- /dev/null +++ b/include/extensions/GUI/CCControlExtension/CCScale9Sprite.h @@ -0,0 +1,332 @@ +/**************************************************************************** +Copyright (c) 2012 cocos2d-x.org + +http://www.cocos2d-x.org + +Created by Jung Sang-Taik on 12. 3. 16.. +Copyright (c) 2012 Neofect. All rights reserved. + +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 __CCScale9Sprite_H__ +#define __CCScale9Sprite_H__ + +#include "cocos2d.h" +#include "../../ExtensionMacros.h" + +NS_CC_EXT_BEGIN + +/** + * @addtogroup GUI + * @{ + * @addtogroup control_extension + * @{ + */ + +/** + * A 9-slice sprite for cocos2d. + * + * 9-slice scaling allows you to specify how scaling is applied + * to specific areas of a sprite. With 9-slice scaling (3x3 grid), + * you can ensure that the sprite does not become distorted when + * scaled. + * + * @see http://yannickloriot.com/library/ios/cccontrolextension/Classes/CCScale9Sprite.html + */ +class CCScale9Sprite : public CCNodeRGBA +{ +public: + CCScale9Sprite(); + virtual ~CCScale9Sprite(); + +public: + /** Original sprite's size. */ + CC_SYNTHESIZE_READONLY(CCSize, m_originalSize, OriginalSize); + /** Prefered sprite's size. By default the prefered size is the original size. */ + + //if the preferredSize component is given as -1, it is ignored + CC_PROPERTY(CCSize, m_preferredSize, PreferredSize); + /** + * The end-cap insets. + * On a non-resizeable sprite, this property is set to CGRectZero; the sprite + * does not use end caps and the entire sprite is subject to stretching. + */ + CC_PROPERTY(CCRect, m_capInsets, CapInsets); + /** Sets the left side inset */ + CC_PROPERTY(float, m_insetLeft, InsetLeft); + /** Sets the top side inset */ + CC_PROPERTY(float, m_insetTop, InsetTop); + /** Sets the right side inset */ + CC_PROPERTY(float, m_insetRight, InsetRight); + /** Sets the bottom side inset */ + CC_PROPERTY(float, m_insetBottom, InsetBottom); + +protected: + bool m_bSpritesGenerated; + CCRect m_spriteRect; + bool m_bSpriteFrameRotated; + CCRect m_capInsetsInternal; + bool m_positionsAreDirty; + + CCSpriteBatchNode* _scale9Image; + CCSprite* _topLeft; + CCSprite* _top; + CCSprite* _topRight; + CCSprite* _left; + CCSprite* _centre; + CCSprite* _right; + CCSprite* _bottomLeft; + CCSprite* _bottom; + CCSprite* _bottomRight; + + bool _opacityModifyRGB; + GLubyte _opacity; + ccColor3B _color; + + void updateCapInset(); + void updatePositions(); + +public: + + virtual void setContentSize(const CCSize & size); + /** + * @js NA + */ + virtual void visit(); + + virtual bool init(); + + virtual bool initWithBatchNode(CCSpriteBatchNode* batchnode, CCRect rect, bool rotated, CCRect capInsets); + virtual bool initWithBatchNode(CCSpriteBatchNode* batchnode, CCRect rect, CCRect capInsets); + /** + * Initializes a 9-slice sprite with a texture file, a delimitation zone and + * with the specified cap insets. + * Once the sprite is created, you can then call its "setContentSize:" method + * to resize the sprite will all it's 9-slice goodness intract. + * It respects the anchorPoint too. + * + * @param file The name of the texture file. + * @param rect The rectangle that describes the sub-part of the texture that + * is the whole image. If the shape is the whole texture, set this to the + * texture's full rect. + * @param capInsets The values to use for the cap insets. + */ + virtual bool initWithFile(const char* file, CCRect rect, CCRect capInsets); + + /** + * Creates a 9-slice sprite with a texture file, a delimitation zone and + * with the specified cap insets. + * + * @see initWithFile:rect:centerRegion: + */ + static CCScale9Sprite* create(const char* file, CCRect rect, CCRect capInsets); + + /** + * Initializes a 9-slice sprite with a texture file and a delimitation zone. The + * texture will be broken down into a 3×3 grid of equal blocks. + * Once the sprite is created, you can then call its "setContentSize:" method + * to resize the sprite will all it's 9-slice goodness intract. + * It respects the anchorPoint too. + * + * @param file The name of the texture file. + * @param rect The rectangle that describes the sub-part of the texture that + * is the whole image. If the shape is the whole texture, set this to the + * texture's full rect. + */ + virtual bool initWithFile(const char* file, CCRect rect); + + /** + * Creates a 9-slice sprite with a texture file and a delimitation zone. The + * texture will be broken down into a 3×3 grid of equal blocks. + * + * @see initWithFile:rect: + */ + static CCScale9Sprite* create(const char* file, CCRect rect); + + /** + * Initializes a 9-slice sprite with a texture file and with the specified cap + * insets. + * Once the sprite is created, you can then call its "setContentSize:" method + * to resize the sprite will all it's 9-slice goodness intract. + * It respects the anchorPoint too. + * + * @param file The name of the texture file. + * @param capInsets The values to use for the cap insets. + */ + virtual bool initWithFile(CCRect capInsets, const char* file); + + /** + * Creates a 9-slice sprite with a texture file. The whole texture will be + * broken down into a 3×3 grid of equal blocks. + * + * @see initWithFile:capInsets: + */ + static CCScale9Sprite* create(CCRect capInsets, const char* file); + + + /** + * Initializes a 9-slice sprite with a texture file. The whole texture will be + * broken down into a 3×3 grid of equal blocks. + * Once the sprite is created, you can then call its "setContentSize:" method + * to resize the sprite will all it's 9-slice goodness intract. + * It respects the anchorPoint too. + * + * @param file The name of the texture file. + */ + virtual bool initWithFile(const char* file); + + /** + * Creates a 9-slice sprite with a texture file. The whole texture will be + * broken down into a 3×3 grid of equal blocks. + * + * @see initWithFile: + */ + static CCScale9Sprite* create(const char* file); + + /** + * Initializes a 9-slice sprite with an sprite frame and with the specified + * cap insets. + * Once the sprite is created, you can then call its "setContentSize:" method + * to resize the sprite will all it's 9-slice goodness intract. + * It respects the anchorPoint too. + * + * @param spriteFrame The sprite frame object. + * @param capInsets The values to use for the cap insets. + */ + virtual bool initWithSpriteFrame(CCSpriteFrame* spriteFrame, CCRect capInsets); + + /** + * Creates a 9-slice sprite with an sprite frame and the centre of its zone. + * Once the sprite is created, you can then call its "setContentSize:" method + * to resize the sprite will all it's 9-slice goodness intract. + * It respects the anchorPoint too. + * + * @see initWithSpriteFrame:centerRegion: + */ + static CCScale9Sprite* createWithSpriteFrame(CCSpriteFrame* spriteFrame, CCRect capInsets); + /** + * Initializes a 9-slice sprite with an sprite frame. + * Once the sprite is created, you can then call its "setContentSize:" method + * to resize the sprite will all it's 9-slice goodness intract. + * It respects the anchorPoint too. + * + * @param spriteFrame The sprite frame object. + */ + virtual bool initWithSpriteFrame(CCSpriteFrame* spriteFrame); + + /** + * Creates a 9-slice sprite with an sprite frame. + * Once the sprite is created, you can then call its "setContentSize:" method + * to resize the sprite will all it's 9-slice goodness intract. + * It respects the anchorPoint too. + * + * @see initWithSpriteFrame: + */ + static CCScale9Sprite* createWithSpriteFrame(CCSpriteFrame* spriteFrame); + + /** + * Initializes a 9-slice sprite with an sprite frame name and with the specified + * cap insets. + * Once the sprite is created, you can then call its "setContentSize:" method + * to resize the sprite will all it's 9-slice goodness intract. + * It respects the anchorPoint too. + * + * @param spriteFrameName The sprite frame name. + * @param capInsets The values to use for the cap insets. + */ + virtual bool initWithSpriteFrameName(const char*spriteFrameName, CCRect capInsets); + + /** + * Creates a 9-slice sprite with an sprite frame name and the centre of its + * zone. + * Once the sprite is created, you can then call its "setContentSize:" method + * to resize the sprite will all it's 9-slice goodness intract. + * It respects the anchorPoint too. + * + * @see initWithSpriteFrameName:centerRegion: + */ + static CCScale9Sprite* createWithSpriteFrameName(const char*spriteFrameName, CCRect capInsets); + + /** + * Initializes a 9-slice sprite with an sprite frame name. + * Once the sprite is created, you can then call its "setContentSize:" method + * to resize the sprite will all it's 9-slice goodness intract. + * It respects the anchorPoint too. + * + * @param spriteFrameName The sprite frame name. + */ + virtual bool initWithSpriteFrameName(const char*spriteFrameName); + + /** + * Creates a 9-slice sprite with an sprite frame name. + * Once the sprite is created, you can then call its "setContentSize:" method + * to resize the sprite will all it's 9-slice goodness intract. + * It respects the anchorPoint too. + * + * @see initWithSpriteFrameName: + */ + static CCScale9Sprite* createWithSpriteFrameName(const char*spriteFrameName); + + /** + * Creates and returns a new sprite object with the specified cap insets. + * You use this method to add cap insets to a sprite or to change the existing + * cap insets of a sprite. In both cases, you get back a new image and the + * original sprite remains untouched. + * + * @param capInsets The values to use for the cap insets. + */ + CCScale9Sprite* resizableSpriteWithCapInsets(CCRect capInsets); + + static CCScale9Sprite* create(); + + // optional + + /** sets the premultipliedAlphaOpacity property. + If set to NO then opacity will be applied as: glColor(R,G,B,opacity); + If set to YES then oapcity will be applied as: glColor(opacity, opacity, opacity, opacity ); + Textures with premultiplied alpha will have this property by default on YES. Otherwise the default value is NO + @since v0.8 + */ + virtual void setOpacityModifyRGB(bool bValue); + + /** returns whether or not the opacity will be applied using glColor(R,G,B,opacity) or glColor(opacity, opacity, opacity, opacity); + @since v0.8 + */ + virtual bool isOpacityModifyRGB(void); + virtual void setOpacity(GLubyte opacity); + virtual GLubyte getOpacity(); + virtual void setColor(const ccColor3B& color); + virtual const ccColor3B& getColor(); + + virtual bool updateWithBatchNode(CCSpriteBatchNode* batchnode, CCRect rect, bool rotated, CCRect capInsets); + + virtual void setSpriteFrame(CCSpriteFrame * spriteFrame); + + virtual void updateDisplayedOpacity(GLubyte parentOpacity); + virtual void updateDisplayedColor(const cocos2d::ccColor3B& parentColor); +}; + +// end of GUI group +/// @} +/// @} + +NS_CC_EXT_END + +#endif // __CCScale9Sprite_H__ diff --git a/include/extensions/GUI/CCEditBox/CCEditBox.h b/include/extensions/GUI/CCEditBox/CCEditBox.h new file mode 100644 index 0000000..2256f0f --- /dev/null +++ b/include/extensions/GUI/CCEditBox/CCEditBox.h @@ -0,0 +1,429 @@ +/**************************************************************************** + Copyright (c) 2010-2012 cocos2d-x.org + Copyright (c) 2012 James Chen + + 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 __CCEDITTEXT_H__ +#define __CCEDITTEXT_H__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" +#include "../CCControlExtension/CCControlExtensions.h" + +NS_CC_EXT_BEGIN + + +enum KeyboardReturnType { + kKeyboardReturnTypeDefault = 0, + kKeyboardReturnTypeDone, + kKeyboardReturnTypeSend, + kKeyboardReturnTypeSearch, + kKeyboardReturnTypeGo +}; + + +/** + * \brief The EditBoxInputMode defines the type of text that the user is allowed + * to enter. + */ +enum EditBoxInputMode +{ + /** + * The user is allowed to enter any text, including line breaks. + */ + kEditBoxInputModeAny = 0, + + /** + * The user is allowed to enter an e-mail address. + */ + kEditBoxInputModeEmailAddr, + + /** + * The user is allowed to enter an integer value. + */ + kEditBoxInputModeNumeric, + + /** + * The user is allowed to enter a phone number. + */ + kEditBoxInputModePhoneNumber, + + /** + * The user is allowed to enter a URL. + */ + kEditBoxInputModeUrl, + + /** + * The user is allowed to enter a real number value. + * This extends kEditBoxInputModeNumeric by allowing a decimal point. + */ + kEditBoxInputModeDecimal, + + /** + * The user is allowed to enter any text, except for line breaks. + */ + kEditBoxInputModeSingleLine +}; + +/** + * \brief The EditBoxInputFlag defines how the input text is displayed/formatted. + */ +enum EditBoxInputFlag +{ + /** + * Indicates that the text entered is confidential data that should be + * obscured whenever possible. This implies EDIT_BOX_INPUT_FLAG_SENSITIVE. + */ + kEditBoxInputFlagPassword = 0, + + /** + * Indicates that the text entered is sensitive data that the + * implementation must never store into a dictionary or table for use + * in predictive, auto-completing, or other accelerated input schemes. + * A credit card number is an example of sensitive data. + */ + kEditBoxInputFlagSensitive, + + /** + * This flag is a hint to the implementation that during text editing, + * the initial letter of each word should be capitalized. + */ + kEditBoxInputFlagInitialCapsWord, + + /** + * This flag is a hint to the implementation that during text editing, + * the initial letter of each sentence should be capitalized. + */ + kEditBoxInputFlagInitialCapsSentence, + + /** + * Capitalize all characters automatically. + */ + kEditBoxInputFlagInitialCapsAllCharacters + +}; + + +class CCEditBox; +class CCEditBoxImpl; + +/** + * @js NA + * @lua NA + */ +class CCEditBoxDelegate +{ +public: + virtual ~CCEditBoxDelegate() {}; + + /** + * This method is called when an edit box gains focus after keyboard is shown. + * @param editBox The edit box object that generated the event. + */ + virtual void editBoxEditingDidBegin(CCEditBox* editBox) {}; + + + /** + * This method is called when an edit box loses focus after keyboard is hidden. + * @param editBox The edit box object that generated the event. + */ + virtual void editBoxEditingDidEnd(CCEditBox* editBox) {}; + + /** + * This method is called when the edit box text was changed. + * @param editBox The edit box object that generated the event. + * @param text The new text. + */ + virtual void editBoxTextChanged(CCEditBox* editBox, const std::string& text) {}; + + /** + * This method is called when the return button was pressed or the outside area of keyboard was touched. + * @param editBox The edit box object that generated the event. + */ + virtual void editBoxReturn(CCEditBox* editBox) = 0; + +}; + +/** + * \brief Class for edit box. + * + * You can use this widget to gather small amounts of text from the user. + * + */ + +class CCEditBox +: public CCControlButton +, public CCIMEDelegate +{ +public: + /** + * Constructor. + */ + CCEditBox(void); + + /** + * Destructor. + */ + virtual ~CCEditBox(void); + + /** + * create a edit box with size. + * @return An autorelease pointer of CCEditBox, you don't need to release it only if you retain it again. + */ + static CCEditBox* create(const CCSize& size, CCScale9Sprite* pNormal9SpriteBg, CCScale9Sprite* pPressed9SpriteBg = NULL, CCScale9Sprite* pDisabled9SpriteBg = NULL); + + /** + * Init edit box with specified size. This method should be invoked right after constructor. + * @param size The size of edit box. + */ + bool initWithSizeAndBackgroundSprite(const CCSize& size, CCScale9Sprite* pNormal9SpriteBg); + + /** + * Gets/Sets the delegate for edit box. + * @lua NA + */ + void setDelegate(CCEditBoxDelegate* pDelegate); + /** + * @js NA + * @lua NA + */ + CCEditBoxDelegate* getDelegate(); + /** + * Registers a script function that will be called for EditBox events. + * + * This handler will be removed automatically after onExit() called. + * @code + * -- lua sample + * local function editboxEventHandler(eventType) + * if eventType == "began" then + * -- triggered when an edit box gains focus after keyboard is shown + * elseif eventType == "ended" then + * -- triggered when an edit box loses focus after keyboard is hidden. + * elseif eventType == "changed" then + * -- triggered when the edit box text was changed. + * elseif eventType == "return" then + * -- triggered when the return button was pressed or the outside area of keyboard was touched. + * end + * end + * + * local editbox = CCEditBox:create(CCSize(...), CCScale9Sprite:create(...)) + * editbox = registerScriptEditBoxHandler(editboxEventHandler) + * @endcode + * + * @param handler A number that indicates a lua function. + * @js NA + */ + void registerScriptEditBoxHandler(int handler); + + /** + * Unregisters a script function that will be called for EditBox events. + * @js NA + */ + void unregisterScriptEditBoxHandler(void); + /** + * get a script Handler + * @js NA + */ + int getScriptEditBoxHandler(void){ return m_nScriptEditBoxHandler ;} + /** + * Set the text entered in the edit box. + * @param pText The given text. + */ + void setText(const char* pText); + + /** + * Get the text entered in the edit box. + * @return The text entered in the edit box. + */ + const char* getText(void); + + /** + * Set the font. + * @param pFontName The font name. + * @param fontSize The font size. + */ + void setFont(const char* pFontName, int fontSize); + + /** + * Set the font name. + * @param pFontName The font name. + */ + void setFontName(const char* pFontName); + + /** + * Set the font size. + * @param fontSize The font size. + */ + void setFontSize(int fontSize); + + /** + * Set the font color of the widget's text. + */ + void setFontColor(const ccColor3B& color); + + /** + * Set the placeholder's font. + * @param pFontName The font name. + * @param fontSize The font size. + */ + void setPlaceholderFont(const char* pFontName, int fontSize); + + /** + * Set the placeholder's font name. + * @param pFontName The font name. + */ + void setPlaceholderFontName(const char* pFontName); + + /** + * Set the placeholder's font size. + * @param fontSize The font size. + */ + void setPlaceholderFontSize(int fontSize); + + /** + * Set the font color of the placeholder text when the edit box is empty. + * Not supported on IOS. + */ + void setPlaceholderFontColor(const ccColor3B& color); + + /** + * Set a text in the edit box that acts as a placeholder when an + * edit box is empty. + * @param pText The given text. + */ + void setPlaceHolder(const char* pText); + + /** + * Get a text in the edit box that acts as a placeholder when an + * edit box is empty. + */ + const char* getPlaceHolder(void); + + /** + * Set the input mode of the edit box. + * @param inputMode One of the EditBoxInputMode constants. + */ + void setInputMode(EditBoxInputMode inputMode); + + /** + * Sets the maximum input length of the edit box. + * Setting this value enables multiline input mode by default. + * Available on Android, iOS and Windows Phone. + * + * @param maxLength The maximum length. + */ + void setMaxLength(int maxLength); + + /** + * Gets the maximum input length of the edit box. + * + * @return Maximum input length. + */ + int getMaxLength(); + + /** + * Set the input flags that are to be applied to the edit box. + * @param inputFlag One of the EditBoxInputFlag constants. + */ + void setInputFlag(EditBoxInputFlag inputFlag); + + /** + * Set the return type that are to be applied to the edit box. + * @param returnType One of the CCKeyboardReturnType constants. + */ + void setReturnType(KeyboardReturnType returnType); + + /* override functions */ + virtual void setPosition(const CCPoint& pos); + virtual void setVisible(bool visible); + virtual void setContentSize(const CCSize& size); + virtual void setAnchorPoint(const CCPoint& anchorPoint); + /** + * @js NA + */ + virtual void visit(void); + /** + * @js NA + * @lua NA + */ + virtual void onEnter(void); + /** + * @js NA + * @lua NA + */ + virtual void onExit(void); + /** + * @js NA + * @lua NA + */ + virtual void keyboardWillShow(CCIMEKeyboardNotificationInfo& info); + /** + * @js NA + * @lua NA + */ + virtual void keyboardDidShow(CCIMEKeyboardNotificationInfo& info); + /** + * @js NA + * @lua NA + */ + virtual void keyboardWillHide(CCIMEKeyboardNotificationInfo& info); + /** + * @js NA + * @lua NA + */ + virtual void keyboardDidHide(CCIMEKeyboardNotificationInfo& info); + + /** callback funtions + * @js NA + */ + void touchDownAction(CCObject *sender, CCControlEvent controlEvent); + +protected: + CCEditBoxImpl* m_pEditBoxImpl; + CCEditBoxDelegate* m_pDelegate; + + EditBoxInputMode m_eEditBoxInputMode; + EditBoxInputFlag m_eEditBoxInputFlag; + KeyboardReturnType m_eKeyboardReturnType; + + std::string m_strText; + std::string m_strPlaceHolder; + + std::string m_strFontName; + std::string m_strPlaceholderFontName; + + int m_nFontSize; + int m_nPlaceholderFontSize; + + ccColor3B m_colText; + ccColor3B m_colPlaceHolder; + + int m_nMaxLength; + float m_fAdjustHeight; + int m_nScriptEditBoxHandler; +}; + +NS_CC_EXT_END + +#endif /* __CCEDITTEXT_H__ */ + diff --git a/include/extensions/GUI/CCEditBox/CCEditBoxImpl.h b/include/extensions/GUI/CCEditBox/CCEditBoxImpl.h new file mode 100644 index 0000000..118a725 --- /dev/null +++ b/include/extensions/GUI/CCEditBox/CCEditBoxImpl.h @@ -0,0 +1,90 @@ +/**************************************************************************** + Copyright (c) 2010-2012 cocos2d-x.org + Copyright (c) 2012 James Chen + + 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 __CCEditBoxIMPL_H__ +#define __CCEditBoxIMPL_H__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" +#include "CCEditBox.h" + +NS_CC_EXT_BEGIN + + +class CCEditBoxImpl +{ +public: + CCEditBoxImpl(CCEditBox* pEditBox) : m_pDelegate(NULL),m_pEditBox(pEditBox) {} + virtual ~CCEditBoxImpl() {} + + virtual bool initWithSize(const CCSize& size) = 0; + virtual void setFont(const char* pFontName, int fontSize) = 0; + virtual void setFontColor(const ccColor3B& color) = 0; + virtual void setPlaceholderFont(const char* pFontName, int fontSize) = 0; + virtual void setPlaceholderFontColor(const ccColor3B& color) = 0; + virtual void setInputMode(EditBoxInputMode inputMode) = 0; + virtual void setInputFlag(EditBoxInputFlag inputFlag) = 0; + virtual void setMaxLength(int maxLength) = 0; + virtual int getMaxLength() = 0; + virtual void setReturnType(KeyboardReturnType returnType) = 0; + virtual bool isEditing() = 0; + + virtual void setText(const char* pText) = 0; + virtual const char* getText(void) = 0; + virtual void setPlaceHolder(const char* pText) = 0; + virtual void doAnimationWhenKeyboardMove(float duration, float distance) = 0; + + virtual void openKeyboard() = 0; + virtual void closeKeyboard() = 0; + + virtual void setPosition(const CCPoint& pos) = 0; + virtual void setVisible(bool visible) = 0; + virtual void setContentSize(const CCSize& size) = 0; + virtual void setAnchorPoint(const CCPoint& anchorPoint) = 0; + /** + * @js NA + */ + virtual void visit(void) = 0; + /** + * @js NA + */ + virtual void onEnter(void) = 0; + + + void setDelegate(CCEditBoxDelegate* pDelegate) { m_pDelegate = pDelegate; }; + CCEditBoxDelegate* getDelegate() { return m_pDelegate; }; + CCEditBox* getCCEditBox() { return m_pEditBox; }; +protected: + CCEditBoxDelegate* m_pDelegate; + CCEditBox* m_pEditBox; +}; + +// This method must be implemented at each subclass of CCEditBoxImpl. +extern CCEditBoxImpl* __createSystemEditBox(CCEditBox* pEditBox); + + +NS_CC_EXT_END + +#endif /* __CCEditBoxIMPL_H__ */ diff --git a/include/extensions/GUI/CCEditBox/CCEditBoxImplAndroid.h b/include/extensions/GUI/CCEditBox/CCEditBoxImplAndroid.h new file mode 100644 index 0000000..6c26ddf --- /dev/null +++ b/include/extensions/GUI/CCEditBox/CCEditBoxImplAndroid.h @@ -0,0 +1,97 @@ +/**************************************************************************** + Copyright (c) 2010-2012 cocos2d-x.org + Copyright (c) 2012 James Chen + + 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 __CCEDITBOXIMPLANDROID_H__ +#define __CCEDITBOXIMPLANDROID_H__ + +#include "cocos2d.h" + +#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) + +#include "ExtensionMacros.h" +#include "CCEditBoxImpl.h" + +NS_CC_EXT_BEGIN + +class CCEditBox; + +class CCEditBoxImplAndroid : public CCEditBoxImpl +{ +public: + CCEditBoxImplAndroid(CCEditBox* pEditText); + virtual ~CCEditBoxImplAndroid(); + + virtual bool initWithSize(const CCSize& size); + virtual void setFont(const char* pFontName, int fontSize); + virtual void setFontColor(const ccColor3B& color); + virtual void setPlaceholderFont(const char* pFontName, int fontSize); + virtual void setPlaceholderFontColor(const ccColor3B& color); + virtual void setInputMode(EditBoxInputMode inputMode); + virtual void setInputFlag(EditBoxInputFlag inputFlag); + virtual void setMaxLength(int maxLength); + virtual int getMaxLength(); + virtual void setReturnType(KeyboardReturnType returnType); + virtual bool isEditing(); + + virtual void setText(const char* pText); + virtual const char* getText(void); + virtual void setPlaceHolder(const char* pText); + virtual void setPosition(const CCPoint& pos); + virtual void setVisible(bool visible); + virtual void setContentSize(const CCSize& size); + virtual void setAnchorPoint(const CCPoint& anchorPoint); + /** + * @js NA + */ + virtual void visit(void); + virtual void onEnter(void); + virtual void doAnimationWhenKeyboardMove(float duration, float distance); + virtual void openKeyboard(); + virtual void closeKeyboard(); + +private: + CCLabelTTF* m_pLabel; + CCLabelTTF* m_pLabelPlaceHolder; + EditBoxInputMode m_eEditBoxInputMode; + EditBoxInputFlag m_eEditBoxInputFlag; + KeyboardReturnType m_eKeyboardReturnType; + + std::string m_strText; + std::string m_strPlaceHolder; + + ccColor3B m_colText; + ccColor3B m_colPlaceHolder; + + int m_nMaxLength; + CCSize m_EditSize; +}; + + +NS_CC_EXT_END + +#endif /* #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) */ + +#endif /* __CCEDITBOXIMPLANDROID_H__ */ + diff --git a/include/extensions/GUI/CCEditBox/CCEditBoxImplIOS.h b/include/extensions/GUI/CCEditBox/CCEditBoxImplIOS.h new file mode 100644 index 0000000..2cf7b0d --- /dev/null +++ b/include/extensions/GUI/CCEditBox/CCEditBoxImplIOS.h @@ -0,0 +1,130 @@ +/**************************************************************************** + Copyright (c) 2010-2012 cocos2d-x.org + Copyright (c) 2012 James Chen + + 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 __CCEditBoxIMPLIOS_H__ +#define __CCEditBoxIMPLIOS_H__ + +#include "cocos2d.h" + +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) + +#include "ExtensionMacros.h" +#include "CCEditBoxImpl.h" + +#import +#import + +@interface CustomUITextField : UITextField +{ +} + +@end + + +@interface EditBoxImplIOS : NSObject +{ + CustomUITextField* textField_; + void* editBox_; + BOOL editState_; +} + +@property(nonatomic, retain) UITextField* textField; +@property(nonatomic, readonly, getter = isEditState) BOOL editState; +@property(nonatomic, assign) void* editBox; + +-(id) initWithFrame: (CGRect) frameRect editBox: (void*) editBox; +-(void) doAnimationWhenKeyboardMoveWithDuration:(float)duration distance:(float)distance; +-(void) setPosition:(CGPoint) pos; +-(void) setContentSize:(CGSize) size; +-(void) visit; +-(void) openKeyboard; +-(void) closeKeyboard; + +@end + +NS_CC_EXT_BEGIN + +class CCEditBox; +/** + * @js NA + * @lua NA + */ +class CCEditBoxImplIOS : public CCEditBoxImpl +{ +public: + CCEditBoxImplIOS(CCEditBox* pEditText); + virtual ~CCEditBoxImplIOS(); + + virtual bool initWithSize(const CCSize& size); + virtual void setFont(const char* pFontName, int fontSize); + virtual void setFontColor(const ccColor3B& color); + virtual void setPlaceholderFont(const char* pFontName, int fontSize); + virtual void setPlaceholderFontColor(const ccColor3B& color); + virtual void setInputMode(EditBoxInputMode inputMode); + virtual void setInputFlag(EditBoxInputFlag inputFlag); + virtual void setMaxLength(int maxLength); + virtual int getMaxLength(); + virtual void setReturnType(KeyboardReturnType returnType); + virtual bool isEditing(); + + virtual void setText(const char* pText); + virtual const char* getText(void); + virtual void setPlaceHolder(const char* pText); + virtual void setPosition(const CCPoint& pos); + virtual void setVisible(bool visible); + virtual void setContentSize(const CCSize& size); + virtual void setAnchorPoint(const CCPoint& anchorPoint); + virtual void visit(void); + virtual void onEnter(void); + virtual void doAnimationWhenKeyboardMove(float duration, float distance); + virtual void openKeyboard(); + virtual void closeKeyboard(); + + virtual void onEndEditing(); + +private: + void initInactiveLabels(const CCSize& size); + void setInactiveText(const char* pText); + void adjustTextFieldPosition(); + void placeInactiveLabels(); + + CCLabelTTF* m_pLabel; + CCLabelTTF* m_pLabelPlaceHolder; + CCSize m_tContentSize; + CCPoint m_obPosition; + CCPoint m_obAnchorPoint; + EditBoxImplIOS* m_systemControl; + int m_nMaxTextLength; + bool m_bInRetinaMode; +}; + + +NS_CC_EXT_END + + +#endif /* #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) */ + +#endif /* __CCEditBoxIMPLIOS_H__ */ + diff --git a/include/extensions/GUI/CCEditBox/CCEditBoxImplMac.h b/include/extensions/GUI/CCEditBox/CCEditBoxImplMac.h new file mode 100644 index 0000000..cdbff56 --- /dev/null +++ b/include/extensions/GUI/CCEditBox/CCEditBoxImplMac.h @@ -0,0 +1,120 @@ +/**************************************************************************** + Copyright (c) 2010-2012 cocos2d-x.org + Copyright (c) 2012 Jozef Pridavok + + 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 __CCEditBoxIMPLMAC_H__ +#define __CCEditBoxIMPLMAC_H__ + +#include "cocos2d.h" + +#if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) + +#import +#import + +#include "ExtensionMacros.h" +#include "CCEditBoxImpl.h" + +@interface CustomNSTextField : NSTextField +{ +} + +@end + +@interface EditBoxImplMac : NSObject +{ + CustomNSTextField* textField_; + void* editBox_; + BOOL editState_; +} + +@property(nonatomic, retain) NSTextField* textField; +@property(nonatomic, readonly, getter = isEditState) BOOL editState; +@property(nonatomic, assign) void* editBox; + +-(id) initWithFrame: (NSRect) frameRect editBox: (void*) editBox; +-(void) doAnimationWhenKeyboardMoveWithDuration:(float)duration distance:(float)distance; +-(void) setPosition:(NSPoint) pos; +-(void) setContentSize:(NSSize) size; +-(void) visit; +-(void) openKeyboard; +-(void) closeKeyboard; + +@end + +NS_CC_EXT_BEGIN + +class CCEditBox; +/** + * @js NA + * @lua NA + */ +class CCEditBoxImplMac : public CCEditBoxImpl +{ +public: + CCEditBoxImplMac(CCEditBox* pEditText); + virtual ~CCEditBoxImplMac(); + + virtual bool initWithSize(const CCSize& size); + virtual void setFont(const char* pFontName, int fontSize); + virtual void setFontColor(const ccColor3B& color); + virtual void setPlaceholderFont(const char* pFontName, int fontSize); + virtual void setPlaceholderFontColor(const ccColor3B& color); + virtual void setInputMode(EditBoxInputMode inputMode); + virtual void setInputFlag(EditBoxInputFlag inputFlag); + virtual void setMaxLength(int maxLength); + virtual int getMaxLength(); + virtual void setReturnType(KeyboardReturnType returnType); + virtual bool isEditing(); + + virtual void setText(const char* pText); + virtual const char* getText(void); + virtual void setPlaceHolder(const char* pText); + virtual void setPosition(const CCPoint& pos); + virtual void setVisible(bool visible); + virtual void setContentSize(const CCSize& size); + virtual void setAnchorPoint(const CCPoint& anchorPoint); + virtual void visit(void); + virtual void doAnimationWhenKeyboardMove(float duration, float distance); + virtual void openKeyboard(); + virtual void closeKeyboard(); + virtual void onEnter(void); +private: + NSPoint convertDesignCoordToScreenCoord(const CCPoint& designCoord, bool bInRetinaMode); + void adjustTextFieldPosition(); + CCSize m_tContentSize; + CCPoint m_obPosition; + CCPoint m_obAnchorPoint; + int m_nMaxTextLength; + bool m_bInRetinaMode; + EditBoxImplMac* m_pSysEdit; +}; + + +NS_CC_EXT_END + +#endif // #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) + +#endif /* __CCEditBoxIMPLMAC_H__ */ + diff --git a/include/extensions/GUI/CCEditBox/CCEditBoxImplTizen.h b/include/extensions/GUI/CCEditBox/CCEditBoxImplTizen.h new file mode 100644 index 0000000..a458a6c --- /dev/null +++ b/include/extensions/GUI/CCEditBox/CCEditBoxImplTizen.h @@ -0,0 +1,98 @@ +/**************************************************************************** + Copyright (c) 2010-2012 cocos2d-x.org + Copyright (c) 2012 James Chen + Copyright (c) 2013 Lee, Jae-Hong + + 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 __CCEDITBOXIMPLTIZEN_H__ +#define __CCEDITBOXIMPLTIZEN_H__ + +#include "cocos2d.h" + +#if (CC_TARGET_PLATFORM == CC_PLATFORM_TIZEN) + +#include "ExtensionMacros.h" +#include "CCEditBoxImpl.h" + +NS_CC_EXT_BEGIN + +class CCEditBox; +/** + * @js NA + * @lua NA + */ +class CCEditBoxImplTizen : public CCEditBoxImpl +{ +public: + CCEditBoxImplTizen(CCEditBox* pEditText); + virtual ~CCEditBoxImplTizen(); + + virtual bool initWithSize(const CCSize& size); + virtual void setFont(const char* pFontName, int fontSize); + virtual void setFontColor(const ccColor3B& color); + virtual void setPlaceholderFont(const char* pFontName, int fontSize); + virtual void setPlaceholderFontColor(const ccColor3B& color); + virtual void setInputMode(EditBoxInputMode inputMode); + virtual void setInputFlag(EditBoxInputFlag inputFlag); + virtual void setMaxLength(int maxLength); + virtual int getMaxLength(); + virtual void setReturnType(KeyboardReturnType returnType); + virtual bool isEditing(); + + virtual void setText(const char* pText); + virtual const char* getText(void); + virtual void setPlaceHolder(const char* pText); + virtual void setPosition(const CCPoint& pos); + virtual void setVisible(bool visible); + virtual void setContentSize(const CCSize& size); + virtual void setAnchorPoint(const CCPoint& anchorPoint); + virtual void visit(void); + virtual void onEnter(void); + virtual void doAnimationWhenKeyboardMove(float duration, float distance); + virtual void openKeyboard(); + virtual void closeKeyboard(); + +private: + CCLabelTTF* m_pLabel; + CCLabelTTF* m_pLabelPlaceHolder; + EditBoxInputMode m_eEditBoxInputMode; + EditBoxInputFlag m_eEditBoxInputFlag; + KeyboardReturnType m_eKeyboardReturnType; + + std::string m_strText; + std::string m_strPlaceHolder; + + ccColor3B m_colText; + ccColor3B m_colPlaceHolder; + + int m_nMaxLength; + CCSize m_EditSize; +}; + + +NS_CC_EXT_END + +#endif /* #if (CC_TARGET_PLATFORM == CC_PLATFORM_TIZEN) */ + +#endif /* __CCEDITBOXIMPLTIZEN_H__ */ + diff --git a/include/extensions/GUI/CCEditBox/CCEditBoxImplWin.h b/include/extensions/GUI/CCEditBox/CCEditBoxImplWin.h new file mode 100644 index 0000000..5639af5 --- /dev/null +++ b/include/extensions/GUI/CCEditBox/CCEditBoxImplWin.h @@ -0,0 +1,103 @@ +/**************************************************************************** + Copyright (c) 2010-2012 cocos2d-x.org + Copyright (c) 2013 Jozef Pridavok + + 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 __CCEditBoxIMPLWIN_H__ +#define __CCEditBoxIMPLWIN_H__ + +#include "cocos2d.h" + +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) + +#include "ExtensionMacros.h" +#include "CCEditBoxImpl.h" + +NS_CC_EXT_BEGIN + +class CCEditBox; +/** + * @js NA + * @lua NA + */ +class CCEditBoxImplWin : public CCEditBoxImpl +{ +public: + CCEditBoxImplWin(CCEditBox* pEditText); + virtual ~CCEditBoxImplWin(); + + virtual bool initWithSize(const CCSize& size); + virtual void setFont(const char* pFontName, int fontSize); + virtual void setFontColor(const ccColor3B& color); + virtual void setPlaceholderFont(const char* pFontName, int fontSize); + virtual void setPlaceholderFontColor(const ccColor3B& color); + virtual void setInputMode(EditBoxInputMode inputMode); + virtual void setInputFlag(EditBoxInputFlag inputFlag); + virtual void setMaxLength(int maxLength); + virtual int getMaxLength(); + virtual void setReturnType(KeyboardReturnType returnType); + virtual bool isEditing(); + + virtual void setText(const char* pText); + virtual const char* getText(void); + virtual void setPlaceHolder(const char* pText); + virtual void setPosition(const CCPoint& pos); + virtual void setVisible(bool visible); + virtual void setContentSize(const CCSize& size); + virtual void setAnchorPoint(const CCPoint& anchorPoint); + virtual void visit(void); + virtual void doAnimationWhenKeyboardMove(float duration, float distance); + virtual void openKeyboard(); + virtual void closeKeyboard(); + virtual void onEnter(void); +private: + + CCLabelTTF* m_pLabel; + CCLabelTTF* m_pLabelPlaceHolder; + EditBoxInputMode m_eEditBoxInputMode; + EditBoxInputFlag m_eEditBoxInputFlag; + KeyboardReturnType m_eKeyboardReturnType; + + std::string m_strText; + std::string m_strPlaceHolder; + + ccColor3B m_colText; + ccColor3B m_colPlaceHolder; + + int m_nMaxLength; + CCSize m_EditSize; + + /* + CCSize m_tContentSize; + HWND m_pSysEdit; + int m_nMaxTextLength; + */ +}; + + +NS_CC_EXT_END + +#endif /* (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) */ + +#endif /* __CCEditBoxIMPLWIN_H__ */ + diff --git a/include/extensions/GUI/CCEditBox/CCEditBoxImplWp8.h b/include/extensions/GUI/CCEditBox/CCEditBoxImplWp8.h new file mode 100644 index 0000000..fe6d51a --- /dev/null +++ b/include/extensions/GUI/CCEditBox/CCEditBoxImplWp8.h @@ -0,0 +1,87 @@ +/**************************************************************************** +Copyright (c) 2014 cocos2d-x.org + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ +#ifndef __CCEditBoxIMPLWP8_H__ +#define __CCEditBoxIMPLWP8_H__ + +#include "ExtensionMacros.h" +#include "CCEditBoxImpl.h" + +NS_CC_EXT_BEGIN + +class CCEditBox; + +class CCEditBoxImplWp8 : public CCEditBoxImpl +{ +public: + CCEditBoxImplWp8(CCEditBox* pEditText); + virtual ~CCEditBoxImplWp8(); + + virtual bool initWithSize(const CCSize& size); + virtual void setFont(const char* pFontName, int fontSize); + virtual void setFontColor(const ccColor3B& color); + virtual void setPlaceholderFont(const char* pFontName, int fontSize); + virtual void setPlaceholderFontColor(const ccColor3B& color); + virtual void setInputMode(EditBoxInputMode inputMode); + virtual void setInputFlag(EditBoxInputFlag inputFlag); + virtual void setMaxLength(int maxLength); + virtual int getMaxLength(); + virtual void setReturnType(KeyboardReturnType returnType); + virtual bool isEditing(); + + virtual void setText(const char* pText); + virtual const char* getText(void); + virtual void setPlaceHolder(const char* pText); + virtual void setPosition(const CCPoint& pos); + virtual void setVisible(bool visible); + virtual void setContentSize(const CCSize& size); + virtual void setAnchorPoint(const CCPoint& anchorPoint); + virtual void visit(void); + virtual void doAnimationWhenKeyboardMove(float duration, float distance); + virtual void openKeyboard(); + virtual void closeKeyboard(); + virtual void onEnter(void); +private: + Platform::String^ stringToPlatformString(std::string strSrc); + std::string PlatformStringTostring(Platform::String^ strSrc); +private: + + CCLabelTTF* m_pLabel; + CCLabelTTF* m_pLabelPlaceHolder; + EditBoxInputMode m_eEditBoxInputMode; + EditBoxInputFlag m_eEditBoxInputFlag; + KeyboardReturnType m_eKeyboardReturnType; + + std::string m_strText; + std::string m_strPlaceHolder; + + ccColor3B m_colText; + ccColor3B m_colPlaceHolder; + + int m_nMaxLength; + CCSize m_EditSize; +}; + +NS_CC_EXT_END + +#endif \ No newline at end of file diff --git a/include/extensions/GUI/CCScrollView/CCScrollView.h b/include/extensions/GUI/CCScrollView/CCScrollView.h new file mode 100644 index 0000000..538a72e --- /dev/null +++ b/include/extensions/GUI/CCScrollView/CCScrollView.h @@ -0,0 +1,356 @@ +/**************************************************************************** + Copyright (c) 2012 cocos2d-x.org + Copyright (c) 2010 Sangwoo Im + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __CCSCROLLVIEW_H__ +#define __CCSCROLLVIEW_H__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" + +NS_CC_EXT_BEGIN + +/** + * @addtogroup GUI + * @{ + */ + +typedef enum { + kCCScrollViewDirectionNone = -1, + kCCScrollViewDirectionHorizontal = 0, + kCCScrollViewDirectionVertical, + kCCScrollViewDirectionBoth +} CCScrollViewDirection; + +class CCScrollView; +/** + * @js NA + * @lua NA + */ +class CCScrollViewDelegate +{ +public: + virtual ~CCScrollViewDelegate() {} + virtual void scrollViewDidScroll(CCScrollView* view) = 0; + virtual void scrollViewDidZoom(CCScrollView* view) = 0; +}; + + +/** + * ScrollView support for cocos2d for iphone. + * It provides scroll view functionalities to cocos2d projects natively. + * @lua NA + */ +class CCScrollView : public CCLayer +{ +public: + /** + * @js ctor + */ + CCScrollView(); + /** + * @js NA + * @lua NA + */ + virtual ~CCScrollView(); + + bool init(); + virtual void registerWithTouchDispatcher(); + + /** + * Returns an autoreleased scroll view object. + * + * @param size view size + * @param container parent object + * @return autoreleased scroll view object + */ + static CCScrollView* create(CCSize size, CCNode* container = NULL); + + /** + * Returns an autoreleased scroll view object. + * + * @param size view size + * @param container parent object + * @return autoreleased scroll view object + */ + static CCScrollView* create(); + + /** + * Returns a scroll view object + * + * @param size view size + * @param container parent object + * @return scroll view object + */ + bool initWithViewSize(CCSize size, CCNode* container = NULL); + + + /** + * Sets a new content offset. It ignores max/min offset. It just sets what's given. (just like UIKit's UIScrollView) + * + * @param offset new offset + * @param If YES, the view scrolls to the new offset + */ + void setContentOffset(CCPoint offset, bool animated = false); + CCPoint getContentOffset(); + /** + * Sets a new content offset. It ignores max/min offset. It just sets what's given. (just like UIKit's UIScrollView) + * You can override the animation duration with this method. + * + * @param offset new offset + * @param animation duration + */ + void setContentOffsetInDuration(CCPoint offset, float dt); + + void setZoomScale(float s); + /** + * Sets a new scale and does that for a predefined duration. + * + * @param s a new scale vale + * @param animated if YES, scaling is animated + */ + void setZoomScale(float s, bool animated); + + float getZoomScale(); + + /** + * Sets a new scale for container in a given duration. + * + * @param s a new scale value + * @param animation duration + */ + void setZoomScaleInDuration(float s, float dt); + /** + * Returns the current container's minimum offset. You may want this while you animate scrolling by yourself + */ + CCPoint minContainerOffset(); + /** + * Returns the current container's maximum offset. You may want this while you animate scrolling by yourself + */ + CCPoint maxContainerOffset(); + /** + * Determines if a given node's bounding box is in visible bounds + * + * @return YES if it is in visible bounds + */ + bool isNodeVisible(CCNode * node); + /** + * Provided to make scroll view compatible with SWLayer's pause method + */ + void pause(CCObject* sender); + /** + * Provided to make scroll view compatible with SWLayer's resume method + */ + void resume(CCObject* sender); + + + bool isDragging() {return m_bDragging;} + bool isTouchMoved() { return m_bTouchMoved; } + bool isBounceable() { return m_bBounceable; } + void setBounceable(bool bBounceable) { m_bBounceable = bBounceable; } + + /** + * size to clip. CCNode boundingBox uses contentSize directly. + * It's semantically different what it actually means to common scroll views. + * Hence, this scroll view will use a separate size property. + */ + CCSize getViewSize() { return m_tViewSize; } + void setViewSize(CCSize size); + + CCNode * getContainer(); + void setContainer(CCNode * pContainer); + + /** + * direction allowed to scroll. CCScrollViewDirectionBoth by default. + */ + CCScrollViewDirection getDirection() { return m_eDirection; } + virtual void setDirection(CCScrollViewDirection eDirection) { m_eDirection = eDirection; } + + CCScrollViewDelegate* getDelegate() { return m_pDelegate; } + void setDelegate(CCScrollViewDelegate* pDelegate) { m_pDelegate = pDelegate; } + + /** override functions */ + // optional + virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent); + virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent); + virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent); + virtual void ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent); + + virtual void setContentSize(const CCSize & size); + virtual const CCSize& getContentSize() const; + + void updateInset(); + /** + * Determines whether it clips its children or not. + */ + bool isClippingToBounds() { return m_bClippingToBounds; } + void setClippingToBounds(bool bClippingToBounds) { m_bClippingToBounds = bClippingToBounds; } + /** + * @js NA + */ + virtual void visit(); + virtual void addChild(CCNode * child, int zOrder, int tag); + virtual void addChild(CCNode * child, int zOrder); + virtual void addChild(CCNode * child); + void setTouchEnabled(bool e); +private: + /** + * Relocates the container at the proper offset, in bounds of max/min offsets. + * + * @param animated If YES, relocation is animated + */ + void relocateContainer(bool animated); + /** + * implements auto-scrolling behavior. change SCROLL_DEACCEL_RATE as needed to choose + * deacceleration speed. it must be less than 1.0f. + * + * @param dt delta + */ + void deaccelerateScrolling(float dt); + /** + * This method makes sure auto scrolling causes delegate to invoke its method + */ + void performedAnimatedScroll(float dt); + /** + * Expire animated scroll delegate calls + */ + void stoppedAnimatedScroll(CCNode* node); + /** + * clip this view so that outside of the visible bounds can be hidden. + */ + void beforeDraw(); + /** + * retract what's done in beforeDraw so that there's no side effect to + * other nodes. + */ + void afterDraw(); + /** + * Zoom handling + */ + void handleZoom(); + +protected: + CCRect getViewRect(); + + /** + * current zoom scale + */ + float m_fZoomScale; + /** + * min zoom scale + */ + float m_fMinZoomScale; + /** + * max zoom scale + */ + float m_fMaxZoomScale; + /** + * scroll view delegate + */ + CCScrollViewDelegate* m_pDelegate; + + CCScrollViewDirection m_eDirection; + /** + * If YES, the view is being dragged. + */ + bool m_bDragging; + + /** + * Content offset. Note that left-bottom point is the origin + */ + CCPoint m_tContentOffset; + + /** + * Container holds scroll view contents, Sets the scrollable container object of the scroll view + */ + CCNode* m_pContainer; + /** + * Determiens whether user touch is moved after begin phase. + */ + bool m_bTouchMoved; + /** + * max inset point to limit scrolling by touch + */ + CCPoint m_fMaxInset; + /** + * min inset point to limit scrolling by touch + */ + CCPoint m_fMinInset; + /** + * Determines whether the scroll view is allowed to bounce or not. + */ + bool m_bBounceable; + + bool m_bClippingToBounds; + + /** + * scroll speed + */ + CCPoint m_tScrollDistance; + /** + * Touch point + */ + CCPoint m_tTouchPoint; + /** + * length between two fingers + */ + float m_fTouchLength; + /** + * UITouch objects to detect multitouch + */ + CCArray* m_pTouches; + /** + * size to clip. CCNode boundingBox uses contentSize directly. + * It's semantically different what it actually means to common scroll views. + * Hence, this scroll view will use a separate size property. + */ + CCSize m_tViewSize; + /** + * max and min scale + */ + float m_fMinScale, m_fMaxScale; + /** + * scissor rect for parent, just for restoring GL_SCISSOR_BOX + */ + CCRect m_tParentScissorRect; + bool m_bScissorRestored; +public: + enum ScrollViewScriptEventType + { + kScrollViewScroll = 0, + kScrollViewZoom, + }; + void registerScriptHandler(int nFunID,int nScriptEventType); + void unregisterScriptHandler(int nScriptEventType); + int getScriptHandler(int nScriptEventType); +private: + std::map m_mapScriptHandler; +}; + +// end of GUI group +/// @} + +NS_CC_EXT_END + +#endif /* __CCSCROLLVIEW_H__ */ diff --git a/include/extensions/GUI/CCScrollView/CCSorting.h b/include/extensions/GUI/CCScrollView/CCSorting.h new file mode 100644 index 0000000..76cb7b5 --- /dev/null +++ b/include/extensions/GUI/CCScrollView/CCSorting.h @@ -0,0 +1,116 @@ +/**************************************************************************** + Copyright (c) 2012 cocos2d-x.org + Copyright (c) 2010 Sangwoo Im + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __CCSORTING_H__ +#define __CCSORTING_H__ + +#include "cocoa/CCArray.h" +#include "ExtensionMacros.h" + +NS_CC_EXT_BEGIN +/** + * @js NA + * @lua NA + */ +class CCSortableObject +{ +public: + virtual ~CCSortableObject() {} + virtual void setObjectID(unsigned int objectID) = 0; + virtual unsigned int getObjectID() = 0; +}; +/** + * @js NA + * @lua NA + */ +class CCArrayForObjectSorting : public CCArray +{ +public: + CCArrayForObjectSorting() : CCArray() {} + /*! + * Inserts a given object into array. + * + * Inserts a given object into array with key and value that are used in + * sorting. "value" must respond to message, compare:, which returns + * (NSComparisonResult). If it does not respond to the message, it is appended. + * If the compare message does not result NSComparisonResult, sorting behavior + * is not defined. It ignores duplicate entries and inserts next to it. + * + * @param object to insert + */ + void insertSortedObject(CCSortableObject* object); + + /*! + * Removes an object in array. + * + * Removes an object with given key and value. If no object is found in array + * with the key and value, no action is taken. + * + * @param value to remove + */ + void removeSortedObject(CCSortableObject* object); + /*! + * Sets a new value of the key for the given object. + * + * In case where sorting value must be changed, this message must be sent to + * keep consistency of being sorted. If it is changed externally, it must be + * sorted completely again. + * + * @param value to set + * @param object the object which has the value + */ + void setObjectID_ofSortedObject(unsigned int tag, CCSortableObject* object); + + CCSortableObject* objectWithObjectID(unsigned int tag); + /*! + * Returns an object with given key and value. + * + * Returns an object with given key and value. If no object is found, + * it returns nil. + * + * @param value to locate object + * @return object found or nil. + */ + CCSortableObject* getObjectWithObjectID(unsigned int tag); + + /*! + * Returns an index of the object with given key and value. + * + * Returns the index of an object with given key and value. + * If no object is found, it returns an index at which the given object value + * would have been located. If object must be located at the end of array, + * it returns the length of the array, which is out of bound. + * + * @param value to locate object + * @return index of an object found + */ + unsigned int indexOfSortedObject(CCSortableObject* obj); + +}; + +NS_CC_EXT_END + +#endif /* __CCSORTING_H__ */ + diff --git a/include/extensions/GUI/CCScrollView/CCTableView.h b/include/extensions/GUI/CCScrollView/CCTableView.h new file mode 100644 index 0000000..4295a37 --- /dev/null +++ b/include/extensions/GUI/CCScrollView/CCTableView.h @@ -0,0 +1,305 @@ +/**************************************************************************** + Copyright (c) 2012 cocos2d-x.org + Copyright (c) 2010 Sangwoo Im + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __CCTABLEVIEW_H__ +#define __CCTABLEVIEW_H__ + +#include "CCScrollView.h" +#include "CCTableViewCell.h" + +#include +#include + +NS_CC_EXT_BEGIN + +class CCTableView; +class CCArrayForObjectSorting; + +typedef enum { + kCCTableViewFillTopDown, + kCCTableViewFillBottomUp +} CCTableViewVerticalFillOrder; + +/** + * Sole purpose of this delegate is to single touch event in this version. + * @js NA + * @lua NA + */ +class CCTableViewDelegate : public CCScrollViewDelegate +{ +public: + /** + * Delegate to respond touch event + * + * @param table table contains the given cell + * @param cell cell that is touched + */ + virtual void tableCellTouched(CCTableView* table, CCTableViewCell* cell) = 0; + + /** + * Delegate to respond a table cell press event. + * + * @param table table contains the given cell + * @param cell cell that is pressed + */ + virtual void tableCellHighlight(CCTableView* table, CCTableViewCell* cell){}; + + /** + * Delegate to respond a table cell release event + * + * @param table table contains the given cell + * @param cell cell that is pressed + */ + virtual void tableCellUnhighlight(CCTableView* table, CCTableViewCell* cell){}; + + /** + * Delegate called when the cell is about to be recycled. Immediately + * after this call the cell will be removed from the scene graph and + * recycled. + * + * @param table table contains the given cell + * @param cell cell that is pressed + */ + virtual void tableCellWillRecycle(CCTableView* table, CCTableViewCell* cell){}; + +}; + + +/** + * Data source that governs table backend data. + * @lua NA + */ +class CCTableViewDataSource +{ +public: + virtual ~CCTableViewDataSource() {} + + /** + * cell size for a given index + * + * @param idx the index of a cell to get a size + * @return size of a cell at given index + */ + virtual CCSize tableCellSizeForIndex(CCTableView *table, unsigned int idx) { + return cellSizeForTable(table); + }; + /** + * cell height for a given table. + * + * @param table table to hold the instances of Class + * @return cell size + */ + virtual CCSize cellSizeForTable(CCTableView *table) { + return CCSizeZero; + }; + /** + * a cell instance at a given index + * + * @param idx index to search for a cell + * @return cell found at idx + */ + virtual CCTableViewCell* tableCellAtIndex(CCTableView *table, unsigned int idx) = 0; + /** + * Returns number of cells in a given table view. + * + * @return number of cells + */ + virtual unsigned int numberOfCellsInTableView(CCTableView *table) = 0; + +}; + + +/** + * UITableView counterpart for cocos2d for iphone. + * + * this is a very basic, minimal implementation to bring UITableView-like component into cocos2d world. + * @lua NA + */ +class CCTableView : public CCScrollView, public CCScrollViewDelegate +{ +public: + /** + * @js ctor + */ + CCTableView(); + /** + * @js NA + */ + virtual ~CCTableView(); + + /** + * An intialized table view object + * + * @param dataSource data source + * @param size view size + * @return table view + */ + static CCTableView* create(CCTableViewDataSource* dataSource, CCSize size); + /** + * An initialized table view object + * + * @param dataSource data source; + * @param size view size + * @param container parent object for cells + * @return table view + */ + static CCTableView* create(CCTableViewDataSource* dataSource, CCSize size, CCNode *container); + + /** + * data source + * @js NA + */ + CCTableViewDataSource* getDataSource() { return m_pDataSource; } + void setDataSource(CCTableViewDataSource* source) { m_pDataSource = source; } + /** + * delegate + * @js NA + */ + CCTableViewDelegate* getDelegate() { return m_pTableViewDelegate; } + void setDelegate(CCTableViewDelegate* pDelegate) { m_pTableViewDelegate = pDelegate; } + + /** + * determines how cell is ordered and filled in the view. + */ + void setVerticalFillOrder(CCTableViewVerticalFillOrder order); + CCTableViewVerticalFillOrder getVerticalFillOrder(); + + + bool initWithViewSize(CCSize size, CCNode* container = NULL); + /** + * Updates the content of the cell at a given index. + * + * @param idx index to find a cell + */ + void updateCellAtIndex(unsigned int idx); + /** + * Inserts a new cell at a given index + * + * @param idx location to insert + */ + void insertCellAtIndex(unsigned int idx); + /** + * Removes a cell at a given index + * + * @param idx index to find a cell + */ + void removeCellAtIndex(unsigned int idx); + /** + * reloads data from data source. the view will be refreshed. + */ + void reloadData(); + /** + * Dequeues a free cell if available. nil if not. + * + * @return free cell + */ + CCTableViewCell *dequeueCell(); + + /** + * Returns an existing cell at a given index. Returns nil if a cell is nonexistent at the moment of query. + * + * @param idx index + * @return a cell at a given index + */ + CCTableViewCell *cellAtIndex(unsigned int idx); + + + virtual void scrollViewDidScroll(CCScrollView* view); + virtual void scrollViewDidZoom(CCScrollView* view) {} + + virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent); + virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent); + virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent); + virtual void ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent); + +protected: + + CCTableViewCell *m_pTouchedCell; + /** + * vertical direction of cell filling + */ + CCTableViewVerticalFillOrder m_eVordering; + + /** + * index set to query the indexes of the cells used. + */ + std::set* m_pIndices; + + /** + * vector with all cell positions + */ + std::vector m_vCellsPositions; + //NSMutableIndexSet *indices_; + /** + * cells that are currently in the table + */ + CCArrayForObjectSorting* m_pCellsUsed; + /** + * free list of cells + */ + CCArrayForObjectSorting* m_pCellsFreed; + /** + * weak link to the data source object + */ + CCTableViewDataSource* m_pDataSource; + /** + * weak link to the delegate object + */ + CCTableViewDelegate* m_pTableViewDelegate; + + CCScrollViewDirection m_eOldDirection; + + int __indexFromOffset(CCPoint offset); + unsigned int _indexFromOffset(CCPoint offset); + CCPoint __offsetFromIndex(unsigned int index); + CCPoint _offsetFromIndex(unsigned int index); + + void _moveCellOutOfSight(CCTableViewCell *cell); + void _setIndexForCell(unsigned int index, CCTableViewCell *cell); + void _addCellIfNecessary(CCTableViewCell * cell); + + void _updateCellPositions(); +public: + void _updateContentSize(); + + enum TableViewScriptEventType + { + kTableViewScroll = 0, + kTableViewZoom, + kTableCellTouched, + kTableCellHighLight, + kTableCellUnhighLight, + kTableCellWillRecycle, + kTableCellSizeForIndex, + kTableCellSizeAtIndex, + kNumberOfCellsInTableView, + }; + void unregisterAllScriptHandler(); +}; + + +NS_CC_EXT_END + +#endif /* __CCTABLEVIEW_H__ */ diff --git a/include/extensions/GUI/CCScrollView/CCTableViewCell.h b/include/extensions/GUI/CCScrollView/CCTableViewCell.h new file mode 100644 index 0000000..bc9a042 --- /dev/null +++ b/include/extensions/GUI/CCScrollView/CCTableViewCell.h @@ -0,0 +1,60 @@ +/**************************************************************************** + Copyright (c) 2012 cocos2d-x.org + Copyright (c) 2010 Sangwoo Im + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __CCTABLEVIEWCELL_H__ +#define __CCTABLEVIEWCELL_H__ + +#include "base_nodes/CCNode.h" +#include "CCSorting.h" + +NS_CC_EXT_BEGIN + +/** + * Abstract class for SWTableView cell node + * @lua NA + */ +class CCTableViewCell: public CCNode, public CCSortableObject +{ +public: + CCTableViewCell() {} + /** + * The index used internally by SWTableView and its subclasses + */ + unsigned int getIdx(); + void setIdx(unsigned int uIdx); + /** + * Cleans up any resources linked to this cell and resets idx property. + */ + void reset(); + + void setObjectID(unsigned int uIdx); + unsigned int getObjectID(); +private: + unsigned int m_uIdx; +}; + +NS_CC_EXT_END + +#endif /* __CCTABLEVIEWCELL_H__ */ diff --git a/include/extensions/LocalStorage/LocalStorage.h b/include/extensions/LocalStorage/LocalStorage.h new file mode 100644 index 0000000..c387046 --- /dev/null +++ b/include/extensions/LocalStorage/LocalStorage.h @@ -0,0 +1,51 @@ +/* + +Copyright (c) 2012 - Zynga Inc. + +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. + +*/ + +/* + Local Storage support for the JS Bindings for iOS. + Works on cocos2d-iphone and cocos2d-x. + */ + +#ifndef __JSB_LOCALSTORAGE_H +#define __JSB_LOCALSTORAGE_H + +#include +#include + +/** Initializes the database. If path is null, it will create an in-memory DB */ +void localStorageInit( const char *fullpath); + +/** Frees the allocated resources */ +void localStorageFree(); + +/** sets an item in the LS */ +void localStorageSetItem( const char *key, const char *value); + +/** gets an item from the LS */ +const char* localStorageGetItem( const char *key ); + +/** removes an item from the LS */ +void localStorageRemoveItem( const char *key ); + +#endif // __JSB_LOCALSTORAGE_H diff --git a/include/extensions/cocos-ext.h b/include/extensions/cocos-ext.h new file mode 100644 index 0000000..a79f26f --- /dev/null +++ b/include/extensions/cocos-ext.h @@ -0,0 +1,90 @@ +#ifndef __COCOS2D_EXT_H__ +#define __COCOS2D_EXT_H__ + +#include "ExtensionMacros.h" +#include "ccMacros.h" + +#ifndef RT_REMOVE +#include "CCBReader/CCBFileLoader.h" +#include "CCBReader/CCBMemberVariableAssigner.h" +#include "CCBReader/CCBReader.h" +#include "CCBReader/CCBSelectorResolver.h" +#include "CCBReader/CCControlButtonLoader.h" +#include "CCBReader/CCControlLoader.h" +#include "CCBReader/CCLabelBMFontLoader.h" +#include "CCBReader/CCLabelTTFLoader.h" +#include "CCBReader/CCLayerColorLoader.h" +#include "CCBReader/CCLayerGradientLoader.h" +#include "CCBReader/CCLayerLoader.h" +#include "CCBReader/CCMenuItemImageLoader.h" +#include "CCBReader/CCMenuItemLoader.h" +#include "CCBReader/CCMenuLoader.h" +#include "CCBReader/CCNodeLoader.h" +#include "CCBReader/CCNodeLoaderLibrary.h" +#include "CCBReader/CCNodeLoaderListener.h" +#include "CCBReader/CCParticleSystemQuadLoader.h" +#include "CCBReader/CCScale9SpriteLoader.h" +#include "CCBReader/CCScrollViewLoader.h" +#include "CCBReader/CCSpriteLoader.h" +#include "CCBReader/CCBAnimationManager.h" +#include "CCBReader/CCBKeyframe.h" +#include "CCBReader/CCBSequence.h" +#include "CCBReader/CCBSequenceProperty.h" +#include "CCBReader/CCBValue.h" +#include "CCBReader/CCData.h" +#include "CCBReader/CCNode+CCBRelativePositioning.h" +#endif + +#include "GUI/CCControlExtension/CCControlExtensions.h" +#include "GUI/CCScrollView/CCScrollView.h" +#include "GUI/CCScrollView/CCTableView.h" +#include "GUI/CCEditBox/CCEditBox.h" + +#include "network/HttpRequest.h" +#include "network/HttpResponse.h" +#include "network/HttpClient.h" + +#ifndef RT_REMOVE +#include "CocoStudio/Armature/CCArmature.h" +#include "CocoStudio/Armature/CCBone.h" +#include "CocoStudio/Armature/animation/CCArmatureAnimation.h" +#include "CocoStudio/Armature/datas/CCDatas.h" +#include "CocoStudio/Armature/display/CCBatchNode.h" +#include "CocoStudio/Armature/display/CCDecorativeDisplay.h" +#include "CocoStudio/Armature/display/CCDisplayManager.h" +#include "CocoStudio/Armature/display/CCSkin.h" +#include "CocoStudio/Armature/physics/CCColliderDetector.h" +#include "CocoStudio/Armature/utils/CCArmatureDataManager.h" +#include "CocoStudio/Armature/utils/CCDataReaderHelper.h" +#include "CocoStudio/Armature/utils/CCTweenFunction.h" +#include "CocoStudio/Armature/external_tool/sigslot.h" + +#include "CocoStudio/Trigger/TriggerBase.h" + +#include "CocoStudio/Components/CCComBase.h" +#include "CocoStudio/Components/CCComAttribute.h" +#include "CocoStudio/Components/CCComAudio.h" +#include "CocoStudio/Components/CCComController.h" +#include "CocoStudio/Components/CCComRender.h" + +#include "CocoStudio/GUI/System/CocosGUI.h" + +#include "CocoStudio/Json/DictionaryHelper.h" + +#include "CocoStudio/Reader/SceneReader.h" + +#include "CocoStudio/Action/CCActionManager.h" +#endif + + +// Physics integration +#if CC_ENABLE_CHIPMUNK_INTEGRATION || CC_ENABLE_BOX2D_INTEGRATION +#include "physics_nodes/CCPhysicsDebugNode.h" +#include "physics_nodes/CCPhysicsSprite.h" +#endif + +#ifndef RT_ADD +#include "spine/spine-cocos2dx.h" +#endif + +#endif /* __COCOS2D_EXT_H__ */ diff --git a/include/extensions/libExtensions.lib b/include/extensions/libExtensions.lib new file mode 100644 index 0000000000000000000000000000000000000000..ec39b059fc005d28ab797cdb3d7efd79424dee3e GIT binary patch literal 357688 zcmeEv4V@#5D6e_tT}bK$}z3l=P*|8dMtgzWGFl6%|n zB=`2KNbZCuNbbZ@fd>%+?>vFyqTA6_DGBSPSes=(t2fsY`b6ld-ua4|yQqlhQNeF%ZG zj^p?k(v9JAguvM=1dtYI10SE_I0rl!z~LO=6X4GP?w_u`6S0V%+I7;9Vguow9=Xh`*l4F3a2Z29TIUYj%7%oN#{CR}{ zZ2uW}xW(}o*kM54{{?vDXo05?0)IV&mQ+Ife@m0)IbD0BQAi z;PGjWf7m3)0N(!qp4eO9B80#{mkL~i5O{Jx06Lxo{#E063hB#$JbMcG_n^Q-2p=MO zatepFH_0JfgNT!p0+c|Gn|hQ*s(|8c7(vw zHwZk55ZGxe$1`>#c?Q^g2Cy@Jr+DUb1ujMi?6OASPK3a-S{%FXO7aYsBLtp3%(2^E zB+qaSLf|>DPw`yDo8el7!1Fe9?7k1lGu(m@cs}Aqu?OPCa1lb_1uF%RmM;MIJdNXp zQzTEZ*Fgf0AOv1?GRNLklBakv_%eJAA+QhhQM|+!xC$Y#??#T7E+Tmbq}fY>{VwHr z*)+*h?2q^`+>8)-`AHlH976I8;BWx&iVHaoJc{HgUI`uyHzEWMI+5d5OG%#L0ffN8 z=Wx6l94QtM0i^W;U?K8>V$q=j4Lq!KL8KqU6$pVhHaJ#4m*g2PMhFaz3LwvifZ_8w zMxcXY%?<*WA_UeVe;6J{2#g}_DBgtMDb}qNcpM?{X8eufsMQ>A*@fg8u0;qO-QXBo zMDh&KIR+eqe5ELX0|U~w1dN}~F@bW&a34Zo@=T60erG@)m4T@fIo2cp7_LGHOiy!E z_9S_R8xaBLI~8han$iW19a4Z*(%3d5eJF}$_WGF z)&QFCqd@u z??dto*CPZ@KAz(}2ar6&JqUsK;&+Po?JaNxLg189j`#0G@(kM%0;f)MeBdCGXSfp~ zunjsWK8W}*T!|1kt;O-7T}htda)iL?NI!}X<9mi%5CUh63p|Ao_z21y#hHjd!)*wG zkAerqSw!Fxguus;e+*9`1kOH_0!J7ek&Idl-A#evm;DXH@pV@`v8IX3L0k$KJC_W3l40j;}EwR`UM=9uOWGgZ|o_6xPJq<;v|l5t|WPiD~Z5W z2!U@+aa@ITWVj9?@NL+lxOz3mcUF)*#Wjd8!`%ph@1jglT#Mfs9zqCwZyU#T`;$Dw zwFrUlA0zM>Lg4z-IDW7%$ul4wegNEXw7??>fgeI2#f=9Gfa8t8kJbs`n;!u;oyqZI zaAkNHA#n41IeyYb@(f7xp8&VO7R66n9JlUH@(iaV1b&A9W;g>OaN8aNXCnlDzMA89 z)K7-X5CXpde+F>+1#riy9KS?*Fx-a_xN{@NuXZ4LhI0@CcO51007Br`n>p^@hvXUV zLJ0f@@)Y;%B5)x>;I{(;Pay>E1y_pSEfcsCA#fkkl;Zat0^s_4;Qq5X{%{D%Gr-m# zfCo=p3pYc1x{Rn}FFXi~l3X-RIgb1965cun$ z0J#4Zc=UXZztu>d0l)nXcnrT&{Cz;+F@(V5h%3cEdIV4g{sBC(o#UTtNS@-!-34w# z2>c82rg#eJ#Bd8j;NKe=3S@V}aV0{)8t1TgBL#+Q5dyg>j{Hufz;G!-pfJg?!w#gt za0x=-X`=#9Ap~~Bw-isWaqM&eDKOlM5O~H`j-8j10>ga>foGn@vCA@2V7MJ2@T@Aw zuCU8+0Yc!}D+C@z2<*0v<2kU$a2-P6x$6Y*&2xe0!4AdlJpy+i1fCDR6nmV<@q%Tf zz;GKvU{Cyw;)S~kY)1&}HOTQIn-mx>LI~`Aw7?Sxfft{_vCjfhV7LJx@RE%j`$8`R zbnXkhv`gTAgus5=I9_%TDKOlK5ZJ%L@$x-Lf#GWifdkfXyaK!!E=C9(*vo;jK!E|a zUI`p@sK9Lqfmb1}6bJ7t0NI0qS05p8FG66!R*r@Hk^;l^2!TbLITjyG3JfVYp;&r**M3JiB61UivF6kXuUa4kZh`xpU~?QWn4X+^PoSm0rVz=~}ghaW%+ z3|AopdItp_KnV1m!*Rq4Qee0bA#mhYj+FZ1f6M+gj^$}x<5Vz?3^FtSeI5rn{+Q#jTxAq9q85dx!UaJ&h>Ga!%O z1gx7BcnTr#=JPm?T1E;Cw;%-GvXSHHJxPJ#Dulq;IL9%B6d2A$2$YWC7)Smx+=URB zxQJsC`A<>aN8oaVz!c(5u^#1~VLL)#8hjXTLI_kgaBSFt6c{c>2po(2rl{rxu0aUQ zpxjc_@IAv-2!T4%k79Nwfg2G5Z#|u(fp{=HiV$d?#L+^$7*Hl#7mkhf^$)IEJv`R4 ze5iYM-{A17)nnDl`0~xIa;;gZ*P3K(Y+z*N%IIh09f9xoSHry{14oYabPjitVsSxd zvsrF6`%AUb`f{VA?C9*6s87_JizYid-q^XkqqA$xf`yAZI@ZBbWoCBFTuxVFu&Zam z0%JRlRM<*SxmsRdYLy2Y^%mk&O&dRRJ!zSYCMB^h1t@^+?(WV;qqJp3y|HS1LwTY# zRByB@we<$^Pp!e+xf>o!xJDmby zyVhzLm1Js8Q%1)^Ft-${z5HPey5?G~dd)C@j3oUrkXwt5hf>6^pXTCRW3V!DtWnG9 z=7*WQspZ)C>6i@VS?^pqeH0CZ{qa+Z#YRp?%5P<`jt;a{sn3*K=`zqzfwAq_SZWy! z<>64NHPub-zP0!mO3j4x zx>cT?O&J|s(Lj9ULh%t&$^`Lm97l4Fibfa7dite zJuAT|DAhap;eOa%u9|sLhLXWp$gCyAL?IH?-&1OphA_7?Vb-L%aWauNwVV(?waG}H zsVZG;BjLqS%&n^%%TNpza!K)1i%~o985b|=tIf`_p%z=b80;Kb+c$t;2L?xmyH<^k z4R)^X?C%JyW*Ev*OLWGW&!MDA$28JrRs-p%Z;qFewdL`lI_5P^d{6@!#6 z#o|KcTGmK#0H7@Z-3AL2VJqgM%pNOYvNesU9bFNjKXFwcPP6J`zs}@o^hC`{5x;)b zG8x_1Ass2d73HjMq9t8PzcsTd(?rv$)C71WPHZOIREY%iC(kn`8&Jvw zEF@0-B^ywQF#VG0xu|CK$9|o%{wh(ohLGPz(sWg#euY3-cf#C|RJ~k=S&&cHEDv=b zs_7l^y{lO=c@ib=pRI`5mLUXux|3%>l9VeYn0EOzK~%Ta_e`^DbRN~MDIv7W#?5iM zHNFpN)~FTE934Cey#cmh#w{twk}>hnm0=cKe?HESk1E&sJg7Hm;3d(m5DDs+4}2t6 zv;;%8B!du{CAAo}6Ek-4Il)PPhosa!4)fCaxL91G^rbO{+u6ysg+<4S>7>I}oyw)y zy`{+_tv0YSaNwn>l2H$1qIB^U3{uGp%ZWn(rA;GAzqRCHfu2n>dB0`VP(jar8ZCYn z(s6_y1!EO{`^wRU9*0zF{5;Ht8hWI%>kKeV9GGabF_I5hP9Cvnnl@7qu$?%V(KKx& z@3%bCs#KeCPK%ylBXMR|GRRVxG?esPb9${55fxTVHTbP34a)T5Ya$)CnlM(=H*BDQ z*_My|6n4#pU7M0Ip@vaIX`j{Pv7eS%GjV2DJ}y*PH5XZJ~uI)HdayLfX(EIoP;_d7tq!%E833VLK`1(5Kd-Qrpka% zY*{y^6060GMY!ar;Skngz#v);j0r?l7}$5~hOt>!(!g4@dKjCHstDMpJ(TP?V?sUC z5i_(St0*zCRx^+(H0Bmtb5hcZ)s==(xE`hF6V_zRCR(Xdl8GuZ=Hk}0loVWfW6ROX zmXbnLQGkndc0ZxYDrHP8$m&*1lohsR+RRwRR;@IIVig&430JF>Ou}l+ctmSd8X8e8 zW-Q!FmBzR$Y-TfBi_#d6Y6-AVu5u;RM=d#1OR}026L$>`GL7c!VyjhJVzJ6naSB(k z42;66%=tuXT3R|$P3COes+X38tH9iLwC1HH5!Do6W40)qP@&D0Wa1#Jm@&y@%1)*} zBk$OH+ZM{PnzOSF*Xed~4eQOwG+N!;LNuy2BTu(QXbU}8TSivVCZa9$qH2RY6E}b) zwK7rxZQZi!9T#tjRhcRSKCyMzm`bb`GZx`mnTA7HhXI3Vbu%UqRbgP?txv{gT}cCL z(duDrHmV|MKY5>1QWcX+=xdkNjJRmZ?8xnsq zs16ebZj~`N?24M$i`Er$!%-bU28o;dlB%0jKwG!0g2Y8qVpXQffKO~4F{To$#f(L` zj-=rb)?vUPT1AWrL{%8rcWa8VSy$4)TC{o?n~kdA_9a_N<;(GY2C0>3aR{!6(hGM2 z8wwQ0W2CjL_Vq7MT!B`Y42x>ni>;Fei5x4hYdKsK&FqGywX8;~pMlY+u$E1??irYJ zWwb0rtC@kRsBplhTO4CfafbUrQ9@NB0sTqatP^z0K9A^4*hMW-Es@~b<$I;Wn$=%> zS|yvIRe z6xL*FG#V8mu)L<_Xq7cG92M8J>(*Q&bFP%8m1uP}G8YvO*-bhM zlGt&(1zAhdz*?xHM+R_OhU1ikILHs5B(@T2v9KM<0h44a3L$1g@90R#hQ1KBAwA*| z)U5mz`c^1Uf8fB$sPFa(eTiZx9wi#CkF=(ib%YP-40RSe*A({~FEuL@W6f5BK1tIv zQrvH1y3`nJHA5-W z^@I+0pLgQ%VHQO$(y^GHL|U@A!}p+3dz2M>s_WrZPec;9`|u-h-C^(Afu6Ckj*h;* zBfJ}bO+<=^ms^9SMrkHu09R-y-KXf4mXy-P-k~*9IEMn4Uo)XcAkl#mF+xWP^dDYy z+oG%3SF5yoDy3?DeOyZTDv0_+=n}V5Mr%bceZXq4v**aM0bllckx3)!+FQOk!hNW- zHz^mRMvdi*$PJp0G;{PSjGKQ>hI%a8qN_M0DbJ(oq)01Xq^;m^oiC(?xw~p=3NObYgIzx$ZUo)exx5#z8w}PfxRT#rKii-QZ0d{zrPD`wX|O?} zdvtskqPIm?ajY~sN&T?Cse$qY9@!~1wrFrd2?QxO9hoB+Xw2HJwwNLt`+Vu#@gI~%Y4Y#i!uAhW1QZ@<^8+NlXp9T^z3g@VJOw^W>kPxv+Tddd77(ufOf z$VA-Y%8^^MvqvVgrDACcPaO6%N}H4o5(ap_VU4j|u~b`ME%()W%Ih2DaZCC@aI95#!r0%vWL2I?L0#?lmHq|(r-T3Ri4;q7n7qIQQVEYB>AcXyDz#f& zygo3qo>(Tyi_AV(#BaB; zq&OuWGswz6gW@Ev$-A{PmYJa}nv>WjZgiDtA6gZTs{lFxBbdO_DZ5IJ^1;-pS9Hqp!_CID_6Krqcc}3)KvYleo&d z!z@(O>kTu_*tCe9FJdg@l-7(&!yL12w(OW8Gpt+Nt*GO<<}TKbaKH5ZP?1 z6ZmFt_=3eC#5ueA1m4C&r3?w*W?M-yk`11+uurcyiD`xgU0Pb?Lo#_9BymmOqRXkK z*BfSPq_|tTT-b_|^@^ z2E1jnHfxo$G;6d|({6(q5f7|ql-8FAOReb+($@9X?RWk4g*+hRUVynS`uoHc|aHdVFR zEyc-}O;kkeOI;S%xW5YdT$toM%&IoRQ#oArxMEkk@9aakN}DT+a53|2JYsZ(Ke~G= zIT71#CmNH)5pa;Ty9rE|vdI&#GG(ba$+K98h|mzVo;-q2iiIQtQz?sbN*qxqQIcj; zI&E!X#oCdTrSWogcz6X|x`mRoOF=VEy~kT}5sRCSI68&Rvvkj{7-fe0%Y|{2+o#!M zE5CceCCsAi?%qn+x#+fmZBgoR3?z=sMMj4olhcOc>Fgpu=}EeT!e&Ats3|L(jOpQ# zfua;#Jo$`y6IPUhON?uyoi72ONE3Ln^4)nr|sJ3g|*i>g^NIY`3LO8$7H}X52D2(#5tYD zwy_Ju*;&VkD;p_z26PuE%O(C=AZD0&lT45Bs}4EQGX=g`hHOf}p;~U0*OVJgdLmz0 zqk}WG>4ahPt#f5eoMJ@-v6Z&EiR(CCkJ2V>V1+vr>RbA1%@*D42WIl?(uO*H6Upg> zi<6b+Y^gOdy|U75VIRNI;U3nQbv7EME${(-Q=x6u=`vhh<_8nHagW4!Y2sLVibkG3 z;c_aXnqCp*!m>u3gJI`haPo^Ehjyo>l@lQ-Q-O0XUK2Wh28xq7w_cek(NkP&r^_{G z&4F&7KuYSZTlD*@eY^C5S-IIcxnZu^>O#J*Z`9{%lYKK-m;x{5R#&9u*nqDtwnG;f zZK|!TmnPNC5nIIbn>Q6KmM1H%uKH%00cd=CDw8!xd%q?yJzc0I!PVXm%MnUWU- z9jZMQcJ7;AeBxh^k4e+EnTX?$jZH(Xz%qC;b##in1qhW0pNASlzg-p>`v$%Bq=pM) zyred+A^pLIt6eH7Ki9VaJ>fYdT_f!be|!!`fS0Qvtt!T+G>bt`8Mno$r&5r+Y{QzE zdJdAwq=zxVE)L%n4$?x_*%jPH6Qq(&k)MldatSG-MJ1gcmkGZL!Yk0(I$|n~y^8b( zjch7ier!*VkuG(rwM8dqSgT>q5@WC7%1pUF*HVuxQ1kjiMJlZh!Jt*by$!T<%V*!6 zDlca5!yHm;aaiEW7Wc9-C6mDYUJ)vpRQdR@MGIBBjC7%%QO}YuV#bk4smEc0^$6!$ z6{Rm8DI1tNGLvRj=Nb(p;&7!^)f;U)-WI>?GvpFBKGYMtC7!()+GXdk(Z zN-0O*s*dRlqE9sJsQUhtSu11d+;{7G(wfaSZJq}!6UXA38AnBgtMiAp=?*b=e2$o< zHm8jepXhK*tu3CFro&{wES<&>J7t3^Tw`bHQ-@zhogs#1v+X+kGHGP&*n%Qmeo*xR zD0juqwM+b;@ufs69H}7fRLglbOXJnDJCCcT+ZC7`rOj3)r3z*r)1p;Oi{h?gTnEKQ zH*^MG^70DOt2fY5_M}xo?JsXM>W!|ssVU~gaMSYJin@9N)>A5=w#_e%!}5dw;<-#Z z7=vm`-nnvGC6q(oWZ*huw)7nD*aSU$GdX67PNj6!Tdg|o zdsl8v!R$dWh1pDuskm!*WqFDY=r!gVVyv18yEa#gJBHI4HI#O(4%cT>N7P7GSk&DU z00%F4c8V50{VfHaIJL`m6!VKsLyO$W12JcYjthi_h;33xx%HPeuPoQrBSb-|fZ48K2Sq#bBaomwaT!AtppZO(qg(u9;CAWyM$S`+AU8?ua?b4M7_o zbVE`IGn=!eiAsw;nxJ%nVRCsOJ60LX1}$p114#xoMVUS3l{m9o zElrer>s1V^kzR@k!mv?eS#B|V3*$ANgVpTX999_{m>{W)${43c8PhzC@}yW((P=*t zYt~?PWpSKTmEG}#<5rBql+1MrMjI=2lmhy)8lS)v38nT0L`xLwrh{D@^>U_s&M;Cm z5)aDCdqrmsGMhd>GrBVCTl?2ZK-N?`Ot^fg#SH$@ZIrVpr<_+~(#%;&c4lL+rM=mT zyB#7j37baRvATut!%^L)LTAbOmyy9JwVqZBXTf4hm&(v;`{$+NM}K&TEzr%1>1spy zkY&*-sjUZxfeB_Y5l+S$lmC zDbe(0#!cm!WvtuN@f4%23;NbH??# z>LkA{T`TqcCsSyiO{bA(mbsVY)+E)^g)C{Zs*2;|RZY#BZ9p))ZpOG(YP4{%pjX~h zX~;$svEDHpn~b{R85zgagkompg0t!_GPv!*sUz+NxL8vW7uBhLC%IrSPUKGh)GYzwhd}sp7WKgZPV*A zHHA(P;FrZ+on9oIZcL$l#Iz< z#x$c!mmhAjGgTGa9H!ReXF{jz4B7O@BoMfy)x_A)_q?K${c)Y6v-seQU|7|3p274E zq*KSYeM%We-3iK2-)$mB?a<}IH2%7o9JAEKF$n$XX5XzWl%}~bwV85DhSzeWR1jlZ z>dFOo8ikB1CF86m?~_20_FeT6O(e+Fzk!#ib^&0 z>bhWUu0q&vRd5a)(%22n*V*08CvmNod%(i|3id-P!dsK0U-)*oWHaKALqATdrrgc# zFf>-d>{rU0*lB0~sgt;9;Vv3BAryBsdQEyI4hOMdrJSf{9N5R9AuQ#PQVHd-u3n#6 zRb!nMJw<}HUuRE1XbLui5{Cm@sfTrCLIj&eYS~D%I9+Onp0-MU;}Z48AJa6V)ZUs( zvw{;wgC%+@)HhceSKOi|(?}Pm=gPdBV10*oRgcJA<#|Qt3M6-a%I9^>i|%3t4_avR;EVNUzcQZ#jTD$85E z(3L#?_O8;J7yUlwxaN}0T&Q>HvWmhPvwg5#^omR|>w)zc;b8eLtf%cGr|*2&P9yUe zhp~bGNG!M+Hy(5_!8|D6on0|KCC>)`b-hkHn=43bTbkX5G=jRaGm2K9)P$fa6(283 zSUStbC#=fl!zLAR&1$x`M^sk?lXVzL zxtvL(%Z_hOqHUk{mOGE7=V?2OS5dO5Vyy@Hz1Eo4>%E~|X2!-{zne*&9{Q9JyKivId!Wopan!@CSKG@W?7 zUES3sXH*i$T~`Mf49+#D{lzMI_CHcd%|&64pEmPb)T%OOV${wY9zzN~7JcqlzuZl*=6*Z}PvgnDpm>+~K%zu~nX- zqL}Iktc&^O<30=Mp{c>_C#nd25s+S8p25?84w2DB9kJg9G!1$2p=x~76aMJLe8sfT zre;N>KEs<~*W*oYY~e7lErib8UqYuxZMR*wl<}qt7Wd=ajy5n(t-Cl=+DzRB_O?gn zcQx9htTloe}m>u_1%7W(*#TMFZHllGh5sK8V#-cGW6tYJ+l9B(tZhH2PT z3K#3+8*oOGZhGPS7um&vCYvBxy^c;O`KG(((?qdeTV8AVFMLv$1rrgUeucN=l{HVl zS|qApz7Xsy(h)OiNotK=z8}1w&)FP^3G7yVqFzl(!L>`6a5udaDEPp0V9)Ek+MqGm ztg-7gm`=J9o_2N42}jE1qn3bnXN@43e!3apyE>*Fs=#Ncj<;c2-Qq1~`F=_I5W-;R zNOe=Qqhsw71Y_{A*c;AcaP^w?8h#(_99`tE`SWIga-SRLPA1-%#ZX_m*K>KGGe{-t zx45#7Tf_u^|yj-CMAO+a2e_2S&Xfk z<;uo#KX}o*|5Zs(S2@-;ov%Z!QyX;_>$Bby+}?m#-4HvCM@sSHY-z5kwSd9bd&JQM z|13cU4aM1VW2)YmDNphzY;d{f1l{9~1dvajgkEybs-`$wZ{d7Pr9M-J2Y~msOTPJH zQrh{-n)XgDiPlvYa7{r-;B^1?E21y)Uo=GS>lRQzY$@Qik5KEIn2NUuiln4e7`!uR1E=f{NL&o>v+ zCase_+KXeI`bmmo*dga>aM=LIpsVz zlg-7?qN3PjEA(9i zm}D8%a30d}GOb)$j|6-DE{pen!k%W#262z6DLWytz zX#^%`;wmHUzWfumwD}6ALtFHLS*vq$!(6lF9qa3x3B1pkyzW6up5JF{i!R2fHi1=V zKD1YFQ=qTGN2dWOnJj7&c_?Ow*yHs2bPTmoR$fk_#S{*abR2dD%@nDZ?}kRmSmiW(JtMWt6l%73M#e8e0N8jbhTZ zeKz7^fL1tk4Rvz4aGl-2c1W~>fri;vczKGq%|tB!22Sdvv*0_rr;I`yt*}^B;e>Qf z(hb%dxkoBL?;q2wccoRq>>F*_5BDf$8~(X8wQ4d#pk*y?Y>-tAw1K)dveDn=pW6G7=gGY|S(c128;Yy>%;ej?P03`_6=Bp@ z>k&`?XhqQHSo@BOiga?RWmD?o$j$)j`TOFyV5oIs>6J=LA`2b=T$_xUvM49LrVhEL zW|Trz93REqXmnyikBy-s%7rdu456u>piYfD2N^e*cI&+Rl}|P_ux_tf#uHC8t;b?W za7TuOXQ26v?A(a(oe%W^-tH(<)$=&%OuKmAfjaCv5?QxTd5E)QLzlzTIRT-=GQGNZ zUbHQclmWLHG~kv}Wr&|<_vwA6!_fO$8fWjbkkSxGw;oHixnG5piJ5=eggAA_ya90} zdBJA`VwZU{j+1*U3bA7yj^9Rki)H)~w-Gjg3c$>+^T9S{MLg^f_ry(6{RXROL%ZhbL?GZl;4QF!?{yCpNHC+%2e zvkmGfN~Z&8Dy7$xz(f%ZQ$ptI9A4rEGIbdUj3u3Gnbb+kPxLv~)PqmjoksItUyfSh z?*-FEO#i}j!eqyP>1EISX5)3lYh(U@iWSQxgNr}H9k9vOA6z!kqK41l%Y!)18XB1O zIXVy*v&>3|AvmFg&kbdT#lbSh|2TJvQw14pr`AGQ^i6JtZFjIC+XNMy^E4D>wraC; ztrb=FMyjGo!|nkr`E=Dc_qj6Rv4!^+Wha@aErFGy!A?}?6~!2GX_dMhaYYO*Cq^m9 zWMWe;qqYQAMv>GdmsTm~h(g{~Z?)JKEuD$OVBN;ODknnO@+8`*`b{)n4Cl`li;?d*aPo8`&DF61-)%^gpP{6wwLpP3F$O_qi(gpj6*IYS zvpi_eTsUY`$CFMnsVnQVh#`vRwVdHe5aWwEy_t|0Q61``S^q3rXbKGC=5owT(5H?A zYx;4kcdT{tKi-pCo>{JzCd$3_Du3%$G2RVaN=D6^3n$uCc%)jUwRE@)rdh00PW`i} zr_dm^uI3+f>=Q}oDT?8eetO^YB0{Xvt5ow-#8bL>Ag5`rIfiYzC4~?%6D2Vm^cM^g zb5LIex8GJbkiPfS7BA5J;V9Wzn09Dmsa0=cyFJ@oA!&T6_m_NL2yeEe)Dh1>S@x4A zb)rNJRWUw|G8TawxNL?#g5?e+s-0XcD$mnX{;r~T?>v@SC`Xi@L3<;GE3V7 z4eM){_&#D{;Zw0lNyeuQIypmr@w|J%o)%43jv`kyuwN;Eafvckl-!?Im&FD5Y?&!A z+H?N&AEz)c@fT+czPTX`yGiOD<};&ExsHEN=%ka%gd_gcHe zxx0UL*_8?}3j6+~vBsRJFo~PO=}Jv8yUb~_*@4lWdY4#{=Ih_J#n>${v zgCpI{qj2uTDn|xgjFIpBwBGVK>s+}<8GQwo7QHrUWbCl$5MJC#UWbS-+tKwDb9rvL zj%T{cdetv(icvhWV5)%GHhH8cQWMREsm)=w^GTyJgeMja1(_{us6@?E^b8S022xQg zinds8OiP&AoSvH*50AF=M=?S&G&oBA8fSDqCXr+ElBuEFTK>xAfm zWzjSzzl=hO1&3>5q?bZRkO3X`WioH1fZN8SwO##mZr%76jPS^jJv5t1m&=GvMYr$f z5^utkacr~pAZycP4Bm$j9E*Ewvukx(&Rep!PqE9@G}_!nXf^1&li^EQSYl>Z=yD6q zbtn6fZbKG#KLKNvMOBbb`|==EXBfryX%Dhal`A4OV`>cJnpLOEaCmryv98#rF})%` z7dqK)%BMdjk-#RkD#oWiH!BUelZ6rr6(Pe(E zfm+y$GZbXD@W^vul7~%u#w8|iPcYx+J83hLLYi6)jZw5b#^CIZpCwp(S{7B8J zMdR$5jOaq~lx&!DMuVA777^`xliKWaHm1_E(ENfEh z5DZ#)F0%>>)m06?r^Ve`msIHK0ekl&*biw4Pu@kp@QG)#!D4`mc*Vk}yzQgaHDQsF zUgn!l2WQZ%;M~7_KpWHYdXGs<2EwjftR=;`G+b;eA)-3s)b83wY1VgMKv7#lR#OO5 zoAj39RW<%_1Fj@M>S`UI2pP|!#bLpgoMB&Gyn;<5wQVMw!eUH(4Qw*$fK|gQr}`73 zoJLKt$tFib&($RND0I#{erZ0d9>HWedp^r8c&V9W&?A_H9*9ZJB!iw}vsG%eI_I!V zR-P@F==6-oLtP9U2KL=E79TzK#xCpC!||dq z^^L^bNX?@uFFqr+Y3C&Pe<-i!-=Y^g`f4_wq}wvV{2{k&&0|TNe~ZNy9b(gak@!{h z$To??=FT#?`&9fzExV@TTy3I0GfTILX)O!;9}iC>3VY5oPB_&F9|+Hjd5>|qIh^Fj zd#!(FJw7I!hR6kvjUrp(xTMw;VdK$IJBq#u5ieQ7X{)EEI5#_~bp;}A@qH;^CgoVs z>GY`~pIa#SnMew2&PCIxaH?&e!Tk^1q`A0b7aeM6E7Id66>(qv7KY8`9m`n%!F`?L ziexv*=t7C?;^f%aXHq5j(23@1X-j$1Ig_Bu2b%ZEhX{D`v`cB2qc~HfQCcWV-#M%h zEpt5%6Koh*UvAKeq28f2;NdvPC2VXe(M{`J4SM-O4Q+SwE!dRY2$c_bUV`I%SP<;7 z6{WL=jBZ;AY==U@ja_uXGFEn*E$w>4Eu4|0u(q>*=A|2(5=ZVljoPGB!O-lU!IYG<8WC}z zO-fg(H8IV`lIlE08!|S)7h&0EEKk<|RNL6VLT~YcC;faH^2KGIn#cCGyv2>B>Kt9; zi>d#K=O<83`eP@h+M}$v5p%eTy;HOU@tQ$>fv|4H>~Nw9wVZ27)mFtvMN`UWMb>L1 z+0c-A^*+J>EnK>A$&#fD7B7BH@b?AcKNl`svS8sN`X9&av`dbV# zMo-L<2Z0mbnIrq2lp|LIN53ma9s^F@nj;6kJ4dbndQQ%fJAe)E$&nr2ngaRN^JbdKzIL5^Go9QGO51}3-X$fLjspUsh7F3gb& zfTf?q-+fj8&KwZQ71pu7O*+=96M6n25et&sg0 z@*Nny4P^j0|L5Rvdyd=-obrnt+4By_0~>ycw7oM&E&-1C70MiN;$6tQU!zO_C*GYS z`~L>t0vqnhk)3~wvIU%QFVg0BNN3=*`%or+pCh*b$K8*#{zHyj2^{r6jywXK{zv4| zgOCHNe}cV-P>z5Ve}+8JdKfZ)LHvQEAIXuYfHVGzGV&1{in}-vG6Lf$vj@8!-6q9C-*hh2+WJR-Rk|thDpw4q!5u zCp+fzWINDR$dkK(*&Xs^=cnb#`9RN(d2&0j;putuB(Qa-JlX9TkOj8xoF~tHW}aLO ztl1?`?gU!T%9CAp&6CT4;b-T`Uc2SVHNb}F!1i+AB{U0Zx8Vo>cdS-WTV|*MOD#{&rt16w!b$-&1W&45#@$degx2e#GldmY~Z z)mhkhE7GI^d%$~}Naq%G0qf@S+$j5OMn)(gB$KJn9K>#ut$87a{+E z?Oz0^ixGEV{7XnDVCyCL?#qbBrFnAPSHS5q#1+{3RmA&iD1*QSUq?B=9C`c=*auF! z0_EtNh|`tGGhpgl;CNM@TnB9ZHp3Rg1l)nkZ$W`)+=0HaSUkf(r4cPx)YaNHpUvis`` zKax{=<%_MQS6US1#%1KU<0{SGgX ztAN4Y0(k&9rw{3S1kxYadL-hz68{Fy>MxLifdY9FxL_6d41(Jm!2vjGb%8t%oH~R! z4WkSI>qZLX5#W?H1+ru<@)kH_6#sq`;tWi#10UeLHzR+JDv(=%jc+NCJ&y(-V0^4V z$T0AUcj>H0=Ws;P(fMQfb<5AIkrIZ z)dIN&n4Q7zHRuP{)sbei$V=e#x57pPc$ZN<_@>;Ttyp9|~UQZ4sZy<+}BIzKVq>FTu z9y*YNSqP$y-T-G)arhk&R>%*-W;OGBzKZuk-NyR$=&2P$iE4(EX%fXR^BRDJ6KP% zcC?;u?PNW}+Sz)hwTtyEYgg;p)^65wtmj(Kvv#+hZ|z~dz}nM#p|zLwB5QB!#nwL7 zORRmZms($l*YoWEsT5K(`USln_UTZD0US}O* zz1}+1dV_VCRkS*+POHo6wtB4P)(Y!ztJmtYjYs6Y( zt+ht2H(BefH(N(pZ?TTH#;jwkk~MBkSd&)SnzGhg(^kdWU>$2!tr@Fk)va0UtyaTo zS}kkN+GuUEHd|Y)~yMwbgpJb+Yvy>%G?dtW&J_Tc=td zu(nwrv`(`=WSwq(*gC`dh;^p*QR^)0W7gT$$E|a$Pgv(#pR~@iK4qP6ecHOf`i!;R z`mA-K^*QVF))%actS?#@TVJv+vA%3wYJJ7J%=)VJHS6ov<<>W>E39u?S6bh)uCl&u zU2T2Gy2kphb*=S1>pJWE*7ep8tQ)K!S~prhvTm||Y~5`A#Ja`$sdcOMGwU|%=hp4k zFRVMPUs`uszq0PKer?@t{l>b-`mJ@Z^*if6>-X0E)*q|~tUp>0T7R-0vi@v6Z2iT0 z#QLlCsP#ANG3)QvGn?cGwhx1 zXWF~i&$4&5pKb4EKgWKq{XBbj`}y`B_6zJi?HAg6*)Ov9wqI=TW52}S*M6zJpZzj> zfBWV30ro5G1MOGZ2idQ(54K-zFR&Ndi|obr68kmwQv0>`GW&J*A@=L-L+v-%huKBD z!|t@Z>~6cqUT&|j54U^mKKls!NPDH-Zx7h3>_PjD_G){`9=1p9HTGJ2)P9q_&VI9f zl>HX_XnV{)#xB|8_JloYm+dKgy*+JL><#v@cGaG-Yj)k9wclzt?55qa=j@I4CVR8J z#Xin{n|-|fcKZbT9rlU#JMEL~ciCI*ciSi1@3G%&zt29!e!qRH{Q-NM{XzRQ`$P8W z_J{2=?2p)I+8?#gvOi{@ZGYT8$Nq$UuKh{-Jo{7j`Sz#n3+&I>+wITV7uuh*KW~4* zzR3QfeX;!|`x5)h_NDe$?91%0+F!H3ZeMPH!@k1)rhTRTE&D3_+xFG=ckFBI@7mYe z-?Oi?zi(e}|G>V%{-J%N{UiG(`^Wap_D}3v?4R1V+CQ^zvwv>iZvVo*!~Ugxr~NDY zF8kN^-S%(nd+guZ_u9X+@3Vhz-*5lHe!%{t{h<9P`yu__as+K<|Qvmdkn zZa;4S!+yg4r~Rb;FZ(I`-!{ovIXjoj<#UDH4!Ni0cFa9Jw^QyJxt(**%rimyXTohC7-Z$j>?Za;LAh(YY^G zuU}IOuv`&+<)V(kWs4VeV6(~s?4YHaXju=g+T0P7@H!$+Ix06+hx14+5LKmOST|s9Yu!F(5x86jPAgIH)C~#++x% z_3DaeN+Blh6? zRi!Fe9O0xj^yE0TwdL`l`oyv2mR7T*{F*6Us2r$Z*A{Q77aBP3ej%k39{iYj$Z;`@ z`7GHfj`>*S+Qx`Tebkumm5yeNjG2QNry$YUi~Bg)Z;Sgn(FgN??D!io^)co%SsjV_ zJjvTh_!PBQRd(d=#&TbAS9lG63Mv=C|E;|D_J67BZ-d_|_EEaESg#ih=vH=U{;%B@ zSCtd)he@4HtX6rK5icTX`h5a1O+RlWrERIJV2QFVMQ764$>x0gJwZ^;sUM1|oH#uO z4Rit%I^BR?Nioe5Z(BYGB9%#Q$0a;jN1?buoIV@(*8G|)Yxm4z46kn4$OpvK6J{7towBY4f*5SL8B^yis|4ksMMBXy=oTDs^sYYLVudjt)i6 z>8Oa$KOIR$E=v9GNERx-*3Lhr9(CsFsF3EIQh_4dl=AU;rW8|Tm~yNW$utcK?TpjX zrOrHEHPQ^!QliL2EgkV0sU@n&OtW!kBxg;68`#bB&79V6HH}Xqf9! zm6OC7g=m?Oe5#-SQY9LBt&*4Lt5jN*hf?8${F2J3@+NuCCYm|2Z}oFWu0t7x-=2Zwua#SrDpO*@`q+C>ph4N4FwIb)-bc$JT^y-zc zku-N3`(eW3q4%wPb~gB(c*Zq;V#O&Hs%1k@rF_EG`%X2(O3QdCJ9I==AKumJPKkM? z+FMGDkEgmmsWnJSxt4HzL05|=m36gbBzs`$B7`-G9*b=+}57F-H(>A;W{mCF~r+d&hQc$ zy@Y)Q;<;*S3Qu$(3*EXK*IeT+yx!nlc*U`?IuoTzv@Y0%4t9~dbDt*LCp=b~oTTkj z-_$^P0+*?l8e25Dgzmd%4V+Y8Ik!{AqUmp@{qFyVV^C@z8AY!=(!<7`aPb>&8Bld{a9!(zp=R9jyy z`bN3j>?*f5mCLo2m0FoLRjlwS}rx| zV^ZqPGr@GG-D{i%={B0Eit+LkUU)G|x`_$qO@%8A`7*dFnEKY9!9MnX6QGFoq>p+QI45>n_zM z(CLifk~UVUH0o6TREnjQ zGMz?golK`Pdoglys7*!4QP-a06M9Ik4aFyn_LA>tY*Wd1)MYLC=zsKI#bF+uYtb1)vQZ7~$i!1?>;rUZ?uYUzKy+;KSKa6c zW@5TLactTrB*q4O10w!9rc|FR% ztz&>8o#=E%-t1FnCLHO?VIh&djI(OiQUj36<`qf)7(sS+G8@$%fjbC`6*CLFW4A?uL=CLw|3 z-ouRmGb@Jd?B9XaF)@oZky3A)bY+{(#=Hc5G_05+5-fK^aaZM~o3e4j($3eF^yi7M z)rgCPvg7rXI#(%$)4{Bz@$_|qT6C@_j%0H88r0@aCGlB{2+_ptL!O$%NGA8ko-mD( z$00T*iG6UAmV~IJ(8Ef_%F=kbIy}4rV=wx|j#sE9dkkD^Sd&2nE60_ckz2TaE)43F zufe-&8L{LUGdCLp)?!ANp2Du4K-^3O5ktCY6-l3TI?~bbIH2uGry|gJ$lWzJ*+QA? zo2vF@foy5s)fBMqx=?Z5k1N6of%~b?+d>!O5ep=S`*j->`7ukUR~>hAvW!cJ=GZD4Y)K0qM1p168Dh{% zF)}JrHNzd;)a}#my94nBOq2I*y;n;e)w9b>u)NZ3#3(GwSgAFNvsxEX4s>YYp2UK z$H%8*Mex(}^ZR*T*UQb$$qjSORu^KozEPj6P4>-TECW5tsY+1egOW)+ue`Eenp77S z)&$U8E>BikxD1DKMd9qJOkx27_iVWAWxGS%DN?6H7A|x|C#H?sqH!2KsXG#K($|zB zJcCR-Mrg)k714dhTJAZ#v1|F@vhHrzW#FS9Eastj)AWZXFUP&iR(al3t=I6Pwn%hI z9dQ#yX5O<}v+zH4O1Kl9q=6I+t4wysb?MQEc4>RY8d5KVl82j);-1O` zeXW*mtBA=S(c9J=L#@ELH(4)g8_)7k8nAYfCW8AcuE)|i$NEJ%a_hfWZjln>4jn35)YIh2?&?lgGl(_Q_)xio1_VsUxrnDX2tj zWs$2G=|UcP9=1;dTzzL>g|a<%qd(VZfc|i$Rn_Zeokoc7GjuC;w@(ktUN2{p3oKfR zggo_)CrsTppQzV3y8WZu&T5ujT2e#TI>c&qDt^o`*C{vR6PJoik7hd~*Cj7U4lVC1 zxi&K=I!+fGobkP-p3%6mAgC2P*Dmo_NItTo!oFmyH0dpruKTI3!Ck^fL{HHJH?ayg z5j$0}Pp9el(vnjRVAU&X+ww-E-sqZ}nqtj{>W~9X>8>6jYQBpLPCVbl1=hXg(j>-0 zh^cy04;q@{ejC|%xFegl2WbpB=oPN$h_b2baP}NK$x&}qj>Dd?Qgs!&Zsv5WUHvXM zBmAl0q=|Z)l3&UzPH+*uMoZ-{Iz9sZuH2YF6B-z&=!*AEVuP?ZK4nAC_$I_@u$eQ_ zRd2QG*fOo0p+JZ3FlB-(%TshSsfHgA5L+!ap_?)ojRmtl!OG0sOeZSWrt&0POM+2R z0i08PoWtM7g(KMbC;j zDLgr!RC@}~V6`n}XRuL*H_|9iia~@ng6 z7C!%>+DJitV*aJC;}Z@m9rd8_`aPR?yEv{SGRY??%8Xjt>9~aK@RnKXGpXe$b>CM^ zE)WUsv~|}fJ$+I??g%#${Ifv(rIN@**DdY|c(y(KG#vl`A^qI(cH`Pc3tr;~?M~NU zYRxs+l)5*e#YdsB!=*0Q$-}s+GTRbO7$0h=+cYOrxv(dt9HjNKqbcydhOkOQ*WKLo zk(GS3I%Bhq&09Kr1z>2pgn9c62@u;O3{BVPs*`+gvKBSIftuYwuIu~@2$NOA9nDC{_^xVvNxQEp4 z*uovJ+bhJN`Ol_K& z3W|YvVyBj=s!(Zz2I`F&YUy`b(1SWrw>z$RbX<3*XJFaqoTC#9yxI<)<3rHVms!I+ z(!}{neead+uRsr-VagyRDs9r7d6uwD^57oHIw1NClWi;LO*5^?2TiW1R8tIu!M9bx z$||HW9m|Kq?nFdf5ppN$-LIl5ya`t4Z~ZudY&_Gurc&O-)~ROB`$Mta-$vkm;sgyzB2`` z0dEmkF0|lm08ELO?Ml3xYql( zfIDg19*thf4kXHKqte3dBG~q=x%E4)vilesYLT(>xgg1Yb~pi9+4skgPrk4X%RYtD zc`r|=*Zw*q9kpt+$uMnObe9!kK_?|>8jF95s-fpmW*a4-L1bI4onkrMz@iz?`LV#l z##rp^k9saC+6u7B7SK(z*PjI@zBxPfDjEi+S>$elK6hLa=OD5s7lk)b9Y&@ty8fzv zSb3CSSpEQy+3*i}DKru(LJ#v;N|ZDO)+b{2c% zhwD^+l2$^w+v<)jDot9h(X(JV5K^L$4@t+*j#bqcx^>GoOHQEnw5zVfK4xB5^ zer(>7`$!fHzn9hMo#vg2zj&^7q##D^ptnmnFv4 z2-c7#3hEDRnuBxAX@ANjJK?^p8hMlsMsJLo1rRfsZo{N zEDQXTVwGmB0%gnS^${A{bh^qIHO`EIX4O2lyk)#zYE0t5OD|6ii4z6>qn({2XmaEHYCXDFb>%Q7l9Su8eWPEzD0!LT%+N*ahrl;nGFjd@E#?{hsI6GEp4Nv1F z;N(zwW)@fNIV;@B3n19>$xAEUb6FLuWGir+Tt~;7_yIHj9}dUGjIHtv{TsS>G34=o zKp8N}n7^$q&)}ezBR?AR1+EhH|C#mNR6EUddZQgLhiTy#;>151XHswLAZoBWb% zohfamm7MMI&#+5>rc!H%ni|?G>^a*)k14omme9Tcb0dql_pze!ps|g7EFWL86oL%h#U0!$ z=1iTzUv1SV>eVEMYnL!#wqGT9C{;{PLi=Wo2}*|v|5huejw_vxINPyNuMO2FjxD#k z#X(Z}6)trDIj#(@ZfbUPtX+a&42=>yfI5a&ty!<(_rcE5MIw)f=Eiw*$M4CK&RF6x za*+bA)XF;c46B6LY7=7Nm}0vb;0UPXTx0MXu;o9HbGlj2%iBmFk0e$Z%9V}fetLH> z4yq~%pnj}vI$t|wW!5`3>vfhIMR>M^rzCY;$T>1nKJHwrKfkXZ*YQM z6`<7S9x0x!)7y6|{Nc^ejh#ww2z|jQMqd5_c|f0Y$C_}@GV60ZqYU~QI1}7N^M!OW z-(oe&>RnKU!A7f5zSGK)r|mQAcAeF5-9}YQfofWXRU$1-#HfD7&4!R!!g+do`F7m1d@ZOPZevqVl@qifVC^Qm=}+5HA|Af7z1 zaUmqqL6nPd^bI$VIZcFb zkr-u86yHeNvbCmk7QD48q>QV-iYnPTNvCevtud;ZMw-TMSvH%|_T)?&bJ~aon{kwm zG?U^!^9I*CpxFy<{1lnawx%*i#g}jKi~CX)?&fAu165mI63aLv6xu7NQbyA@F@9;T zcHo{7%^+vqhb56#Z|hr55(+TL(VsT*4{F>3N@=)S@Gyip+Mz|tH%MX&cOEIRYN*q8 ziv=#X(D>g?5%M}sw@i(y#_~)?Y~)I0d6b}nI{8Dm(v{uLCG}q1QtN)@ll6L7XCfdt zJrLJT3x$F1+>v%?kYW_OJ(H?xIE>?Op%D4$SVVb}6b46?^NlMN%goL?n_u z4jO&88H>nC{WQ6#azaNgZa%S)9E)U6PQhVQ(tg~aoat2|&KeBzmhKbLsMTFPY<4Lk zplH*v*5j9BUANj=LQhSphBPS5OB9LyN2=D0Z|)P(R(FTAp>ZN?a*xXBf9VET_H?6Y zflRg|cr`j!O0zXU z1nJ3my`%S=+wCbzxLO^yWzbYKqQzuFw1Rq!XhqbaKABuE<7Tbl{W3v0g9~PYg4#FC zxME@xFn#on&uO@&SYGmdp17!V{2YsK7D%pu&*39^W3G!ya%G(MDn>++%Rb3eceMB_ zZTt-}$}XI?w@$r}S0V3u6|&MDWTOL49$}|rnk#Dj+_{R-sMaj{u_`p9A1|vNeWP1S z5N$SB?As#lC8XIsC621_Je_Z2f$O6uO~uou-Ud-N{2sjO){xT*{*oQ#6$! zqtomrAYc*Ty{4Pz;V#G7GG%<_6K#>`WgtNX?phqZlfvZACwKViyLt(w$G;ewG(jeA z2|#aSdi4_KuY3mFo0mk7vbxMSO}ksc^yma`NO6|hSyK5HfH6pMe{$^5>sve4&6ja8 zdym~{Q5)J|%Iu~l+HAUxoY5f-FZFb9c=A~aUYeBTE_uv? z-z$o;Pb}_UB(32fYYoGlQ|v*z6rG%RRT8`a-FueY9?6r|y=ciNn)aq8ns?6d&bt$- zz560Oy{7vWf-CL;p7TJ_lpQZify0 zVSe9Iq|BweaA}m^xI~kj-nitgjd`n>aSae{Q{BEr`*J0>s_EXY?)0dvo(bT-8LcnV^Xr zSkjNnNLF>+KF+z>2;$loC$V*9cLpq~!E?M!&PUUMRB(%hcj8py{sqcqL_*Oux{0{9 zQJVElhbt1_6-#%yl2?z6ZdY>4o1s*IEgK;l?&RTboHbcp2pyM5?(OMD(D2ZhX;@yH z^dFQ>p&@i6!c0R8w}*Dl;rh<0Z-GZgAzP^t8t9!DBkv`(bfSi;h~<%_&1|n)qIy~&yzAuDQAG&|+{fj~`VS_-lS*C*5lfjNWzaiI)m_cB8w zeBG#o;K4xONY%5XZ(FX#9HxbRrI|!`jWO3I)F$Z_B0ocqw0_K|lO1f7QzK-&^~0nn z_kGnn*!sy3PcTW}pb4y>=BXOr^7*sbK{>rYUI64s`^Vf~Bk$Mfq4v*Rb>)D2zebMK zKStja?7ZX|WBq^>)Gj$EAn{D)D|6c>~6k@#T?y%ZfY*$ymCYJCHsnRN75%2SoeX@DCHa zm}&o+>c;8WnJSo=)8J1)mx8iEKD*ILfRKSYt!a~!_>kvD9C_fjcOGa1s$q(R@dQA*EhDe7B1}8Hs&wRuT`~6kuc7U*SsC< zVqppbBOPf z;2cQW`OZ;ZGu=6oXIQ(Zahk{OA#NMjJ;rINmWN2Y%W^E7Kc)`8bCAmdBnN=h2;)K8 z?1H9s#&Po4O=VE&0Jr&59zokI<=^}43)=|FP@sO#+d;p&E`KZ65@Gw7|JitEj@J;c2bFIh`sjaJ*Ze1y0~pZeioM2d#GBCX_tG2}Kz; zQl8Y&zwJ_?Vc)0SAk^`qm8<9L9!(oG+O2jy!)YDt8SGQY-r)1>GFy@YiOc=VafpZ1yZpchQdmJ(mwbLQvgZ7)esW>*3R1#NfGOw^VKO%Sy0 zyc@rR2e^|k8G=83D0hrBa{#OG=MCZ;{}DKp3(HKdj?zg+cPF;r*m3bV(jLL&A#XI^b#Tc`-5sX$ zl`lwcPEWh%&0qWc@pyWyn;0?>9@?GH-Jj-pDN^L@R0ut_{&~FTCuj=l2>Bk`Ib(mzhCU$ajwE<&~XV7mjAcSWtIGk`C?o(_SBiXd@jZnlaIU$e=U+6N%u8zs<- zcish=s4F|`OSM|Hy1I(JY*>`t$y01i$eZ&kSUk8fzjQZNndS>FRx5`tL$d>8y*SvL ztqZ7ey;==4ylM(*6|BBxrG5|>9|gRnmYzN?)-I+V)>n-YO~ z;T63cIosnJ^hw@_K0Y{Aspo`aChZ|@rP85RZ#GdbuI{hHbGPu)ZSOjqARjKHO@9QZR3BC zMeJAvpO0|tvU0v_*$n9eRark?a=b3RkuMHg?IwJ+FsW>xg`CBd9fa-{4OBBe9eE0D za545A`Xr;h!@8oJ6j)8#-*2m1Jevxe18o=5Cl`TI*>#!_W}^Hk?-K}uR{TLmI^_h+ zXe1~;IFWZ+3tD?Vq;!BHSs`!JBKyZ0^;PwK%&X|tuX?!)-=r=yWxaFIPM|qca?neX z{z5Xink1d`txkfXP(1li8+7I0t$$u@k~f$F=Rs{)Fs;_p*F}S*HoTFJk9_!3*VL-B zStZ5XHV>J^=9*|P*@uozBapPw5Z1HNw#uC(0LMLRJ|V_|0VN=%&Dqq`Z=cu~lU^Hd zdNL?F=G{VJ%o_-ab%Rq4{^^jas?Cp&HE^b&8*X-JbuPcFls$rW#lrB0z&5A5dW;jST&zvW5n5` z&NyCF0{l7H^IV<>{(=+^Fb4bfJEypN3R3>$UUQ(BT5n2dZa7bp6|>@t zMP(0~8?amH>vQIAI@R-20_{w?D<<Df6w?zHCX(DW(^=GbgIS2Bk2AvQ1R#NIsthNp1+*6k$G4Firkb#byLG zR)Dk+DIXJIdR07|pIU15fOonO!t;jeg&ki}L($fG9w85CAPX@+B6f>g<<>|jmrnU z?y%EbJ%XDZ%%*4kS`-?uc&6cex8C$Kmk=ujKP1f-yf}Xi(F0>IwVDuSf=*5O zdZ^qcyl07RmBxa0St!j6uDXcx;`?#=y--r0ixw=Hv2vUW<~T?O`7;@`h4Z3?<&D#e zi@9l&5)l%d;7}C%0`nDIQ80w>j)9YFhNyQ&^2))Vj(0-{ojl`wUnfns*Sa54 zTkG&9XDhu@_%AgJ%lZbX8!D6d=nX>SR~=zV)*%FKUJ5CX>9p67*CeL7qi6f0BgrGdaHXp zBJ5B%1xRr{KnF)l__)*5U&9UH)~(WXOa~a!aIJpre9}1>9KvE~rK0n(WgOAN5g?R? zw~mHK@ET(GYSI+Z#)65-D~rAr00ZYSCJ1tgXlL6#4+lsKJSj02l+H8$f~@oK7BuV& zc2hRS9W{~$oDzi53Eb)o`=z_7f4*#p!L_NYVRZ?h9(7~0-;4pd2CFU+h|ARxQ$){HdQZaW*4gv)^YBiIhl_aqy*0*lNv9;TvuAq zcd`5|qF)MTEM`><(g-b`S!e9o!&aG5i&t&MSrGzKTxTSnbi5%CE++M+yu<6(lEoST zt5a7-IQn|(dGaL#;e8b}rrx;b5v3n;iobJ8B!LjL&$?KZm&v@vza>^EM_Gw*1L>lr9al_LXL;+&aVVZnpK~b=cd)T)~}>jkDUI| zzf(95#}K}{2?KXfcn&%fl*N%G>lD1~ZZRc^vv8DqFP-O>lL?0gGS zt#;hIcD-6+mCeICL~X_(j5z3at+aXA9k!ck^*|6zHI{@+OvP62mGRwiC@98M1y2<2 z<}4l0MnUP$7Xfe6B@VKsH-Ie8f`~q#LdjSqczG^1QgU)%G9Tyz-SFDvqxCLiREzGl*jde1Hy*lZ95NSX(A@~XM0_tf_EH~07n22`f!)*BAN0yX(4;|J|zVeK6FcDNy^ zg(W@UBplwtMLmIdSur^i=Gg^3dDwz^QgE3_Q$~?N01HmzM(Xx@NNdyL_YqyASo?;nup6H3ZsZYzK`o0VzIpgV7x6cA^03m2w9}o%Hafcz;ff^vsXZEk{$H z*@w@y+9Nv_V2VKtqWv%jIN($FLhk&rF`ifhhHvs;m8USB>GBtA_1>r+{!6Xos)*97 zaU&Z($XgQjl`W)?lVrC*uQ4wsvAG8B>2{AUbkasu5L$vm65_Qm3}>7~_$Oev7mC8D zhxNX!%*wv%uJeVRQojmAFSYtDh^9eCe*w7Z!pL9Jgp9W^irO zz_C`zr4MjxL~@vqEcU?xjw=gNnvHB<^0{Sd>yXEg$B^-2I&L1^2IkRSNpHpD1rs$7 z#&}alg2WurbtIt z3Js8bC-afoy5%#df`lmZh76$*gIazdaWW?$*F5rEhIC){5X3=4UhG4k*oywUoCvGX^rp z0qp}2(hyE+TE}Fc%f7v|UqYWZaAVU=4K3_2rAIo>RF6ifMeuPh@`&ZU#YwP`sVGSa zEWJq4+k}Qf1?F6Sgo=6OzD1aX6(^>==G4h0iVT!#Ngre}b0OvBT`%+lJjW#Si!Jc( zz>3hlgS5~7F*{IU7V&s$8-%P;QEhJA_VT81 zZX2RuKqgwm{MoLPv*tH2n>j1&cVKhRq;OjwV2nS!J;SbMx#RdT4EMAy#Av*0817fP zm(jNHIEYIZ425+41*n;6B$!Dkq#9LRXxw{ReQ=o`AH&sStBbQV@c`4Nc6kOkBcRJ5 zoD5^-wT<*IXy$z%dchsQz1d$*R{An(o^)WKiYwd;t^RTc35K3u#;vKp0{LHU%mHJM zM3&EPs9`jA9F+bA~}%Y6k<)8 z9pbncA)dtSJKz|cAb6a90_fZI`=NHVHP||YYUSo;a&&wMO*Mf;$mQ-J7-U_mJdVxE z+gW_|9P}xzR$r`^xvKy9PG}uGNRIFqV3=qZK=o&cNzCH>#l_?Z3Pt5yyUyQ1yKMDG ziv5A#Lx#alswqF`65M?RK%Qt}X~%J;=DykjpM*{51kQa_zlK6Y)cuTIvvbty#G9-G z5)!gDuXl%jAEFY_unu#JbQA!ELa`2Z@1H)nyLTTr+3-S_dQU}8C&!^Gw!dtaDW+ey zv)qB!zh3J=SyC~?Bd7{0l!nlEbp2ykwV?-Pq%#w&_d&POZQHmNDY-KzN` zzR}v22pb3rgS4FvWfhfIw^!4}L+mMOT}jrk3qO?Ud%?hI+v&?+>l}7mG!Q5heDEPS zuEW#eFwSeW7!Ae>BjY&f?RR@e33Nuso(7Pq+rZnCcTS_}!f|&1A*WXQ47<^x+H329 z{@8_^Y}x&x%_=*5W`<~_S*6`K_N+bVm(T}+3H0M9ChjVySf7ZIp17;#C(2n+M+hT9 z=4|jpdeAgJN0)LKgXUxVwSqrDpA%ij_7bcr%u*eEt{4r0Frt#&JPA5WY7@zxFcC-h z+N9(8HHml*6=|PNGg0SH`iaziikv#hHxq)srFd{$wu3O8vM4sR)ISX!JAiJ+vk6d$ zDsm@tzH!yrAk7OE1H)SPqgN*Na3V<-8SM^WGC+rcT$}$JCLbP+r!D$IIiTYcuDrRX z$QMbHOgVd+3e@Jrya_ljW6qd}4m0#s5D71~Qq7Fjf#EcyZpS&s4Vf3JxF7Vr4ag7H z$E1g*52+NH5)<7A0yx>2N0`LYO3`d3+rB~`j%G$9*QvM$n z3}s`&HI2vEa?e%-dVymz(vzw%XSwurYt9}(SIn3F_k33OowAtHnT|lt?7naoGs~2F zZFfzu(!3BSx1dJ=a;?)1`3+|BWfprd2%|B5iRL20IofxMxF>9^@s&0l?fE7;>qU<+ zpWhg1Z=3*Lgu@)oQ6gvs+0+N{(I}yk5)?+;9T2X13bw``B4Jz@SKg$QfQj-#h3q8z zQoB6oLx3}KPJL4%oP8;94+_q^Do~y2K zm2EV)0hAuM175&9sQ`Jgu%vkUO2a&Q1!9He(ZbO1f0?u^5WF#u2a0#PEMLzjKh>7{t(bK4L z9M}R&)37k9Xc_3?3SFvZ?Y-FT#!BKKo5;8hd(95Cuywg&pNKXTf@UDIHFwwb-Gp4^ zQJR*OSCdW@fh^XESY)x!z$6Q+4;7F@_}`Tx5tGckPE>M2yLVMdl*#WcuAmI6BHe>0 zN7uUJlrir5>lop@2dB4!&R5dHm?Je>7Y*7neNPLhWyjzUkA`(D=%2uxT+`06B=v@% zFzz0#?rq3thTY0(-xfC5BdDza4n_aC5pN=53AP#hNOY}XOk~_ET$+o#P|#C)0CHv? z?bc$z8|4Cn)o(%&7AE(mTlnU#CztHx7t>{4B5SNic^{K7RZ(cVgJtD8yxZoorp!Ko zK_biHMm6UOksa=-Ms6txq;sz}ZEJ1D1l`&_=MK9fl<9_POTgT+4YJ0B!qz7+qQ2Nm zh|^QhaH%Qn{NN<0p?Q~cQ|s0OIxw3dxGM^H9hJ}I-TX8ScQHxJCi29}Flbs=ESV^h z=Nx2N>Ts3I|44qPD(-iag^%rEp6r?18d18iA5zk8p9M@MVlx2yK=105+6>5KR)9ePJuZs@vj zqf|fhp}qP_Vwlye4|W-BLHQ&)EZ5LmL9$f$wi+|I1t$`V9_qdgmzAdYEGAEHLf#$J z$IIuqvYVn$0UNusvy#(~0B|PHUAY<@o4g1Wq$?Di=@G5hx1;6k+Ff-rOH)Q+52sR3@+{X=* zx9tuGG0$?RsWuuIc^;#1GXQ0o*Bhb*OirK)kQ00OV)j`6%r7A+bDJ!$ z7gDGNEo-_*$554HRHoWo#1?A)EsN9!H2nQUf7#ivKWO_XCs?Pz8lGFS! zp1INbD`lUD^ef2D%w9jpSK-TOwL!sq4ZLxbG-cSuw;rU2J3^A;%O@?ugdx)^k-lsm z>~oa#&@fxsyadFS_899OCPciA<25OlegS+x(5Nh%HU>RK4vSz5nLcadM&nQkZcN)r zZ1+WHDQnwrf=h8itA0+GDT66!GWmAG#wDpDma`NaLAuUxA_9|ZPF`N9=Of5EMQc?5 z;(=GRE|JApwM0_uc$!jpB0PGf-X5X`KA$ykDF{zmMr&58Ux8lF9v2&)ltNY+13U(L zd7O{Y>|dj$e>UdT?bhD%H7EhWHtYS``u6$rwXK!y^}B0J^IP*%&w0)*+FzAZmASc7 z)3dX;Ykz#pboQ^6)AG;neWW(?ZOwLj>N)af^4Ff(Zm-;t{qo*Np1M0=H#E_@7^Q-CHwmXXdFV< zr^4qwtjVSBX+=^_P2tf!e-p~LC9%>6Pn|tG?KQ>0R>8jU(-mm5e$SM4#72_0r{!U} z<=#iCm=*xjO(2XyF@Xzi8q?#(M^u@f%g?WhXbTYCY(XS1oq6?|_mO@*iq0$ zp;@IO)u3(<-UFx}XQ1Lan|ut%-QCKxJPJBebPYUyY@}9VM&08lm>AQ{x)ZP|C@t{e zEL4%GL|B9$Vd8OTCiobPy?c~(^F$slE1|d?Pf3g?nRu?c3i5qq;-aFs=_6UFtVD{s zYab=?(2+J$&~xcS*`yyGh$jwZ&dk^?niY_kPd1RqTlGm;?Wc3kvM$Nz0oPNQxZ+TX z^3;5cfe2muCqX63n)z4;CXrJh`QPP6VxKzdR)32H-A=1B3eniOD${m*W&?QZ<9N7& z2*;HUrzJeY3Vc4``*?|u?yU*Up{rK5XJc{Po)-bjQ^TEBg)QnYKB8$C? z1h+p!BJ@6!6`N`jluorBpxQITF$tPwKFS$rnmjwBHcgJ;VWxZ|pD1zqLfG+Tg=9HH zmc9_E_bd)7>%ol4U(YVkcrsn$@)xCTJ}Dei6#ATTSbZ2HzpadA9D|fCy(q2o96q)< z^m1q&jGIj7nDj@xM{p+aX+^{UDm+|K=tM;{XCxk9)+TxExRT%whlYM0?A&ZHA}ev& zyG8jB=1N#xEn9q|n@b_ehj2R!RU|4oeAyV6I90+!r*ucBm4llwE^)^Q*dkHPAqDON zRHw_Rl6G={smCJ-C^m0Nlgh9P@K$q%jVuneDE;!>3=`atXJ+q-R8{1n87j|nK^B3pWs&O(w&Ja8JybP12o$mv@gU@Fpi?o9dYE^-&UXWt)J!TPC z$2hngBi}C!#1n}!4m$;J$7cnSiZ{y%GF9y^4Zgl}ph2stnxbLk!o@#(m@ZG*hN8^rSIN`8qL+sNaGE`P$>5AtBH^#0!~F?xM76T;@uznC>%FR(fNG!sHaP;AdY<@VW31{;-$ z(lD_3{5O+9c*dcJF2J5P4TPjGCk!52Z&N;$#K7nE>`V${MY5otIdd=2aNoel^YerO z=4v%c#vGVV8&gIRT5Z#C~+OZ&W zc(%g8@p;X0)59vou0%)sxh92-*wJGZ8R7K`gU04HLUz1DN9Oi`g+YtDpFN3<_J>Uh z89}waMCS93O$r-v3I+u>%2zfaWR+>@{MD_c7s2@)mXVDwc=;Sh$hRvwLa!ffLiD35 zsjf8Ao~h3+pSBs_1E z!FPv4o?x4$PtNd_y>Mttic}+eni%_JQWaIN%uod9i3J$C>@y%Y(KrL>A^DUPAL%cg z(B3)j_?QFyDuJqYhu3*{YM~mXKM*2^a|nWkq~?7!KIVMgs(CuX~gXlAdI=Dl{mH!s&!Q z{ESe9@{K7EIJTT3ZX&N`U^}iiVj)~0el8+`Sq&cr!R#?~gxg0bTmKT(b`Z^xY2}upg`g%PZ z;RIxd!_L82#^>?yO+FCzc?gH8`8U^jd}2v4Y>Xj-hP&5iq#`ur4Bpqil8ulM zGEr&wRcvG-B8E#lsuK6BO@!X$mRM3oianj<@S%mT83EIzC5<#*b+j)Av|l?C+Q~^9 zX~ybE@fP}ZqavM%#F2)BjuUOLw~T~yB2q^Z(~vrtCG_-#FyYRa+`HtybQbijpHKZ38oRS+coz-VE?A^u?LDNu12cN$N-j3@g|`D z<|wHBB8!c=V%Gr;!2B)aV-68teC{ARU4QHNmsZ2AQM-JP~p;zvQU1g zgwI(>VizeRP|Izh{4fU%Po#{1Q;K3;rl2?UM|d~`MGALcsR;RxvJv_P3Kt)xYk!P~ zFGQTMcbKwJ-pRv9h?AI9dlwH?h%jMOjnZR3p5r6Rt4=LU_~cU6>pu~SFnjDhOBljd z?3Oe=_TD<~irAy?Cqt2~t}VyTp`t1ce<~E$grpp`n?KFKHUar2jZVW>$7s~ggd&@W zWTUbNe>N0ZOqoVd>gPi7OhlSd9oK%|M3x^rORKX;))Cdk<`+ynu0qU6Sg1}_zi7ka zD8019;mXcCoNwl=2TIrtR=i@TW8 z4kqRf{c4VdE}o2ogsQFhwH%4BSP~5tLI|?=ih9@T*IB48-nlTJm#ElH6E-^PHS*t3 z&{0L4T+@!rVbqP{-3*L@rV5*e)DHh951-#$;iHp*Vnc3WmfmkM(1n;R+?_owodO0n z%)9+<2DYf@m7v#q7??r~7dE{d*sv?|?^v+$O&2yI=`JyL5IxtwTOjflGRM&XR4=vP z%h8a9%XT2_Q%7a~y*Cueq;Jd)+X{P={C+sbK(Wf@Eb4ap2P|}cp~}W4)3Xh($G4sS zFdSQmNM&;#^*+!ag<~T`YD{YVaX6w7fy$;9+d1wbo<-6%a+E3@))uSb2Zf;|5VL^I#%x3;?5gZFPZempEU3IDCWHEBUVw z=~DXu?z)W9OZrRjg*d zfiel@DF^{LW&vA(QdKPB!rpywsmC>)h6_6U=`?Iiti73)qE+9UE3k^2!&ZTUmf)mZ zZZMX?J*89?{DZ_Q_OUx(uYT1l=HR+-zp8RERZiJ`HE#sUK3HJt9JG_w&QfyFOOpOV zGPs%~o%5|uf<~<{r)z_*{JZtf3&MLV`{6vVDQ94MI+CA<$}f0`Smh9$Vc?0a_fhF# zA`g*111NQlkD{NcUNH}KVRWa}gn?ws6DqsqVTf`s*#}CF$HZ(@l^MHsNq~zVj;I<9 z5w}@L4(f`_(cO^`!~wcr@P5-BHV#p$;lHHvFq&0CRDD0fjoR1wYwcvP+q-8R0>vNc z#!hw*8U;98-p$xGNgHr~h#R+8a*e_;Z0vJ(F24@gALYi*>u4~_CPY22A4;smS;2fl zsAZaoZiQf{gGUpn-IbCj!Zn0!{4fHwvleR<(0mT5*w5)6(E2eJ)ZSYmTb#2`XT@%5 zqrc*@7R0&Z%yzLk85+;HW%%P1#EbP#16&pf-o7&vn$(<``zly*vMEjAemsqPlj7>h zOK;R|_&Sixb^xSSf(GOwVxs*?&6qIb1*CE`+Bw}u_r@_AO4rs$rs zKG6J`Uc@|g6SxF6)v0`mPb}5|aijV{vQZx#R=t_x7%PnuE23V;d{&NaTV$K~VF_nb z6kJrdr)LXX?Jh*v$kcw22X-Pw-N8@F(a6FvI5An{7;J6eXeR)qvV&uv5aLdBo4|$z z8JFtqVX}Bw?;N1n9#*1(5VvcMM*2?Pf-BjPO-(93`5cLO*xP6|E+2;R9{-J`si9XDliM?#@3bIZmhmF~S!;&iN+IQ+FuQjf`}@z1gM2b*Z@1@RybjRLjfi%@!KdoN@bzYl|Z-sJz2dHe^28kn?yPd=(Se4KSdlvYFfO2uEoak|u)|&$3#pJ} z=j(e(du!_)7`l~6RGx9?d7Ra-6P+e=`a;1fB&}mMedZxB?T3mTHk;zajiRcdrn_L} zzy);~>9A~WrYh;?HN+apEDi7q%nM7AcwpMDAFu*#VPtH;30V2;WL5T_6ID`+5m3gW zrQI8Z??^6oL*Brt-8sYKK*V7Z7(dsW%|gGwFesF%61h z8yR28CDtOHfTw69Mc7UT$)%*%$KEks84)j*K;67vlp=e@Fac*h1U`Xcq#|)fJfmnk z%G-7^MGF0ay4P1b{Q)NS0$RFp@#efetJ2m9rEmRPFUAlD&C7pT8Fg=eU;>xBcZ)oSysf`0^_a9g*R1bXOJ(mJYRUFyzZ(vi_R%wz*9hehnx z?Ba>f5B8dbU7++%iZ$uaH}4zv2MfRj2fgmF(_B4*@Gv0tCe8zWYwJ-Y09B*6o8r9M zIp3`}{Q^`3*R7!VJ56|1UW}-cW(!*);g*8hS!y+*TCauGdf6sZZDcX%DI`GlTW9hG zd(UUwnP&G`QA1Ao1C2RvYo}*lyao95B?{&(xa8!)dzXki@=I~W zP_3WVw!_xY?ynauEN`4%T+IDmDPuuJJLnYaLEvL`+qy5yuomK@kQ~0y69O-;7@!0r zp|#tLnCbO$0xcPc3WGX=gt5zKtnI83Sb3qHFz{@yAgc84En&|BG$C3=az&%wPR?ZG z;$>S9_qMthwY&UdLNuPW^KuvXW6yzhDKklBW}shX%%_{i#)Fxgt zPBOf?ZBl4_*Sk3K(x(_Gv2fb;$rjLcU*fDE!*wr#9xz_YRv)_R*-DzM%<(h zBt}ecE4H0v)ACRmVnC4)+UujRzu=LA5Sn}CtvkIawXT>}n0(HhcAxf+jx+0pN2APYf2<(6 zyG`|j?kX6SR$boPO(Z_7*lm$}V3&_2vSF_WyS&vJw8K0g(pF8|mpjZRE)6S0Uc@Ub zNKsG*=^-#ugG3OYGl_bSUWQnSI&!_u%23xufK6i}BGQ+LF4;U>6v zP{u87H%o9>N>bBT6%VOhT46Tx(1|qA7|lIv@zC0%srLffD`m8_V3njTel-ESZt7kw zuC-4{F5_$%e`K=w=mq_ z7nWZNjcyRQuoMR!^&0#uGj#m!t`H=1G}{W(&MZ(yZHS-4Cr|>+K8Rxe>vd5C>VL zGf^SDkFS;pl~$f|XX!J6K6I4>Tq2OmgVdWKuaRhnilOXtp-1y`x%c@~3tSsXuK~uq z7R)>$gjC<$Psh+OOp9~>p>mf$U1CC)+d_9R=)!wF-b69*7)9DqDg)#* zRBY#yeQdBD;LD1IOqyAS7P|{%%4=0*7qgcVMux^doiYuQ=cHy%H$z!jRw1OEMpwYC*|XN8vmw$IM6iRz5BJ-U%_LOOUS;P0WN$me8e*Xq~K zC!GVRxg-eF_>;i>L zKMLdPb&LkMpmZmzA;rZ=z03W1B*qa47{HD9mQHJQ1@;mEs;d3P6llvkStC<8505%&E$+Jw^SznwXP4kFW zmw=|Z*T`j@f(2+dPT4f1YMH)7B0H`(S_6FO%X?)5V9VCcWy?Z&)iA7?JHcXjV+mJ) z@n?s{rdNfC^?#|vC2qL&b{-5;5^8KV!h+Tt%1S;y&KYSA>VAwC(C^}o zd#GRKKpG%1y+GM}KVy#sV=vCHE^uCHb%9gy)#)@SkrCBzhi7s$y*)MM!lY{Q4Xrl$`Yk7|#ctr24Gw zw1Y>bqfn3P=JM7uwoHop@kQEOBH!a1baY$SkI~=mM}`}${7Q^-ZZ-d$$Y8l)72~Vi z-=0x}uMxGTzDS7xQlR<}5NfbE+MY#Jky*g)vy@v|lPN2r@a%>a2fOV$3M zS*@o3A87@Wy!r~T)6+K_D_9XRz?>y+oHY$$Q zyclo|<m)KIhk|*A z)lAuuUTn7@%gZ5XPQd#9(GouN5RDFwt1~Do?8kC!P|&ilb`BCBx#hJBOZH+~_8wDS z!FQ@SMLEk2RmDv7w0>6!Ig`L=jl$4q)OP#0e_X{pK|-@RnecJ{go>F-;#6YE5-mG{ z*;t8gt3Rn?HS!bOIb_loAGNZPu*`p|gmQwcz?T+;|LCVn$VXv_jLvp;;NvA~Gk-?K z3w@utXk8*WCeQw?fe~HcOq^?WQnFDJ-teE3DDkD{a%j$G1VAQ;c5xKKU@Lp++1kp7 zz4z2BC_gU|hdS;fSuE6T?H4jkn6_||w>2vJ=oclXe$vyt@|2%&BUYb3D&z5&GGx&b z_1OGH^(g*jJ37*WkCVwtRfqhF1C={D500t5l^mN|mD}y!=-0x1_E#k?MmtWB9%I!@ zS=|WiRZ-Q5zoxJ1T&sQZ8A+8{JJs>c!e1}&4O-Bt2LM9#RhpNSrx@B~H-sqCLeKnH z&_~sn!d2`PmBPPatYEF)JNeo%!jtrFiLaGh6jcuF9QoS`JsIrYdYRtWx9hVY(l_vk`LSO`l{J_{N$3kSJPcMx8VkP4fIlvMp~ z1)<2B0&HF)+J${oT<<|#hxNYkR`;g!B^Nl?(dgyy;A4H(?_{_xwfZfn(%z_JZx1C> zVmlaaXly%{h&cYPKsHQLH7zWQqOE1dZr)xKvVmys4~}Gi&&t9w{fry~MSl-*w>r(_ z+J*hiZf}q@vyU$>iblq8V@Ur1|08zdw#DorXFR=;!*8&9KAQprxz!x!(w%zI^Svql z7Wxh|GTR_VJkQkK;P=aDPDaK^Rc(0uS7C?$pp41Kh%u=p6JHEu3xMno6=VTfqYeSX z<|c=HsRE)u(hyNEnYc;B#WU-OK|JH8si{BC@%YmJYU|MWDev-uSr+3q#ofTBx;J8f zfm3m$N@d2~sr64J-SMrBq7kkc1@fHjR3;jYETc$7$~J$WjvZRr3%^)Ui8VZCQnc?~ zz&7}qPpxqM_L2rWB5~b4S0VOmK|NLBV-DMHmxker!bLg z@@He9^RWU~{!!7cKaYYl7Cr6#Td=3#2S&wN5HsGs&)MbLYXIk8s5rB-_~v->EfWwE zlyyWWy1!J{vsUk4HYK#@#-d0&=#V@e>)lC0w*6IX#9|3b0c<4MRw4RS|FyP;R%h5x z$&L?twB^4P_Bd4&i`PbD6JniK`zgS8GX6%zpSdowL>M~lL>O71NYjTjtw7n*Z_e(& zxDGh~*2D<}wj5SEheyX8eoXoLhN!{%J8dP$z1AQJeY-4GiiK5@j*E1&tPtJI|2{tE zLfXgS9YVwZg9Clwdu604!sc;8g8yS2oUtiOboKhDGGfI8FS`M_~@?@xoYOaYlNR>JGaOdlRhr-?TONpt?S_6>3_!XKib= zB+Ih-AQYT7H=eUdoJz>Ce^=Le34%7+MtZ&ZwRMnPnMEPMXXnfcnazzv=EZ+F5a*FO zn;%s;(;0x-(tygB|IZXLUtQEs>M^-zokp-OK2y@T9Gm;uKb9<>QlK3d2{7{qO!q;Oj5Ib9Rjci6i_el!rE6 z+=r?){@)ZAq%0pFLwIDXiwK*jT?0pWn=u~N$2(ODD)3@xB^UbyoR+4LK`)G! z+>{~fAopW7`bgm}Hg^#_cyo$q1^Q&Ru~+8Fp{fvX`8+5^g=#bl6Neo}ukz*ZrgRt@ zySWIv`QQ}g1tlB79Wi>Xvs1Du_bz(cY$RU-< z@vs!%#;|{=9s_rT$Suy;bfY5D4^MGziehaQna#R$3w|~xidK)vFb(0MZviPSFC;r1 zID)@yTvTQIBU4-=Q3#$YYl$uwJ}E22M%?UU>W%6TAuxK2(u&(J37D%RsD4(DBJhUz zN=TsW-KXjhKU6^~^PW!1hO5j-#jkq}?gLHnXvB3nxxUw}_nPn`@k+{t^^T(*j zcObcSvP5U|ab?Dh{jnzY$&#Iqov84B9AamH>_GQSbJ^(q*h%+jftxIfZ|n@TU9 zG;X4@{-Y50QT-a4g5pif2l&lM>BiIb){B8RKUyGdb#4r#)V<`%h_nOdKeYS4j?b6o z-0QfQ>_)o(I%GR$%09)3$$gDOTWj*jKE{d6eb(b4qjEt$7Lj%L?t|_Pm@AoPev4M) zob+*Vi7LCj?QVOv#c|rP=VxKhZxQ%A%bkJRv~;pONa6W79goLWj>LHmZHHdkkGJBX z(`4)if~`r2s)eU!sPM5ly-&AHfrb#^pxfxST|2omCtj*s#8#H`eSDUDt=<81u7}SJ zM!6ZCcGxj51ghSe;lCD8w-AS#6q--a(2T-z?7by=-9IfwBV)Mw?u2fyy$vE;a#V=S zil?VIH@l6?$zTz>hwedeyGrKi<70vw^V{vK{c3e*4*phydxRKQgR4%z+kroa3h0?g za*y(MJR?It+)J-n%MeO!(&(36s*bz+lyC5v2Cnm6cgoJ+)EBxeP9S+Sbl5h z-B@-9;Uk?ZqhvIQ-aUa1(YLDz@m47OQ?eJ;$=$Q47dB1>WAvrRM$+(vrFlm%R(3M1 z9Xwyw61~$-`_a>3Hm4(lD_^M&N@r4(__TV~tjL>GXf>L+m?%B}T!{(7c1iBi3(}#r z^(c2(D!1%;DLVAOKQP&tM34IC7ufhuzN2c7bOWP2XD=u)-mn>?l{x7e(tXX>z=!d| z0)JXpfRcW`Az~7uqw4@HzU3>}$u&1pY~C1XTw|E18>i=>e0_O$8g{|H5!_Q&A*!s- z2CqZOp0q6l<&!n9zbE^nrW1{-N&S#if_hZ^( zn){E8vRFTc6dQ2632{c(MFUcxEA}+-l=-lcQ$4sAGUUUfXxA(@KI%rji1_;AT7~rn zkQtKSvGTnq*;LWGv2N5AqHb!bgctiVshoP^XbBCnEYK#MptjHHu~(bqy9mnXfH~Q& zM3=y?1POdD$4L55@Su;|3?zy*k(Wjpc?DHi%bnqC*?_khqTr!k?p~32QjOM!K1kWM zRj9N8RS*dy(Ls4tVicha=^fJ?fVLxr3Rew(pkR$ePj}7rT`AVVeDl6xe^690uO6ZQ zFE@*E)luiaNw2RAz``{OcFryrIxsJ)O**XaS74;;zbVp%+A^wa~s@ZR~aMF-)=MD zdx;la_xlK5Dq ziY{ne%2B#)J442~d!c%Zee0s?d@f0hBNSA|qoGWI)wRSWI6pfQU$-ruKFo|lx137t zgY8*3XGTlknEE}-C$p=qD*~Ah2;13s0>tI?DIoZ%-^Hp zHJZo!;0Ch+pTb0s=9lD%#rsN-E-c@<_TCbZzII_g0z#R9r=KT$P4uM&!Zf!QI6!es z*t^Z9+LLOOFak#R-Q{HpMsR0_XaA}Z;#hYVf`#lYu6#Fj>cpNcUEEM)kcE!jQWb1#|>1wb%V%55l??X_(}PU5|`YK0&CT_-(+s z=fFwza>y^)aZwVlfHg9d7!2I(4totWF-gB_u8{IyDPvtO7Cr|Mm0wMX8H#-mAY`cL zg4vuG8D>oxlyb%*Vz+Ze3%DXNvF9!!pJtVGM}sVVS6r^Znaazjdd1%PW{b2$>oxb&kkU5+w*%Ylt#V$qE9nRHy3=zDdf-K6?> zcU{Ox_cfjo2ROd&A?|m_E_B}9%BTp5sP8LW2>GdM4uW#e2E~UxC)zf2UFg{aI6=sm z$ofuXS6k4gf6~aL0x=@D>mZK@5*Zd_Ee!YfMS^EQOP6TX+Eh-=FhhrJHbJ%dEVG5B zNEy5omtC=9@?0jNvfK`h%Vkv5`>KLWxGVi63vwH>F%tInH8(~N34@@rA{(`g)Tz#H^|n*N|! zjgwJ9Rq(x1QjF1l&t;Tw&nK0&{3#T!ldb&iLFbL~3z z5%q{z$bEvK@k007YCa~~y_N9Jf0`SqM{h9zv$a=+pzWuth@l-Mo){Kw#h8>JX496co_KAJ7?PkDx`Tm8g$?o6$B{*pefpUyw)4q88qOz(Ogh&L8FV+upwCi~ zUBsTVV?pEZs0?Hp*sy!dXRFw@plW>_qOp-twQir2ApL7lehkj{jH=EgeOUaSfyHR;0pB)_Erjf_B9O?VK z0$b~7cr@Q`cdsT*BXNRGPqYg=HU+8v37@Z{G~jt1Y3Nmsgp#tV-$0^t6A|50c6i*K zrgHMWfJQe+j*s2mGkd9G)II(}iLceUfjRMubd)zJCw?)B@`2{WFQL($3?~v9@oy~f z4WaejUV=R_GA&Fz$&iPQm6!ga=;8|DY5P(YtC6Ckw#Y6sH#|WtDyT2&k+F zhtG|~UEnJus`M#^;)v5$>~bVzg#YU+OUOcQc6MOgQ$odAze>jy{`iE;rODn;$~*Vf zZge5!ixs()Y3au8^E})>za~St0Zr(@bGY4W2WEdco||UxEpZyYR$^<{8_7zyjgeHZ zC&|^yd4zp+=aPIKh0Jq*asgyhj)<+kMa6e0C^u#xlZ%eJIeonkou7jCODKPji3+*5 z+EK;~Z}RcZND-~ynz0V?8-nn9NE;OD{txkMVh+A`LlRGrbIG`}Q1j_n-%zTT3V3nIxCH zFCu#csCSdT(?E-rZ)kUN$SZ34Wdd(Hfy0@>nDhr(ue^X<9Wa+8`C2OS8l-dRy}+U0qodopevC3I0Nu`<@*^=UURRX-IUybI z8vyV3=6KV`@A5X{L7)Y9mYR);KgHE#PbES8J^!PNN%qK|2+GItHdJQi1x8=r6Q5t`AX8p408rb%q>RJIY;AW5wA$q?4?1I8NCEWrHe-bkw; z^y3fas~8M>olN);)+TDjojKWH{9=-ia;41hX+C4OjGI97A0p6tY)=+w_DPfmh;b4z z$Kr=G%$rHQ*Erm$Ll9o8U9_daW4o(3eGVx<^pE7o+Hjr%9$Jm&x1=nIA9bRl4R(ja zlFfgV$M?r1w!`kQ-CV50yY3hZQ}nQHH}TBGLRTT~JMWa}Qkyn68_7h>Kr@$nBB-v4 z?~*u`E<9n0N5Uvb?eTNi{3ljl5-MBe$0b^b!y4gjBA$r1a(j{hmy#4e{zQ&Vyz3Yy zT*Qt$T?nz|a&6pecS@qJq)^ zkSZQ6?1IGRFJcFO#)`PuA z5W7=QCMBPVYT%!jNWuF6&m5+0L_1(2WU9{no-Km4U+CFfDGhJqoZ#K&7fSfh>o5j5 z{yr00_!o0@gLbm8hOsYpkGg1n2jZpcUs7?3$kGkf&yaWt=a);!xdhg`hDGx6%-ADM z32^MMsE8*?WsT9wzC8qFVRu(-74O#t#fR&E-@UHZ-3K3i9sqZ(lt9V z**K|t&~Hhc-C^UfXv9%8t+8Ew@fzf~`f_)gst*2bi7nW99>+?d?ilaMFkxC#kc%Li z-Av`2{*FY|PkNfyRfI-tTbN2n@L5l_TYJmb;QhHi#H9PTHQVhe?jBN6n%~Wk8F%a; zTRu{?fK=dy&3Pwi@ZYnebKC96`F2?RQz;W~3|v?n{9XsHQIf{FyGhky{=SL}A5YnY z&c|R27?11tJSdT52i3jz4ji-uLhSwp(qU8dqef1RT19>)U5KPN;T;onGf$0NP5Ej&t;n}$ot3h_?a z-y+rlHtWPnycOB62(~&mr}Cz!mQGJ-CkVXxud%VO{wJcuFPa55E8F1cnJQO7y8oTF zmdwAf+G!?QQyiu9vwcBl=L@S$UkR=)k_V#V=(qJMSjXRM>)7rb-uSyhtmYrI)$D*( ze=%uXZwL!C=b9Uf$A}k`|52<4T|-M?a-|Q@!C~>mFp;J5Y(P5;aZmLb;uil;h;rCz zbdQcP88|2rr?zet+kDA5Ee$aJgl++6|8t5*c)4?wH~c>pY+xYF4@&yfbx`9-xe5^p z`!59>M4#c2iu8?v!cO(QPY{oWR1U{~7dSBl)~;VqnzF<(r1mAKV32)ssaw?lSP);x z>*Yf*$EixM%-ZuzIv@f6SHak;9~>k-bib}_UMjYq-^Y3z$49eOiJ0^M73d*talQi# z@c?r$B{x4@!Mk^hGM0B$O9Z)By9=wS36E2psH>LM!keRF{=bw)^p#i=6GY$xLH znYG(NuRs>?0SUxA108tpi~-;B60n28q$0;vUtq!q%Q%Qhg;Bif;Lg~0d?Pa fgo?>0O`T-oO4HL)K^au40+k-ABce2>6VLwxY$CN( literal 0 HcmV?d00001 diff --git a/include/extensions/network/HttpClient.h b/include/extensions/network/HttpClient.h new file mode 100644 index 0000000..9470517 --- /dev/null +++ b/include/extensions/network/HttpClient.h @@ -0,0 +1,120 @@ +/**************************************************************************** + Copyright (c) 2010-2012 cocos2d-x.org + Copyright (c) 2012 greathqy + + 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 __CCHTTPREQUEST_H__ +#define __CCHTTPREQUEST_H__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" + +#include "HttpRequest.h" +#include "HttpResponse.h" + +NS_CC_EXT_BEGIN + +/** + * @addtogroup Network + * @{ + */ + + +/** @brief Singleton that handles asynchrounous http requests + * Once the request completed, a callback will issued in main thread when it provided during make request + * @js NA + * @lua NA + */ +class CCHttpClient : public CCObject +{ +public: + /** Return the shared instance **/ + static CCHttpClient *getInstance(); + + /** Relase the shared instance **/ + static void destroyInstance(); + + /** + * Add a get request to task queue + * @param request a CCHttpRequest object, which includes url, response callback etc. + please make sure request->_requestData is clear before calling "send" here. + * @return NULL + */ + void send(CCHttpRequest* request); + + + /** + * Change the connect timeout + * @param timeout + * @return NULL + */ + inline void setTimeoutForConnect(int value) {_timeoutForConnect = value;}; + + /** + * Get connect timeout + * @return int + * + */ + inline int getTimeoutForConnect() {return _timeoutForConnect;} + + + /** + * Change the download timeout + * @param value + * @return NULL + */ + inline void setTimeoutForRead(int value) {_timeoutForRead = value;}; + + + /** + * Get download timeout + * @return int + */ + inline int getTimeoutForRead() {return _timeoutForRead;}; + +private: + CCHttpClient(); + virtual ~CCHttpClient(); + bool init(void); + + /** + * Init pthread mutex, semaphore, and create new thread for http requests + * @return bool + */ + bool lazyInitThreadSemphore(); + /** Poll function called from main thread to dispatch callbacks when http requests finished **/ + void dispatchResponseCallbacks(float delta); + +private: + int _timeoutForConnect; + int _timeoutForRead; + + // std::string reqId; +}; + +// end of Network group +/// @} + +NS_CC_EXT_END + +#endif //__CCHTTPREQUEST_H__ diff --git a/include/extensions/network/HttpRequest.h b/include/extensions/network/HttpRequest.h new file mode 100644 index 0000000..30097d7 --- /dev/null +++ b/include/extensions/network/HttpRequest.h @@ -0,0 +1,235 @@ +/**************************************************************************** + Copyright (c) 2010-2012 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __HTTP_REQUEST_H__ +#define __HTTP_REQUEST_H__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" + +NS_CC_EXT_BEGIN + +class CCHttpClient; +class CCHttpResponse; +typedef void (CCObject::*SEL_HttpResponse)(CCHttpClient* client, CCHttpResponse* response); +#define httpresponse_selector(_SELECTOR) (cocos2d::extension::SEL_HttpResponse)(&_SELECTOR) + +/** + @brief defines the object which users must packed for CCHttpClient::send(HttpRequest*) method. + Please refer to samples/TestCpp/Classes/ExtensionTest/NetworkTest/HttpClientTest.cpp as a sample + @since v2.0.2 + @js NA + @lua NA + */ + +class CCHttpRequest : public CCObject +{ +public: + /** Use this enum type as param in setReqeustType(param) */ + typedef enum + { + kHttpGet, + kHttpPost, + kHttpPut, + kHttpDelete, + kHttpUnkown, + } HttpRequestType; + + /** Constructor + Because HttpRequest object will be used between UI thead and network thread, + requestObj->autorelease() is forbidden to avoid crashes in CCAutoreleasePool + new/retain/release still works, which means you need to release it manually + Please refer to HttpRequestTest.cpp to find its usage + */ + CCHttpRequest() + { + _requestType = kHttpUnkown; + _url.clear(); + _requestData.clear(); + _tag.clear(); + _pTarget = NULL; + _pSelector = NULL; + _pUserData = NULL; + }; + + /** Destructor */ + virtual ~CCHttpRequest() + { + if (_pTarget) + { + _pTarget->release(); + } + }; + + /** Override autorelease method to avoid developers to call it */ + CCObject* autorelease(void) + { + CCAssert(false, "HttpResponse is used between network thread and ui thread \ + therefore, autorelease is forbidden here"); + return NULL; + } + + // setter/getters for properties + + /** Required field for HttpRequest object before being sent. + kHttpGet & kHttpPost is currently supported + */ + inline void setRequestType(HttpRequestType type) + { + _requestType = type; + }; + /** Get back the kHttpGet/Post/... enum value */ + inline HttpRequestType getRequestType() + { + return _requestType; + }; + + /** Required field for HttpRequest object before being sent. + */ + inline void setUrl(const char* url) + { + _url = url; + }; + /** Get back the setted url */ + inline const char* getUrl() + { + return _url.c_str(); + }; + + /** Option field. You can set your post data here + */ + inline void setRequestData(const char* buffer, unsigned int len) + { + _requestData.assign(buffer, buffer + len); + }; + /** Get the request data pointer back */ + inline char* getRequestData() + { + return &(_requestData.front()); + } + /** Get the size of request data back */ + inline int getRequestDataSize() + { + return _requestData.size(); + } + + /** Option field. You can set a string tag to identify your request, this tag can be found in HttpResponse->getHttpRequest->getTag() + */ + inline void setTag(const char* tag) + { + _tag = tag; + }; + /** Get the string tag back to identify the request. + The best practice is to use it in your MyClass::onMyHttpRequestCompleted(sender, HttpResponse*) callback + */ + inline const char* getTag() + { + return _tag.c_str(); + }; + + /** Option field. You can attach a customed data in each request, and get it back in response callback. + But you need to new/delete the data pointer manully + */ + inline void setUserData(void* pUserData) + { + _pUserData = pUserData; + }; + /** Get the pre-setted custom data pointer back. + Don't forget to delete it. HttpClient/HttpResponse/HttpRequest will do nothing with this pointer + */ + inline void* getUserData() + { + return _pUserData; + }; + + /** Required field. You should set the callback selector function at ack the http request completed + */ + CC_DEPRECATED_ATTRIBUTE inline void setResponseCallback(CCObject* pTarget, SEL_CallFuncND pSelector) + { + setResponseCallback(pTarget, (SEL_HttpResponse) pSelector); + } + + inline void setResponseCallback(CCObject* pTarget, SEL_HttpResponse pSelector) + { + _pTarget = pTarget; + _pSelector = pSelector; + + if (_pTarget) + { + _pTarget->retain(); + } + } + /** Get the target of callback selector funtion, mainly used by CCHttpClient */ + inline CCObject* getTarget() + { + return _pTarget; + } + + /* This sub class is just for migration SEL_CallFuncND to SEL_HttpResponse, + someday this way will be removed */ + class _prxy + { + public: + _prxy( SEL_HttpResponse cb ) :_cb(cb) {} + ~_prxy(){}; + operator SEL_HttpResponse() const { return _cb; } + CC_DEPRECATED_ATTRIBUTE operator SEL_CallFuncND() const { return (SEL_CallFuncND) _cb; } + protected: + SEL_HttpResponse _cb; + }; + + /** Get the selector function pointer, mainly used by CCHttpClient */ + inline _prxy getSelector() + { + return _prxy(_pSelector); + } + + /** Set any custom headers **/ + inline void setHeaders(std::vector pHeaders) + { + _headers=pHeaders; + } + + /** Get custom headers **/ + inline std::vector getHeaders() + { + return _headers; + } + + +protected: + // properties + HttpRequestType _requestType; /// kHttpRequestGet, kHttpRequestPost or other enums + std::string _url; /// target url that this request is sent to + std::vector _requestData; /// used for POST + std::string _tag; /// user defined tag, to identify different requests in response callback + CCObject* _pTarget; /// callback target of pSelector function + SEL_HttpResponse _pSelector; /// callback function, e.g. MyLayer::onHttpResponse(CCHttpClient *sender, CCHttpResponse * response) + void* _pUserData; /// You can add your customed data here + std::vector _headers; /// custom http headers +}; + +NS_CC_EXT_END + +#endif //__HTTP_REQUEST_H__ diff --git a/include/extensions/network/HttpResponse.h b/include/extensions/network/HttpResponse.h new file mode 100644 index 0000000..89e7d77 --- /dev/null +++ b/include/extensions/network/HttpResponse.h @@ -0,0 +1,185 @@ +/**************************************************************************** + Copyright (c) 2010-2012 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __HTTP_RESPONSE__ +#define __HTTP_RESPONSE__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" +#include "HttpRequest.h" + +NS_CC_EXT_BEGIN + +/** + @brief defines the object which users will receive at onHttpCompleted(sender, HttpResponse) callback + Please refer to samples/TestCpp/Classes/ExtensionTest/NetworkTest/HttpClientTest.cpp as a sample + @since v2.0.2 + @js NA + @lua NA + */ +class CCHttpResponse : public CCObject +{ +public: + /** Constructor, it's used by CCHttpClient internal, users don't need to create HttpResponse manually + @param request the corresponding HttpRequest which leads to this response + */ + CCHttpResponse(CCHttpRequest* request) + { + _pHttpRequest = request; + if (_pHttpRequest) + { + _pHttpRequest->retain(); + } + + _succeed = false; + _responseData.clear(); + _errorBuffer.clear(); + } + + /** Destructor, it will be called in CCHttpClient internal, + users don't need to desturct HttpResponse object manully + */ + virtual ~CCHttpResponse() + { + if (_pHttpRequest) + { + _pHttpRequest->release(); + } + } + + /** Override autorelease method to prevent developers from calling it */ + CCObject* autorelease(void) + { + CCAssert(false, "HttpResponse is used between network thread and ui thread \ + therefore, autorelease is forbidden here"); + return NULL; + } + + // getters, will be called by users + + /** Get the corresponding HttpRequest object which leads to this response + There's no paired setter for it, coz it's already setted in class constructor + */ + inline CCHttpRequest* getHttpRequest() + { + return _pHttpRequest; + } + + /** To see if the http reqeust is returned successfully, + Althrough users can judge if (http return code = 200), we want an easier way + If this getter returns false, you can call getResponseCode and getErrorBuffer to find more details + */ + inline bool isSucceed() + { + return _succeed; + }; + + /** Get the http response raw data */ + inline std::vector* getResponseData() + { + return &_responseData; + } + + /** get the Rawheader **/ + inline std::vector* getResponseHeader() + { + return &_responseHeader; + } + + /** Get the http response errorCode + * I know that you want to see http 200 :) + */ + inline int getResponseCode() + { + return _responseCode; + } + + /** Get the rror buffer which will tell you more about the reason why http request failed + */ + inline const char* getErrorBuffer() + { + return _errorBuffer.c_str(); + } + + // setters, will be called by CCHttpClient + // users should avoid invoking these methods + + + /** Set if the http request is returned successfully, + Althrough users can judge if (http code == 200), we want a easier way + This setter is mainly used in CCHttpClient, users mustn't set it directly + */ + inline void setSucceed(bool value) + { + _succeed = value; + }; + + + /** Set the http response raw buffer, is used by CCHttpClient + */ + inline void setResponseData(std::vector* data) + { + _responseData = *data; + } + + /** Set the http response Header raw buffer, is used by CCHttpClient + */ + inline void setResponseHeader(std::vector* data) + { + _responseHeader = *data; + } + + + /** Set the http response errorCode + */ + inline void setResponseCode(int value) + { + _responseCode = value; + } + + + /** Set the error buffer which will tell you more the reason why http request failed + */ + inline void setErrorBuffer(const char* value) + { + _errorBuffer.clear(); + _errorBuffer.assign(value); + }; + +protected: + bool initWithRequest(CCHttpRequest* request); + + // properties + CCHttpRequest* _pHttpRequest; /// the corresponding HttpRequest pointer who leads to this response + bool _succeed; /// to indecate if the http reqeust is successful simply + std::vector _responseData; /// the returned raw data. You can also dump it as a string + std::vector _responseHeader; /// the returned raw header data. You can also dump it as a string + int _responseCode; /// the status code returned from libcurl, e.g. 200, 404 + std::string _errorBuffer; /// if _responseCode != 200, please read _errorBuffer to find the reason + +}; + +NS_CC_EXT_END + +#endif //__HTTP_RESPONSE_H__ diff --git a/include/extensions/network/WebSocket.h b/include/extensions/network/WebSocket.h new file mode 100644 index 0000000..33aed3d --- /dev/null +++ b/include/extensions/network/WebSocket.h @@ -0,0 +1,166 @@ +/**************************************************************************** + Copyright (c) 2010-2013 cocos2d-x.org + Copyright (c) 2013 James Chen + + 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. + +"[WebSocket module] is based in part on the work of the libwebsockets project +(http://libwebsockets.org)" + + ****************************************************************************/ + +#ifndef __CC_WEBSOCKET_H__ +#define __CC_WEBSOCKET_H__ + +#include "ExtensionMacros.h" +#include "cocos2d.h" +#include "libwebsockets.h" +#include + +NS_CC_EXT_BEGIN + +class WsThreadHelper; +class WsMessage; + +class WebSocket +{ +public: + /** + * @js ctor + */ + WebSocket(); + /** + * @js NA + * @lua NA + */ + virtual ~WebSocket(); + + /** + * @brief Data structure for message + */ + struct Data + { + Data():bytes(NULL), len(0), isBinary(false){} + char* bytes; + int len; + bool isBinary; + }; + + /** + * @brief Errors in websocket + */ + enum ErrorCode + { + kErrorTimeout = 0, + kErrorConnectionFailure, + kErrorUnknown + }; + + /** + * @brief The delegate class to process websocket events. + * @js NA + * @lua NA + */ + class Delegate + { + public: + virtual ~Delegate() {} + virtual void onOpen(WebSocket* ws) = 0; + virtual void onMessage(WebSocket* ws, const Data& data) = 0; + virtual void onClose(WebSocket* ws) = 0; + virtual void onError(WebSocket* ws, const ErrorCode& error) = 0; + }; + + + /** + * @brief The initialized method for websocket. + * It needs to be invoked right after websocket instance is allocated. + * @param delegate The delegate which want to receive event from websocket. + * @param url The URL of websocket server. + * @return true: Success, false: Failure + * @js NA + */ + bool init(const Delegate& delegate, + const std::string& url, + const std::vector* protocols = NULL); + + /** + * @brief Sends string data to websocket server. + */ + void send(const std::string& message); + + /** + * @brief Sends binary data to websocket server. + */ + void send(const unsigned char* binaryMsg, unsigned int len); + + /** + * @brief Closes the connection to server. + */ + void close(); + + /** + * Websocket state + */ + enum State + { + kStateConnecting = 0, + kStateOpen, + kStateClosing, + kStateClosed + }; + + /** + * @brief Gets current state of connection. + */ + State getReadyState(); +private: + virtual void onSubThreadStarted(); + virtual int onSubThreadLoop(); + virtual void onSubThreadEnded(); + virtual void onUIThreadReceiveMessage(WsMessage* msg); + + + friend class WebSocketCallbackWrapper; + int onSocketCallback(struct libwebsocket_context *ctx, + struct libwebsocket *wsi, + enum libwebsocket_callback_reasons reason, + void *user, void *in, size_t len); + +private: + State _readyState; + std::string _host; + unsigned int _port; + std::string _path; + + friend class WsThreadHelper; + WsThreadHelper* _wsHelper; + + struct libwebsocket* _wsInstance; + struct libwebsocket_context* _wsContext; + Delegate* _delegate; + int _SSLConnection; + struct libwebsocket_protocols* _wsProtocols; +}; + +NS_CC_EXT_END + +#endif /* defined(__CC_JSB_WEBSOCKET_H__) */ diff --git a/include/extensions/physics_nodes/CCPhysicsDebugNode.h b/include/extensions/physics_nodes/CCPhysicsDebugNode.h new file mode 100644 index 0000000..4bb2868 --- /dev/null +++ b/include/extensions/physics_nodes/CCPhysicsDebugNode.h @@ -0,0 +1,70 @@ +/* Copyright (c) 2012 Scott Lembcke and Howling Moon Software + * Copyright (c) 2012 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 __PHYSICSNODES_DEBUGNODE_H__ +#define __PHYSICSNODES_DEBUGNODE_H__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" + +#if CC_ENABLE_CHIPMUNK_INTEGRATION + +#include "chipmunk.h" + +NS_CC_EXT_BEGIN + +/** + A CCBaseData that draws the components of a physics engine. + + Supported physics engines: + - Chipmunk + - Objective-Chipmunk + + @since v2.1 + @js NA + @lua NA + */ + +class CCPhysicsDebugNode : public CCDrawNode +{ +protected: + cpSpace *m_pSpacePtr; + +public: + /** Create a debug node for a regular Chipmunk space. */ + static CCPhysicsDebugNode* create(cpSpace *space); + + virtual ~CCPhysicsDebugNode(); + + virtual void draw(); + + cpSpace* getSpace() const; + void setSpace(cpSpace *space); + + CCPhysicsDebugNode(); +}; + +NS_CC_EXT_END + +#endif // CC_ENABLE_CHIPMUNK_INTEGRATION + +#endif // __PHYSICSNODES_DEBUGNODE_H__ diff --git a/include/extensions/physics_nodes/CCPhysicsSprite.h b/include/extensions/physics_nodes/CCPhysicsSprite.h new file mode 100644 index 0000000..7db8b50 --- /dev/null +++ b/include/extensions/physics_nodes/CCPhysicsSprite.h @@ -0,0 +1,134 @@ +/* Copyright (c) 2012 Scott Lembcke and Howling Moon Software + * Copyright (c) 2012 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 __PHYSICSNODES_CCPHYSICSSPRITE_H__ +#define __PHYSICSNODES_CCPHYSICSSPRITE_H__ + +#include "cocos2d.h" +#include "ExtensionMacros.h" + +#if CC_ENABLE_CHIPMUNK_INTEGRATION +#include "chipmunk.h" +#elif CC_ENABLE_BOX2D_INTEGRATION +class b2Body; +#else // CC_ENABLE_BOX2D_INTEGRATION +#error "You must define either CC_ENABLE_CHIPMUNK_INTEGRATION or CC_ENABLE_BOX2D_INTEGRATION to use CCPhysicsSprite.h" +#endif + +NS_CC_EXT_BEGIN +/** A CCSprite subclass that is bound to a physics body. + It works with: + - Chipmunk: Preprocessor macro CC_ENABLE_CHIPMUNK_INTEGRATION should be defined + - Objective-Chipmunk: Preprocessor macro CC_ENABLE_CHIPMUNK_INTEGRATION should be defined + - Box2d: Preprocessor macro CC_ENABLE_BOX2D_INTEGRATION should be defined + + Features and Limitations: + - Scale and Skew properties are ignored. + - Position and rotation are going to updated from the physics body + - If you update the rotation or position manually, the physics body will be updated + - You can't enble both Chipmunk support and Box2d support at the same time. Only one can be enabled at compile time + * @js NA + * @lua NA + */ +class CCPhysicsSprite : public CCSprite +{ +protected: + bool m_bIgnoreBodyRotation; +#if CC_ENABLE_CHIPMUNK_INTEGRATION + cpBody *m_pCPBody; + +#elif CC_ENABLE_BOX2D_INTEGRATION + b2Body *m_pB2Body; + + // Pixels to Meters ratio + float m_fPTMRatio; +#endif // CC_ENABLE_CHIPMUNK_INTEGRATION +public: + CCPhysicsSprite(); + + static CCPhysicsSprite* create(); + /** Creates an sprite with a texture. + The rect used will be the size of the texture. + The offset will be (0,0). + */ + static CCPhysicsSprite* createWithTexture(CCTexture2D *pTexture); + + /** Creates an sprite with a texture and a rect. + The offset will be (0,0). + */ + static CCPhysicsSprite* createWithTexture(CCTexture2D *pTexture, const CCRect& rect); + + /** Creates an sprite with an sprite frame. */ + static CCPhysicsSprite* createWithSpriteFrame(CCSpriteFrame *pSpriteFrame); + + /** Creates an sprite with an sprite frame name. + An CCSpriteFrame will be fetched from the CCSpriteFrameCache by name. + If the CCSpriteFrame doesn't exist it will raise an exception. + @since v0.9 + */ + static CCPhysicsSprite* createWithSpriteFrameName(const char *pszSpriteFrameName); + + /** Creates an sprite with an image filename. + The rect used will be the size of the image. + The offset will be (0,0). + */ + static CCPhysicsSprite* create(const char *pszFileName); + + /** Creates an sprite with an image filename and a rect. + The offset will be (0,0). + */ + static CCPhysicsSprite* create(const char *pszFileName, const CCRect& rect); + + virtual bool isDirty(); + + /** Keep the sprite's rotation separate from the body. */ + bool isIgnoreBodyRotation() const; + void setIgnoreBodyRotation(bool bIgnoreBodyRotation); + + virtual const CCPoint& getPosition(); + virtual void getPosition(float* x, float* y); + virtual float getPositionX(); + virtual float getPositionY(); + virtual void setPosition(const CCPoint &position); + virtual float getRotation(); + virtual void setRotation(float fRotation); + virtual CCAffineTransform nodeToParentTransform(); + +#if CC_ENABLE_CHIPMUNK_INTEGRATION + /** Body accessor when using regular Chipmunk */ + cpBody* getCPBody() const; + void setCPBody(cpBody *pBody); +#elif CC_ENABLE_BOX2D_INTEGRATION + /** Body accessor when using box2d */ + b2Body* getB2Body() const; + void setB2Body(b2Body *pBody); + + float getPTMRatio() const; + void setPTMRatio(float fPTMRatio); +#endif // CC_ENABLE_BOX2D_INTEGRATION + +protected: + void updatePosFromPhysics(); +}; + +NS_CC_EXT_END + +#endif // __PHYSICSNODES_CCPHYSICSSPRITE_H__ diff --git a/include/extensions/spine/Animation.h b/include/extensions/spine/Animation.h new file mode 100644 index 0000000..b7d922c --- /dev/null +++ b/include/extensions/spine/Animation.h @@ -0,0 +1,132 @@ +/******************************************************************************* + * Copyright (c) 2013, Esoteric Software + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * 2. 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. + * + * 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. + ******************************************************************************/ + +#ifndef SPINE_ANIMATION_H_ +#define SPINE_ANIMATION_H_ + +namespace cocos2d { namespace extension { + +typedef struct Timeline Timeline; +struct Skeleton; + +typedef struct { + const char* const name; + float duration; + + int timelineCount; + Timeline** timelines; +} Animation; + +Animation* Animation_create (const char* name, int timelineCount); +void Animation_dispose (Animation* self); + +void Animation_apply (const Animation* self, struct Skeleton* skeleton, float time, int/*bool*/loop); +void Animation_mix (const Animation* self, struct Skeleton* skeleton, float time, int/*bool*/loop, float alpha); + +/**/ + +struct Timeline { + const void* const vtable; +}; + +void Timeline_dispose (Timeline* self); +void Timeline_apply (const Timeline* self, struct Skeleton* skeleton, float time, float alpha); + +/**/ + +typedef struct { + Timeline super; + float* curves; /* dfx, dfy, ddfx, ddfy, dddfx, dddfy, ... */ +} CurveTimeline; + +void CurveTimeline_setLinear (CurveTimeline* self, int frameIndex); +void CurveTimeline_setStepped (CurveTimeline* self, int frameIndex); + +/* Sets the control handle positions for an interpolation bezier curve used to transition from this keyframe to the next. + * cx1 and cx2 are from 0 to 1, representing the percent of time between the two keyframes. cy1 and cy2 are the percent of + * the difference between the keyframe's values. */ +void CurveTimeline_setCurve (CurveTimeline* self, int frameIndex, float cx1, float cy1, float cx2, float cy2); +float CurveTimeline_getCurvePercent (const CurveTimeline* self, int frameIndex, float percent); + +/**/ + +typedef struct BaseTimeline { + CurveTimeline super; + int const framesLength; + float* const frames; /* time, angle, ... for rotate. time, x, y, ... for translate and scale. */ + int boneIndex; +} RotateTimeline; + +RotateTimeline* RotateTimeline_create (int frameCount); + +void RotateTimeline_setFrame (RotateTimeline* self, int frameIndex, float time, float angle); + +/**/ + +typedef struct BaseTimeline TranslateTimeline; + +TranslateTimeline* TranslateTimeline_create (int frameCount); + +void TranslateTimeline_setFrame (TranslateTimeline* self, int frameIndex, float time, float x, float y); + +/**/ + +typedef struct BaseTimeline ScaleTimeline; + +ScaleTimeline* ScaleTimeline_create (int frameCount); + +void ScaleTimeline_setFrame (ScaleTimeline* self, int frameIndex, float time, float x, float y); + +/**/ + +typedef struct { + CurveTimeline super; + int const framesLength; + float* const frames; /* time, r, g, b, a, ... */ + int slotIndex; +} ColorTimeline; + +ColorTimeline* ColorTimeline_create (int frameCount); + +void ColorTimeline_setFrame (ColorTimeline* self, int frameIndex, float time, float r, float g, float b, float a); + +/**/ + +typedef struct { + Timeline super; + int const framesLength; + float* const frames; /* time, ... */ + int slotIndex; + const char** const attachmentNames; +} AttachmentTimeline; + +AttachmentTimeline* AttachmentTimeline_create (int frameCount); + +/* @param attachmentName May be 0. */ +void AttachmentTimeline_setFrame (AttachmentTimeline* self, int frameIndex, float time, const char* attachmentName); + +}} // namespace cocos2d { namespace extension { + +#endif /* SPINE_ANIMATION_H_ */ diff --git a/include/extensions/spine/AnimationState.h b/include/extensions/spine/AnimationState.h new file mode 100644 index 0000000..5362281 --- /dev/null +++ b/include/extensions/spine/AnimationState.h @@ -0,0 +1,66 @@ +/******************************************************************************* + * Copyright (c) 2013, Esoteric Software + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * 2. 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. + * + * 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. + ******************************************************************************/ + +#ifndef SPINE_ANIMATIONSTATE_H_ +#define SPINE_ANIMATIONSTATE_H_ + +#include + +namespace cocos2d { namespace extension { + +typedef struct { + AnimationStateData* const data; + Animation* const animation; + float time; + int/*bool*/loop; +} AnimationState; + +/* @param data May be 0 for no mixing. */ +AnimationState* AnimationState_create (AnimationStateData* data); +void AnimationState_dispose (AnimationState* self); + +void AnimationState_update (AnimationState* self, float delta); + +void AnimationState_apply (AnimationState* self, struct Skeleton* skeleton); + +/* @param animationName May be 0. */ +void AnimationState_setAnimationByName (AnimationState* self, const char* animationName, int/*bool*/loop); +/* @param animation May be 0. */ +void AnimationState_setAnimation (AnimationState* self, Animation* animation, int/*bool*/loop); + +/** @param animationName May be 0. + * @param delay May be <= 0 to use duration of previous animation minus any mix duration plus the negative delay. */ +void AnimationState_addAnimationByName (AnimationState* self, const char* animationName, int/*bool*/loop, float delay); +/** @param animation May be 0. + * @param delay May be <= 0 to use duration of previous animation minus any mix duration plus the negative delay. */ +void AnimationState_addAnimation (AnimationState* self, Animation* animation, int/*bool*/loop, float delay); + +void AnimationState_clearAnimation (AnimationState* self); + +int/*bool*/AnimationState_isComplete (AnimationState* self); + +}} // namespace cocos2d { namespace extension { + +#endif /* SPINE_ANIMATIONSTATE_H_ */ diff --git a/include/extensions/spine/AnimationStateData.h b/include/extensions/spine/AnimationStateData.h new file mode 100644 index 0000000..ea45653 --- /dev/null +++ b/include/extensions/spine/AnimationStateData.h @@ -0,0 +1,49 @@ +/******************************************************************************* + * Copyright (c) 2013, Esoteric Software + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * 2. 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. + * + * 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. + ******************************************************************************/ + +#ifndef SPINE_ANIMATIONSTATEDATA_H_ +#define SPINE_ANIMATIONSTATEDATA_H_ + +#include +#include + +namespace cocos2d { namespace extension { + +typedef struct { + SkeletonData* const skeletonData; + const void* const entries; +} AnimationStateData; + +AnimationStateData* AnimationStateData_create (SkeletonData* skeletonData); +void AnimationStateData_dispose (AnimationStateData* self); + +void AnimationStateData_setMixByName (AnimationStateData* self, const char* fromName, const char* toName, float duration); +void AnimationStateData_setMix (AnimationStateData* self, Animation* from, Animation* to, float duration); +/* Returns 0 if there is no mixing between the animations. */ +float AnimationStateData_getMix (AnimationStateData* self, Animation* from, Animation* to); + +}} // namespace cocos2d { namespace extension { + +#endif /* SPINE_ANIMATIONSTATEDATA_H_ */ diff --git a/include/extensions/spine/Atlas.h b/include/extensions/spine/Atlas.h new file mode 100644 index 0000000..ea5ca9b --- /dev/null +++ b/include/extensions/spine/Atlas.h @@ -0,0 +1,106 @@ +/******************************************************************************* + * Copyright (c) 2013, Esoteric Software + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * 2. 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. + * + * 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. + ******************************************************************************/ + +#ifndef SPINE_ATLAS_H_ +#define SPINE_ATLAS_H_ + +namespace cocos2d { namespace extension { + +typedef enum { + ATLAS_ALPHA, ATLAS_INTENSITY, ATLAS_LUMINANCE_ALPHA, ATLAS_RGB565, ATLAS_RGBA4444, ATLAS_RGB888, ATLAS_RGBA8888 +} AtlasFormat; + +typedef enum { + ATLAS_NEAREST, + ATLAS_LINEAR, + ATLAS_MIPMAP, + ATLAS_MIPMAP_NEAREST_NEAREST, + ATLAS_MIPMAP_LINEAR_NEAREST, + ATLAS_MIPMAP_NEAREST_LINEAR, + ATLAS_MIPMAP_LINEAR_LINEAR +} AtlasFilter; + +typedef enum { + ATLAS_MIRROREDREPEAT, ATLAS_CLAMPTOEDGE, ATLAS_REPEAT +} AtlasWrap; + +typedef struct AtlasPage AtlasPage; +struct AtlasPage { + const char* name; + AtlasFormat format; + AtlasFilter minFilter, magFilter; + AtlasWrap uWrap, vWrap; + + void* rendererObject; + int width, height; + + AtlasPage* next; +}; + +AtlasPage* AtlasPage_create (const char* name); +void AtlasPage_dispose (AtlasPage* self); + +/**/ + +typedef struct AtlasRegion AtlasRegion; +struct AtlasRegion { + const char* name; + int x, y, width, height; + float u, v, u2, v2; + int offsetX, offsetY; + int originalWidth, originalHeight; + int index; + int/*bool*/rotate; + int/*bool*/flip; + int* splits; + int* pads; + + AtlasPage* page; + + AtlasRegion* next; +}; + +AtlasRegion* AtlasRegion_create (); +void AtlasRegion_dispose (AtlasRegion* self); + +/**/ + +typedef struct { + AtlasPage* pages; + AtlasRegion* regions; +} Atlas; + +/* Image files referenced in the atlas file will be prefixed with dir. */ +Atlas* Atlas_readAtlas (const char* data, int length, const char* dir); +/* Image files referenced in the atlas file will be prefixed with the directory containing the atlas file. */ +Atlas* Atlas_readAtlasFile (const char* path); +void Atlas_dispose (Atlas* atlas); + +/* Returns 0 if the region was not found. */ +AtlasRegion* Atlas_findRegion (const Atlas* self, const char* name); + +}} // namespace cocos2d { namespace extension { + +#endif /* SPINE_ATLAS_H_ */ diff --git a/include/extensions/spine/AtlasAttachmentLoader.h b/include/extensions/spine/AtlasAttachmentLoader.h new file mode 100644 index 0000000..20e9046 --- /dev/null +++ b/include/extensions/spine/AtlasAttachmentLoader.h @@ -0,0 +1,43 @@ +/******************************************************************************* + * Copyright (c) 2013, Esoteric Software + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * 2. 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. + * + * 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. + ******************************************************************************/ + +#ifndef SPINE_ATLASATTACHMENTLOADER_H_ +#define SPINE_ATLASATTACHMENTLOADER_H_ + +#include +#include + +namespace cocos2d { namespace extension { + +typedef struct { + AttachmentLoader super; + Atlas* atlas; +} AtlasAttachmentLoader; + +AtlasAttachmentLoader* AtlasAttachmentLoader_create (Atlas* atlas); + +}} // namespace cocos2d { namespace extension { + +#endif /* SPINE_ATLASATTACHMENTLOADER_H_ */ diff --git a/include/extensions/spine/Attachment.h b/include/extensions/spine/Attachment.h new file mode 100644 index 0000000..7be7cf0 --- /dev/null +++ b/include/extensions/spine/Attachment.h @@ -0,0 +1,49 @@ +/******************************************************************************* + * Copyright (c) 2013, Esoteric Software + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * 2. 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. + * + * 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. + ******************************************************************************/ + +#ifndef SPINE_ATTACHMENT_H_ +#define SPINE_ATTACHMENT_H_ + +namespace cocos2d { namespace extension { + +struct Slot; + +typedef enum { + ATTACHMENT_REGION, ATTACHMENT_REGION_SEQUENCE +} AttachmentType; + +typedef struct Attachment Attachment; +struct Attachment { + const char* const name; + AttachmentType type; + + const void* const vtable; +}; + +void Attachment_dispose (Attachment* self); + +}} // namespace cocos2d { namespace extension { + +#endif /* SPINE_ATTACHMENT_H_ */ diff --git a/include/extensions/spine/AttachmentLoader.h b/include/extensions/spine/AttachmentLoader.h new file mode 100644 index 0000000..5fd81f5 --- /dev/null +++ b/include/extensions/spine/AttachmentLoader.h @@ -0,0 +1,52 @@ +/******************************************************************************* + * Copyright (c) 2013, Esoteric Software + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * 2. 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. + * + * 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. + ******************************************************************************/ + +#ifndef SPINE_ATTACHMENTLOADER_H_ +#define SPINE_ATTACHMENTLOADER_H_ + +#include +#include + +namespace cocos2d { namespace extension { + +typedef struct AttachmentLoader AttachmentLoader; +struct AttachmentLoader { + const char* error1; + const char* error2; + + const void* const vtable; +#ifdef __cplusplus + AttachmentLoader () : error1(0), error2(0), vtable(0) {} +#endif +}; + +void AttachmentLoader_dispose (AttachmentLoader* self); + +/* Returns 0 to not load an attachment. If 0 is returned and AttachmentLoader.error1 is set, an error occurred. */ +Attachment* AttachmentLoader_newAttachment (AttachmentLoader* self, Skin* skin, AttachmentType type, const char* name); + +}} // namespace cocos2d { namespace extension { + +#endif /* SPINE_ATTACHMENTLOADER_H_ */ diff --git a/include/extensions/spine/Bone.h b/include/extensions/spine/Bone.h new file mode 100644 index 0000000..3f4688a --- /dev/null +++ b/include/extensions/spine/Bone.h @@ -0,0 +1,59 @@ +/******************************************************************************* + * Copyright (c) 2013, Esoteric Software + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * 2. 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. + * + * 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. + ******************************************************************************/ + +#ifndef SPINE_BONE_H_ +#define SPINE_BONE_H_ + +#include + +namespace cocos2d { namespace extension { + +typedef struct Bone Bone; +struct Bone { + BoneData* const data; + Bone* const parent; + float x, y; + float rotation; + float scaleX, scaleY; + + float const m00, m01, worldX; /* a b x */ + float const m10, m11, worldY; /* c d y */ + float const worldRotation; + float const worldScaleX, worldScaleY; +}; + +void Bone_setYDown (int/*bool*/yDown); + +/* @param parent May be 0. */ +Bone* Bone_create (BoneData* data, Bone* parent); +void Bone_dispose (Bone* self); + +void Bone_setToSetupPose (Bone* self); + +void Bone_updateWorldTransform (Bone* self, int/*bool*/flipX, int/*bool*/flipY); + +}} // namespace cocos2d { namespace extension { + +#endif /* SPINE_BONE_H_ */ diff --git a/include/extensions/spine/BoneData.h b/include/extensions/spine/BoneData.h new file mode 100644 index 0000000..54126a7 --- /dev/null +++ b/include/extensions/spine/BoneData.h @@ -0,0 +1,46 @@ +/******************************************************************************* + * Copyright (c) 2013, Esoteric Software + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * 2. 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. + * + * 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. + ******************************************************************************/ + +#ifndef SPINE_BONEDATA_H_ +#define SPINE_BONEDATA_H_ + +namespace cocos2d { namespace extension { + +typedef struct BoneData BoneData; +struct BoneData { + const char* const name; + BoneData* const parent; + float length; + float x, y; + float rotation; + float scaleX, scaleY; +}; + +BoneData* BoneData_create (const char* name, BoneData* parent); +void BoneData_dispose (BoneData* self); + +}} // namespace cocos2d { namespace extension { + +#endif /* SPINE_BONEDATA_H_ */ diff --git a/include/extensions/spine/CCSkeleton.h b/include/extensions/spine/CCSkeleton.h new file mode 100644 index 0000000..12bc666 --- /dev/null +++ b/include/extensions/spine/CCSkeleton.h @@ -0,0 +1,100 @@ +/******************************************************************************* + * Copyright (c) 2013, Esoteric Software + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * 2. 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. + * + * 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. + ******************************************************************************/ + +#ifndef SPINE_CCSKELETON_H_ +#define SPINE_CCSKELETON_H_ + +#include +#include "cocos2d.h" + +namespace cocos2d { namespace extension { + +/** +Draws a skeleton. +*/ +class CCSkeleton: public cocos2d::CCNodeRGBA, public cocos2d::CCBlendProtocol { +public: + Skeleton* skeleton; + Bone* rootBone; + float timeScale; + bool debugSlots; + bool debugBones; + bool premultipliedAlpha; + + static CCSkeleton* createWithData (SkeletonData* skeletonData, bool ownsSkeletonData = false); + static CCSkeleton* createWithFile (const char* skeletonDataFile, Atlas* atlas, float scale = 1); + static CCSkeleton* createWithFile (const char* skeletonDataFile, const char* atlasFile, float scale = 1); + + CCSkeleton (SkeletonData* skeletonData, bool ownsSkeletonData = false); + CCSkeleton (const char* skeletonDataFile, Atlas* atlas, float scale = 1); + CCSkeleton (const char* skeletonDataFile, const char* atlasFile, float scale = 1); + + virtual ~CCSkeleton (); + + virtual void update (float deltaTime); + virtual void draw (); + virtual cocos2d::CCRect boundingBox (); + + // --- Convenience methods for common Skeleton_* functions. + void updateWorldTransform (); + + void setToSetupPose (); + void setBonesToSetupPose (); + void setSlotsToSetupPose (); + + /* Returns 0 if the bone was not found. */ + Bone* findBone (const char* boneName) const; + /* Returns 0 if the slot was not found. */ + Slot* findSlot (const char* slotName) const; + + /* Sets the skin used to look up attachments not found in the SkeletonData defaultSkin. Attachments from the new skin are + * attached if the corresponding attachment from the old skin was attached. Returns false if the skin was not found. + * @param skin May be 0.*/ + bool setSkin (const char* skinName); + + /* Returns 0 if the slot or attachment was not found. */ + Attachment* getAttachment (const char* slotName, const char* attachmentName) const; + /* Returns false if the slot or attachment was not found. */ + bool setAttachment (const char* slotName, const char* attachmentName); + + // --- CCBlendProtocol + CC_PROPERTY(cocos2d::ccBlendFunc, blendFunc, BlendFunc); + virtual void setOpacityModifyRGB (bool value); + virtual bool isOpacityModifyRGB (); + +protected: + CCSkeleton (); + void setSkeletonData (SkeletonData* skeletonData, bool ownsSkeletonData); + cocos2d::CCTextureAtlas* getTextureAtlas (RegionAttachment* regionAttachment) const; + +private: + bool ownsSkeletonData; + Atlas* atlas; + void initialize (); +}; + +}} // namespace cocos2d { namespace extension { + +#endif /* SPINE_CCSKELETON_H_ */ diff --git a/include/extensions/spine/CCSkeletonAnimation.h b/include/extensions/spine/CCSkeletonAnimation.h new file mode 100644 index 0000000..e38ef9c --- /dev/null +++ b/include/extensions/spine/CCSkeletonAnimation.h @@ -0,0 +1,73 @@ +/******************************************************************************* + * Copyright (c) 2013, Esoteric Software + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * 2. 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. + * + * 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. + ******************************************************************************/ + +#ifndef SPINE_CCSKELETONANIMATION_H_ +#define SPINE_CCSKELETONANIMATION_H_ + +#include +#include +#include "cocos2d.h" + +namespace cocos2d { namespace extension { + +/** +Draws an animated skeleton, providing a simple API for applying one or more animations and queuing animations to be played later. +*/ +class CCSkeletonAnimation: public CCSkeleton { +public: + std::vector states; + + static CCSkeletonAnimation* createWithData (SkeletonData* skeletonData); + static CCSkeletonAnimation* createWithFile (const char* skeletonDataFile, Atlas* atlas, float scale = 1); + static CCSkeletonAnimation* createWithFile (const char* skeletonDataFile, const char* atlasFile, float scale = 1); + + CCSkeletonAnimation (SkeletonData* skeletonData); + CCSkeletonAnimation (const char* skeletonDataFile, Atlas* atlas, float scale = 1); + CCSkeletonAnimation (const char* skeletonDataFile, const char* atlasFile, float scale = 1); + + virtual ~CCSkeletonAnimation (); + + virtual void update (float deltaTime); + + void addAnimationState (AnimationStateData* stateData = 0); + void setAnimationStateData (AnimationStateData* stateData, int stateIndex = 0); + void setMix (const char* fromAnimation, const char* toAnimation, float duration, int stateIndex = 0); + void setAnimation (const char* name, bool loop, int stateIndex = 0); + void addAnimation (const char* name, bool loop, float delay = 0, int stateIndex = 0); + void clearAnimation (int stateIndex = 0); + +protected: + CCSkeletonAnimation (); + +private: + typedef CCSkeleton super; + std::vector stateDatas; + + void initialize (); +}; + +}} // namespace cocos2d { namespace extension { + +#endif /* SPINE_CCSKELETONANIMATION_H_ */ diff --git a/include/extensions/spine/Json.h b/include/extensions/spine/Json.h new file mode 100644 index 0000000..35cccd6 --- /dev/null +++ b/include/extensions/spine/Json.h @@ -0,0 +1,77 @@ +/* + Copyright (c) 2009 Dave Gamble + + Permission is hereby granted, dispose 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. + */ + +/* Esoteric Software: Removed everything except parsing, shorter method names, more get methods, double to float, formatted. */ + +#ifndef SPINE_JSON_H_ +#define SPINE_JSON_H_ + +namespace cocos2d { namespace extension { + +/* Json Types: */ +#define Json_False 0 +#define Json_True 1 +#define Json_NULL 2 +#define Json_Number 3 +#define Json_String 4 +#define Json_Array 5 +#define Json_Object 6 + +/* The Json structure: */ +typedef struct Json { + struct Json* next; + struct Json* prev; /* next/prev allow you to walk array/object chains. Alternatively, use getSize/getItemAt/getItem */ + struct Json* child; /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */ + + int type; /* The type of the item, as above. */ + + const char* valuestring; /* The item's string, if type==Json_String */ + int valueint; /* The item's number, if type==Json_Number */ + float valuefloat; /* The item's number, if type==Json_Number */ + + const char* name; /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */ +} Json; + +/* Supply a block of JSON, and this returns a Json object you can interrogate. Call Json_dispose when finished. */ +Json* Json_create (const char* value); + +/* Delete a Json entity and all subentities. */ +void Json_dispose (Json* json); + +/* Returns the number of items in an array (or object). */ +int Json_getSize (Json* json); + +/* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */ +Json* Json_getItemAt (Json* json, int item); + +/* Get item "string" from object. Case insensitive. */ +Json* Json_getItem (Json* json, const char* string); +const char* Json_getString (Json* json, const char* name, const char* defaultValue); +float Json_getFloat (Json* json, const char* name, float defaultValue); +int Json_getInt (Json* json, const char* name, int defaultValue); + +/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when Json_create() returns 0. 0 when Json_create() succeeds. */ +const char* Json_getError (void); + +}} // namespace cocos2d { namespace extension { + +#endif /* SPINE_JSON_H_ */ diff --git a/include/extensions/spine/RegionAttachment.h b/include/extensions/spine/RegionAttachment.h new file mode 100644 index 0000000..8374c81 --- /dev/null +++ b/include/extensions/spine/RegionAttachment.h @@ -0,0 +1,60 @@ +/******************************************************************************* + * Copyright (c) 2013, Esoteric Software + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * 2. 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. + * + * 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. + ******************************************************************************/ + +#ifndef SPINE_REGIONATTACHMENT_H_ +#define SPINE_REGIONATTACHMENT_H_ + +#include +#include +#include + +namespace cocos2d { namespace extension { + +typedef enum { + VERTEX_X1 = 0, VERTEX_Y1, VERTEX_X2, VERTEX_Y2, VERTEX_X3, VERTEX_Y3, VERTEX_X4, VERTEX_Y4 +} VertexIndex; + +typedef struct RegionAttachment RegionAttachment; +struct RegionAttachment { + Attachment super; + float x, y, scaleX, scaleY, rotation, width, height; + + void* rendererObject; + int regionOffsetX, regionOffsetY; /* Pixels stripped from the bottom left, unrotated. */ + int regionWidth, regionHeight; /* Unrotated, stripped pixel size. */ + int regionOriginalWidth, regionOriginalHeight; /* Unrotated, unstripped pixel size. */ + + float offset[8]; + float uvs[8]; +}; + +RegionAttachment* RegionAttachment_create (const char* name); +void RegionAttachment_setUVs (RegionAttachment* self, float u, float v, float u2, float v2, int/*bool*/rotate); +void RegionAttachment_updateOffset (RegionAttachment* self); +void RegionAttachment_computeVertices (RegionAttachment* self, float x, float y, Bone* bone, float* vertices); + +}} // namespace cocos2d { namespace extension { + +#endif /* SPINE_REGIONATTACHMENT_H_ */ diff --git a/include/extensions/spine/Skeleton.h b/include/extensions/spine/Skeleton.h new file mode 100644 index 0000000..54fa5aa --- /dev/null +++ b/include/extensions/spine/Skeleton.h @@ -0,0 +1,92 @@ +/******************************************************************************* + * Copyright (c) 2013, Esoteric Software + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * 2. 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. + * + * 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. + ******************************************************************************/ + +#ifndef SPINE_SKELETON_H_ +#define SPINE_SKELETON_H_ + +#include +#include +#include + +namespace cocos2d { namespace extension { + +typedef struct Skeleton Skeleton; +struct Skeleton { + SkeletonData* const data; + + int boneCount; + Bone** bones; + Bone* const root; + + int slotCount; + Slot** slots; + Slot** drawOrder; + + Skin* const skin; + float r, g, b, a; + float time; + int/*bool*/flipX, flipY; + float x, y; +}; + +Skeleton* Skeleton_create (SkeletonData* data); +void Skeleton_dispose (Skeleton* self); + +void Skeleton_updateWorldTransform (const Skeleton* self); + +void Skeleton_setToSetupPose (const Skeleton* self); +void Skeleton_setBonesToSetupPose (const Skeleton* self); +void Skeleton_setSlotsToSetupPose (const Skeleton* self); + +/* Returns 0 if the bone was not found. */ +Bone* Skeleton_findBone (const Skeleton* self, const char* boneName); +/* Returns -1 if the bone was not found. */ +int Skeleton_findBoneIndex (const Skeleton* self, const char* boneName); + +/* Returns 0 if the slot was not found. */ +Slot* Skeleton_findSlot (const Skeleton* self, const char* slotName); +/* Returns -1 if the slot was not found. */ +int Skeleton_findSlotIndex (const Skeleton* self, const char* slotName); + +/* Sets the skin used to look up attachments not found in the SkeletonData defaultSkin. Attachments from the new skin are + * attached if the corresponding attachment from the old skin was attached. + * @param skin May be 0.*/ +void Skeleton_setSkin (Skeleton* self, Skin* skin); +/* Returns 0 if the skin was not found. See Skeleton_setSkin. + * @param skinName May be 0. */ +int Skeleton_setSkinByName (Skeleton* self, const char* skinName); + +/* Returns 0 if the slot or attachment was not found. */ +Attachment* Skeleton_getAttachmentForSlotName (const Skeleton* self, const char* slotName, const char* attachmentName); +/* Returns 0 if the slot or attachment was not found. */ +Attachment* Skeleton_getAttachmentForSlotIndex (const Skeleton* self, int slotIndex, const char* attachmentName); +/* Returns 0 if the slot or attachment was not found. */ +int Skeleton_setAttachment (Skeleton* self, const char* slotName, const char* attachmentName); + +void Skeleton_update (Skeleton* self, float deltaTime); + +}} // namespace cocos2d { namespace extension { + +#endif /* SPINE_SKELETON_H_*/ diff --git a/include/extensions/spine/SkeletonData.h b/include/extensions/spine/SkeletonData.h new file mode 100644 index 0000000..b05bc45 --- /dev/null +++ b/include/extensions/spine/SkeletonData.h @@ -0,0 +1,66 @@ +/******************************************************************************* + * Copyright (c) 2013, Esoteric Software + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * 2. 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. + * + * 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. + ******************************************************************************/ + +#ifndef SPINE_SKELETONDATA_H_ +#define SPINE_SKELETONDATA_H_ + +#include +#include +#include +#include + +namespace cocos2d { namespace extension { + +typedef struct { + int boneCount; + BoneData** bones; + + int slotCount; + SlotData** slots; + + int skinCount; + Skin** skins; + Skin* defaultSkin; + + int animationCount; + Animation** animations; +} SkeletonData; + +SkeletonData* SkeletonData_create (); +void SkeletonData_dispose (SkeletonData* self); + +BoneData* SkeletonData_findBone (const SkeletonData* self, const char* boneName); +int SkeletonData_findBoneIndex (const SkeletonData* self, const char* boneName); + +SlotData* SkeletonData_findSlot (const SkeletonData* self, const char* slotName); +int SkeletonData_findSlotIndex (const SkeletonData* self, const char* slotName); + +Skin* SkeletonData_findSkin (const SkeletonData* self, const char* skinName); + +Animation* SkeletonData_findAnimation (const SkeletonData* self, const char* animationName); + +}} // namespace cocos2d { namespace extension { + +#endif /* SPINE_SKELETONDATA_H_ */ diff --git a/include/extensions/spine/SkeletonJson.h b/include/extensions/spine/SkeletonJson.h new file mode 100644 index 0000000..1fd9b28 --- /dev/null +++ b/include/extensions/spine/SkeletonJson.h @@ -0,0 +1,52 @@ +/******************************************************************************* + * Copyright (c) 2013, Esoteric Software + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * 2. 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. + * + * 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. + ******************************************************************************/ + +#ifndef SPINE_SKELETONJSON_H_ +#define SPINE_SKELETONJSON_H_ + +#include +#include +#include +#include +#include + +namespace cocos2d { namespace extension { + +typedef struct { + float scale; + AttachmentLoader* attachmentLoader; + const char* const error; +} SkeletonJson; + +SkeletonJson* SkeletonJson_createWithLoader (AttachmentLoader* attachmentLoader); +SkeletonJson* SkeletonJson_create (Atlas* atlas); +void SkeletonJson_dispose (SkeletonJson* self); + +SkeletonData* SkeletonJson_readSkeletonData (SkeletonJson* self, const char* json); +SkeletonData* SkeletonJson_readSkeletonDataFile (SkeletonJson* self, const char* path); + +}} // namespace cocos2d { namespace extension { + +#endif /* SPINE_SKELETONJSON_H_ */ diff --git a/include/extensions/spine/Skin.h b/include/extensions/spine/Skin.h new file mode 100644 index 0000000..f8d76a5 --- /dev/null +++ b/include/extensions/spine/Skin.h @@ -0,0 +1,55 @@ +/******************************************************************************* + * Copyright (c) 2013, Esoteric Software + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * 2. 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. + * + * 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. + ******************************************************************************/ + +#ifndef SPINE_SKIN_H_ +#define SPINE_SKIN_H_ + +#include + +namespace cocos2d { namespace extension { + +struct Skeleton; + +typedef struct { + const char* const name; +} Skin; + +Skin* Skin_create (const char* name); +void Skin_dispose (Skin* self); + +/* The Skin owns the attachment. */ +void Skin_addAttachment (Skin* self, int slotIndex, const char* name, Attachment* attachment); +/* Returns 0 if the attachment was not found. */ +Attachment* Skin_getAttachment (const Skin* self, int slotIndex, const char* name); + +/* Returns 0 if the slot or attachment was not found. */ +const char* Skin_getAttachmentName (const Skin* self, int slotIndex, int attachmentIndex); + +/** Attach each attachment in this skin if the corresponding attachment in oldSkin is currently attached. */ +void Skin_attachAll (const Skin* self, struct Skeleton* skeleton, const Skin* oldSkin); + +}} // namespace cocos2d { namespace extension { + +#endif /* SPINE_SKIN_H_ */ diff --git a/include/extensions/spine/Slot.h b/include/extensions/spine/Slot.h new file mode 100644 index 0000000..47b2a7f --- /dev/null +++ b/include/extensions/spine/Slot.h @@ -0,0 +1,58 @@ +/******************************************************************************* + * Copyright (c) 2013, Esoteric Software + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * 2. 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. + * + * 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. + ******************************************************************************/ + +#ifndef SPINE_SLOT_H_ +#define SPINE_SLOT_H_ + +#include +#include +#include + +namespace cocos2d { namespace extension { + +struct Skeleton; + +typedef struct Slot { + SlotData* const data; + struct Skeleton* const skeleton; + Bone* const bone; + float r, g, b, a; + Attachment* const attachment; +} Slot; + +Slot* Slot_create (SlotData* data, struct Skeleton* skeleton, Bone* bone); +void Slot_dispose (Slot* self); + +/* @param attachment May be 0 to clear the attachment for the slot. */ +void Slot_setAttachment (Slot* self, Attachment* attachment); + +void Slot_setAttachmentTime (Slot* self, float time); +float Slot_getAttachmentTime (const Slot* self); + +void Slot_setToSetupPose (Slot* self); + +}} // namespace cocos2d { namespace extension { + +#endif /* SPINE_SLOT_H_ */ diff --git a/include/extensions/spine/SlotData.h b/include/extensions/spine/SlotData.h new file mode 100644 index 0000000..660c306 --- /dev/null +++ b/include/extensions/spine/SlotData.h @@ -0,0 +1,48 @@ +/******************************************************************************* + * Copyright (c) 2013, Esoteric Software + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * 2. 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. + * + * 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. + ******************************************************************************/ + +#ifndef SPINE_SLOTDATA_H_ +#define SPINE_SLOTDATA_H_ + +#include + +namespace cocos2d { namespace extension { + +typedef struct { + const char* const name; + const BoneData* const boneData; + const char* const attachmentName; + float r, g, b, a; +} SlotData; + +SlotData* SlotData_create (const char* name, BoneData* boneData); +void SlotData_dispose (SlotData* self); + +/* @param attachmentName May be 0 for no setup pose attachment. */ +void SlotData_setAttachmentName (SlotData* self, const char* attachmentName); + +}} // namespace cocos2d { namespace extension { + +#endif /* SPINE_SLOTDATA_H_ */ diff --git a/include/extensions/spine/extension.h b/include/extensions/spine/extension.h new file mode 100644 index 0000000..37ae496 --- /dev/null +++ b/include/extensions/spine/extension.h @@ -0,0 +1,145 @@ +/******************************************************************************* + * Copyright (c) 2013, Esoteric Software + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * 2. 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. + * + * 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. + ******************************************************************************/ + +/* + Implementation notes: + + - An OOP style is used where each "class" is made up of a struct and a number of functions prefixed with the struct name. + + - struct fields that are const are readonly. Either they are set in a create function and can never be changed, or they can only + be changed by calling a function. + + - Inheritance is done using a struct field named "super" as the first field, allowing the struct to be cast to its "super class". + This works because a pointer to a struct is guaranteed to be a pointer to the first struct field. + + - Classes intended for inheritance provide init/deinit functions which subclasses must call in their create/dispose functions. + + - Polymorphism is done by a base class providing function pointers in its init function. The public API delegates to this + function. + + - Subclasses do not provide a dispose function, instead the base class' dispose function should be used, which will delegate to + a dispose function. + + - Classes not designed for inheritance cannot be extended. They may use an internal subclass to hide private data and don't + expose function pointers. + + - The public API hides implementation details such init/deinit functions. An internal API is exposed in extension.h to allow + classes to be extended. Internal functions begin with underscore (_). + + - OOP in C tends to lose type safety. Macros are provided in extension.h to give context for why a cast is being done. + */ + +#ifndef SPINE_EXTENSION_H_ +#define SPINE_EXTENSION_H_ + +/* All allocation uses these. */ +#define MALLOC(TYPE,COUNT) ((TYPE*)_malloc(sizeof(TYPE) * COUNT)) +#define CALLOC(TYPE,COUNT) ((TYPE*)_calloc(1, sizeof(TYPE) * COUNT)) +#define NEW(TYPE) CALLOC(TYPE,1) + +/* Gets the direct super class. Type safe. */ +#define SUPER(VALUE) (&VALUE->super) + +/* Cast to a super class. Not type safe, use with care. Prefer SUPER() where possible. */ +#define SUPER_CAST(TYPE,VALUE) ((TYPE*)VALUE) + +/* Cast to a sub class. Not type safe, use with care. */ +#define SUB_CAST(TYPE,VALUE) ((TYPE*)VALUE) + +/* Casts away const. Can be used as an lvalue. Not type safe, use with care. */ +#define CONST_CAST(TYPE,VALUE) (*(TYPE*)&VALUE) + +/* Gets the vtable for the specified type. Not type safe, use with care. */ +#define VTABLE(TYPE,VALUE) ((_##TYPE##Vtable*)((TYPE*)VALUE)->vtable) + +/* Frees memory. Can be used on const types. */ +#define FREE(VALUE) _free((void*)VALUE) + +/* Allocates a new char[], assigns it to TO, and copies FROM to it. Can be used on const types. */ +#define MALLOC_STR(TO,FROM) strcpy(CONST_CAST(char*, TO) = (char*)malloc(strlen(FROM) + 1), FROM) + +#include +#include +#include +#include +#include +#include +#include + +namespace cocos2d { namespace extension { + +/* + * Functions that must be implemented: + */ + +void _AtlasPage_createTexture (AtlasPage* self, const char* path); +void _AtlasPage_disposeTexture (AtlasPage* self); +char* _Util_readFile (const char* path, int* length); + +/* + * Internal API available for extension: + */ + +void* _malloc (size_t size); +void* _calloc (size_t num, size_t size); +void _free (void* ptr); + +void _setMalloc (void* (*_malloc) (size_t size)); +void _setFree (void (*_free) (void* ptr)); + +char* _readFile (const char* path, int* length); + +/**/ + +void _AttachmentLoader_init (AttachmentLoader* self, /**/ + void (*dispose) (AttachmentLoader* self), /**/ + Attachment* (*newAttachment) (AttachmentLoader* self, Skin* skin, AttachmentType type, const char* name)); +void _AttachmentLoader_deinit (AttachmentLoader* self); +void _AttachmentLoader_setError (AttachmentLoader* self, const char* error1, const char* error2); +void _AttachmentLoader_setUnknownTypeError (AttachmentLoader* self, AttachmentType type); + +/**/ + +void _Attachment_init (Attachment* self, const char* name, AttachmentType type, /**/ + void (*dispose) (Attachment* self)); +void _Attachment_deinit (Attachment* self); + +/**/ + +void _Timeline_init (Timeline* self, /**/ + void (*dispose) (Timeline* self), /**/ + void (*apply) (const Timeline* self, Skeleton* skeleton, float time, float alpha)); +void _Timeline_deinit (Timeline* self); + +/**/ + +void _CurveTimeline_init (CurveTimeline* self, int frameCount, /**/ + void (*dispose) (Timeline* self), /**/ + void (*apply) (const Timeline* self, Skeleton* skeleton, float time, float alpha)); +void _CurveTimeline_deinit (CurveTimeline* self); + +}} // namespace cocos2d { namespace extension { + +#endif /* SPINE_EXTENSION_H_ */ diff --git a/include/extensions/spine/spine-cocos2dx.h b/include/extensions/spine/spine-cocos2dx.h new file mode 100644 index 0000000..baa42de --- /dev/null +++ b/include/extensions/spine/spine-cocos2dx.h @@ -0,0 +1,40 @@ +/******************************************************************************* + * Copyright (c) 2013, Esoteric Software + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * 2. 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. + * + * 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. + ******************************************************************************/ + +#ifndef SPINE_COCOS2DX_H_ +#define SPINE_COCOS2DX_H_ + +#include +#include "cocos2d.h" +#include +#include + +namespace cocos2d { namespace extension { + +void RegionAttachment_updateQuad (RegionAttachment* self, Slot* slot, cocos2d::ccV3F_C4B_T2F_Quad* quad, bool premultiplied = false); + +}} // namespace cocos2d { namespace extension { + +#endif /* SPINE_COCOS2DX_H_ */ diff --git a/include/extensions/spine/spine.h b/include/extensions/spine/spine.h new file mode 100644 index 0000000..d312d91 --- /dev/null +++ b/include/extensions/spine/spine.h @@ -0,0 +1,46 @@ +/******************************************************************************* + * Copyright (c) 2013, Esoteric Software + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * 2. 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. + * + * 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. + ******************************************************************************/ + +#ifndef SPINE_SPINE_H_ +#define SPINE_SPINE_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#endif /* SPINE_SPINE_H_ */ diff --git a/include/gd/audio_nodes/FMODAudioEngine.h b/include/gd/audio_nodes/FMODAudioEngine.h new file mode 100644 index 0000000..fc70223 --- /dev/null +++ b/include/gd/audio_nodes/FMODAudioEngine.h @@ -0,0 +1,59 @@ +#ifndef __FMODAUDIOENGINE_H__ +#define __FMODAUDIOENGINE_H__ + +#include + +namespace gd { + class FMODAudioEngine : public cocos2d::CCNode { + protected: + cocos2d::CCDictionary* m_pDictionary; + std::string m_sFilePath; + float m_fBackgroundMusicVolume; + float m_fEffectsVolume; + float m_fPulse1; + float m_fPulse2; + float m_fPulse3; + int m_nPulseCounter; + bool m_bMetering; + bool m_bFading; + bool m_bFadeIn; + float m_fFadeInDuration; + void* /*FMOD::Sound*/ m_pSound; + void* /*FMOD::ChannelGroup*/ m_pChannelGroup; + bool m_bPaused; + bool* m_pbBackgroundMusicPlaying; + void* /*FMOD::FMOD_DSP_METERING_INFO*/ m_pMeteringInfo; + int /*FMOD::FMOD_RESULT*/ m_eLastResult; + PAD(0x8); + int m_nMusicOffset; + + public: + static FMODAudioEngine* sharedEngine() { + return reinterpret_cast( + base + 0x239F0 + )(); + } + void preloadEffect(std::string filename) { + return reinterpret_cast( + base + 0x24240 + )(this, filename); + } + //my own function + void reloadEffects() { + using namespace std::filesystem; + + std::vector oggs = {}; + path defaults = current_path() / "Resources"; + for (auto file : directory_iterator{ defaults }) { + if (file.path().extension() == ".ogg") + oggs.push_back(file.path().filename().string()); + } + for (auto ogg : oggs) { + m_pDictionary->removeObjectForKey(ogg); + this->preloadEffect(ogg); + } + } + }; +} + +#endif \ No newline at end of file diff --git a/include/gd/include/GDProtocols.h b/include/gd/include/GDProtocols.h new file mode 100644 index 0000000..5ce491d --- /dev/null +++ b/include/gd/include/GDProtocols.h @@ -0,0 +1,16 @@ +#ifndef __GDPROTOCOLS_H__ +#define __GDPROTOCOLS_H__ + +#include + +namespace gd { + + class FLAlertLayer; + + class FLAlertLayerProtocol { + public: + virtual void FLAlert_Clicked(gd::FLAlertLayer*, bool btn2) {}; + }; +} + +#endif \ No newline at end of file diff --git a/include/gd/include/gd.h b/include/gd/include/gd.h index 43e3de4..d6e2e48 100644 --- a/include/gd/include/gd.h +++ b/include/gd/include/gd.h @@ -12,6 +12,8 @@ namespace gd { } } +#include "GDProtocols.h" + #include "layers_scenes_transitions_nodes/FLAlertLayer.h" #include "layers_scenes_transitions_nodes/GJDropDownLayer.h" #include "layers_scenes_transitions_nodes/GJListLayer.h" @@ -21,8 +23,12 @@ namespace gd { #include "manager_nodes/GManager.h" #include "manager_nodes/GameManager.h" +#include "manager_nodes/GameSoundManager.h" #include "menu_nodes/CCMenuItemSpriteExtra.h" +#include "menu_nodes/CCMenuItemToggler.h" + +#include "audio_nodes/FMODAudioEngine.h" #include "sprite_nodes/ButtonSprite.h" diff --git a/include/gd/layers_scenes_transitions_nodes/FLAlertLayer.h b/include/gd/layers_scenes_transitions_nodes/FLAlertLayer.h index 12a7b91..46819c1 100644 --- a/include/gd/layers_scenes_transitions_nodes/FLAlertLayer.h +++ b/include/gd/layers_scenes_transitions_nodes/FLAlertLayer.h @@ -5,6 +5,7 @@ namespace gd { + class FLAlertLayerProtocol; class ButtonSprite; class ScrollingLayer; @@ -12,12 +13,12 @@ namespace gd { class FLAlertLayer : public cocos2d::CCLayerColor { protected: cocos2d::CCMenu* m_pButtonMenu; - PAD(4); + int m_nUnknown; cocos2d::CCObject* m_pTarget; PAD(8); cocos2d::CCLayer* m_pLayer; - PAD(4); - bool m_bUnknown; + int m_nZOrder2; + bool m_bDontTransition; ButtonSprite* m_pButton1; ButtonSprite* m_pButton2; ScrollingLayer* m_pScrollingLayer; @@ -26,6 +27,76 @@ namespace gd { bool m_bSingleButton; //? public: + //CCNode vtable + virtual void onEnter() { + return reinterpret_cast( + base + 0x23750 + )(this); + } + virtual void registerWithTouchDispatcher() { + return reinterpret_cast( + base + 0x236F0 + )(this); + } + + //CCTouchDelegate vtable + virtual bool ccTouchBegan(cocos2d::CCTouch* pTouch, cocos2d::CCEvent* pEvent) { + return reinterpret_cast( + base + 0x233C0 + )(reinterpret_cast(this) + 0xEC, pTouch, pEvent); + } + virtual void ccTouchMoved(cocos2d::CCTouch* pTouch, cocos2d::CCEvent* pEvent) { + return reinterpret_cast( + base + 0x23510 + )(reinterpret_cast(this) + 0xEC, pTouch, pEvent); + } + virtual void ccTouchEnded(cocos2d::CCTouch* pTouch, cocos2d::CCEvent* pEvent) { + return reinterpret_cast( + base + 0x23450 + )(reinterpret_cast(this) + 0xEC, pTouch, pEvent); + } + virtual void ccTouchCancelled(cocos2d::CCTouch* pTouch, cocos2d::CCEvent* pEvent) { + return reinterpret_cast( + base + 0x234C0 + )(reinterpret_cast(this) + 0xEC, pTouch, pEvent); + } + + //CCKeyboardDelegate vtable + virtual void keyDown(cocos2d::enumKeyCodes key) { + return reinterpret_cast( + base + 0x23250 + )(this, key); + } + + //CCKeypadDelegate vtable + virtual void keyBackClicked() { + return reinterpret_cast( + base + 0x232C0 + )(reinterpret_cast(this) + 0xF4); + } + + //vtable + virtual void show() { + return reinterpret_cast( + base + 0x23560 + )(this); + } + FLAlertLayer() { + reinterpret_cast( + base + 0x224B0 + )(this); + } + + void onBtn1(cocos2d::CCObject* btn) { + return reinterpret_cast( + base + 0x23340 + )(this, btn); + } + void onBtn2(cocos2d::CCObject* btn) { + return reinterpret_cast( + base + 0x23380 + )(this, btn); + } /*FLAlertLayer supports colors of text for the caption. wrap desired text in "" * where x is the color desired. colors are: * r - red @@ -36,17 +107,27 @@ namespace gd { * and more that i'm too lazy to find. * MAKE SURE YOU FOLLOW THIS FORMAT. ROB'S PARSING CAN AND WILL MESS UP OTHERWISE. */ - static FLAlertLayer* create(cocos2d::CCObject* target, const char* title, + static FLAlertLayer* create(FLAlertLayerProtocol* target, const char* title, const char* btn1, const char* btn2, std::string caption) { static_assert(sizeof(std::string) == 24, "std::string in debug mode does not work correctly with FLAlertLayer!"); - auto pRet = reinterpret_cast( base + 0x22680 )(target, title, btn1, btn2, caption); //clean stack. __asm add esp, 0x20 + return pRet; + } + static FLAlertLayer* create(FLAlertLayerProtocol* target, const char* title, + const char* btn1, const char* btn2, float width, std::string caption) { + static_assert(sizeof(std::string) == 24, "std::string in debug mode does not work correctly with FLAlertLayer!"); + auto pRet = reinterpret_cast( + base + 0x22730 + )(target, title, btn1, btn2, width, caption); + __asm add esp, 0x24 + return pRet; } - virtual void show() {} }; #pragma runtime_checks("s", restore) } diff --git a/include/gd/layers_scenes_transitions_nodes/GJDropDownLayer.h b/include/gd/layers_scenes_transitions_nodes/GJDropDownLayer.h index 88eca89..97459da 100644 --- a/include/gd/layers_scenes_transitions_nodes/GJDropDownLayer.h +++ b/include/gd/layers_scenes_transitions_nodes/GJDropDownLayer.h @@ -87,6 +87,17 @@ namespace gd { base + 0x113940 )(this); } + GJDropDownLayer() { + reinterpret_cast( + base + 0x038470 + )(this); + } + bool init(const char* title, float height) { + __asm movss xmm2, height + return reinterpret_cast( + base + 0x113530 + )(this, title); + } static GJDropDownLayer* create(const char* title, float height) { GJDropDownLayer* pRet = new GJDropDownLayer(); @@ -99,17 +110,6 @@ namespace gd { return nullptr; } } - GJDropDownLayer() { - reinterpret_cast( - base + 0x038470 - )(this); - } - bool init(const char* title, float height) { - __asm movss xmm2, height - return reinterpret_cast( - base + 0x113530 - )(this, title); - } }; } diff --git a/include/gd/layers_scenes_transitions_nodes/GJListLayer.h b/include/gd/layers_scenes_transitions_nodes/GJListLayer.h index 5c35966..b8a72d5 100644 --- a/include/gd/layers_scenes_transitions_nodes/GJListLayer.h +++ b/include/gd/layers_scenes_transitions_nodes/GJListLayer.h @@ -10,16 +10,13 @@ namespace gd { CCObject* m_pTarget; public: - virtual ~GJListLayer() { - reinterpret_cast( - base + 0x12DFD0 - )(this, true); - } static GJListLayer* create(CCObject* target, const char* title, cocos2d::ccColor4B color, float width, float height) { __asm movss xmm3, width auto pRet = reinterpret_cast( base + 0x12E000 )(target, title, color, height); + __asm add esp, 0x8 + return pRet; } }; #pragma runtime_checks("s", restore) diff --git a/include/gd/layers_scenes_transitions_nodes/MenuLayer.h b/include/gd/layers_scenes_transitions_nodes/MenuLayer.h index 2eae1a7..b806195 100644 --- a/include/gd/layers_scenes_transitions_nodes/MenuLayer.h +++ b/include/gd/layers_scenes_transitions_nodes/MenuLayer.h @@ -4,7 +4,10 @@ #include namespace gd { - class MenuLayer : public cocos2d::CCLayer { + + class FLAlertLayerProtocol; + + class MenuLayer : public cocos2d::CCLayer, public gd::FLAlertLayerProtocol { public: static MenuLayer* create() { return reinterpret_cast( diff --git a/include/gd/manager_nodes/GManager.h b/include/gd/manager_nodes/GManager.h index 8bfcdb9..93a01dd 100644 --- a/include/gd/manager_nodes/GManager.h +++ b/include/gd/manager_nodes/GManager.h @@ -3,9 +3,30 @@ #include +class DS_Dictionary; + namespace gd { + class GManager : public cocos2d::CCNode { - //idc + protected: + std::string m_sFileName; + bool m_bSetup; + bool m_bSaved; + + public: + void save() { + return reinterpret_cast( + base + 0x29250 + )(this, m_sFileName); + } + virtual void setup() { + return reinterpret_cast( + base + 0x28F60 + )(this); + } + virtual void encodeDataTo(DS_Dictionary* data) {} + virtual void dataLoaded(DS_Dictionary* data) {} + virtual void firstLoad() {} }; } diff --git a/include/gd/manager_nodes/GameSoundManager.h b/include/gd/manager_nodes/GameSoundManager.h new file mode 100644 index 0000000..a107516 --- /dev/null +++ b/include/gd/manager_nodes/GameSoundManager.h @@ -0,0 +1,26 @@ +#ifndef __GAMESOUNDMANAGER_H__ +#define __GAMESOUNDMANAGER_H__ + +#include +#include + +namespace gd { + class GameSoundManager : public cocos2d::CCNode { + protected: + cocos2d::CCDictionary* m_pDictionary1; + cocos2d::CCDictionary* m_pDictionary2; + PAD(12); + bool m_bPreloaded; + PAD(4); + std::string m_sFilePath; + + public: + static GameSoundManager* sharedState() { + return reinterpret_cast( + base + 0x24800 + )(); + } + }; +} + +#endif \ No newline at end of file diff --git a/include/gd/menu_nodes/CCMenuItemSpriteExtra.h b/include/gd/menu_nodes/CCMenuItemSpriteExtra.h index 452d673..f454ae3 100644 --- a/include/gd/menu_nodes/CCMenuItemSpriteExtra.h +++ b/include/gd/menu_nodes/CCMenuItemSpriteExtra.h @@ -6,10 +6,14 @@ namespace gd { #pragma runtime_checks("s", off) class CCMenuItemSpriteExtra : public cocos2d::CCMenuItemSprite { + protected: + float m_fUnknown; + float m_fUnknown2; + public: - static CCMenuItemSpriteExtra* create(cocos2d::CCSprite* sprite, + static CCMenuItemSpriteExtra* create(cocos2d::CCNode* sprite, cocos2d::CCObject* target, cocos2d::SEL_MenuHandler callback) { - auto pRet = reinterpret_cast( base + 0x18EE0 )(sprite, target, callback); @@ -17,6 +21,12 @@ namespace gd { __asm add esp, 0x8 return pRet; } + void setSizeMult(float mult) { + __asm movss xmm1, mult + return reinterpret_cast( + base + 0x19080 + )(this); + } }; #pragma runtime_checks("s", restore) } diff --git a/include/gd/menu_nodes/CCMenuItemToggler.h b/include/gd/menu_nodes/CCMenuItemToggler.h new file mode 100644 index 0000000..59fa402 --- /dev/null +++ b/include/gd/menu_nodes/CCMenuItemToggler.h @@ -0,0 +1,45 @@ +#ifndef __CCMENUITEMTOGGLER_H__ +#define __CCMENUITEMTOGGLER_H__ + +#include + +namespace gd { + + class CCMenuItemSpriteExtra; + + #pragma runtime_checks("s", off) + class CCMenuItemToggler : public cocos2d::CCMenuItem { + protected: + CCMenuItemSpriteExtra* m_pOnButton; + CCMenuItemSpriteExtra* m_pOffButton; + bool m_bOn; + bool m_bUnknown; + + public: + static CCMenuItemToggler* create(cocos2d::CCNode* off, cocos2d::CCNode* on, + cocos2d::CCObject* target, cocos2d::SEL_MenuHandler callback) { + auto pRet = reinterpret_cast( + base + 0x19600 + )(off, on, target, callback); + __asm add esp, 0x8 + return pRet; + } + void setSizeMult(float mult) { + __asm movss xmm1, mult + return reinterpret_cast( + base + 0x19850 + )(this); + } + //my own function + inline bool isOn() { return m_bOn; } + void toggle(bool on) { + return reinterpret_cast( + base + 0x199B0 + )(this, on); + } + }; + #pragma runtime_checks("s", restore) +} + +#endif \ No newline at end of file diff --git a/src/Entry.cpp b/src/Entry.cpp index d7e2da8..337b07c 100644 --- a/src/Entry.cpp +++ b/src/Entry.cpp @@ -1,13 +1,13 @@ #include "pch.h" #include "memory/Tools.h" #include "memory/Hooks.h" -#include "logic/layers/LoaderLayer.h" +#include "logic/nodes/LoaderManager.h" DWORD WINAPI Entry(LPVOID hModule) { if (!Log::init()) { MessageBox(0, "ERROR: Could not initialize logging.", "textureldr", MB_ICONERROR | MB_OK); } - if (gd::init() && init()) { + if (gd::init() && LoaderManager::sharedState()) { Log::info("Setting up hooks."); Hook LoadingLayer_loadingFinished = { @@ -84,8 +84,7 @@ BOOL APIENTRY DllMain(HMODULE hModule, { if (ul_reason_for_call == DLL_PROCESS_ATTACH) { HANDLE _ = CreateThread(0, 0, Entry, hModule, 0, nullptr); - if (_) - CloseHandle(_); + if (_) CloseHandle(_); } return TRUE; } \ No newline at end of file diff --git a/src/logic/layers/LoaderLayer.cpp b/src/logic/layers/LoaderLayer.cpp index a3d1b50..217aceb 100644 --- a/src/logic/layers/LoaderLayer.cpp +++ b/src/logic/layers/LoaderLayer.cpp @@ -3,10 +3,10 @@ using namespace cocos2d; -HorizontalList LoaderLayer::s_lQuality = { "Quality" }; - -VerticalList LoaderLayer::s_lAll = { "Available", 10, &s_lApplied }; -VerticalList LoaderLayer::s_lApplied = { "Applied", 10, &s_lAll }; +enum { + kPlistWarningLayer, + kQualityWarningLayer +}; bool LoaderLayer::init() { auto winSize = CCDirector::sharedDirector()->getWinSize(); @@ -26,8 +26,17 @@ bool LoaderLayer::init() { auto bottomRight = CCSprite::createWithSpriteFrameName("GJ_sideArt_001.png"); bottomRight->setFlipX(true); bottomRight->setPosition({ winSize.width - cornerSize.width / 2, cornerSize.height / 2 }); + auto topLeft = CCSprite::createWithSpriteFrameName("GJ_sideArt_001.png"); + topLeft->setFlipY(true); + topLeft->setPosition({ cornerSize.width / 2, winSize.height - cornerSize.height / 2 }); + auto topRight = CCSprite::createWithSpriteFrameName("GJ_sideArt_001.png"); + topRight->setFlipX(true); + topRight->setFlipY(true); + topRight->setPosition({ winSize.width - cornerSize.width / 2, winSize.height - cornerSize.height / 2 }); this->addChild(bottomLeft); this->addChild(bottomRight); + this->addChild(topLeft); + this->addChild(topRight); auto buttons = CCMenu::create(); this->addChild(buttons); @@ -37,7 +46,7 @@ bool LoaderLayer::init() { this, menu_selector(LoaderLayer::onApply) ); - applyBtn->setPosition(0.0f, 0.0f); + applyBtn->setPosition(95.0f, -135.0f); buttons->addChild(applyBtn); auto backBtn = gd::CCMenuItemSpriteExtra::create( @@ -48,228 +57,160 @@ bool LoaderLayer::init() { backBtn->setPosition(-winSize.width / 2 + 25.0f, winSize.height / 2 - 25.0f); buttons->addChild(backBtn); + auto reloadSprite = CCSprite::createWithSpriteFrameName("GJ_replayBtn_001.png"); + reloadSprite->setScale(0.85f); auto reloadBtn = gd::CCMenuItemSpriteExtra::create( - CCSprite::createWithSpriteFrameName("GJ_updateBtn_001.png"), + reloadSprite, this, - menu_selector(LoaderLayer::getPacks) + menu_selector(LoaderLayer::onRefresh) ); reloadBtn->setPosition(winSize.width / 2 - 35.0f, -winSize.height / 2 + 35.0f); + reloadBtn->setSizeMult(1.5f); buttons->addChild(reloadBtn); - auto optionsBtn = gd::CCMenuItemSpriteExtra::create( - CCSprite::createWithSpriteFrameName("GJ_optionsBtn_001.png"), + auto dropDownSprite = CCSprite::createWithSpriteFrameName("GJ_optionsBtn02_001.png"); + dropDownSprite->setScale(1.3f); + auto dropDownBtn = gd::CCMenuItemSpriteExtra::create( + dropDownSprite, + this, + menu_selector(LoaderLayer::onDropDown) + ); + dropDownBtn->setPosition(-winSize.width / 2 + 35.0f, -winSize.height / 2 + 35.0f); + dropDownBtn->setSizeMult(1.5f); + buttons->addChild(dropDownBtn); + + auto folderSprite = CCSprite::createWithSpriteFrameName("GJ_duplicateBtn_001.png"); + folderSprite->setScale(1.1f); + auto folderBtn = gd::CCMenuItemSpriteExtra::create( + folderSprite, this, - menu_selector(LoaderLayer::onOptions) + menu_selector(LoaderLayer::onFolder) ); - optionsBtn->setPosition(-winSize.width / 2 + 35.0f, -winSize.height / 2 + 35.0f); - buttons->addChild(optionsBtn); + folderBtn->setPosition(winSize.width / 2 - 35.0f, winSize.height / 2 - 35.0f); + folderBtn->setSizeMult(1.5f); + buttons->addChild(folderBtn); - s_lQuality.enter(this); - s_lAll.enter(this); - s_lApplied.enter(this); + auto loaderManager = LoaderManager::sharedState(); + + m_plQuality = HorizontalList::create(loaderManager->m_dQuality); + m_plQuality->setPosition(-95.0f, -135.0f); + this->addChild(m_plQuality); + + m_plAll = VerticalList::create(loaderManager->m_dAll); + m_plAll->setPosition(-95.0f, 100.0f); + m_plApplied = VerticalList::create(loaderManager->m_dApplied); + m_plApplied->setPosition(95.0f, 100.0f); + m_plAll->setTarget(m_plApplied); + m_plApplied->setTarget(m_plAll); + this->addChild(m_plAll); + this->addChild(m_plApplied); this->setKeypadEnabled(true); return true; } -LoaderLayer* LoaderLayer::create() { - LoaderLayer* pRet = new LoaderLayer(); - if (pRet && pRet->init()) { - pRet->autorelease(); - return pRet; - } - else { - CC_SAFE_DELETE(pRet); - return nullptr; - } -} - void LoaderLayer::keyBackClicked() { this->onExit(nullptr); } -void LoaderLayer::onApply(cocos2d::CCObject*) { - s_lQuality.exit(); - s_lAll.exit(); - s_lApplied.exit(); - - CCDirector::sharedDirector()->updateContentScale(static_cast(s_lQuality.getIndex() + 1)); +void LoaderLayer::FLAlert_Clicked(gd::FLAlertLayer* layer, bool btn2) { + if (!btn2) return; + if (layer->getTag() == kPlistWarningLayer) { + auto loaderManager = LoaderManager::sharedState(); + if (loaderManager->m_bCheckQuality) { + if (!loaderManager->checkQuality()) { + auto alert = gd::FLAlertLayer::create( + this, "Warning", "Cancel", "Yes", 300.0f, "Packs may not line up with quality.\nDo you want to Continue?" + ); + alert->setTag(kQualityWarningLayer); + alert->show(); + return; + } + } + } + this->reloadAll(); +} - auto gameManager = gd::GameManager::sharedState(); - gameManager->setQuality(static_cast(s_lQuality.getIndex() + 1)); - gameManager->reloadAll(false, false, true); +void LoaderLayer::onApply(cocos2d::CCObject*) { + auto loaderManager = LoaderManager::sharedState(); + if (loaderManager->m_bCheckPlists) { + if (!loaderManager->checkPlists()) { + auto alert = gd::FLAlertLayer::create( + this, "Warning", "Cancel", "Yes", 300.0f, "Packs may display incorrectly.\nDo you want to Continue?" + ); + alert->setTag(kPlistWarningLayer); + alert->show(); + return; + } + } + if (loaderManager->m_bCheckQuality) { + if (!loaderManager->checkQuality()) { + auto alert = gd::FLAlertLayer::create( + this, "Warning", "Cancel", "Yes", 300.0f, "Packs may not line up with quality.\nDo you want to Continue?" + ); + alert->setTag(kQualityWarningLayer); + alert->show(); + return; + } + } + this->reloadAll(); } -void LoaderLayer::onOptions(cocos2d::CCObject*) { - auto options = LoaderOptionsLayer::create(); - this->addChild(options); - options->setPosition(0.0f, 0.0f); - options->showLayer(false); +void LoaderLayer::onDropDown(cocos2d::CCObject*) { + auto dropDown = LoaderDropDownLayer::create(); + this->addChild(dropDown); + dropDown->setPosition(0.0f, 0.0f); + dropDown->showLayer(false); } void LoaderLayer::onExit(cocos2d::CCObject*) { - s_lQuality.exit(); - s_lAll.exit(); - s_lApplied.exit(); - auto scene = CCScene::create(); scene->addChild(gd::MenuLayer::create()); CCDirector::sharedDirector()->replaceScene(CCTransitionFade::create(0.5f, scene)); } -void LoaderLayer::getPacks(cocos2d::CCObject*) { - std::string text = LoaderLayer::getPacks(true); - auto alert = gd::FLAlertLayer::create(nullptr, "Update", "OK", nullptr, text); +void LoaderLayer::onRefresh(cocos2d::CCObject*) { + std::string text = LoaderManager::sharedState()->updatePacks(true); + m_plAll->updateList(); + m_plApplied->updateList(); + + auto alert = gd::FLAlertLayer::create(nullptr, "Update", "OK", nullptr, 350.0f, text); alert->show(); } -std::string LoaderLayer::getPacks(bool generate) { - using namespace std::filesystem; - - std::vector packsList = {}; - - /*all characters allowed by stock bigFont.fnt and goldFont.fnt. - * excludes '\', '/', ':', '*', '?', '"', '<', '>', and '|' since windows - * folders can't have those symbols, and '•' since it acts weird and i can't - * be bothered lol - */ - constexpr std::string_view filter = " !#$%&'()+,-.0123456789;=@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{}~"; - unsigned int invalid = 0; - - Log::info("Searching for packs."); - path packs = current_path() / "packs"; - if (exists(packs)) { - if (is_directory(packs)) { - Log::info("Packs directory found. Iterating."); - for (directory_entry pack : directory_iterator{ packs }) { - if (is_directory(pack)) { - bool valid = true; - for (auto c : pack.path().filename().u8string()) { - if (filter.find(c) == filter.npos) { - valid = false; - break; - } - } - - if (valid) - packsList.push_back(pack.path().filename().string()); - else - ++invalid; - } - } - - Log::info(packsList.size(), " packs found."); - } - else - MessageBox(0, "ERROR: packs is an existing file.\n please remove it to use textureldr.", "textureldr", MB_OK | MB_ICONERROR); - } - else { - Log::error("No packs directory found. Creating new directory."); - create_directories(packs); - } - - unsigned int added = 0; - unsigned int removed = 0; - - if (!(s_lAll.getEntries().empty() && s_lApplied.getEntries().empty())) { - added = s_lAll.ifNotFound(packsList, true); - removed = s_lAll.ifNotFound(packsList, false); - } - else { - s_lAll.setEntries(packsList); - added = packsList.size(); - } - - if (generate) { - std::stringstream text = {}; - if (added != 0 || removed != 0) { - text << "" << added << " " << ((added == 1) ? "pack" : "packs") << " added.\n"; - //for some silly reason, color markers don't work directly after a newline! - //@robtop fix??? - text << " " << removed << " " << ((removed == 1) ? "pack" : "packs") << " removed.\n"; - } - else { - text << "Nothing changed!\n"; - } - - if (invalid > 0) { - text << '\n'; - if (invalid == 1) { - text << "1 pack had an invalid name, and was ignored.\n"; - } - else { - text << invalid << " packs had invalid names, and were ignored.\n"; - } - } - return text.str(); - } - else { - return ""; - } +void LoaderLayer::onFolder(cocos2d::CCObject*) { + CCApplication::sharedApplication()->openURL("packs"); } -bool LoaderLayer::load() { - using namespace tinyxml2; - - Log::info("Attempting to load savefile."); - s_pFile = new XMLDocument(); - if (s_pFile->LoadFile(s_sFilePath)) { - Log::error("Could not load config.dat. Trying backup.dat."); - if (s_pFile->LoadFile(s_sBackupPath)) { - Log::error("Could not load backup.dat."); - return false; - } +void LoaderLayer::reloadAll() { + auto loaderManager = LoaderManager::sharedState(); - Log::info("Loaded backup.dat. Saving."); - s_pFile->SaveFile(s_sFilePath, false); - } - else { - Log::info("Loaded config.dat. Saving."); - s_pFile->SaveFile(s_sBackupPath, false); - } + CCDirector::sharedDirector()->updateContentScale( + static_cast(loaderManager->m_dQuality.m_uOffset + 1) + ); - if (!s_lQuality.load(s_pFile) || - !s_lAll.load(s_pFile) || - !s_lApplied.load(s_pFile)) { - return false; - } - return true; + auto gameManager = gd::GameManager::sharedState(); + gameManager->setQuality( + static_cast(loaderManager->m_dQuality.m_uOffset + 1) + ); + gameManager->reloadAll(false, false, true); } -bool LoaderLayer::save() { - using namespace tinyxml2; - - s_pFile->DeleteChildren(); - - if (!s_lQuality.save(s_pFile) || - !s_lAll.save(s_pFile) || - !s_lApplied.save(s_pFile)) { - return false; +LoaderLayer* LoaderLayer::create() { + LoaderLayer* pRet = new LoaderLayer(); + if (pRet && pRet->init()) { + pRet->autorelease(); + return pRet; } - - return s_pFile->SaveFile(s_sFilePath) == XML_SUCCESS; -} - -const std::vector& LoaderLayer::getApplied() { - return s_lApplied.getEntries(); -} - -bool init() { - if (!LoaderLayer::load()) { - LoaderLayer::getPacks(false); - LoaderLayer::s_lQuality.setEntries({ "Low", "Medium", "High" }); - LoaderLayer::s_lQuality.setOffset(2); + else { + CC_SAFE_DELETE(pRet); + return nullptr; } - LoaderLayer::s_lQuality.setPosition(0.0f, -130.0f); - LoaderLayer::s_lAll.setPosition(-120.0f, 95.0f); - LoaderLayer::s_lApplied.setPosition(120.0f, 95.0f); - - return true; } -void __stdcall enter(cocos2d::CCObject*) { +void __fastcall LoaderLayer::scene(gd::MenuLayer* This, void*, cocos2d::CCObject* btn) { auto scene = CCScene::create(); scene->addChild(LoaderLayer::create()); diff --git a/src/logic/layers/LoaderLayer.h b/src/logic/layers/LoaderLayer.h index 5064ec2..70c122b 100644 --- a/src/logic/layers/LoaderLayer.h +++ b/src/logic/layers/LoaderLayer.h @@ -2,47 +2,35 @@ #define __LOADERLAYER_H__ #include "pch.h" -#include "LoaderOptionsLayer.h" +#include "more/LoaderDropDownLayer.h" #include "../nodes/List.h" +#include "../nodes/LoaderManager.h" -class HorizontalList; -class VerticalList; +class LoaderLayer : public cocos2d::CCLayer, gd::FLAlertLayerProtocol { +protected: + HorizontalList* m_plQuality; + VerticalList* m_plAll; + VerticalList* m_plApplied; -class LoaderLayer : public cocos2d::CCLayer { -private: - static HorizontalList s_lQuality; - static VerticalList s_lAll, s_lApplied; - static inline tinyxml2::XMLDocument* s_pFile = nullptr; - static inline constexpr char s_sFilePath[] = "packs/config.dat"; - static inline constexpr char s_sBackupPath[] = "packs/backup.dat"; +protected: + virtual bool init(); -private: - virtual bool init() override; + virtual void keyBackClicked(); - static LoaderLayer* create(); - - virtual void keyBackClicked() override; + virtual void FLAlert_Clicked(gd::FLAlertLayer* layer, bool btn2); void onApply(cocos2d::CCObject*); - void onOptions(cocos2d::CCObject*); + void onDropDown(cocos2d::CCObject*); void onExit(cocos2d::CCObject*); + void onRefresh(cocos2d::CCObject*); + void onFolder(cocos2d::CCObject*); - void getPacks(cocos2d::CCObject*); - - static std::string getPacks(bool generate); + void reloadAll(); public: - static bool load(); - static bool save(); - - static const std::vector& getApplied(); - - friend bool init(); - friend void __stdcall enter(cocos2d::CCObject*); + static LoaderLayer* create(); + static void __fastcall scene(gd::MenuLayer* This, void*, cocos2d::CCObject* btn); }; -bool init(); -void __stdcall enter(cocos2d::CCObject*); - #endif diff --git a/src/logic/layers/LoaderOptionsLayer.cpp b/src/logic/layers/LoaderOptionsLayer.cpp deleted file mode 100644 index 3556889..0000000 --- a/src/logic/layers/LoaderOptionsLayer.cpp +++ /dev/null @@ -1,26 +0,0 @@ -#include "pch.h" -#include "LoaderOptionsLayer.h" - -using namespace cocos2d; - -void LoaderOptionsLayer::customSetup() { - auto testBtn = gd::CCMenuItemSpriteExtra::create( - gd::ButtonSprite::create("hey", 0, false, "goldFont.fnt", "GJ_button_01.png", 0.0f, 1.0f), - this, - nullptr - ); - m_pLayer->addChild(CCMenu::createWithItem(testBtn)); -} - -LoaderOptionsLayer* LoaderOptionsLayer::create() { - LoaderOptionsLayer* pRet = new LoaderOptionsLayer(); - if (pRet && pRet->init("Options", 220.0f)) { - pRet->autorelease(); - return pRet; - } - else { - CC_SAFE_DELETE(pRet); - return nullptr; - } -} - diff --git a/src/logic/layers/LoaderOptionsLayer.h b/src/logic/layers/LoaderOptionsLayer.h deleted file mode 100644 index 6e81c02..0000000 --- a/src/logic/layers/LoaderOptionsLayer.h +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef __LOADEROPTIONSLAYER_H__ -#define __LOADEROPTIONSLAYER_H__ - -#include "pch.h" - -class LoaderOptionsLayer : public gd::GJDropDownLayer { -protected: - - -protected: - virtual void customSetup(); - -public: - static LoaderOptionsLayer* create(); -}; - -#endif - diff --git a/src/logic/layers/more/LoaderAboutLayer.cpp b/src/logic/layers/more/LoaderAboutLayer.cpp new file mode 100644 index 0000000..ad892b8 --- /dev/null +++ b/src/logic/layers/more/LoaderAboutLayer.cpp @@ -0,0 +1,104 @@ +#include "pch.h" +#include "LoaderAboutLayer.h" + +using namespace cocos2d; +using namespace extension; + +bool LoaderAboutLayer::init() { + auto winSize = CCDirector::sharedDirector()->getWinSize(); + + if (!this->initWithColor({ 0, 0, 0, 75 })) return false; + m_pLayer = CCLayer::create(); + this->addChild(m_pLayer); + + auto bg = CCScale9Sprite::create("GJ_square01.png", { 0.0f, 0.0f, 80.0f, 80.0f }); + bg->setContentSize({ 360.0f, 260.0f }); + bg->setPosition(winSize.width / 2, winSize.height / 2); + m_pLayer->addChild(bg); + + m_pButtonMenu = CCMenu::create(); + m_pLayer->addChild(m_pButtonMenu); + + auto title = CCLabelBMFont::create("About", "goldFont.fnt"); + title->setScale(0.9f); + title->setPosition(winSize.width / 2, winSize.height / 2 + 110.0f); + m_pLayer->addChild(title); + + auto version = CCLabelBMFont::create("textureldr " VERSION, "bigFont.fnt"); + version->setScale(0.7f); + version->setPosition(winSize.width / 2, winSize.height / 2 + 80.0f); + m_pLayer->addChild(version); + + auto author = CCLabelBMFont::create("by PoweredByPie", "goldFont.fnt"); + author->setScale(0.5f); + auto authorBtn = gd::CCMenuItemSpriteExtra::create( + author, + this, + menu_selector(LoaderAboutLayer::onAuthor) + ); + m_pButtonMenu->addChild(authorBtn); + authorBtn->setPosition(0.0f, 60.0f); + + auto thanksTitle = CCLabelBMFont::create("thank you to", "bigFont.fnt"); + thanksTitle->setPosition(winSize.width / 2, winSize.height / 2 + 20.0f); + thanksTitle->setScale(0.6f); + thanksTitle->setColor({ 50, 255, 50 }); + m_pLayer->addChild(thanksTitle); + + auto thanks = CCMenu::create(); + thanks->addChild(CCLabelBMFont::create( + "absol\n" + "iad\n" + "adaf\n" + "mat\n" + "tobuu\n", + "goldFont.fnt", kCCLabelAutomaticWidth, kCCTextAlignmentCenter)); + thanks->addChild(CCLabelBMFont::create( + "andre\n" + "cos8o\n" + "figment\n" + "hjfod\n" + "fadey\n", + "goldFont.fnt", kCCLabelAutomaticWidth, kCCTextAlignmentCenter)); + //how do you center a ccmenu :( + thanks->setPosition(winSize.width / 2 - 75.0f, winSize.height / 2 - 90.0f); + thanks->setScale(0.7f); + thanks->alignItemsHorizontallyWithPadding(30.0f); + m_pLayer->addChild(thanks); + + auto closeBtn = gd::CCMenuItemSpriteExtra::create( + CCSprite::createWithSpriteFrameName("GJ_closeBtn_001.png"), + this, + menu_selector(LoaderAboutLayer::onClose) + ); + m_pButtonMenu->addChild(closeBtn); + closeBtn->setPosition( + closeBtn->convertToNodeSpace({ (winSize.width / 2) - 198.0f, (winSize.height / 2) + 102.0f }) + ); + closeBtn->setSizeMult(1.5f); + + this->setKeypadEnabled(true); + this->setTouchEnabled(true); + return true; +} + +void LoaderAboutLayer::onClose(cocos2d::CCObject*) { + this->setKeypadEnabled(false); + this->removeFromParentAndCleanup(true); +} + +void LoaderAboutLayer::onAuthor(cocos2d::CCObject*) { + CCApplication::sharedApplication()->openURL("https://github.com/poweredbypie"); +} + +LoaderAboutLayer* LoaderAboutLayer::create() { + LoaderAboutLayer* pRet = new LoaderAboutLayer(); + if (pRet && pRet->init()) { + pRet->autorelease(); + return pRet; + } + else { + CC_SAFE_DELETE(pRet); + return nullptr; + } +} \ No newline at end of file diff --git a/src/logic/layers/more/LoaderAboutLayer.h b/src/logic/layers/more/LoaderAboutLayer.h new file mode 100644 index 0000000..5dd6ada --- /dev/null +++ b/src/logic/layers/more/LoaderAboutLayer.h @@ -0,0 +1,17 @@ +#ifndef __LOADERABOUTLAYER_H__ +#define __LOADERABOUTLAYER_H__ + +#include "pch.h" + +class LoaderAboutLayer : public gd::FLAlertLayer { +protected: + virtual bool init(); + + void onClose(cocos2d::CCObject*); + void onAuthor(cocos2d::CCObject*); + +public: + static LoaderAboutLayer* create(); +}; + +#endif \ No newline at end of file diff --git a/src/logic/layers/more/LoaderDropDownLayer.cpp b/src/logic/layers/more/LoaderDropDownLayer.cpp new file mode 100644 index 0000000..e8ac8fe --- /dev/null +++ b/src/logic/layers/more/LoaderDropDownLayer.cpp @@ -0,0 +1,49 @@ +#include "pch.h" +#include "LoaderDropDownLayer.h" + +using namespace cocos2d; + +void LoaderDropDownLayer::customSetup() { + auto winSize = CCDirector::sharedDirector()->getWinSize(); + + auto menu = CCMenu::create(); + m_pLayer->addChild(menu); + + auto optionsBtn = gd::CCMenuItemSpriteExtra::create( + gd::ButtonSprite::create("Options", 150, true, "goldFont.fnt", "GJ_button_01.png", 0.0f, 1.0f), + this, + menu_selector(LoaderDropDownLayer::onOptions) + ); + menu->addChild(optionsBtn); + auto aboutBtn = gd::CCMenuItemSpriteExtra::create( + gd::ButtonSprite::create("About", 150, true, "goldFont.fnt", "GJ_button_01.png", 0.0f, 1.0f), + this, + menu_selector(LoaderDropDownLayer::onAbout) + ); + menu->addChild(aboutBtn); + + menu->alignItemsVerticallyWithPadding(20.0f); +} + +void LoaderDropDownLayer::onOptions(cocos2d::CCObject*) { + auto options = LoaderOptionsLayer::create(); + options->show(); +} + +void LoaderDropDownLayer::onAbout(cocos2d::CCObject*) { + auto about = LoaderAboutLayer::create(); + about->show(); +} + +LoaderDropDownLayer* LoaderDropDownLayer::create() { + LoaderDropDownLayer* pRet = new LoaderDropDownLayer(); + if (pRet && pRet->init("More", 220.0f)) { + pRet->autorelease(); + return pRet; + } + else { + CC_SAFE_DELETE(pRet); + return nullptr; + } +} + diff --git a/src/logic/layers/more/LoaderDropDownLayer.h b/src/logic/layers/more/LoaderDropDownLayer.h new file mode 100644 index 0000000..271088f --- /dev/null +++ b/src/logic/layers/more/LoaderDropDownLayer.h @@ -0,0 +1,21 @@ +#ifndef __LOADERDROPDOWNLAYER_H__ +#define __LOADERDROPDOWNLAYER_H__ + +#include "pch.h" +#include "LoaderOptionsLayer.h" +#include "LoaderAboutLayer.h" + +class LoaderDropDownLayer : public gd::GJDropDownLayer { +protected: + +protected: + virtual void customSetup(); + void onOptions(cocos2d::CCObject*); + void onAbout(cocos2d::CCObject*); + +public: + static LoaderDropDownLayer* create(); +}; + +#endif + diff --git a/src/logic/layers/more/LoaderOptionsLayer.cpp b/src/logic/layers/more/LoaderOptionsLayer.cpp new file mode 100644 index 0000000..f88ef20 --- /dev/null +++ b/src/logic/layers/more/LoaderOptionsLayer.cpp @@ -0,0 +1,144 @@ +#include "pch.h" +#include "LoaderOptionsLayer.h" + +using namespace cocos2d; +using namespace extension; + +bool LoaderOptionsLayer::init() { + auto winSize = CCDirector::sharedDirector()->getWinSize(); + + if (!this->initWithColor({ 0, 0, 0, 75 })) return false; + + auto bg = CCScale9Sprite::create("GJ_square01.png", { 0.0f, 0.0f, 80.0f, 80.0f }); + bg->setContentSize({ 360.0f, 260.0f }); + bg->setPosition(winSize.width / 2, winSize.height / 2); + m_pLayer->addChild(bg); + + m_pButtonMenu = CCMenu::create(); + m_pLayer->addChild(m_pButtonMenu); + + auto title = CCLabelBMFont::create("Options", "goldFont.fnt"); + title->setScale(0.9f); + title->setPosition(winSize.width / 2, winSize.height / 2 + 110.0f); + m_pLayer->addChild(title); + + auto loaderManager = LoaderManager::sharedState(); + + this->createToggler("Reload SFX", + loaderManager->m_bReloadSFX, + "Reload .ogg files on Apply.\n" + "Increases performance if toggled off."); + this->createToggler("Reload Music", + loaderManager->m_bReloadMusic, + "Reload menuLoop.mp3 on Apply.\n" + "May slightly increase performance if toggled off."); + this->createToggler("Check .plists", + loaderManager->m_bCheckPlists, + "Check .plist / .fnt files on Apply.\n" + "Will warn user if plists will break pack combination.\n" + "Increases performance if toggled off."); + this->createToggler("Check Quality", + loaderManager->m_bCheckQuality, + "Check quality of applied packs on Apply.\n" + "Will warn user if current quality does not line up with pack quality.\n" + "Increases performance if toggled off."); + + auto closeBtn = gd::CCMenuItemSpriteExtra::create( + CCSprite::createWithSpriteFrameName("GJ_closeBtn_001.png"), + this, + menu_selector(LoaderOptionsLayer::onClose) + ); + m_pButtonMenu->addChild(closeBtn); + closeBtn->setPosition( + closeBtn->convertToNodeSpace({ (winSize.width / 2) - 198.0f, (winSize.height / 2) + 102.0f }) + ); + closeBtn->setSizeMult(1.5f); + + this->setKeypadEnabled(true); + this->setTouchEnabled(true); + return true; +} + +LoaderOptionsLayer::LoaderOptionsLayer() { + m_fLastX = -140.0f; + m_fLastY = 65.0f; + + m_pLayer = CCLayer::create(); + this->addChild(m_pLayer); +} + +void LoaderOptionsLayer::onClose(cocos2d::CCObject*) { + this->setKeypadEnabled(false); + this->removeFromParentAndCleanup(true); +} + +void LoaderOptionsLayer::createToggler(const char* title, bool& toggle, const char* description) { + + if (m_fLastY <= -100.0f) { + m_fLastY = 65.0f; + m_fLastX += 170.0f; + } + if (m_fLastX >= 40.0f) { + //handle this when u have >10 settings + } + + auto offSprite = CCSprite::createWithSpriteFrameName("GJ_checkOff_001.png"); + offSprite->setScale(0.75f); + auto onSprite = CCSprite::createWithSpriteFrameName("GJ_checkOn_001.png"); + onSprite->setScale(0.75f); + auto toggler = gd::CCMenuItemToggler::create( + offSprite, + onSprite, + this, + menu_selector(LoaderOptionsLayer::toggleToggler) + ); + toggler->setUserData(&toggle); + //idk why this doesnt work + toggler->toggle(toggle); + toggler->setPosition(0.0f + m_fLastX, 0.0f + m_fLastY); + m_pButtonMenu->addChild(toggler); + + if (description) { + auto infoSprite = CCSprite::createWithSpriteFrameName("GJ_infoIcon_001.png"); + infoSprite->setScale(0.5f); + auto info = gd::CCMenuItemSpriteExtra::create( + infoSprite, + this, + menu_selector(LoaderOptionsLayer::viewTogglerDescription) + ); + //i know this isn't gonna be modified anyway + info->setUserData(const_cast(description)); + info->setPosition(-20.0f + m_fLastX, 20.0f + m_fLastY); + m_pButtonMenu->addChild(info); + } + + auto label = CCLabelBMFont::create(title, "bigFont.fnt"); + label->setPosition(75.0f + m_fLastX, 0.0f + m_fLastY); + label->limitLabelWidth(110.0f, 15.0f, 0.0f); + m_pButtonMenu->addChild(label); + + m_fLastY -= 40.0f; +} + +void LoaderOptionsLayer::toggleToggler(cocos2d::CCObject* toggler) { + bool* toggle = static_cast(static_cast(toggler)->getUserData()); + *toggle = !*toggle; +} + +void LoaderOptionsLayer::viewTogglerDescription(cocos2d::CCObject* info) { + auto alert = gd::FLAlertLayer::create(nullptr, "Info", "OK", 0, 350.0f, + static_cast(static_cast(info)->getUserData())); + alert->show(); +} + +LoaderOptionsLayer* LoaderOptionsLayer::create() { + LoaderOptionsLayer* pRet = new LoaderOptionsLayer(); + if (pRet && pRet->init()) { + pRet->autorelease(); + return pRet; + } + else { + CC_SAFE_DELETE(pRet); + return nullptr; + } +} \ No newline at end of file diff --git a/src/logic/layers/more/LoaderOptionsLayer.h b/src/logic/layers/more/LoaderOptionsLayer.h new file mode 100644 index 0000000..f253eb2 --- /dev/null +++ b/src/logic/layers/more/LoaderOptionsLayer.h @@ -0,0 +1,27 @@ +#ifndef __LOADEROPTIONSLAYER_H__ +#define __LOADEROPTIONSLAYER_H__ + +#include "pch.h" +#include "../../nodes/LoaderManager.h" + +class LoaderOptionsLayer : public gd::FLAlertLayer { +protected: + float m_fLastX; + float m_fLastY; + +protected: + virtual bool init(); + + LoaderOptionsLayer(); + + void onClose(cocos2d::CCObject*); + + void createToggler(const char* title, bool& toggle, const char* description); + void toggleToggler(cocos2d::CCObject* toggler); + void viewTogglerDescription(cocos2d::CCObject* info); + +public: + static LoaderOptionsLayer* create(); +}; + +#endif \ No newline at end of file diff --git a/src/logic/nodes/List.cpp b/src/logic/nodes/List.cpp index 5170258..a3a3c48 100644 --- a/src/logic/nodes/List.cpp +++ b/src/logic/nodes/List.cpp @@ -2,6 +2,7 @@ #include "List.h" using namespace cocos2d; +using namespace extension; #define ARROW CCSprite::createWithSpriteFrameName("edit_rightBtn_001.png") @@ -10,44 +11,26 @@ enum { kListDownBtn, kVerticalListSwapUpBtn, kVerticalListSwapDownBtn, - kVerticalListMoveBtn + kVerticalListMoveBtn, + kVerticalListBackground }; -//HorizontalList -void HorizontalList::navigate(cocos2d::CCObject* btn) { - if (!m_vEntries.empty()) { - if (btn->getTag() == kListUpBtn) { - if (m_uOffset != 0) - --m_uOffset; - } - else { - if (m_uOffset < m_vEntries.size() - 1) - ++m_uOffset; - } - - this->updateList(); - } +//ListData +ListData::ListData(const char* title, unsigned int length, ListData* target) { + m_sTitle = title; + m_uMaxLength = length; + m_pTarget = target; + m_uLength = 0; + m_uOffset = 0; + m_uIndex = 0; } -void HorizontalList::updateList() { - this->getLength(); - - if (m_uLength != 0) { - if (!m_bEntered) { - m_pLabels[0] = CCLabelBMFont::create(m_vEntries[m_uOffset].c_str(), "bigFont.fnt"); - m_pLabels[0]->setPosition(m_obPosition.x, m_obPosition.y); - m_pMenu->addChild(m_pLabels[0]); - } - else { - m_pLabels[0]->setString(m_vEntries[m_uOffset].c_str()); - } - m_pLabels[0]->limitLabelWidth(90.0f, 0.8f, 0.0f); - } -} +//HorizontalList +bool HorizontalList::init() { + m_pLabels = new CCLabelBMFont* [m_pData.m_uMaxLength]; -void HorizontalList::enter(LoaderLayer* parent) { m_pMenu = CCMenu::create(); - parent->addChild(m_pMenu); + this->addChild(m_pMenu); auto upBtn = gd::CCMenuItemSpriteExtra::create( ARROW, @@ -68,249 +51,168 @@ void HorizontalList::enter(LoaderLayer* parent) { downBtn->setPosition(m_obPosition.x + 70.0f, m_obPosition.y); m_pMenu->addChild(downBtn); - this->updateList(); - - m_bEntered = true; -} - -bool HorizontalList::load(tinyxml2::XMLDocument* file) { - using namespace tinyxml2; + //verify offset + if (!m_pData.m_vEntries.empty() && m_pData.m_uOffset > m_pData.m_vEntries.size() - 1) + m_pData.m_uOffset = m_pData.m_vEntries.size() - 1; + else if (m_pData.m_uOffset < 0) + m_pData.m_uOffset = 0; - if (auto list = file->FirstChildElement(m_sTitle)) { - if (list->QueryUnsignedAttribute("offset", &m_uOffset)) - return false; - - for (auto i = list->FirstChildElement("entry"); - i; - i = i->NextSiblingElement()) - m_vEntries.push_back(i->GetText()); - - if (!m_vEntries.empty() && m_uOffset > m_vEntries.size() - 1) - m_uOffset = m_vEntries.size() - 1; - else if (m_uOffset < 0) - m_uOffset = 0; - - return true; - } - return false; -} - -bool HorizontalList::save(tinyxml2::XMLDocument* file) { - using namespace tinyxml2; + this->getLength(); - auto list = file->NewElement(m_sTitle); - list->SetAttribute("offset", m_uOffset); - file->InsertEndChild(list); - for (auto entry : m_vEntries) { - auto i = file->NewElement("entry"); - i->InsertEndChild(file->NewText(entry.c_str())); - list->InsertEndChild(i); + if (m_pData.m_uLength != 0) { + m_pLabels[0] = CCLabelBMFont::create(m_pData.m_vEntries[m_pData.m_uOffset].c_str(), "bigFont.fnt"); + m_pLabels[0]->setPosition(m_obPosition.x, m_obPosition.y); + m_pLabels[0]->limitLabelWidth(90.0f, 0.8f, 0.0f); + m_pMenu->addChild(m_pLabels[0]); } return true; } -HorizontalList::HorizontalList(const char* title) { - m_sTitle = title; - //m_uMaxLength is always 1 for horizontal lists - m_pLabels = new CCLabelBMFont* [m_uMaxLength]; -} - -void HorizontalList::setEntries(const std::vector& vec) { - m_vEntries = vec; +void HorizontalList::updateList() { + this->getLength(); - if (m_bEntered) - this->updateList(); + if (m_pData.m_uLength != 0) { + m_pLabels[0]->setString(m_pData.m_vEntries[m_pData.m_uOffset].c_str()); + m_pLabels[0]->limitLabelWidth(90.0f, 0.8f, 0.0f); + } } -void HorizontalList::setOffset(unsigned int offset) { - if (offset > m_vEntries.size() - 1) { - Log::error("New offset is out of bounds."); - return; - } - m_uOffset = offset; +void HorizontalList::navigate(cocos2d::CCObject* btn) { + if (!m_pData.m_vEntries.empty()) { + if (btn->getTag() == kListUpBtn) { + if (m_pData.m_uOffset != 0) + --m_pData.m_uOffset; + } + else if (btn->getTag() == kListDownBtn) { + if (m_pData.m_uOffset < m_pData.m_vEntries.size() - 1) + ++m_pData.m_uOffset; + } - if (m_bEntered) this->updateList(); + } } -unsigned int HorizontalList::ifNotFound(const std::vector& other, bool add) { - unsigned int count = 0; - - if (add) { - for (unsigned int i = 0; i < other.size(); ++i) { - if (std::find(m_vEntries.begin(), m_vEntries.end(), other[i]) == m_vEntries.end()) { - m_vEntries.insert(m_vEntries.begin(), other[i]); - ++count; - } - } +HorizontalList* HorizontalList::create(ListData& data) { + HorizontalList* pRet = new HorizontalList(data); + if (pRet && pRet->init()) { + pRet->autorelease(); + return pRet; } else { - for (unsigned int i = 0; i < m_vEntries.size(); ++i) { - if (std::find(other.begin(), other.end(), m_vEntries[i]) == other.end()) { - m_vEntries.erase(m_vEntries.begin() + i); - --i; - - //move to the start of the list, im too lazy - m_uOffset = 0; - ++count; - } - } + CC_SAFE_DELETE(pRet); + return nullptr; } +} - if (m_bEntered) - this->updateList(); - - return count; +void HorizontalList::setPosition(float x, float y) { + m_obPosition = ccp(x, y); + //this->updateList(); } //VerticalList void VerticalList::navigate(cocos2d::CCObject* btn) { if (btn->getTag() == kListUpBtn) { - if (m_uIndex > 0) - --m_uIndex; - else if (m_uOffset > 0) - --m_uOffset; + if (m_pData.m_uIndex > 0) + --m_pData.m_uIndex; + else if (m_pData.m_uOffset > 0) + --m_pData.m_uOffset; } - else { - if (m_uIndex + 1 < m_uLength) - ++m_uIndex; - else if (m_uMaxLength < m_vEntries.size() && - m_uOffset < m_vEntries.size() - m_uMaxLength) - ++m_uOffset; + else if (btn->getTag() == kListDownBtn) { + if (m_pData.m_uIndex + 1 < m_pData.m_uLength) + ++m_pData.m_uIndex; + else if (m_pData.m_uMaxLength < m_pData.m_vEntries.size() && + m_pData.m_uOffset < m_pData.m_vEntries.size() - m_pData.m_uMaxLength) + ++m_pData.m_uOffset; } - updateList(); + this->updateList(); } void VerticalList::swap(cocos2d::CCObject* btn) { if (btn->getTag() == kVerticalListSwapUpBtn) { - if (m_uIndex > 0) { - std::iter_swap(m_vEntries.begin() + m_uIndex + m_uOffset, m_vEntries.begin() + m_uIndex + m_uOffset - 1); - --m_uIndex; + if (m_pData.m_uIndex > 0) { + std::iter_swap(m_pData.m_vEntries.begin() + m_pData.m_uIndex + m_pData.m_uOffset, + m_pData.m_vEntries.begin() + m_pData.m_uIndex + m_pData.m_uOffset - 1); + --m_pData.m_uIndex; } } - else { - if (m_uIndex + 1 < m_uLength) { - std::iter_swap(m_vEntries.begin() + m_uIndex + m_uOffset, m_vEntries.begin() + m_uIndex + m_uOffset + 1); - ++m_uIndex; + else if (btn->getTag() == kVerticalListSwapDownBtn) { + if (m_pData.m_uIndex + 1 < m_pData.m_uLength) { + std::iter_swap(m_pData.m_vEntries.begin() + m_pData.m_uIndex + m_pData.m_uOffset, + m_pData.m_vEntries.begin() + m_pData.m_uIndex + m_pData.m_uOffset + 1); + ++m_pData.m_uIndex; } } - updateList(); + this->updateList(); } void VerticalList::move(cocos2d::CCObject*) { - m_pTarget->m_vEntries.insert(m_pTarget->m_vEntries.begin(), m_vEntries[m_uIndex + m_uOffset]); - m_vEntries.erase(m_vEntries.begin() + m_uIndex + m_uOffset); + m_pData.m_pTarget->m_vEntries.insert(m_pData.m_pTarget->m_vEntries.begin(), + m_pData.m_vEntries[m_pData.m_uIndex + m_pData.m_uOffset]); + m_pData.m_vEntries.erase(m_pData.m_vEntries.begin() + m_pData.m_uIndex + m_pData.m_uOffset); - getLength(); + this->getLength(); - if (m_vEntries.size() >= m_uMaxLength && - m_uLength < m_uMaxLength) - --m_uOffset; - else if (m_uLength < m_uIndex + 1 && - m_uLength > 0) - --m_uIndex; + if (m_pData.m_vEntries.size() >= m_pData.m_uMaxLength && + m_pData.m_uLength < m_pData.m_uMaxLength) + --m_pData.m_uOffset; + else if (m_pData.m_uLength < m_pData.m_uIndex + 1 && + m_pData.m_uLength > 0) + --m_pData.m_uIndex; - updateList(); + this->updateList(); m_pTarget->updateList(); } void VerticalList::updateLabels() { - getLength(); - if (!m_bEntered) { - for (unsigned int i = 0; i < m_uMaxLength; ++i) { - if (i < m_uLength) { - m_pLabels[i] = CCLabelBMFont::create(m_vEntries[m_uOffset + i].c_str(), "bigFont.fnt"); - } - else { - m_pLabels[i] = CCLabelBMFont::create("", "bigFont.fnt"); - } - m_pLabels[i]->setPosition(m_obPosition.x, m_obPosition.y - 20.0f * i); - m_pLabels[i]->limitLabelWidth(95.0f, 0.6f, 0.0f); - m_pMenu->addChild(m_pLabels[i]); + this->getLength(); + + for (unsigned int i = 0; i < m_pData.m_uMaxLength; ++i) { + if (i < m_pData.m_uLength) { + m_pLabels[i]->setString(m_pData.m_vEntries[m_pData.m_uOffset + i].c_str()); } - } - else { - for (unsigned int i = 0; i < m_uMaxLength; ++i) { - if (i < m_uLength) { - m_pLabels[i]->setString(m_vEntries[m_uOffset + i].c_str()); - } - else { - m_pLabels[i]->setString(""); - } - m_pLabels[i]->limitLabelWidth(95.0f, 0.6f, 0.0f); + else { + m_pLabels[i]->setString(""); } + m_pLabels[i]->limitLabelWidth(95.0f, 0.6f, 0.0f); } } void VerticalList::updateSelector() { float mult = m_obPosition.x < 0 ? 55.0f : -55.0f; - CCMenuItemSprite* moveBtn; - CCMenuItemSprite* swapUpBtn; - CCMenuItemSprite* swapDownBtn; - - if (!m_bEntered) { - moveBtn = CCMenuItemSprite::create( - ARROW, - ARROW, - nullptr, - this, - menu_selector(VerticalList::move) - ); - moveBtn->setTag(kVerticalListMoveBtn); - moveBtn->setRotation(mult == -55.0f ? 180.0f : 0.0f); - moveBtn->setScale(0.5f); - m_pMenu->addChild(moveBtn); - - swapUpBtn = CCMenuItemSprite::create( - ARROW, - ARROW, - nullptr, - this, - menu_selector(VerticalList::swap) - ); - swapUpBtn->setTag(kVerticalListSwapUpBtn); - swapUpBtn->setRotation(-90.0f); - swapUpBtn->setScale(0.5f); - m_pMenu->addChild(swapUpBtn); - - swapDownBtn = CCMenuItemSprite::create( - ARROW, - ARROW, - nullptr, - this, - menu_selector(VerticalList::swap) - ); - swapDownBtn->setTag(kVerticalListSwapDownBtn); - swapDownBtn->setRotation(90.0f); - swapDownBtn->setScale(0.5f); - m_pMenu->addChild(swapDownBtn); - } - else { - moveBtn = static_cast(m_pMenu->getChildByTag(kVerticalListMoveBtn)); - swapUpBtn = static_cast(m_pMenu->getChildByTag(kVerticalListSwapUpBtn)); - swapDownBtn = static_cast(m_pMenu->getChildByTag(kVerticalListSwapDownBtn)); - } + auto moveBtn = static_cast(m_pMenu->getChildByTag(kVerticalListMoveBtn)); + auto swapUpBtn = static_cast(m_pMenu->getChildByTag(kVerticalListSwapUpBtn)); + auto swapDownBtn = static_cast(m_pMenu->getChildByTag(kVerticalListSwapDownBtn)); - if (m_vEntries.size() - m_uOffset == 0) + if (m_pData.m_vEntries.size() - m_pData.m_uOffset == 0) toggle({ moveBtn, swapUpBtn, swapDownBtn }, false); else { - moveBtn->setPosition(m_obPosition.x + mult, m_obPosition.y - 20.0f * m_uIndex); - swapUpBtn->setPosition(m_obPosition.x - mult, m_obPosition.y + 5.0f - 20.0f * m_uIndex); - swapDownBtn->setPosition(m_obPosition.x - mult, m_obPosition.y - 5.0f - 20.0f * m_uIndex); + moveBtn->setPosition(mult, -20.0f * m_pData.m_uIndex); + swapUpBtn->setPosition(-mult, 5.0f - 20.0f * m_pData.m_uIndex); + swapDownBtn->setPosition(-mult, -5.0f - 20.0f * m_pData.m_uIndex); toggle({ moveBtn, swapUpBtn, swapDownBtn }, true); } } -void VerticalList::enter(LoaderLayer* parent) { +bool VerticalList::init() { + m_pLabels = new CCLabelBMFont* [m_pData.m_uMaxLength]; + m_pMenu = CCMenu::create(); - parent->addChild(m_pMenu); + this->addChild(m_pMenu); - auto title = CCLabelBMFont::create(m_sTitle, "goldFont.fnt"); + auto bg = CCScale9Sprite::create("square02b_001.png", { 0.0f, 0.0f, 80.0f, 80.0f }); + bg->setPosition(m_obPosition.x, m_obPosition.y - 90.0f); + bg->setColor({ 0, 0, 0 }); + bg->setOpacity(75); + bg->setContentSize({ 150.0f, 20.0f * m_pData.m_uMaxLength + 45.0f }); + bg->setTag(kVerticalListBackground); + m_pMenu->addChild(bg); + + auto title = CCLabelBMFont::create(m_pData.m_sTitle, "goldFont.fnt"); title->setPosition(m_obPosition.x, m_obPosition.y + 50.0f); m_pMenu->addChild(title); @@ -320,7 +222,7 @@ void VerticalList::enter(LoaderLayer* parent) { menu_selector(VerticalList::navigate) ); upBtn->setTag(kListUpBtn); - upBtn->setPosition(m_obPosition.x, m_obPosition.y + 25.0f); + upBtn->setPosition(m_obPosition.x, m_obPosition.y + 20.0f); upBtn->setRotation(-90.0f); m_pMenu->addChild(upBtn); @@ -330,111 +232,88 @@ void VerticalList::enter(LoaderLayer* parent) { menu_selector(VerticalList::navigate) ); downBtn->setTag(kListDownBtn); - downBtn->setPosition(m_obPosition.x, m_obPosition.y - 205.0f); + downBtn->setPosition(m_obPosition.x, m_obPosition.y - 200.0f); downBtn->setRotation(90.0f); m_pMenu->addChild(downBtn); - this->updateList(); - - m_bEntered = true; -} - -bool VerticalList::load(tinyxml2::XMLDocument* file) { - using namespace tinyxml2; - - if (auto list = file->FirstChildElement(m_sTitle)) { - if (list->QueryUnsignedAttribute("offset", &m_uOffset) || - list->QueryUnsignedAttribute("index", &m_uIndex)) - return false; + if (m_pData.m_uMaxLength < m_pData.m_vEntries.size()) { + if (m_pData.m_uOffset > m_pData.m_vEntries.size() - m_pData.m_uMaxLength) + m_pData.m_uOffset = m_pData.m_vEntries.size() - m_pData.m_uMaxLength; + else if (m_pData.m_uOffset < 0) + m_pData.m_uOffset = 0; + } + else { + m_pData.m_uOffset = 0; + } - for (auto i = list->FirstChildElement("entry"); - i; - i = i->NextSiblingElement()) - m_vEntries.push_back(i->GetText()); + this->getLength(); - if (m_uMaxLength < m_vEntries.size()) { - if (m_uOffset > m_vEntries.size() - m_uMaxLength) - m_uOffset = m_vEntries.size() - m_uMaxLength; - else if (m_uOffset < 0) - m_uOffset = 0; + for (unsigned int i = 0; i < m_pData.m_uMaxLength; ++i) { + if (i < m_pData.m_uLength) { + m_pLabels[i] = CCLabelBMFont::create(m_pData.m_vEntries[m_pData.m_uOffset + i].c_str(), "bigFont.fnt"); } - else - m_uOffset = 0; - - return true; + else { + m_pLabels[i] = CCLabelBMFont::create("", "bigFont.fnt"); + } + m_pLabels[i]->setPosition(m_obPosition.x, m_obPosition.y - 20.0f * i); + m_pMenu->addChild(m_pLabels[i]); } - return false; -} -bool VerticalList::save(tinyxml2::XMLDocument* file) { - using namespace tinyxml2; - - auto list = file->NewElement(m_sTitle); - list->SetAttribute("offset", m_uOffset); - list->SetAttribute("index", m_uIndex); - file->InsertEndChild(list); - for (auto entry : m_vEntries) { - auto i = file->NewElement("entry"); - i->InsertEndChild(file->NewText(entry.c_str())); - list->InsertEndChild(i); - } + this->updateLabels(); - return true; -} + auto moveSprite = ARROW; + moveSprite->setScale(0.5f); + auto moveBtn = gd::CCMenuItemSpriteExtra::create( + moveSprite, + this, + menu_selector(VerticalList::move) + ); + moveBtn->setTag(kVerticalListMoveBtn); + m_pMenu->addChild(moveBtn); -VerticalList::VerticalList(const char* title, unsigned int length, VerticalList* target) { - m_sTitle = title; - m_uMaxLength = length; - m_pTarget = target; + auto swapUpSprite = ARROW; + swapUpSprite->setScale(0.5f); + auto swapUpBtn = gd::CCMenuItemSpriteExtra::create( + swapUpSprite, + this, + menu_selector(VerticalList::swap) + ); + swapUpBtn->setTag(kVerticalListSwapUpBtn); + swapUpBtn->setRotation(-90.0f); + m_pMenu->addChild(swapUpBtn); + + auto swapDownSprite = ARROW; + swapDownSprite->setScale(0.5f); + auto swapDownBtn = gd::CCMenuItemSpriteExtra::create( + swapDownSprite, + this, + menu_selector(VerticalList::swap) + ); + swapDownBtn->setTag(kVerticalListSwapDownBtn); + swapDownBtn->setRotation(90.0f); + m_pMenu->addChild(swapDownBtn); + + this->updateSelector(); - m_pLabels = new CCLabelBMFont* [m_uMaxLength]; + return true; } -unsigned int VerticalList::ifNotFound(const std::vector& other, bool add) { - unsigned int count = 0; - std::vector old = { m_vEntries }; - old.insert(old.end(), m_pTarget->m_vEntries.begin(), m_pTarget->m_vEntries.end()); - - if (add) { - for (unsigned int i = 0; i < other.size(); ++i) { - if (std::find(old.begin(), old.end(), other[i]) == old.end()) { - m_vEntries.insert(m_vEntries.begin(), other[i]); - ++count; - } - } +VerticalList* VerticalList::create(ListData& data) { + VerticalList* pRet = new VerticalList(data); + if (pRet && pRet->init()) { + pRet->autorelease(); + return pRet; } else { - for (unsigned int i = 0; i < old.size(); ++i) { - if (std::find(other.begin(), other.end(), old[i]) == other.end()) { - auto index = std::find(m_vEntries.begin(), m_vEntries.end(), old[i]); - if (index != m_vEntries.end()) { - m_vEntries.erase(index); - } - else { - index = std::find(m_pTarget->m_vEntries.begin(), m_pTarget->m_vEntries.end(), old[i]); - m_pTarget->m_vEntries.erase(index); - } - - //move to the start of the list, im too lazy to do calculation - m_uOffset = 0; - m_uIndex = 0; - ++count; - } - } + CC_SAFE_DELETE(pRet); + return nullptr; } - - if (m_bEntered) - updateList(); - - return count; } -void VerticalList::setOffset(unsigned int offset) { - //this isn't used; i just have it for consistency's sake. - if (offset > m_vEntries.size() - m_uMaxLength - 1) { - Log::error("New offset is out of bounds."); - return; - } +void VerticalList::setPosition(float x, float y) { + m_obPosition = ccp(x, y); + auto moveBtn = static_cast(m_pMenu->getChildByTag(kVerticalListMoveBtn)); + moveBtn->setRotation(m_obPosition.x > 0 ? 180.0f : 0.0f); - m_uOffset = offset; + this->updateList(); } \ No newline at end of file diff --git a/src/logic/nodes/List.h b/src/logic/nodes/List.h index 06aee23..816fad2 100644 --- a/src/logic/nodes/List.h +++ b/src/logic/nodes/List.h @@ -2,30 +2,39 @@ #define __LIST_H__ #include "pch.h" -#include "../layers/LoaderLayer.h" class LoaderLayer; +struct ListData { + const char* m_sTitle; + std::vector m_vEntries; + unsigned int m_uMaxLength; + unsigned int m_uLength; + unsigned int m_uOffset; + unsigned int m_uIndex; + ListData* m_pTarget; + + ListData(const char* title, unsigned int length, ListData* target); + ListData() { /*doesn't matter since only used in default ctor of LoaderManager*/ }; +}; + class HorizontalList : public cocos2d::CCNode { protected: - const char* m_sTitle = ""; - std::vector m_vEntries = {}; + ListData& m_pData; cocos2d::CCLabelBMFont** m_pLabels = nullptr; - unsigned int m_uMaxLength = 1; - unsigned int m_uLength = 0; - unsigned int m_uOffset = 0; - cocos2d::CCMenu* m_pMenu = nullptr; - bool m_bEntered = false; - protected: - HorizontalList() = default; + HorizontalList(ListData& data) : m_pData{ data } {} + virtual ~HorizontalList() { delete[] m_pLabels; } + + virtual bool init(); inline void getLength() { - m_uLength = m_vEntries.size() - m_uOffset < m_uMaxLength ? - (m_vEntries.size() - m_uOffset) - : m_uMaxLength; + m_pData.m_uLength = m_pData.m_vEntries.size() - + m_pData.m_uOffset < m_pData.m_uMaxLength ? + (m_pData.m_vEntries.size() - m_pData.m_uOffset) + : m_pData.m_uMaxLength; } inline void toggle(std::vector btns, bool enable) { for (auto btn : btns) { @@ -33,60 +42,40 @@ class HorizontalList : public cocos2d::CCNode { btn->setEnabled(enable); } } + virtual void navigate(cocos2d::CCObject* btn); public: - virtual void navigate(cocos2d::CCObject* btn); + static HorizontalList* create(ListData& data); virtual void updateList(); - - virtual void enter(LoaderLayer* parent); - inline void exit() { - this->removeAllChildren(); - m_pMenu = nullptr; - m_bEntered = false; - } - - HorizontalList(const char* title); - - virtual bool load(tinyxml2::XMLDocument* file); - virtual bool save(tinyxml2::XMLDocument* file); - - void setEntries(const std::vector& vec); - virtual void setOffset(unsigned int offset); - virtual unsigned int ifNotFound(const std::vector& other, bool add); - - const inline unsigned int getIndex() { return m_uOffset; }; - const inline std::vector& getEntries() { return m_vEntries; }; + virtual void setPosition(float x, float y); }; class VerticalList : public HorizontalList { -protected: - unsigned int m_uIndex = 0; VerticalList* m_pTarget; protected: + VerticalList(ListData& data) : HorizontalList(data) {} + + virtual bool init(); + virtual void navigate(cocos2d::CCObject* btn) override; void swap(cocos2d::CCObject* btn); void move(cocos2d::CCObject*); void updateLabels(); void updateSelector(); + +public: + static VerticalList* create(ListData& data); + virtual inline void updateList() override { updateLabels(); updateSelector(); } + virtual void setPosition(float x, float y); -public: - virtual void enter(LoaderLayer* parent) override; - - VerticalList(const char* title, unsigned int length, VerticalList* target); - - virtual bool load(tinyxml2::XMLDocument* file) override; - virtual bool save(tinyxml2::XMLDocument* file) override; - - virtual void setOffset(unsigned int offset) override; - - virtual unsigned int ifNotFound(const std::vector& other, bool add) override; + void setTarget(VerticalList* target) { m_pTarget = target; } }; #endif \ No newline at end of file diff --git a/src/logic/nodes/LoaderManager.cpp b/src/logic/nodes/LoaderManager.cpp new file mode 100644 index 0000000..ee75ddd --- /dev/null +++ b/src/logic/nodes/LoaderManager.cpp @@ -0,0 +1,309 @@ +#include "pch.h" +#include "LoaderManager.h" + +using namespace cocos2d; + +#define ALL "All" +#define APPLIED "Applied" +#define QUALITY "Quality" + +bool LoaderManager::init() { + m_sFileName = "CCLoaderManager.dat"; + + m_dAll = { ALL, 10, &m_dApplied }; + m_dApplied = { APPLIED, 10, &m_dAll }; + m_dQuality = { QUALITY, 1, nullptr }; + + this->setup(); + + return true; +} + +void LoaderManager::encodeListTo(DS_Dictionary* data, const ListData& list) { + if (!data->stepIntoSubDictWithKey(list.m_sTitle)) { + data->setSubDictForKey(list.m_sTitle); + data->stepIntoSubDictWithKey(list.m_sTitle); + } + data->setStringArrayForKey("entries", list.m_vEntries); + data->setIntegerForKey("offset", list.m_uOffset); + data->setIntegerForKey("index", list.m_uIndex); + data->stepOutOfSubDict(); +} + +bool LoaderManager::loadListFrom(DS_Dictionary* data, ListData& list) { + if (!data->stepIntoSubDictWithKey(list.m_sTitle)) { + return false; + } + list.m_vEntries = data->getStringArrayForKey("entries"); + list.m_uOffset = data->getIntegerForKey("offset"); + list.m_uIndex = data->getIntegerForKey("index"); + //handle error checking in GUI class. + + data->stepOutOfSubDict(); +} + +void LoaderManager::encodeDataTo(DS_Dictionary* data) { + data->setStringForKey("version", VERSION); + + this->encodeListTo(data, m_dAll); + this->encodeListTo(data, m_dApplied); + this->encodeListTo(data, m_dQuality); + + data->setBoolForKey("reloadSFX", m_bReloadSFX); + data->setBoolForKey("reloadMusic", m_bReloadMusic); + data->setBoolForKey("checkPlists", m_bCheckPlists); + data->setBoolForKey("checkQuality", m_bCheckQuality); +} + +void LoaderManager::dataLoaded(DS_Dictionary* data) { + if (data->getStringForKey("version") != VERSION || + !this->loadListFrom(data, m_dAll) || + !this->loadListFrom(data, m_dApplied) || + !this->loadListFrom(data, m_dQuality)) { + this->firstLoad(); + return; + } + + m_bReloadSFX = data->getBoolForKey("reloadSFX"); + m_bReloadMusic = data->getBoolForKey("reloadMusic"); + m_bCheckPlists = data->getBoolForKey("checkPlists"); + m_bCheckQuality = data->getBoolForKey("checkQuality"); +} + +void LoaderManager::firstLoad() { + this->updatePacks(false); + m_dQuality.m_vEntries = { "Low", "Medium", "High" }; + m_dQuality.m_uOffset = 2; + + m_bReloadSFX = true; + m_bReloadMusic = true; + m_bCheckPlists = true; + m_bCheckQuality = true; +} + +void LoaderManager::syncVectors(const std::vector& other, unsigned int& added, unsigned int& removed) { + std::vector old = m_dAll.m_vEntries; + old.insert(old.end(), m_dApplied.m_vEntries.begin(), m_dApplied.m_vEntries.end()); + + //add new packs not found in old ones + for (unsigned int i = 0; i < other.size(); ++i) { + if (std::find(old.begin(), old.end(), other[i]) == old.end()) { + m_dAll.m_vEntries.insert(m_dAll.m_vEntries.begin(), other[i]); + ++added; + } + } + + //remove packs not found in new packs + for (unsigned int i = 0; i < old.size(); ++i) { + if (std::find(other.begin(), other.end(), old[i]) == other.end()) { + auto index = std::find(m_dAll.m_vEntries.begin(), m_dAll.m_vEntries.end(), old[i]); + if (index != m_dAll.m_vEntries.end()) { + m_dAll.m_vEntries.erase(index); + } + else { + index = std::find(m_dApplied.m_vEntries.begin(), m_dApplied.m_vEntries.end(), old[i]); + m_dApplied.m_vEntries.erase(index); + } + + //move to the start of the list, im too lazy to do calculation + m_dAll.m_uIndex = 0; + m_dAll.m_uOffset = 0; + ++removed; + } + } +} + +bool LoaderManager::checkPlists() { + using namespace std::filesystem; + + std::vector plists = {}; + + /*checks for all plists in applied pack folders. then looks for pngs + * that don't have corresponding plists, and sees if it's in the plists vector. + * if so, and if the plist is at a higher index than the png, warn. + * does not check for if plists are standalone; that is slower to do, and + * a normal texture pack should always have a corresponding png for a modded + * plist. otherwise it would always mess up lol + */ + for (auto packName : m_dApplied.m_vEntries) { + path pack = current_path() / "packs" / packName; + if (exists(pack)) { + for (directory_entry file : directory_iterator{ pack }) { + if (file.path().extension() == ".plist" || + file.path().extension() == ".fnt") { + plists.push_back(file.path()); + } + } + } + } + for (unsigned int i = 0; i < m_dApplied.m_vEntries.size(); ++i) { + path pack = current_path() / "packs" / m_dApplied.m_vEntries[i]; + if (exists(pack)) { + for (directory_entry file : directory_iterator{ pack }) { + if (file.path().extension() == ".png") { + if (!exists(file.path().stem().replace_extension(".plist")) && + !exists(file.path().stem().replace_extension(".fnt"))) { + auto index = std::find_if(plists.begin(), plists.end(), [file](path x) { + return x.stem() == file.path().stem(); + }); + if (index != plists.end()) { + if (std::find(m_dApplied.m_vEntries.begin(), + m_dApplied.m_vEntries.end(), + plists[index - plists.begin()].parent_path().filename().string()) + - m_dApplied.m_vEntries.begin() > i) { + return false; + } + } + } + + } + } + } + } + return true; +} + +bool LoaderManager::checkQuality() { + using namespace std::filesystem; + + /*imo an invalid pack is one that has textures that have uhd variants, + * that don't align with your current quality. if it just has like music + * or textures that dont have uhd variants, i shouldn't warn you cuz then + * it'd warn you like everytime lol + */ + bool valid = true; + std::vector pngs = {}; + path defaults = current_path() / "Resources"; + for (auto file : directory_iterator{ defaults }) { + if (file.path().extension() == ".png") { + auto filename = file.path().stem().string(); + if (filename.substr(filename.size() - 3) == "uhd") { + //check this pointer arithmetic, idk if 5 is correct + //trying to remove uhd thing + pngs.push_back(filename.substr(0, filename.size() - 4)); + } + } + } + for (auto packName : m_dApplied.m_vEntries) { + path pack = current_path() / "packs" / packName; + if (exists(pack)) { + for (auto file : directory_iterator{ pack }) { + if (file.path().extension() == ".png") { + auto filename = file.path().stem().string(); + if (std::find_if(pngs.begin(), pngs.end(), [filename](std::string x) { + return x == filename.substr(0, x.size()); + }) != pngs.end()) { + switch (m_dQuality.m_uOffset) { + case 0: + if (filename.substr(filename.size() - 2) != "hd") return true; + else valid = false; + break; + case 1: + if (filename.substr(filename.size() - 3) == "-hd") return true; + else valid = false; + break; + case 2: + if (filename.substr(filename.size() - 4) == "-uhd") return true; + else valid = false; + break; + } + } + } + } + } + } + + return valid; +} + +LoaderManager* LoaderManager::sharedState() { + if (!s_sharedLoaderManager) { + s_sharedLoaderManager = new LoaderManager(); + s_sharedLoaderManager->init(); + } + + return s_sharedLoaderManager; +} + +std::string LoaderManager::updatePacks(bool generate) { + using namespace std::filesystem; + + std::vector packsList = {}; + + /*all characters allowed by stock bigFont.fnt and goldFont.fnt. + * excludes '\', '/', ':', '*', '?', '"', '<', '>', and '|' since windows + * folders can't have those symbols, and '•' since it acts weird and i can't + * be bothered lol + */ + constexpr std::string_view filter = " !#$%&'()+,-.0123456789;=@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{}~"; + unsigned int invalid = 0; + + Log::info("Searching for packs."); + path packs = current_path() / "packs"; + if (exists(packs)) { + if (is_directory(packs)) { + Log::info("Packs directory found. Iterating."); + for (directory_entry pack : directory_iterator{ packs }) { + if (is_directory(pack)) { + bool valid = true; + for (auto c : pack.path().filename().u8string()) { + if (filter.find(c) == filter.npos) { + valid = false; + break; + } + } + + if (valid) + packsList.push_back(pack.path().filename().string()); + else + ++invalid; + } + } + + Log::info(packsList.size(), " packs found."); + } + else + MessageBox(0, "ERROR: packs is an existing file.\n please remove it to use textureldr.", "textureldr", MB_OK | MB_ICONERROR); + } + else { + Log::error("No packs directory found. Creating new directory."); + create_directories(packs); + } + + unsigned int added = 0; + unsigned int removed = 0; + + if (!(m_dAll.m_vEntries.empty() && m_dApplied.m_vEntries.empty())) { + this->syncVectors(packsList, added, removed); + } + else { + m_dAll.m_vEntries = packsList; + added = packsList.size(); + } + + if (generate) { + std::stringstream text; + if (added != 0 || removed != 0) { + text << "" << added << " " << ((added == 1) ? "pack" : "packs") << " added.\n"; + //for some silly reason, color markers don't work directly after a newline! + //@robtop fix??? + text << " " << removed << " " << ((removed == 1) ? "pack" : "packs") << " removed.\n"; + } + else { + text << "Nothing changed!\n"; + } + + if (invalid > 0) { + if (invalid == 1) { + text << "1 pack had an invalid name, and was ignored.\n"; + } + else { + text << invalid << " packs had invalid names, and were ignored.\n"; + } + } + return text.str(); + } + else { + return ""; + } +} \ No newline at end of file diff --git a/src/logic/nodes/LoaderManager.h b/src/logic/nodes/LoaderManager.h new file mode 100644 index 0000000..5364c97 --- /dev/null +++ b/src/logic/nodes/LoaderManager.h @@ -0,0 +1,40 @@ +#ifndef __LOADERMANAGER_H__ +#define __LOADERMANAGER_H__ + +#include "pch.h" +#include "List.h" + +class LoaderManager : public gd::GManager { +protected: + static inline LoaderManager* s_sharedLoaderManager = nullptr; + +public: + ListData m_dAll; + ListData m_dApplied; + ListData m_dQuality; + bool m_bReloadSFX; + bool m_bReloadMusic; + bool m_bCheckPlists; + bool m_bCheckQuality; + +protected: + virtual bool init(); + + virtual void encodeDataTo(DS_Dictionary* data); + virtual void dataLoaded(DS_Dictionary* data); + virtual void firstLoad(); + + void syncVectors(const std::vector& other, unsigned int& added, unsigned int& removed); + + inline void encodeListTo(DS_Dictionary* data, const ListData& list); + inline bool loadListFrom(DS_Dictionary* data, ListData& list); + +public: + static LoaderManager* sharedState(); + + std::string updatePacks(bool generate); + bool checkPlists(); + bool checkQuality(); +}; + +#endif \ No newline at end of file diff --git a/src/memory/Hooks.h b/src/memory/Hooks.h index 71ef439..5308d30 100644 --- a/src/memory/Hooks.h +++ b/src/memory/Hooks.h @@ -3,6 +3,7 @@ #include "pch.h" +#include "../logic/nodes/LoaderManager.h" #include "../logic/layers/LoaderLayer.h" namespace addrs { @@ -10,7 +11,7 @@ namespace addrs { inline auto pSpriteSize = reinterpret_cast(gd::base + 0x190F01); inline auto ppCallback = reinterpret_cast(gd::base + 0x190F13); inline auto pFolderBtn = reinterpret_cast(gd::base + 0x297B34); - inline auto pNewCallback = enter; + inline auto pNewCallback = LoaderLayer::scene; } namespace gates { @@ -23,6 +24,9 @@ namespace gates { namespace hooks { void __fastcall LoadingLayer_loadingFinished(gd::LoadingLayer* This) { This->setWillFadeIn(false); + if (LoaderManager::sharedState()->m_bReloadSFX) { + gd::FMODAudioEngine::sharedEngine()->reloadEffects(); + } return gates::LoadingLayer_loadingFinished(This); } @@ -37,21 +41,22 @@ namespace hooks { gates::GameManager_dataLoaded(This, DS_Dictionary); //add all of 'em back lol fileUtils->removeAllPaths(); - for (auto i : LoaderLayer::getApplied()) { + for (auto i : LoaderManager::sharedState()->m_dApplied.m_vEntries) { gates::CCFileUtils_addSearchPath(fileUtils, ("packs/" + i).c_str()); } gates::CCFileUtils_addSearchPath(fileUtils, "Resources"); } void __fastcall AppDelegate_trySaveGame(cocos2d::CCObject* This) { - if (!LoaderLayer::save()) - Log::error("Could not save savefile."); + LoaderManager::sharedState()->save(); return gates::AppDelegate_trySaveGame(This); } void __fastcall CCFileUtils_addSearchPath(cocos2d::CCFileUtils* This, void*, const char* path) { - gd::MenuLayer::fadeInMusic(" "); - for (auto i : LoaderLayer::getApplied()) { + if (LoaderManager::sharedState()->m_bReloadMusic) { + gd::MenuLayer::fadeInMusic(" "); + } + for (auto i : LoaderManager::sharedState()->m_dApplied.m_vEntries) { gates::CCFileUtils_addSearchPath(This, ("packs/" + i).c_str()); } return gates::CCFileUtils_addSearchPath(This, path); diff --git a/src/pch.h b/src/pch.h index 78f5a0b..708004a 100644 --- a/src/pch.h +++ b/src/pch.h @@ -26,6 +26,11 @@ //game / engine headers #include +#include + #include +//version string +#define VERSION "v2.0a" + #endif //PCH_H diff --git a/src/textureldr.vcxproj b/src/textureldr.vcxproj index cee53c6..0939122 100644 --- a/src/textureldr.vcxproj +++ b/src/textureldr.vcxproj @@ -64,13 +64,13 @@ Use pch.h stdcpp17 - $(SolutionDir)include\cocos2dx\kazmath\include;$(SolutionDir)include\cocos2dx\platform\third_party\win32\OGLES;$(SolutionDir)include\cocos2dx\platform\third_party\win32\pthread;$(SolutionDir)include\cocos2dx\platform\third_party\win32\libwebp;$(SolutionDir)include\cocos2dx\platform\third_party\win32\libtiff;$(SolutionDir)include\cocos2dx\platform\third_party\win32\libjpeg;$(SolutionDir)include\cocos2dx\platform\third_party\win32\libpng;$(SolutionDir)include\cocos2dx\platform\third_party\win32\zlib;$(SolutionDir)include\cocos2dx\platform\third_party\win32\iconv;$(SolutionDir)include\cocos2dx\platform\win32;$(SolutionDir)include\cocos2dx\;$(SolutionDir)include\cocos2dx\include;$(SolutionDir)include\gd\include;$(SolutionDir)include\gd;%(AdditionalIncludeDirectories) + $(SolutionDir)include\cocos2dx\kazmath\include;$(SolutionDir)include\cocos2dx\platform\third_party\win32\OGLES;$(SolutionDir)include\cocos2dx\platform\third_party\win32\pthread;$(SolutionDir)include\cocos2dx\platform\third_party\win32\libwebp;$(SolutionDir)include\cocos2dx\platform\third_party\win32\libtiff;$(SolutionDir)include\cocos2dx\platform\third_party\win32\libjpeg;$(SolutionDir)include\cocos2dx\platform\third_party\win32\libpng;$(SolutionDir)include\cocos2dx\platform\third_party\win32\zlib;$(SolutionDir)include\cocos2dx\platform\third_party\win32\iconv;$(SolutionDir)include\cocos2dx\platform\win32;$(SolutionDir)include\cocos2dx\;$(SolutionDir)include\cocos2dx\include;$(SolutionDir)include\gd\include;$(SolutionDir)include\gd;$(SolutionDir)include\extensions;%(AdditionalIncludeDirectories) Windows true false - $(SolutionDir)include\cocos2dx\libcocos2d.lib;%(AdditionalDependencies) + $(SolutionDir)include\cocos2dx\libcocos2d.lib;$(SolutionDir)include\extensions\libExtensions.lib;%(AdditionalDependencies) @@ -84,7 +84,7 @@ Use pch.h stdcpp17 - $(SolutionDir)include\cocos2dx\kazmath\include;$(SolutionDir)include\cocos2dx\platform\third_party\win32\OGLES;$(SolutionDir)include\cocos2dx\platform\third_party\win32\pthread;$(SolutionDir)include\cocos2dx\platform\third_party\win32\libwebp;$(SolutionDir)include\cocos2dx\platform\third_party\win32\libtiff;$(SolutionDir)include\cocos2dx\platform\third_party\win32\libjpeg;$(SolutionDir)include\cocos2dx\platform\third_party\win32\libpng;$(SolutionDir)include\cocos2dx\platform\third_party\win32\zlib;$(SolutionDir)include\cocos2dx\platform\third_party\win32\iconv;$(SolutionDir)include\cocos2dx\platform\win32;$(SolutionDir)include\cocos2dx\;$(SolutionDir)include\cocos2dx\include;$(SolutionDir)include\gd\include;$(SolutionDir)include\gd;%(AdditionalIncludeDirectories) + $(SolutionDir)include\cocos2dx\kazmath\include;$(SolutionDir)include\cocos2dx\platform\third_party\win32\OGLES;$(SolutionDir)include\cocos2dx\platform\third_party\win32\pthread;$(SolutionDir)include\cocos2dx\platform\third_party\win32\libwebp;$(SolutionDir)include\cocos2dx\platform\third_party\win32\libtiff;$(SolutionDir)include\cocos2dx\platform\third_party\win32\libjpeg;$(SolutionDir)include\cocos2dx\platform\third_party\win32\libpng;$(SolutionDir)include\cocos2dx\platform\third_party\win32\zlib;$(SolutionDir)include\cocos2dx\platform\third_party\win32\iconv;$(SolutionDir)include\cocos2dx\platform\win32;$(SolutionDir)include\cocos2dx\;$(SolutionDir)include\cocos2dx\include;$(SolutionDir)include\gd\include;$(SolutionDir)include\gd;$(SolutionDir)include\extensions;%(AdditionalIncludeDirectories) Windows @@ -92,7 +92,7 @@ true true false - $(SolutionDir)include\cocos2dx\libcocos2d.lib;%(AdditionalDependencies) + $(SolutionDir)include\cocos2dx\libcocos2d.lib;$(SolutionDir)include\extensions\libExtensions.lib;%(AdditionalDependencies) @@ -204,6 +204,9 @@ + + + @@ -268,7 +271,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -276,14 +316,19 @@ + + - + + + + @@ -291,15 +336,17 @@ - + + + + Create Create - diff --git a/src/textureldr.vcxproj.filters b/src/textureldr.vcxproj.filters index 1c86d72..db21ec8 100644 --- a/src/textureldr.vcxproj.filters +++ b/src/textureldr.vcxproj.filters @@ -154,6 +154,42 @@ {0df54374-65c9-4b8f-a5c1-0bb8ba12ba5a} + + {e7c63b72-db53-4059-bb0f-48144ee40e12} + + + {78408c16-9ca2-4164-99cd-64163067da3e} + + + {c9388b38-88b8-43ff-ab35-0aa893049836} + + + {b9eccd79-1668-445c-8e53-c8b897df79ef} + + + {8114714a-6437-494c-82d0-9f2a517ad547} + + + {5558773b-cdce-43d9-9f7f-8341b8d3b0b1} + + + {723cd6c5-0301-4545-a0d9-fc12b3ca80c1} + + + {d4e0d9f1-b13f-4514-9ae7-518d6a689489} + + + {8661d32a-0478-41a4-93b8-0eec95369e55} + + + {8f9ac076-7c5a-45f2-840f-75776153d7a4} + + + {15cd10d1-f1b6-4e8d-897a-ccd44687fcec} + + + {c4eb58d2-9aea-4720-90fe-08d87f454cfa} + @@ -690,9 +726,6 @@ Header Files - - Source Files\logic\layers - Source Files @@ -729,6 +762,144 @@ Header Files\include\gd\manager_nodes + + Header Files\include\gd\menu_nodes + + + Source Files\logic\nodes + + + Header Files\include\cocos2d\robtop\xml + + + Header Files\include\cocos2d\robtop\xml + + + Header Files\include\cocos2d\robtop\xml + + + Header Files\include\gd\audio_nodes + + + Header Files\include\gd\manager_nodes + + + Header Files\include\extensions\AssetsManager + + + Header Files\include\extensions\GUI\CCControlExtension + + + Header Files\include\extensions\GUI\CCControlExtension + + + Header Files\include\extensions\GUI\CCControlExtension + + + Header Files\include\extensions\GUI\CCControlExtension + + + Header Files\include\extensions\GUI\CCControlExtension + + + Header Files\include\extensions\GUI\CCControlExtension + + + Header Files\include\extensions\GUI\CCControlExtension + + + Header Files\include\extensions\GUI\CCControlExtension + + + Header Files\include\extensions\GUI\CCControlExtension + + + Header Files\include\extensions\GUI\CCControlExtension + + + Header Files\include\extensions\GUI\CCControlExtension + + + Header Files\include\extensions\GUI\CCControlExtension + + + Header Files\include\extensions\GUI\CCControlExtension + + + Header Files\include\extensions\GUI\CCEditBox + + + Header Files\include\extensions\GUI\CCEditBox + + + Header Files\include\extensions\GUI\CCEditBox + + + Header Files\include\extensions\GUI\CCEditBox + + + Header Files\include\extensions\GUI\CCEditBox + + + Header Files\include\extensions\GUI\CCEditBox + + + Header Files\include\extensions\GUI\CCEditBox + + + Header Files\include\extensions\GUI\CCEditBox + + + Header Files\include\extensions\GUI\CCScrollView + + + Header Files\include\extensions\GUI\CCScrollView + + + Header Files\include\extensions\GUI\CCScrollView + + + Header Files\include\extensions\GUI\CCScrollView + + + Header Files\include\extensions\LocalStorage + + + Header Files\include\extensions\network + + + Header Files\include\extensions\network + + + Header Files\include\extensions\network + + + Header Files\include\extensions\network + + + Header Files\include\extensions + + + Header Files\include\extensions + + + Header Files\include\extensions\physics_nodes + + + Header Files\include\extensions\physics_nodes + + + Header Files\include\gd\include + + + Source Files\logic\layers\more + + + Source Files\logic\layers\more + + + Source Files\logic\layers\more + @@ -743,14 +914,20 @@ Source Files\logic\nodes - - Source Files\logic\layers + + Source Files\logic\nodes + + + Source Files\logic\layers\more + + + Source Files\logic\layers\more + + + Source Files\logic\layers\more - - misc - misc diff --git a/todo.txt b/todo.txt deleted file mode 100644 index 80f284b..0000000 --- a/todo.txt +++ /dev/null @@ -1,17 +0,0 @@ -TODO: - -add a background or something lol - -find out why CCSprite::setColor ends up with cocos not being able to draw the node correctly - -iterate through directories to determine which detail level each pack supports - -add warning for packs that don't have .fnt/.plist files for corresponding .pngs, to warn of potential garbled packs - -hook CCKeyboardDispatcher::dispatchKeyboardMSG for shortcut - -rewrite with cocos headers at some point, makes things much easier - -add safeguards for invalid folder names (since GD only allows english characters, and fmod crashes with non-english folder names sometimes) - -ButtonSprite is stupid because it's hardcoded to resize to size 1.0f. bruh. fix that or inherit from CCMenuItem and do yourself \ No newline at end of file