/// <summary> /// Initializes a StateMachine with a default state defined by owner. Initialization /// includes a reference value identifying the state. /// </summary> /// <param name="defaultState">Default state.</param> /// <param name="stateRef">A StateRef value identifying the state.</param> public StateMachine(iState defaultState, StateRef stateRef) { l_validStates = new Dictionary <StateRef, iState> (); l_validStates.Add(stateRef, defaultState); i_currentState = defaultState; sr_currentStateRef = stateRef; }
/// <summary> /// Executes a specified task in an asynchronous manner, waiting for its completion. /// </summary> /// <param name="task">Task to execute.</param> public void Execute(Task task) { // create state object var taskState = new StateRef <object>(new AutoResetEvent(false)); // queue a task and wait for it to finish executing task.ContinueWith(TaskCompletionHandler, taskState); taskState.Lock.WaitOne(); // check for and rethrow any exceptions if (taskState.Exception != null) { throw new Exception("Exception occured while executing asynchronous code.", taskState.Exception); } // completion method void TaskCompletionHandler(Task t, object state) { // retrieve state data var stateRef = state as StateRef <object>; // retrieve any exceptions or cancellation status if (t.IsFaulted) { stateRef.Exception = t.Exception; } else if (t.IsCanceled) { stateRef.Exception = new TaskCanceledException(t); } // signal that the execution is done stateRef.Lock.Set(); } }
internal void SaveThis(ModelSaveContext ctx) { Host.CheckValue(ctx, nameof(ctx)); ctx.CheckAtModel(); Host.Assert(InitialWindowSize == 0); Host.Assert(2 <= SeasonalWindowSize); Host.Assert(0 <= DiscountFactor && DiscountFactor <= 1); Host.Assert(Enum.IsDefined(typeof(ErrorFunction), ErrorFunction)); Host.Assert(Model != null); // *** Binary format *** // <base> // int: _seasonalWindowSize // float: _discountFactor // byte: _errorFunction // bool: _isAdaptive // State: StateRef // AdaptiveSingularSpectrumSequenceModeler: _model base.SaveModel(ctx); ctx.Writer.Write(SeasonalWindowSize); ctx.Writer.Write(DiscountFactor); ctx.Writer.Write((byte)ErrorFunction); ctx.Writer.Write(IsAdaptive); StateRef.Save(ctx.Writer); ctx.SaveModel(Model, "SSA"); }
private void RenderLinksForState(StateEditorGUI state) { StateMachineEditorLink[] links = state.GetEditableObject().GetEditorLinks(); if (links != null) { float fraction = 1.0f / (links.Length + 1.0f); float current = fraction; foreach (StateMachineEditorLink link in links) { StateRef stateRef = link.GetStateRef(); if (stateRef.IsInternal()) { StateEditorGUI toState = FindStateForLink(stateRef); if (toState != null) { RenderLink(link.GetDescription(), state, toState, current); } } else { RenderExternalLink(link, state, current); } current += fraction; } } }
/// <summary> /// Executes a specified task in an asynchronous manner, waiting for its completion, and returning the result. /// </summary> /// <typeparam name="T">Type of the Task's return value.</typeparam> /// <param name="task">Task to execute.</param> /// <returns>Task's result.</returns> public T Execute <T>(Task <T> task) { // create state object var taskState = new StateRef <T>(new AutoResetEvent(false)); // queue a task and wait for it to finish executing task.ContinueWith(TaskCompletionHandler, taskState); taskState.Lock.WaitOne(); // check for and rethrow any exceptions if (taskState.Exception != null) { throw taskState.Exception; } // return the result, if any if (taskState.HasResult) { return(taskState.Result); } // throw exception if no result throw new Exception("Task returned no result."); // completion method void TaskCompletionHandler(Task <T> t, object state) { // retrieve state data var stateRef = state as StateRef <T>; // retrieve any exceptions or cancellation status if (t.IsFaulted) { if (t.Exception.InnerExceptions.Count == 1) // unwrap if 1 { stateRef.Exception = t.Exception.InnerException; } else { stateRef.Exception = t.Exception; } } else if (t.IsCanceled) { stateRef.Exception = new TaskCanceledException(t); } // return the result from the task, if any if (t.IsCompleted && !t.IsFaulted) { stateRef.HasResult = true; stateRef.Result = t.Result; } // signal that the execution is done stateRef.Lock.Set(); } }
public void LoadExternalState(StateMachineExternalStateEditorGUI state) { if (ShowOnLoadSaveChangesDialog()) { StateRef stateRef = state.ExternalStateRef.GetStateRef(); string fileName = AssetDatabase.GetAssetPath(stateRef.GetExternalFile()._editorAsset); LoadFile(fileName); } }
public StateMachine(TStateType initialState) { var reference = new StateRef { State = initialState }; _stateReader = () => reference.State; _stateWriter = s => reference.State = s; }
/// <summary> /// Initializes a state machine in the pre-start state (used for gameplay scenes with a countdown) with a defined target "first" state. /// </summary> /// <param name="stateRefIn">The StateRef pointing to our desired state</param> public StateMachine(StateRef stateRefIn) { iState prestart = new PreStartState(stateRefIn); l_validStates = new Dictionary <StateRef, iState>(); l_validStates.Add(StateRef.PRESTART_STATE, prestart); i_currentState = prestart; sr_currentStateRef = StateRef.PRESTART_STATE; }
public override void SetPosition(Vector2 position) { StateRef externalStateRef = ExternalStateRef.GetStateRef(); externalStateRef._editorExternalLinkPosition = position; ExternalStateRef.SetStateRef(externalStateRef); MarkAsDirty(true); }
internal void SaveThis(ModelSaveContext ctx) { ctx.CheckAtModel(); base.SaveModel(ctx); // *** Binary format *** // <base> // State: StateRef StateRef.Save(ctx.Writer); }
/// <summary> /// Creates a new StateRef object containing state and a new Timer that will use the callback and state. /// The Timer will initially not be started. The returned object will be passed into the callback as its /// argument. Start the Timer by invoking StateRef.Start. Dispose the Timer, and release references to it, /// state, and the StateRef by invoking StateRef.Dispose. No references are held on the Timer, state or /// the StateRef until StateRef.Start is invoked. See the class documentation for a usage example. /// </summary> public StateRef <T> Create <T>(T state, TypedCallback <T> callback) { StateRef <T> stateRef = new StateRef <T>(); stateRef.Parent = this; stateRef.State = state; stateRef.Timer = new System.Threading.Timer( new TimerCallback((s) => { callback.Invoke((StateRef <T>)s); }), stateRef, Timeout.Infinite, Timeout.Infinite); return(stateRef); }
/// <summary> /// Initializes a new instance of the <see cref="ActionState"/> class. /// </summary> /// <param name="stack"></param> /// <param name="state"></param> /// <param name="currentToken"></param> public ActionState(Frame stack, StateRef state, CodePoint currentToken) : this() { #region Contract Contract.Requires<ArgumentNullException>(stack != null); #endregion this.Stack = stack; this.NextState = state; this.CurrentToken = currentToken; }
private static object FixupStateRefs(object obj, object stateMachine) { if (obj.GetType() == typeof(StateRef)) { StateRef StateRef = (StateRef)obj; StateRef.SetParentStatemachine((StateMachine)stateMachine); return(StateRef); } return(obj); }
private protected override void SaveModel(ModelSaveContext ctx) { ctx.CheckAtModel(); Host.Assert(InitialWindowSize == 0); base.SaveModel(ctx); // *** Binary format *** // <base> // State: StateRef StateRef.Save(ctx.Writer); }
internal void SaveThis(ModelSaveContext ctx) { ctx.CheckAtModel(); Host.Assert(InitialWindowSize == 0); base.SaveModel(ctx); // *** Binary format *** // <base> // State: StateRef StateRef.Save(ctx.Writer); }
public StateDTree GetChild(StateRef stateIn) { foreach (StateDTree child in l_children) { if (child.GetState() == stateIn) { return(child); } } return(null); }
new public AudioDTree GetChild(StateRef stateIn) { foreach (AudioDTree child in l_children) { if (child.GetState() == stateIn) { return(child); } } return(this); }
public static IEnumerator Run(StateMachineComponent stateMachine, StateRef startState, GameObject sourceObject = null) { State state = startState.GetState(sourceObject != null ? sourceObject : stateMachine.gameObject); if (state != null) { #if UNITY_EDITOR && DEBUG string debugFileName = startState.GetExternalFile().GetFilePath(); StateMachineDebug.OnStateStarted(stateMachine, state, debugFileName); #endif return(state.PerformState(stateMachine)); } return(null); }
private StateEditorGUI FindStateForLink(StateRef link) { int stateId = link.GetStateID(); if (stateId != -1) { foreach (StateEditorGUI state in _editableObjects) { if (stateId == state.GetStateId()) { return(state); } } } return(null); }
private static object FixupStateRefs(object obj, object stateMachine) { if (obj.GetType() == typeof(StateRef)) { StateRef StateRef = (StateRef)obj; StateRef.SetParentStatemachine((StateMachine)stateMachine); return(StateRef); } #if UNITY_EDITOR else if (obj.GetType() == typeof(LocalisedStringRef)) { LocalisedStringRef localisedStringRef = (LocalisedStringRef)obj; localisedStringRef.SetAutoNameParentName(((StateMachine)stateMachine)._name); return(localisedStringRef); } #endif return(obj); }
/// <summary> /// Parses the parse table from the specified AST. /// </summary> /// <param name="ast">The AST.</param> /// <returns>The resulting <see cref="ParseTable"/>.</returns> private ParseTable Parse(ITerm ast) { #region Contract Contract.Requires<ArgumentNullException>(ast != null); Contract.Ensures(Contract.Result<ParseTable>() != null); #endregion var pt = ast.ToCons("parse-table", 5); int version = pt[0].ToInt32(); Assert(version == 4 || version == 6, "Only version 4 or 6 parse tables are supported."); var initialState = new StateRef(pt[1].ToInt32()); var labels = ParseLabels((IListTerm)pt[2]); var states = ParseStates((IListTerm)pt[3].ToCons("states", 1)[0], labels); var priorities = ParsePriorities((IListTerm)pt[4].ToCons("priorities", 1)[0]); // TODO: Injections? return new ParseTable(initialState, states, labels, priorities); }
ListAllStateReferences( Guid chainId, long lowestIndex = 0, long highestIndex = long.MaxValue) { byte[] prefix = StateRefKeyPrefix; var stateRefs = new List <StateRef>(); foreach (Iterator it in IterateDb(_stateRefDb, prefix, chainId)) { byte[] key = it.Key(); int stateKeyLength = key.Length - sizeof(long) - prefix.Length; byte[] stateKeyBytes = key.Skip(prefix.Length).Take(stateKeyLength).ToArray(); string stateKey = RocksDBStoreBitConverter.GetString(stateKeyBytes); byte[] indexBytes = key.Skip(prefix.Length + stateKeyLength).ToArray(); long index = RocksDBStoreBitConverter.ToInt64(indexBytes); if (index < lowestIndex || index > highestIndex) { continue; } var hash = new HashDigest <SHA256>(it.Value()); var stateRef = new StateRef { StateKey = stateKey, BlockHash = hash, BlockIndex = index, }; stateRefs.Add(stateRef); } return(stateRefs .GroupBy(stateRef => stateRef.StateKey) .ToImmutableDictionary( g => g.Key, g => (IImmutableList <HashDigest <SHA256> >)g .Select(r => r.BlockHash).ToImmutableList() )); }
private void RenderExternalLink(StateMachineEditorLink link, StateEditorGUI fromState, int linkIndex) { StateMachineExternalStateEditorGUI externalState = null; StateRef stateRef = link.GetStateRef(); //Find external link for this state foreach (StateEditorGUI state in _editableObjects) { StateMachineExternalStateEditorGUI extState = state as StateMachineExternalStateEditorGUI; if (extState != null) { StateRef extStateRef = extState.ExternalStateRef.GetStateRef(); if (extStateRef.GetStateID() == stateRef.GetStateID() && extStateRef.GetExternalFile().GetFileGUID() == stateRef.GetExternalFile().GetFileGUID()) { externalState = extState; break; } } } //If none exists, create a new one if (externalState == null) { externalState = (StateMachineExternalStateEditorGUI)AddNewObject(new StateMachineExternalState()); externalState.ExternalStateRef = link; _editableObjects.Add(externalState); } if (!externalState.ExternalHasRendered) { externalState.CalcBounds(_style); bool selected = _selectedObjects.Contains(externalState); Color borderColor = selected ? _style._stateBackgroundSelected : _style._stateBackground; Rect renderedRect = GetScreenRect(externalState.GetBounds()); externalState.Render(renderedRect, borderColor, _style._externalStateColor, _style, selected ? 2.0f : 1.0f); externalState.ExternalHasRendered = true; } RenderLink(link.GetDescription(), fromState, externalState, linkIndex); }
public AudioRef GetAudioState() { AudioRef foundClip = AudioRef.ERROR_CLIP; StateRef airState = c_airMachine.GetCurrentState(); StateRef rideState = c_accelMachine.GetCurrentState(); StateRef turnState = c_turnMachine.GetCurrentState(); StateRef groundState = StateRef.TERR_SNOW; // currently always snow // obey the order of the tree: air, ground, turn, terre AudioDTree currentBranch = t_audioStateTree.GetChild(airState); currentBranch = currentBranch.GetChild(rideState); currentBranch = currentBranch.GetChild(turnState); currentBranch = currentBranch.GetChild(groundState); foundClip = currentBranch.GetLeaf(); return(foundClip); }
private void RenderLinksForState(StateEditorGUI state) { StateMachineEditorLink[] links = state.GetEditableObject().GetEditorLinks(); if (links != null) { for (int j = 0; j < links.Length; j++) { StateRef stateRef = links[j].GetStateRef(); if (stateRef.IsInternal()) { StateEditorGUI toState = FindStateForLink(stateRef); RenderLink(links[j].GetDescription(), state, toState, j); } else { RenderExternalLink(links[j], state, j); } } } }
internal void SaveThis(ModelSaveContext ctx) { Host.CheckValue(ctx, nameof(ctx)); ctx.CheckAtModel(); Host.Assert(InitialWindowSize == 0); Host.Assert(Model != null); // *** Binary format *** // <base> // bool: _isAdaptive // int32: Horizon // State: StateRef // AdaptiveSingularSpectrumSequenceModeler: _model base.SaveModel(ctx); ctx.Writer.Write(IsAdaptive); ctx.Writer.Write(Horizon); ctx.Writer.Write(ConfidenceLevel); StateRef.Save(ctx.Writer); ctx.SaveModel(Model, "SSA"); }
/// <summary> /// Executes a command on the state machine, changing the state /// </summary> public void Execute(Command cmd, bool SkipTransition = false, bool ForceTransition = false) { StateRef e_nextState = i_currentState.GetNextState(cmd); bool foundState = l_validStates.TryGetValue(e_nextState, out i_currentState); if (!foundState) { Debug.Log("ERROR: State Not Found!"); return; } // when pausing and unpausing, we want to skip the transition action as, in terms of game physics, the state shouldn't change if (SkipTransition) { sr_currentStateRef = e_nextState; return; } if (e_nextState != sr_currentStateRef || ForceTransition) { i_currentState.TransitionAct(); sr_currentStateRef = e_nextState; } }
/// <summary> /// Adds a new state to the list with a reference to the state. /// </summary> /// <returns><c>true</c>, if state was added</returns> /// <param name="newState">New state.</param> /// <param name="stateRef">State reference.</param> public bool AddState(iState newState, StateRef stateRef) { l_validStates.Add(stateRef, newState); return(true); }
/// <summary> /// Gets an active stack frame with the specified state, /// or creates and adds one if there is none. /// </summary> /// <param name="state">The state to look for.</param> /// <returns>A <see cref="Frame"/> with the specified state.</returns> private Frame GetOrCreateActiveFrame(StateRef state) { #region Contract Contract.Ensures(Contract.Result<Frame>() != null); Contract.Ensures(Contract.Result<Frame>().State == state); #endregion var frame = GetActiveFrame(state); if (frame == null) { frame = new Frame(state); this.activeStacks.PushFront(frame); } return frame; }
/// <summary> /// Gets the state that corresponds to the specified state reference. /// </summary> /// <param name="stateRef">The state reference.</param> /// <returns>The corresponding <see cref="State"/>.</returns> private State GetState(StateRef stateRef) { #region Contract Contract.Ensures(Contract.Result<State>() != null); #endregion return this.parseTable.States[stateRef.Index]; }
public StateDTree() { this.s_heldState = StateRef.ERROR_STATE; this.l_children = new List <StateDTree>(); }
/// <summary> /// Parses the gotos from the parse table. /// </summary> /// <param name="listTerm">A list of goto terms.</param> /// <returns>The parsed gotos.</returns> /// <example> /// A goto term might look like this: /// <code> /// goto([range(9,10),13,32],21) /// </code> /// </example> private IReadOnlyList<Goto> ParseGotos(IListTerm listTerm) { #region Contract Contract.Requires<ArgumentNullException>(listTerm != null); Contract.Ensures(Contract.Result<IReadOnlyList<Goto>>() != null); #endregion var result = new Goto[listTerm.Count]; int index = 0; foreach (var term in from t in listTerm.SubTerms select t.ToCons("goto", 2)) { var characters = ParseCharacterRanges((IListTerm)term[0]); var labels = ParseLabelRanges((IListTerm)term[0]); var nextState = new StateRef(term[1].ToInt32()); result[index++] = new Goto(nextState, characters, labels); } return result; }
/// <summary> /// Parses a shift action item. /// </summary> /// <param name="term">The term.</param> /// <returns>The parsed action item.</returns> /// <example> /// The term might look like this: /// <code> /// shift(22) /// </code> /// </example> private ActionItem ParseShift(IConsTerm term) { #region Contract Contract.Requires<ArgumentNullException>(term != null); Contract.Requires<ArgumentException>(term.IsCons("shift", 1)); Contract.Ensures(Contract.Result<ActionItem>() != null); #endregion var nextState = new StateRef(term[0].ToInt32()); return new ShiftActionItem(nextState); }
/// <summary> /// Initializes a new instance of the <see cref="Frame"/> class. /// </summary> /// <param name="state">The current state.</param> public Frame(StateRef state) { this.State = state; this.Links = new Collection<Link>(); }
public static object PropertyField(object obj, GUIContent label, ref bool dataChanged, GUIStyle style, params GUILayoutOption[] options) { StateRef state = (StateRef)obj; if (label == null) { label = new GUIContent(); } label.text += " (" + state + ")"; bool editorCollapsed = !EditorGUILayout.Foldout(!state._editorCollapsed, label); if (editorCollapsed != state._editorCollapsed) { state._editorCollapsed = editorCollapsed; dataChanged = true; } if (!editorCollapsed) { int origIndent = EditorGUI.indentLevel; EditorGUI.indentLevel++; EditorGUI.BeginChangeCheck(); eType type = (eType)EditorGUILayout.EnumPopup("Link Type", state.IsInternal() ? eType.Internal : eType.External); if (EditorGUI.EndChangeCheck()) { //If type has changed create a new ref with file set to null if internal or a blank asset ref if external. state = new StateRef(type == eType.External ? -1 : 0, state.GetParentStateMachine()); dataChanged = true; } switch (type) { case eType.Internal: { StateMachine stateMachine = state.GetParentStateMachine(); if (stateMachine != null) { int stateId = state.GetStateID(); //If changed state id create new state ref if (DrawStateNamePopUps(stateMachine._states, ref stateId)) { state = new StateRef(stateId, stateMachine); dataChanged = true; } } } break; case eType.External: { TextAsset asset = EditorGUILayout.ObjectField("File", state.GetExternalFile()._editorAsset, typeof(TextAsset), false) as TextAsset; //If asset changed update GUIDS if (state.GetExternalFile()._editorAsset != asset) { state = new StateRef(asset, -1, state.GetParentStateMachine()); dataChanged = true; } if (asset != null) { StateMachine stateMachines = Serializer.FromFile <StateMachine>(AssetDatabase.GetAssetPath(asset)); int stateId = state.GetStateID(); if (DrawStateNamePopUps(stateMachines._states, ref stateId)) { state = new StateRef(asset, stateId, state.GetParentStateMachine()); dataChanged = true; } } } break; } EditorGUI.indentLevel = origIndent; } return(state); }
public BeforeInvokeArgs(PipeInvocation invocation, StateRef stateRef) { _stateRef = stateRef; Invocation = invocation; }
public PreStartState(StateRef nextStateIn) { this.nextState = nextStateIn; }
/// <summary> /// Gets an active stack frame with the specified state. /// </summary> /// <param name="state">The state to look for.</param> /// <returns>A <see cref="Frame"/> with the specified state; /// or <see langword="null"/> when not found.</returns> private Frame GetActiveFrame(StateRef state) { #region Contract Contract.Ensures(Contract.Result<Frame>() == null || Contract.Result<Frame>().State == state); #endregion return this.activeStacks.FirstOrDefault(f => f.State == state); }
/// <summary> /// Initializes a new instance of the <see cref="ShiftActionItem"/> class. /// </summary> /// <param name="nextState">Reference to the next state.</param> public ShiftActionItem(StateRef nextState) { this.NextState = nextState; }
// TODO: Can currentToken be removed? /// <summary> /// Enqueues the specified stack frame and next state for the shifter. /// </summary> /// <param name="stack">The current stack frame.</param> /// <param name="nextState">The next state.</param> /// <param name="currentToken">The current token.</param> public void EnqueueForShifter(Frame stack, StateRef nextState, CodePoint currentToken) { #region Contract Contract.Requires<ArgumentNullException>(stack != null); Contract.Requires<ArgumentNullException>(nextState != null); #endregion this.forShifter.PushFront(new ActionState(stack, nextState, currentToken)); }
/// <param name="st0"></param> /// <param name="nextState"></param> /// <param name="label"></param> /// <param name="kids">A list of trees.</param> /// <param name="path"></param> private void Reducer(Frame st0, StateRef nextState, LabelRef label, IReadOnlyList<IParseNode> kids, Path path) { var production = this.parseTable.Labels[label.Index].Production; Contract.Assert(!production.IsRecover); // t := application of a -> A to kids IParseNode t = ApplyProduction(production, kids, /* TODO */ 0, /* TODO */ 0, /* TODO */ false, /* TODO */ false); Frame st1 = GetActiveFrame(nextState); if (st1 != null) { // A stack with state nextState exists. Check for ambiguities. Link nl = st1.TryGetParentLink(st0); if (nl != null) { // There exists a direct link from st1 to st0. // TODO: Add `t` to the possiblities of the ambiguity node at `tree(nl)` if (production.IsReject) nl.Reject(); // TODO: Can't modify a link. //nl.Label = t; } else { // There is no direct link from st1 to st0. nl = new Link(st0, t, path.Length); st1.Links.Add(nl); if (production.IsReject) nl.Reject(); ActorOnActiveStacksOverNewLink(nl); } } else { // Found no existing stack frame with state nextState. st1 = new Frame(nextState); this.activeStacks.PushFront(st1); this.forActorDelayed.PushFront(st1); var nl = new Link(st0, t, path.Length); st1.Links.Add(nl); if (production.IsReject) nl.Reject(); } }