public void Update() { if (!Enable || m_wasShutdown) { return; } // Do transition to another state if (CanEnterQueuedState()) { if (m_currentState != null && m_queuedState != null) { m_currentState.ExitState(this, QueuedStateId); } m_previousState = m_currentState; // Store prev state ... m_currentState = m_queuedState; // Set to next state ... m_queuedState = null; // Remove queued state ... m_currentState.EnterState(this, PreviousStateId, m_context); } // Clear queued states which cannot be entered ... else { m_queuedState = null; } // Update current state ... if (m_currentState != null) { m_currentState.UpdateState(this); } }
public IFsmState GetState(string name) { IFsmState state = null; m_StateDic.TryGetValue(name, out state); return(state); }
public virtual void Shutdown() { if (m_registeredStates == null || m_registeredStates.Count <= 0) { return; } if (m_currentState != null) { m_currentState.ExitState(this, m_emptyStateID); } foreach (KeyValuePair <StateKey, IFsmState <StateKey> > kvp in m_registeredStates) { IFsmState <StateKey> thisState = GetStateById(kvp.Key); if (thisState == null) { continue; } thisState.ShutdownState(this); } m_registeredStates.Clear(); m_registeredStates = null; m_wasShutdown = true; Enable = false; }
/// <summary> /// 解除注册状态 /// </summary> /// <param name="state"></param> public void UnSubscribeState(IFsmState state) { if (_stateInfo.ContainsKey(state)) _stateInfo.Remove(state); else Log.E("Not Exist State "); }
public void ChangeState(T stateKey) { m_CurState?.OnExit(); m_CurStateID = stateKey; m_CurState = m_StateDict[stateKey]; m_CurState.OnEnter(); }
public IFsm Optimize() { var newFsm = new Fsm(); var newStateByOldId = new IFsmState[_states.Count]; foreach (var st in _states) { if ((st.InTransitions.Count > 0 || st.OutTransitions.Count > 0) && !st.IsDeleted) { var newState = newFsm.CreateState(); newStateByOldId[st.Id] = newState; if (st.IsFinal) { newState.SetFinal(); } } } _transitions.Where(t => !t.IsDeleted) .Distinct() .ForEach(t => newFsm.CreateTransition(newStateByOldId[t.From.Id], newStateByOldId[t.To.Id], t.Condition)); if (this.InitialState != null) { newFsm.SetInitialState(newStateByOldId[this.InitialState.Id]); } return(newFsm); }
public FsmSystem(IFsmState defaultState) { _states = new Dictionary <string, IFsmState>(); _transitions = new List <FsmTransitionChain>(); NowState = defaultState; AddState(defaultState); }
public IFsmTransition CreateTransition(IFsmState from, IFsmState to, IFsmTransitionCondition Condition) { if (from.Fsm != this) { throw new ArgumentException(); } if (to.Fsm != this) { throw new ArgumentException(); } var fromState = _states[from.Id]; var toState = _states[to.Id]; if (fromState.IsDeleted || toState.IsDeleted) { throw new ArgumentException(); } var transition = new FsmTransition(this, fromState, toState, Condition); fromState.RegisterOutTransition(transition); toState.RegisterInTransition(transition); _transitions.Add(transition); return(transition); }
public void ChangeState <T>(object userData = null) where T : IFsmState { Type type = typeof(T); IFsmState state = null; var enumerator = m_StateDic.GetEnumerator(); while (enumerator.MoveNext()) { if (enumerator.Current.Value.GetType() == type) { state = enumerator.Current.Value; break; } } if (state != null) { if (CurrentState != null) { CurrentState.OnLeave(); } CurrentState = state; CurrentState.OnEnter(userData); } else { throw new DrbException("Fsm '{0}' not exists state '{1}'", Name, type.FullName); } }
/// <summary> /// 注册状态 /// </summary> /// <param name="state"></param> public void SubscribeState(IFsmState state) { if (!_stateInfo.ContainsKey(state)) _stateInfo.Add(state, new StateInfo(state)); else Log.E(" Have Exist State "); }
public void DestoryTransition(IFsmState trail) { var sameOne = _transitions.Find((t) => { return t.trail == trail; }); if (sameOne != null) _transitions.Remove(sameOne); else throw new Exception("The Trastion not Exist"); }
/// <summary> /// Executes the timer event on the corresponding state of the finite state machine. /// </summary> /// <param name="fsmState">Actual state of the finite state machine, the event should execute on.</param> public override void Execute(IFsmState fsmState) { if (fsmState == null) { throw new ArgumentNullException(@"fsmState"); } fsmState.OnTimerEvent(this.timerArgs); }
public CatFsm(IFsmState initState, IFsmState[] allStates) { _initState = initState; foreach (var s in allStates) { _fsmStates.Add(s.GetType(), s); } }
public void AddState(IFsmState state) { if (_states.ContainsKey(state.Name)) { throw new ArgumentException($"已存在状态:{state.Name}"); } _states.Add(state.Name, state); }
/// <summary> /// Creates a new Finite State Machine and changes the state to startState. /// </summary> /// <param name="context">Type</param> /// <param name="startState">Start State</param> public FiniteStateMachine(T context, IFsmState <T> startState) { this.Context = context; this.CurrentState = startState; startState.Machine = this; startState.Context = context; this.CurrentState.Begin(); stateDictionary.Add(startState.GetType(), startState); }
public void RegisterState(StateKey id, IFsmState <StateKey> state) { if (state == null || m_wasShutdown) { return; } m_registeredStates[id] = state; state.InitializeState(this); }
public void DisposeFsm() { m_CurStateFsm?.OnFinishState(); m_CurState = -1; m_CurStateFsm = null; m_FsmList = null; }
/// <summary> /// Creates an FSM. Takes an Owner and a state that should be assumed to be the default "empty" state. /// </summary> /// <param name="Owner"></param> /// <param name="emptyState">Note: this is the state transitioned from the first time you queue a state, and transitioned to when you shut down.</param> public Fsm(object Owner, StateKey emptyState) { Enable = true; this.m_owner = Owner; m_queuedState = null; m_currentState = null; m_previousState = null; m_registeredStates = new Dictionary <StateKey, IFsmState <StateKey> >(); m_emptyStateID = emptyState; }
/// <summary> /// hanges the active state to the given state type. An instance of that type should /// already had been registered to use this method. /// </summary> /// <typeparam name="TState">The State you want to change to</typeparam> /// <returns></returns> public TState ChangeState <TState>() where TState : IFsmState <T> { PreviousState = CurrentState; CurrentState = stateDictionary[typeof(TState)]; PreviousState.End(); CurrentState.Begin(); return((TState)CurrentState); }
private void Awake() { IFsmState[] allStates = new IFsmState[] { new PlayState(this), new SleepState(this), new EatState(this) }; // starts from play _catFsm = new CatFsm(allStates[0], allStates); }
public void ExcuteNewState(TLabel newState) { if (!_stateDic.ContainsKey(newState)) { DebugMsg.LogError("状态机内不包含此状态对象:" + newState); return; } IFsmState <TLabel> state = _stateDic[newState]; state.Enter(); }
protected void AddView(IFsmState <T> state) { T key = state.Label; if (_viewDic.ContainsKey(key)) { DebugMsg.LogError("已包含当前键值"); } else { _viewDic.Add(key, state); } }
public Fsm(string name, params string[] stateTypes) : this(name) { if (stateTypes != null && stateTypes.Length > 0) { IFsmState[] states = new IFsmState[stateTypes.Length]; for (int i = 0; i < stateTypes.Length; i++) { Type procedureType = Type.GetType(stateTypes[i]); states[i] = (FsmState)Activator.CreateInstance(procedureType, this); } AddState(states); } }
public static IFsm RemoveEmptyTransitions(this IFsm fsm) { var newStateByOldId = new IFsmState[fsm.States.Count]; var newFsm = new Fsm(); var visitedStates = new SortedSet <IFsmState>(); foreach (var st in fsm.States) { visitedStates.Clear(); if (fsm.InitialState == st || st.InTransitions.Any(t => !t.Condition.IsSigma)) { var newState = newFsm.CreateState(); newStateByOldId[st.Id] = newState; if (st.Flatten(s => s.OutTransitions.Where(t => t.Condition.IsSigma).Select(t => t.To), visitedStates.Add).Any(s => s.IsFinal)) { newState.SetFinal(); } } } newFsm.SetInitialState(newStateByOldId[fsm.InitialState.Id]); var visitedTransitions = new SortedSet <string>(); for (int oldStateId = 0; oldStateId < newStateByOldId.Length; oldStateId++) { List <int> endStates = new List <int>(); if (newStateByOldId[oldStateId] != null) { foreach (var t in fsm.States[oldStateId].OutTransitions) { if (!t.Condition.IsSigma) { newFsm.CreateTransition(newStateByOldId[oldStateId], newStateByOldId[t.To.Id], t.Condition); // newFsm.CreateTransition(newStateByOldId[oldStateId], newStateByOldId.Where(l => l != null).Single(k => t.To.Id == k.Id), t.Character, null); } else { visitedTransitions.Clear(); t.Flatten(ct => ct.To.OutTransitions.Where(nt => nt.Condition.IsSigma && ct.To != t.From), tt => visitedTransitions.Add(tt.ToString())) .SelectMany(ct => ct.To.OutTransitions.Where(nt => !nt.Condition.IsSigma)) .ForEach(ct => newFsm.CreateTransition(newStateByOldId[oldStateId], newStateByOldId[ct.To.Id], ct.Condition)); } } } } return(newFsm); }
/// <summary> /// 删除过渡线 /// </summary> /// <param name="head"></param> /// <param name="trail"></param> /// <returns></returns> public void DestoryTransition(IFsmState head, IFsmState trail) { if (!_stateInfo.ContainsKey(head)) { Log.E("Subscribe Head State Fist"); return; } if (!_stateInfo.ContainsKey(trail)) { Log.E("Subscribe Trail State Fist"); return; } _stateInfo[head].DestoryTransition(trail); }
public void ChangeState(string stateName, object userData = null) { IFsmState state = null; if (!m_StateDic.TryGetValue(stateName, out state)) { throw new DrbException("Fsm '{0}' not exists state '{1}'", Name, stateName); } if (CurrentState != null) { CurrentState.OnLeave(); } CurrentState = state; CurrentState.OnEnter(userData); }
public void UpdateTick() { if (_currentState != null) { var next = _currentState.ShoudExit(); if (next != null && next != _currentState.GetType()) { _currentState.OnExit(); _currentState = _fsmStates[next]; _currentState.OnEnter(); } _currentState.OnUpdate(); } }
/// <summary> /// 注册状态 /// </summary> /// <param name="_state"></param> public void RegistState(IFsmState _state) { if (m_FsmList == null) { m_FsmList = new KeyValueList <int, IFsmState>(); } if (m_FsmList.IsContainsKey(_state.FsmStateName)) { Debug.LogFormat("已存在该转状态: {0},不要重复注册!", _state.FsmStateName); return; } m_FsmList.Put(_state.FsmStateName, _state); }
public void SetInitialState(IFsmState state) { if (state.Fsm != this) { throw new ArgumentException(); } var initialState = _states[state.Id]; if (initialState.IsDeleted) { throw new ArgumentException(); } this.InitialState = initialState; }
public T GetState <T>() where T : IFsmState { Type type = typeof(T); IFsmState state = null; var enumerator = m_StateDic.GetEnumerator(); while (enumerator.MoveNext()) { if (enumerator.Current.Value.GetType() == type) { state = enumerator.Current.Value; break; } } return((T)state); }
/// <summary> /// Switch the state of the StateMachine /// </summary> /// <param name="state">The typeof() of the state being switched to</param> /// <returns>Success of the state change. Will return false if StateMachine is in the middle of a transition</returns> public bool ChangeState(Type state) { if (_stateLookup.ContainsKey(state) == false) throw new ArgumentException("Cannot change to state. Make sure it was added to StateMachine.Initialize", state.Name); if (IsTransitioning) return false; // When coming to change state from the started phase, go immediately to the enter phase _statePhase = (_statePhase == StatePhase.Started) ? StatePhase.Enter : StatePhase.Exit; _nextState = _stateLookup[state]; if (_statePhase == StatePhase.Exit) { exitIterator = _currentState.Exit(); } enterIterator = _nextState.Enter(); return true; }
// This function works with the base class to couple state classes to the // machine. In this example, the state machine is passed as the first // argument to setup. The BaseSampleState class expects this in its Setup() // function. In your own implementations, you can pass other arguments here protected override void SetupState(IFsmState state) { state.Setup(this); }
protected abstract void SetupState(IFsmState state);
private void StateEnterComplete() { _statePhase = StatePhase.Update; _currentState = _nextState; _nextState = null; exitIterator = null; enterIterator = null; InternalStateChange(); }