RUStateTransition.cpp 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. //
  2. // RUStateTransition.cpp
  3. // RoleTool
  4. //
  5. // Created by 徐炼新 on 2023/4/19.
  6. //
  7. #include "RUStateTransition.h"
  8. #include "RUState.h"
  9. #include <stdio.h>
  10. NS_RU_BEGIN
  11. StateTransition* StateTransition::create(StateMachine* machine,
  12. const FsmTransition* transition,
  13. std::function<void(StateTransition*, std::function<void(void)>, bool)> cf) {
  14. auto st = new StateTransition();
  15. st->autorelease();
  16. st->retain();
  17. st->_machine = machine;
  18. st->_transition = transition;
  19. st->_cf = cf;
  20. return st;
  21. }
  22. void StateTransition::setEvent(const std::string& eventName,
  23. const std::map<std::string, std::string>& eventParams,
  24. std::function<void(void)> handleEventCb) {
  25. _eventName = eventName;
  26. _eventParams = eventParams;
  27. _cf4Event = handleEventCb;
  28. }
  29. void StateTransition::interrupt() {
  30. // 打断当前的转移
  31. _bIsInterrupted = true;
  32. }
  33. void StateTransition::execute() {
  34. // 事件结束的回调处理
  35. auto execHandleEventCb = [=](void){
  36. if (_cf) {
  37. auto cf = _cf;
  38. _cf = nullptr;
  39. cf(this, _cf4Event, _bIsInterrupted);
  40. }
  41. };
  42. /***
  43. 执行顺序
  44. 1.老状态exit
  45. 2.老状态before_switch_actions动作
  46. 3.设置新状态
  47. 4.新状态after_switch_actions动作
  48. 5.新状态entry
  49. 6.事件结束回调
  50. ***/
  51. State* fromState = _machine->getState(_transition->fromState);
  52. State* toState = _machine->getState(_transition->toState);
  53. const std::vector<StateActInfo>& beforeSwitchActInfos = _transition->beforeSwitchActInfos;
  54. const std::vector<StateActInfo>& afterSwitchActInfos = _transition->afterSwitchActInfos;
  55. auto execEntry = [=](void){
  56. if (_bIsInterrupted) {
  57. execHandleEventCb();
  58. } else {
  59. _machine->setRunningStateName(_transition->toState);
  60. retain();
  61. toState->entry([=](){
  62. execHandleEventCb();
  63. release();
  64. });
  65. }
  66. };
  67. auto execAfterSwitchAct = [=](void) {
  68. if (_bIsInterrupted) {
  69. execHandleEventCb();
  70. } else {
  71. StateActInfo evt;
  72. evt.actType = _eventName;
  73. evt.actParams = _eventParams;
  74. toState->afterSwitch(afterSwitchActInfos, evt, execEntry);
  75. }
  76. };
  77. auto execBeforeSwitchAct = [=](void) {
  78. if (_bIsInterrupted) {
  79. execHandleEventCb();
  80. } else {
  81. StateActInfo evt;
  82. evt.actType = _eventName;
  83. evt.actParams = _eventParams;
  84. fromState->beforeSwitch(beforeSwitchActInfos, evt, execAfterSwitchAct);
  85. }
  86. };
  87. fromState->exit(execBeforeSwitchAct);
  88. }
  89. NS_RU_END