CCMenu.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. /****************************************************************************
  2. Copyright (c) 2008-2010 Ricardo Quesada
  3. Copyright (c) 2010-2012 cocos2d-x.org
  4. Copyright (c) 2013-2016 Chukong Technologies Inc.
  5. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  6. http://www.cocos2d-x.org
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in
  14. all copies or substantial portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. THE SOFTWARE.
  22. ****************************************************************************/
  23. #include "2d/CCMenu.h"
  24. #include "2d/CCCamera.h"
  25. #include "base/CCDirector.h"
  26. #include "base/CCTouch.h"
  27. #include "base/CCEventListenerTouch.h"
  28. #include "base/CCEventDispatcher.h"
  29. #include "base/ccUTF8.h"
  30. #include "platform/CCStdC.h"
  31. #include <vector>
  32. using namespace std;
  33. NS_CC_BEGIN
  34. enum
  35. {
  36. kDefaultPadding = 5,
  37. };
  38. //
  39. //CCMenu
  40. //
  41. Menu::~Menu()
  42. {
  43. CCLOGINFO("In the destructor of Menu. %p", this);
  44. }
  45. Menu* Menu::create()
  46. {
  47. return Menu::create(nullptr, nullptr);
  48. }
  49. #if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
  50. Menu * Menu::variadicCreate(MenuItem* item, ...)
  51. {
  52. va_list args;
  53. va_start(args,item);
  54. Menu *ret = Menu::createWithItems(item, args);
  55. va_end(args);
  56. return ret;
  57. }
  58. #else
  59. Menu * Menu::create(MenuItem* item, ...)
  60. {
  61. va_list args;
  62. va_start(args,item);
  63. Menu *ret = Menu::createWithItems(item, args);
  64. va_end(args);
  65. return ret;
  66. }
  67. #endif
  68. Menu* Menu::createWithArray(const Vector<MenuItem*>& arrayOfItems)
  69. {
  70. auto ret = new (std::nothrow) Menu();
  71. if (ret && ret->initWithArray(arrayOfItems))
  72. {
  73. ret->autorelease();
  74. }
  75. else
  76. {
  77. CC_SAFE_DELETE(ret);
  78. }
  79. return ret;
  80. }
  81. Menu* Menu::createWithItems(MenuItem* item, va_list args)
  82. {
  83. Vector<MenuItem*> items;
  84. if( item )
  85. {
  86. items.pushBack(item);
  87. MenuItem *i = va_arg(args, MenuItem*);
  88. while(i)
  89. {
  90. items.pushBack(i);
  91. i = va_arg(args, MenuItem*);
  92. }
  93. }
  94. return Menu::createWithArray(items);
  95. }
  96. Menu* Menu::createWithItem(MenuItem* item)
  97. {
  98. return Menu::create(item, nullptr);
  99. }
  100. bool Menu::init()
  101. {
  102. return initWithArray(Vector<MenuItem*>());
  103. }
  104. bool Menu::initWithArray(const Vector<MenuItem*>& arrayOfItems)
  105. {
  106. if (Layer::init())
  107. {
  108. _enabled = true;
  109. // menu in the center of the screen
  110. Size s = Director::getInstance()->getWinSize();
  111. this->setIgnoreAnchorPointForPosition(true);
  112. setAnchorPoint(Vec2(0.5f, 0.5f));
  113. this->setContentSize(s);
  114. setPosition(s.width/2, s.height/2);
  115. int z=0;
  116. for (auto& item : arrayOfItems)
  117. {
  118. this->addChild(item, z);
  119. z++;
  120. }
  121. _selectedItem = nullptr;
  122. _state = Menu::State::WAITING;
  123. // enable cascade color and opacity on menus
  124. setCascadeColorEnabled(true);
  125. setCascadeOpacityEnabled(true);
  126. auto touchListener = EventListenerTouchOneByOne::create();
  127. touchListener->setSwallowTouches(true);
  128. touchListener->onTouchBegan = CC_CALLBACK_2(Menu::onTouchBegan, this);
  129. touchListener->onTouchMoved = CC_CALLBACK_2(Menu::onTouchMoved, this);
  130. touchListener->onTouchEnded = CC_CALLBACK_2(Menu::onTouchEnded, this);
  131. touchListener->onTouchCancelled = CC_CALLBACK_2(Menu::onTouchCancelled, this);
  132. _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this);
  133. return true;
  134. }
  135. return false;
  136. }
  137. /*
  138. * override add:
  139. */
  140. void Menu::addChild(Node * child)
  141. {
  142. Layer::addChild(child);
  143. }
  144. void Menu::addChild(Node * child, int zOrder)
  145. {
  146. Layer::addChild(child, zOrder);
  147. }
  148. void Menu::addChild(Node * child, int zOrder, int tag)
  149. {
  150. CCASSERT( dynamic_cast<MenuItem*>(child) != nullptr, "Menu only supports MenuItem objects as children");
  151. Layer::addChild(child, zOrder, tag);
  152. }
  153. void Menu::addChild(Node * child, int zOrder, const std::string &name)
  154. {
  155. CCASSERT( dynamic_cast<MenuItem*>(child) != nullptr, "Menu only supports MenuItem objects as children");
  156. Layer::addChild(child, zOrder, name);
  157. }
  158. void Menu::onEnter()
  159. {
  160. #if CC_ENABLE_SCRIPT_BINDING
  161. if (_scriptType == kScriptTypeJavascript)
  162. {
  163. if (ScriptEngineManager::sendNodeEventToJSExtended(this, kNodeOnEnter))
  164. return;
  165. }
  166. #endif
  167. Layer::onEnter();
  168. }
  169. void Menu::onExit()
  170. {
  171. #if CC_ENABLE_SCRIPT_BINDING
  172. if (_scriptType == kScriptTypeJavascript)
  173. {
  174. if (ScriptEngineManager::sendNodeEventToJSExtended(this, kNodeOnExit))
  175. return;
  176. }
  177. #endif
  178. if (_state == Menu::State::TRACKING_TOUCH)
  179. {
  180. if (_selectedItem)
  181. {
  182. _selectedItem->unselected();
  183. _selectedItem = nullptr;
  184. }
  185. _state = Menu::State::WAITING;
  186. }
  187. Layer::onExit();
  188. }
  189. void Menu::removeChild(Node* child, bool cleanup)
  190. {
  191. CCASSERT(dynamic_cast<MenuItem*>(child) != nullptr, "Menu only supports MenuItem objects as children");
  192. if (_selectedItem == child)
  193. {
  194. _selectedItem = nullptr;
  195. }
  196. Node::removeChild(child, cleanup);
  197. }
  198. //Menu - Events
  199. bool Menu::onTouchBegan(Touch* touch, Event* /*event*/)
  200. {
  201. auto camera = Camera::getVisitingCamera();
  202. if (_state != Menu::State::WAITING || ! _visible || !_enabled || !camera)
  203. {
  204. return false;
  205. }
  206. for (Node *c = this->_parent; c != nullptr; c = c->getParent())
  207. {
  208. if (c->isVisible() == false)
  209. {
  210. return false;
  211. }
  212. }
  213. _selectedItem = this->getItemForTouch(touch, camera);
  214. if (_selectedItem)
  215. {
  216. _state = Menu::State::TRACKING_TOUCH;
  217. _selectedWithCamera = camera;
  218. _selectedItem->selected();
  219. return true;
  220. }
  221. return false;
  222. }
  223. void Menu::onTouchEnded(Touch* /*touch*/, Event* /*event*/)
  224. {
  225. CCASSERT(_state == Menu::State::TRACKING_TOUCH, "[Menu ccTouchEnded] -- invalid state");
  226. this->retain();
  227. if (_selectedItem)
  228. {
  229. _selectedItem->unselected();
  230. _selectedItem->activate();
  231. }
  232. _state = Menu::State::WAITING;
  233. _selectedWithCamera = nullptr;
  234. this->release();
  235. }
  236. void Menu::onTouchCancelled(Touch* /*touch*/, Event* /*event*/)
  237. {
  238. CCASSERT(_state == Menu::State::TRACKING_TOUCH, "[Menu ccTouchCancelled] -- invalid state");
  239. this->retain();
  240. if (_selectedItem)
  241. {
  242. _selectedItem->unselected();
  243. }
  244. _state = Menu::State::WAITING;
  245. this->release();
  246. }
  247. void Menu::onTouchMoved(Touch* touch, Event* /*event*/)
  248. {
  249. CCASSERT(_state == Menu::State::TRACKING_TOUCH, "[Menu ccTouchMoved] -- invalid state");
  250. MenuItem *currentItem = this->getItemForTouch(touch, _selectedWithCamera);
  251. if (currentItem != _selectedItem)
  252. {
  253. if (_selectedItem)
  254. {
  255. _selectedItem->unselected();
  256. }
  257. _selectedItem = currentItem;
  258. if (_selectedItem)
  259. {
  260. _selectedItem->selected();
  261. }
  262. }
  263. }
  264. //Menu - Alignment
  265. void Menu::alignItemsVertically()
  266. {
  267. this->alignItemsVerticallyWithPadding(kDefaultPadding);
  268. }
  269. void Menu::alignItemsVerticallyWithPadding(float padding)
  270. {
  271. float height = -padding;
  272. for(const auto &child : _children)
  273. height += child->getContentSize().height * child->getScaleY() + padding;
  274. float y = height / 2.0f;
  275. for(const auto &child : _children) {
  276. child->setPosition(0, y - child->getContentSize().height * child->getScaleY() / 2.0f);
  277. y -= child->getContentSize().height * child->getScaleY() + padding;
  278. }
  279. }
  280. void Menu::alignItemsHorizontally(void)
  281. {
  282. this->alignItemsHorizontallyWithPadding(kDefaultPadding);
  283. }
  284. void Menu::alignItemsHorizontallyWithPadding(float padding)
  285. {
  286. float width = -padding;
  287. for(const auto &child : _children)
  288. width += child->getContentSize().width * child->getScaleX() + padding;
  289. float x = -width / 2.0f;
  290. for(const auto &child : _children) {
  291. child->setPosition(x + child->getContentSize().width * child->getScaleX() / 2.0f, 0);
  292. x += child->getContentSize().width * child->getScaleX() + padding;
  293. }
  294. }
  295. void Menu::alignItemsInColumns(int columns, ...)
  296. {
  297. va_list args;
  298. va_start(args, columns);
  299. this->alignItemsInColumns(columns, args);
  300. va_end(args);
  301. }
  302. void Menu::alignItemsInColumns(int columns, va_list args)
  303. {
  304. CCASSERT(columns >= 0, "Columns must be >= 0");
  305. ValueVector rows;
  306. while (columns)
  307. {
  308. rows.push_back(Value(columns));
  309. columns = va_arg(args, int);
  310. }
  311. alignItemsInColumnsWithArray(rows);
  312. }
  313. void Menu::alignItemsInColumnsWithArray(const ValueVector& rows)
  314. {
  315. int height = -5;
  316. size_t row = 0;
  317. int rowHeight = 0;
  318. int columnsOccupied = 0;
  319. int rowColumns = 0;
  320. for(const auto &child : _children) {
  321. CCASSERT(row < rows.size(), "row should less than rows.size()!");
  322. rowColumns = rows[row].asInt();
  323. // can not have zero columns on a row
  324. CCASSERT(rowColumns, "rowColumns can't be 0.");
  325. float tmp = child->getContentSize().height;
  326. rowHeight = (unsigned int)((rowHeight >= tmp || isnan(tmp)) ? rowHeight : tmp);
  327. ++columnsOccupied;
  328. if (columnsOccupied >= rowColumns)
  329. {
  330. height += rowHeight + 5;
  331. columnsOccupied = 0;
  332. rowHeight = 0;
  333. ++row;
  334. }
  335. }
  336. // check if too many rows/columns for available menu items
  337. CCASSERT(! columnsOccupied, "columnsOccupied should be 0.");
  338. Size winSize = getContentSize();
  339. row = 0;
  340. rowHeight = 0;
  341. rowColumns = 0;
  342. float w = 0.0;
  343. float x = 0.0;
  344. float y = (float)(height / 2);
  345. for(const auto &child : _children) {
  346. if (rowColumns == 0)
  347. {
  348. rowColumns = rows[row].asInt();
  349. w = winSize.width / (1 + rowColumns);
  350. x = w;
  351. }
  352. float tmp = child->getContentSize().height;
  353. rowHeight = (unsigned int)((rowHeight >= tmp || isnan(tmp)) ? rowHeight : tmp);
  354. child->setPosition(x - winSize.width / 2,
  355. y - child->getContentSize().height / 2);
  356. x += w;
  357. ++columnsOccupied;
  358. if (columnsOccupied >= rowColumns)
  359. {
  360. y -= rowHeight + 5;
  361. columnsOccupied = 0;
  362. rowColumns = 0;
  363. rowHeight = 0;
  364. ++row;
  365. }
  366. }
  367. }
  368. void Menu::alignItemsInRows(int rows, ...)
  369. {
  370. va_list args;
  371. va_start(args, rows);
  372. this->alignItemsInRows(rows, args);
  373. va_end(args);
  374. }
  375. void Menu::alignItemsInRows(int rows, va_list args)
  376. {
  377. ValueVector array;
  378. while (rows)
  379. {
  380. array.push_back(Value(rows));
  381. rows = va_arg(args, int);
  382. }
  383. alignItemsInRowsWithArray(array);
  384. }
  385. void Menu::alignItemsInRowsWithArray(const ValueVector& columns)
  386. {
  387. vector<int> columnWidths;
  388. vector<int> columnHeights;
  389. int width = -10;
  390. int columnHeight = -5;
  391. size_t column = 0;
  392. int columnWidth = 0;
  393. int rowsOccupied = 0;
  394. int columnRows;
  395. for(const auto &child : _children) {
  396. // check if too many menu items for the amount of rows/columns
  397. CCASSERT(column < columns.size(), "column should be less than columns.size().");
  398. columnRows = columns[column].asInt();
  399. // can't have zero rows on a column
  400. CCASSERT(columnRows, "columnRows can't be 0.");
  401. // columnWidth = fmaxf(columnWidth, [item contentSize].width);
  402. float tmp = child->getContentSize().width;
  403. columnWidth = (unsigned int)((columnWidth >= tmp || isnan(tmp)) ? columnWidth : tmp);
  404. columnHeight += (int)(child->getContentSize().height + 5);
  405. ++rowsOccupied;
  406. if (rowsOccupied >= columnRows)
  407. {
  408. columnWidths.push_back(columnWidth);
  409. columnHeights.push_back(columnHeight);
  410. width += columnWidth + 10;
  411. rowsOccupied = 0;
  412. columnWidth = 0;
  413. columnHeight = -5;
  414. ++column;
  415. }
  416. }
  417. // check if too many rows/columns for available menu items.
  418. CCASSERT(! rowsOccupied, "rowsOccupied should be 0.");
  419. Size winSize = getContentSize();
  420. column = 0;
  421. columnWidth = 0;
  422. columnRows = 0;
  423. float x = (float)(-width / 2);
  424. float y = 0.0;
  425. for(const auto &child : _children) {
  426. if (columnRows == 0)
  427. {
  428. columnRows = columns[column].asInt();
  429. y = (float) columnHeights[column];
  430. }
  431. // columnWidth = fmaxf(columnWidth, [item contentSize].width);
  432. float tmp = child->getContentSize().width;
  433. columnWidth = (unsigned int)((columnWidth >= tmp || isnan(tmp)) ? columnWidth : tmp);
  434. child->setPosition(x + columnWidths[column] / 2,
  435. y - winSize.height / 2);
  436. y -= child->getContentSize().height + 10;
  437. ++rowsOccupied;
  438. if (rowsOccupied >= columnRows)
  439. {
  440. x += columnWidth + 5;
  441. rowsOccupied = 0;
  442. columnRows = 0;
  443. columnWidth = 0;
  444. ++column;
  445. }
  446. }
  447. }
  448. MenuItem* Menu::getItemForTouch(Touch *touch, const Camera *camera)
  449. {
  450. Vec2 touchLocation = touch->getLocation();
  451. for (const auto &item: _children)
  452. {
  453. MenuItem* child = dynamic_cast<MenuItem*>(item);
  454. if (nullptr == child || false == child->isVisible() || false == child->isEnabled())
  455. {
  456. continue;
  457. }
  458. Rect rect;
  459. rect.size = child->getContentSize();
  460. if (isScreenPointInRect(touchLocation, camera, child->getWorldToNodeTransform(), rect, nullptr))
  461. {
  462. return child;
  463. }
  464. }
  465. return nullptr;
  466. }
  467. void Menu::setOpacityModifyRGB(bool /*value*/)
  468. {}
  469. bool Menu::isOpacityModifyRGB() const
  470. {
  471. return false;
  472. }
  473. std::string Menu::getDescription() const
  474. {
  475. return StringUtils::format("<Menu | Tag = %d>", _tag);
  476. }
  477. NS_CC_END