Пример #1
0
    //Initialises or if it already excists turns on the main menu.
    public void OnEnter(MenuData group)
    {
        if (stateGroup != null)
        {
            stateGroup.SetActive(true);
        }
        else
        {
            canvas       = GameObject.FindGameObjectWithTag("Canvas");
            stateMachine = canvas.GetComponent <StateMachine>();

            stateGroup = Actor.Instantiate(group.MenuGroup, canvas.GetComponent <Transform>().position, Quaternion.identity);
            stateGroup.transform.SetParent(canvas.transform);

            OnStateSwitch = stateMachine.SwitchState;

            creditsButton = stateGroup.transform.Find("CreditsButton").GetComponent <Button>();
            startButton   = stateGroup.transform.Find("StartButton").GetComponent <Button>();
            exitButton    = stateGroup.transform.Find("ExitButton").GetComponent <Button>();
        }

        stateGroup.SetActive(true);

        creditsButton.onClick.AddListener(() => OnStateSwitch(typeof(CreditState)));
        startButton.onClick.AddListener(() => {
            SceneManager.LoadScene("SampleScene");
            Cursor.visible = false;
        });
        exitButton.onClick.AddListener(() => Application.Quit());
    }
Пример #2
0
        //  private List<PointWithDistance> _visibleCells;

        protected Animal(bool isPassable, Size size, uint id, uint speed, string name, int viewRadius, Point position)
        {
            IsPassable = isPassable;

            Size = size;

            Id = id;

            Speed = speed;

            Name = name;

            ViewRadius = viewRadius;
            ViewSight  = new Size((uint)ViewRadius, (uint)ViewRadius);
            Position   = position;

            ObjectWithState = new ObjectWithState(
                new List <ObjectState>
            {
                new ObjectState(ObjectStates.ObjectStates.Staying)
                {
                    TickCount = STAYING_BASE_TICKCOUNT, Distribution = STAYING_BASE_TICKCOUNT / 10, Eternal = false
                },
                new ObjectState(ObjectStates.ObjectStates.Hungry)
                {
                    TickCount = 300, Distribution = 30, Eternal = true
                }
            },
                false, null, OnChangeState);

            StateEvent.FireEvent();
        }
 private void OnStateChanged(StateEvent stateEvent)
 {
     foreach (var component in _components)
     {
         component.StateEventReceived(stateEvent);
     }
 }
Пример #4
0
 private void Halt()
 {
     _stateQueue.Clear();
     _stateQueue.Enqueue(new Halting(this));
     _stateQueue.Enqueue(new Halt());
     StateEvent.FireEvent();
 }
Пример #5
0
 public override Task HandleEvent(StateEvent state)
 {
     return(Task.Run(() =>
     {
         _logger.Info("Handling state change event {0}", state.State);
     }));
 }
Пример #6
0
        public unsafe void InitializeWithEvent(InputEventPtr eventPtr, InputControl control)
        {
            // Must be an event carrying state.
            Debug.Assert(eventPtr.IsA <StateEvent>() || eventPtr.IsA <DeltaStateEvent>());

            ////TODO: support delta events
            if (eventPtr.IsA <DeltaStateEvent>())
            {
                throw new NotImplementedException("delta event support not yet implemented");
            }

            m_Control = control;

            // Copy event data.
            var stateEventPtr = StateEvent.From(eventPtr);
            var stateSize     = stateEventPtr->stateSizeInBytes;
            var buffer        = new byte[stateSize];

            fixed(byte *stateDataPtr = buffer)
            {
                UnsafeUtility.MemCpy(new IntPtr(stateDataPtr), stateEventPtr->state, stateSize);
            }

            m_StateBuffers        = new byte[1][];
            m_StateBuffers[0]     = buffer;
            m_SelectedStateBuffer = BufferSelector.Default;
        }
Пример #7
0
 void Awake()
 {
     if (onStateChanged == null)
     {
         onStateChanged = new StateEvent();
     }
 }
Пример #8
0
    public void RemoveEvent(AnimatorEventType type, StateEvent action, string stateName)
    {
        int         hash = Animator.StringToHash(stateName);
        EventStruct eventValue;

        if (!Events.TryGetValue(hash, out eventValue))
        {
            return;
        }
        switch (type)
        {
        case AnimatorEventType.Enter:
            eventValue.EnterEvents -= action;
            break;

        case AnimatorEventType.Exit:
            eventValue.ExitEvents -= action;
            break;

        case AnimatorEventType.Running:
            eventValue.RunningEvents -= action;
            break;

        default:
            throw new ArgumentOutOfRangeException("type", type, null);
        }
    }
Пример #9
0
    public void Performance_SearchForChangedButtonInEvent_UsingEnumerateChangedControls()
    {
        // Using Touchscreen as it is generally our worst-case device. This setup
        // is somewhat artificial for the touchscreen, though, as we'd not normally
        // send a full state event for the entire device but rather only send
        // individual TouchState events.
        var touchscreen = InputSystem.AddDevice <Touchscreen>();

        using (StateEvent.From(touchscreen, out var eventPtr))
        {
            touchscreen.touches[6].pressure.WriteValueIntoEvent(0.5f, eventPtr);

            Measure.Method(() =>
            {
                var foundIt = false;
                foreach (var control in eventPtr.EnumerateChangedControls())
                {
                    if (control is AxisControl axis)
                    {
                        // Make sure we're actually finding the right control.
                        Assert.That(axis, Is.SameAs(touchscreen.touches[6].pressure));
                        foundIt = true;
                        break;     // Found.
                    }
                }
                Assert.That(foundIt, Is.True);
            })
            .MeasurementCount(500)
            .WarmupCount(5)
            .Run();
        }
    }
Пример #10
0
        /************************************************/

        public State(string name, StateEvent beginE, StateEvent updateE, StateEvent endE)
        {
            this.m_stateName   = name;
            this.m_beginEvent  = beginE;
            this.m_updateEvent = updateE;
            this.m_endEvent    = endE;
        }
    private unsafe void InputSystem_onEvent(UnityEngine.InputSystem.LowLevel.InputEventPtr eventPtr, InputDevice device)
    {
        if (m_State == State.Idle || m_EventReceiveType != EventReceiveType.NewInputViaCallbacks)
        {
            return;
        }

        var touchScreenDevice = device as Touchscreen;

        if (touchScreenDevice == null)
        {
            return;
        }

        if (!eventPtr.IsA <StateEvent>())
        {
            return;
        }
        var stateEvent = StateEvent.From(eventPtr);

        if (stateEvent->stateFormat != TouchState.Format)
        {
            return;
        }
        var touchState = (TouchState *)stateEvent->state;

        if (touchState->phase == UnityEngine.InputSystem.TouchPhase.Began)
        {
            HandleEventReceive((int)touchState->position.y);
        }
    }
Пример #12
0
        StateDelegate heating(StateEvent e)
        {
            switch (e.Signal)
            {
            case Signal.Entry:
                System.Console.WriteLine("  heating: entering state");
                return(null);

            case Signal.Init:
                InitTransitionState(toasting);
                return(null);

            case Signal.Exit:
                System.Console.WriteLine("  heating: exiting state");
                return(null);

            case (Signal)OvenSignal.OpenDoor:
                System.Console.WriteLine("  heating: OPEN_DOOR signal!");
                TransitionState(doorOpen);
                return(null);

            case (Signal)OvenSignal.Toasting:
                System.Console.WriteLine("  heating: TOASTING signal!");
                TransitionState(toasting);
                return(null);

            case (Signal)OvenSignal.Baking:
                System.Console.WriteLine("  heating: BAKING signal!");
                TransitionState(baking);
                return(null);
            }
            return(oven);
        }
Пример #13
0
    public void Devices_SupportSensorsWithVector3Control(string layoutName, string controlName, bool isAffectedByGravity, bool isAffectedByOrientation)
    {
        const float kSensorStandardGravity = 9.80665f;
        const float kMultiplier            = -1.0f / kSensorStandardGravity;

        var device  = InputSystem.AddDevice(layoutName);
        var control = (Vector3Control)device[controlName];

        using (StateEvent.From(device, out var stateEventPtr))
        {
            var value = new Vector3(0.1f, 0.2f, 0.3f);
            ////FIXME: Seems like written value doesn't through processor, for ex, AndroidCompensateDirectionProcessor, thus we need to manually apply preprocessing
            if (isAffectedByGravity)
            {
                control.WriteValueIntoEvent(value / kMultiplier, stateEventPtr);
            }
            else
            {
                control.WriteValueIntoEvent(value, stateEventPtr);
            }

            InputSystem.QueueEvent(stateEventPtr);
            InputSystem.QueueEvent(stateEventPtr);
            InputSystem.Update();

            runtime.screenOrientation = ScreenOrientation.LandscapeLeft;
            InputSystem.settings.compensateForScreenOrientation = false;
            Assert.That(control.ReadValue(), Is.EqualTo(value).Using(Vector3EqualityComparer.Instance));

            InputSystem.settings.compensateForScreenOrientation = true;
            Assert.That(control.ReadValue(), Is.EqualTo(isAffectedByOrientation ? new Vector3(-value.y, value.x, value.z) : value).Using(Vector3EqualityComparer.Instance));
        }
    }
Пример #14
0
        public unsafe bool MergeForward(InputEventPtr currentEventPtr, InputEventPtr nextEventPtr)
        {
            if (currentEventPtr.type != StateEvent.Type || nextEventPtr.type != StateEvent.Type)
            {
                return(false);
            }

            var currentEvent = StateEvent.FromUnchecked(currentEventPtr);
            var nextEvent    = StateEvent.FromUnchecked(nextEventPtr);

            if (currentEvent->stateFormat != MouseState.Format || nextEvent->stateFormat != MouseState.Format)
            {
                return(false);
            }

            var currentState = (MouseState *)currentEvent->state;
            var nextState    = (MouseState *)nextEvent->state;

            // if buttons or clickCount changed we need to process it, so don't merge events together
            if (currentState->buttons != nextState->buttons || currentState->clickCount != nextState->clickCount)
            {
                return(false);
            }

            nextState->delta  += currentState->delta;
            nextState->scroll += currentState->scroll;
            return(true);
        }
Пример #15
0
    public void Devices_SupportSensorsWithQuaternionControl(string layoutName, string controlName)
    {
        var device  = InputSystem.AddDevice(layoutName);
        var control = (QuaternionControl)device[controlName];

        using (StateEvent.From(device, out var stateEventPtr))
        {
            var rotation = new Vector3(5.0f, 12.0f, 16.0f);
            var q        = Quaternion.Euler(rotation);

            // The 4th value is ignored and is calculated from other three
            control.WriteValueIntoEvent(new Quaternion(q.x, q.y, q.z, 1234567.0f), stateEventPtr);

            InputSystem.QueueEvent(stateEventPtr);
            InputSystem.QueueEvent(stateEventPtr);
            InputSystem.Update();

            runtime.screenOrientation = ScreenOrientation.LandscapeLeft;
            InputSystem.settings.compensateForScreenOrientation = false;
            Assert.That(control.ReadValue(), Is.EqualTo(q).Within(0.01));
            Assert.That(control.ReadValue().eulerAngles, Is.EqualTo(rotation).Using(Vector3EqualityComparer.Instance));

            InputSystem.settings.compensateForScreenOrientation = true;
            Assert.That(control.ReadValue().eulerAngles, Is.EqualTo(new Vector3(rotation.x, rotation.y, Mathf.Repeat(rotation.z - 90.0f, 360.0f))).Using(Vector3EqualityComparer.Instance));
        }
    }
Пример #16
0
        internal void RewriteKnowledges(Dictionary <string, uint> newKnowledges)
        {
            var allKnowledges = newKnowledges.Where(t => t.Value > 0).Select(t =>
            {
                Knowledges knowledge;
                var knowledgeExist = Knowledges.TryParse(t.Key, true, out knowledge);
                return(new
                {
                    t.Key,
                    KnKey = knowledge,
                    KnowledgeExist = knowledgeExist,
                    t.Value
                });
            }).ToList();

            _knowledgeses = allKnowledges.Where(t => t.KnowledgeExist).ToDictionary(t => t.KnKey, t => t.Value);
            _knowledgeses[Knowledges.Nothing] = 100;

            _ObjectKnowledgeses = _ObjectKnowledgeses.Join(allKnowledges.Where(t => !t.KnowledgeExist), t => t.Key, u => u.Key,
                                                           (pair, kn) => new KeyValuePair <string, uint>(pair.Key, kn.Value))
                                  .ToDictionary(pair => pair.Key, pair => pair.Value);

            HeroLifeCycle.NextGen();

            _stateQueue.Clear();
            StateEvent.FireEvent();
        }
Пример #17
0
        /// <summary>
        /// Set the control to the given value by sending a state event with the value to the
        /// control's device.
        /// </summary>
        /// <param name="control">An input control on a device that has been added to the system.</param>
        /// <param name="state">New value for the input control.</param>
        /// <typeparam name="TValue">Value type of the given control.</typeparam>
        /// <example>
        /// <code>
        /// var gamepad = InputSystem.AddDevice&lt;Gamepad&gt;();
        /// Set(gamepad.leftButton, 1);
        /// </code>
        /// </example>
        public void Set <TValue>(InputControl <TValue> control, TValue state, double absoluteTime = -1, double timeOffset = 0)
            where TValue : struct
        {
            if (control == null)
            {
                throw new ArgumentNullException(nameof(control));
            }
            if (!control.device.added)
            {
                throw new ArgumentException(
                          $"Device of control '{control}' has not been added to the system", nameof(control));
            }

            using (StateEvent.From(control.device, out var eventPtr))
            {
                ////REVIEW: should we by default take the time from the device here?
                if (absoluteTime >= 0)
                {
                    eventPtr.time = absoluteTime;
                }
                eventPtr.time += timeOffset;
                control.WriteValueIntoEvent(state, eventPtr);
                InputSystem.QueueEvent(eventPtr);
            }

            InputSystem.Update();
        }
Пример #18
0
    public unsafe void Events_CanCreateStateEventFromDevice()
    {
        var mouse = InputSystem.AddDevice <Mouse>();

        InputSystem.QueueStateEvent(mouse, new MouseState {
            delta = Vector2.one
        });
        InputSystem.Update();

        using (var buffer = StateEvent.From(mouse, out var eventPtr))
        {
            Assert.That(mouse.delta.x.ReadValueFromEvent(eventPtr, out var xVal), Is.True);
            Assert.That(xVal, Is.EqualTo(1).Within(0.00001));

            Assert.That(mouse.delta.y.ReadValueFromEvent(eventPtr, out var yVal), Is.True);
            Assert.That(yVal, Is.EqualTo(1).Within(0.00001));

            var stateEventPtr = StateEvent.From(eventPtr);

            Assert.That(stateEventPtr->baseEvent.deviceId, Is.EqualTo(mouse.id));
            Assert.That(stateEventPtr->baseEvent.time, Is.EqualTo(runtime.currentTime));
            Assert.That(stateEventPtr->baseEvent.sizeInBytes, Is.EqualTo(buffer.Length));
            Assert.That(stateEventPtr->baseEvent.sizeInBytes,
                        Is.EqualTo(InputEvent.kBaseEventSize + sizeof(FourCC) + mouse.stateBlock.alignedSizeInBytes));
            Assert.That(stateEventPtr->stateSizeInBytes, Is.EqualTo(mouse.stateBlock.alignedSizeInBytes));
            Assert.That(stateEventPtr->stateFormat, Is.EqualTo(mouse.stateBlock.format));
        }
    }
    public static void GlobalPrefab(int _index, GameObject _parentObj, int _state, int _ev)
    {
        GameObject nextPrefab = Instantiate(coreData.globalPrefabs[_index], _parentObj.transform.position, _parentObj.transform.rotation, _parentObj.transform);

        nextPrefab.transform.localScale = _parentObj.transform.localScale;
        if (_state != -1)
        {
            StateEvent thisEvent = coreData.characterStates[_state].events[_ev];

            nextPrefab.transform.localPosition += new Vector3(thisEvent.parameters[0].val, thisEvent.parameters[1].val, thisEvent.parameters[2].val);
            nextPrefab.transform.localRotation  = Quaternion.Euler(new Vector3(thisEvent.parameters[3].val, thisEvent.parameters[4].val, thisEvent.parameters[5].val));
            nextPrefab.transform.localScale     = Vector3.Scale(nextPrefab.transform.localScale, new Vector3(thisEvent.parameters[6].val, thisEvent.parameters[7].val, thisEvent.parameters[8].val));
        }

        //foreach (Animator myAnimator in nextPrefab.transform.GetComponentsInChildren<Animator>())
        //{
        //    VFXControl[] behaviors = myAnimator.GetBehaviours<VFXCOntrol>();
        //    for (int i = 0; i < behaviors.Length; i++)
        //    {
        //        behaviors[i].vfxRoot = nextPrefab.transform;
        //    }
        //    if (_state != -1)
        //    {
        //        StateEvent thisEvent = coreData.characterStates[_state].events[_ev];
        //        myAnimator.speed *= thisEvent.parameters[9].val;
        //    }
        //}
    }
Пример #20
0
        void OnStateEvent(StateEvent e)
        {
            switch (e.type)
            {
            case EventType.Save:
                SaveState(e.label);
                break;

            case EventType.Load:
                LoadState(e.label);
                break;

            case EventType.SaveInitial:
                SaveInitialState();
                break;

            case EventType.LoadInitial:
                LoadInitialState();
                break;

            case EventType.LoadLast:
                LoadLastState();
                break;

            default:
                break;
            }
        }
Пример #21
0
        public override Task Publish(string senderId, List <object> data, Dictionary <string, string> context)
        {
            return(Task.Run(() => {
                var path = EndPointConfig.Properties["Path"];
                if (string.IsNullOrEmpty(path))
                {
                    _logger.Error("Property 'Path' is missing from the end point config properties");
                    var stateEvent = new StateEvent()
                    {
                        SenderId = Id,
                        State = CollectorConstants.STATE_PUBLISHER_ERROR,
                        ExtraInfo = "Path property is missing."
                    };
                    _collector.SignalEvent(stateEvent);
                    return;
                }

                CreateDirectory(EndPointConfig.Properties["Path"]);
                foreach (var point in data)
                {
                    var entity = point as IEntity;
                    var payload = JsonConvert.SerializeObject(entity);
                    var logEntry = string.Format("Entity : {0}", payload);
                    var fullPath = string.Format("{0}\\publisher-log.txt", path);
                    using (StreamWriter file = new StreamWriter(fullPath, File.Exists(fullPath)))
                    {
                        file.WriteLine(logEntry);
                    }
                }
            }));
        }
Пример #22
0
        StateDelegate negated2(StateEvent e)
        {
            switch (e.Signal)
            {
            case Signal.Entry:
                Negate();
                return(null);

            case (Signal)CalcSignal.Digit0:
                TransitionState(zero2);
                return(null);

            case (Signal)CalcSignal.Digit1_9:
                Append(((CalcEvent)e).Key);
                TransitionState(int2);
                return(null);

            case (Signal)CalcSignal.Point:
                Append('.');
                TransitionState(frac2);
                return(null);

            case (Signal)CalcSignal.ClearEntry:
                Zero();
                TransitionState(opEntered);
                return(null);
            }
            return(on);
        }
Пример #23
0
        StateDelegate opEntered(StateEvent e)
        {
            switch (e.Signal)
            {
            case Signal.Entry:
                clearOnNext = true;
                negative    = false;
                return(null);

            case (Signal)CalcSignal.Operator:
                if (((CalcEvent)e).Key == '-')
                {
                    TransitionState(negated2);
                    return(null);
                }
                break;

            case (Signal)CalcSignal.Digit0:
                Append('0');
                clearOnNext = true;
                TransitionState(zero2);
                return(null);

            case (Signal)CalcSignal.Digit1_9:
                Append(((CalcEvent)e).Key);
                TransitionState(int2);
                return(null);

            case (Signal)CalcSignal.Point:
                Append('.');
                TransitionState(frac2);
                return(null);
            }
            return(on);
        }
Пример #24
0
        internal unsafe IntPtr GetStatePtrFromStateEvent(InputEventPtr eventPtr)
        {
            if (!eventPtr.valid)
            {
                throw new ArgumentNullException("eventPtr");
            }

            uint   stateOffset;
            FourCC stateFormat;
            uint   stateSizeInBytes;
            IntPtr statePtr;

            if (eventPtr.IsA <DeltaStateEvent>())
            {
                var deltaEvent = DeltaStateEvent.From(eventPtr);

                // If it's a delta event, we need to subtract the delta state offset if it's not set to the root of the device
                stateOffset      = deltaEvent->stateOffset;
                stateFormat      = deltaEvent->stateFormat;
                stateSizeInBytes = deltaEvent->deltaStateSizeInBytes;
                statePtr         = deltaEvent->deltaState;
            }
            else if (eventPtr.IsA <StateEvent>())
            {
                var stateEvent = StateEvent.From(eventPtr);

                stateOffset      = 0;
                stateFormat      = stateEvent->stateFormat;
                stateSizeInBytes = stateEvent->stateSizeInBytes;
                statePtr         = stateEvent->state;
            }
            else
            {
                throw new ArgumentException("Event must be a state or delta state event", "eventPtr");
            }


            // Make sure we have a state event compatible with our device. The event doesn't
            // have to be specifically for our device (we don't require device IDs to match) but
            // the formats have to match and the size must be within range of what we're trying
            // to read.
            if (stateFormat != device.m_StateBlock.format)
            {
                throw new InvalidOperationException(
                          string.Format(
                              "Cannot read control '{0}' from {1} with format {2}; device '{3}' expects format {4}",
                              path, eventPtr.type, stateFormat, device, device.m_StateBlock.format));
            }

            // Once a device has been added, global state buffer offsets are baked into control hierarchies.
            // We need to unsubtract those offsets here.
            stateOffset += device.m_StateBlock.byteOffset;

            if (m_StateBlock.byteOffset - stateOffset + m_StateBlock.alignedSizeInBytes > stateSizeInBytes)
            {
                return(IntPtr.Zero);
            }

            return(new IntPtr(statePtr.ToInt64() - (int)stateOffset));
        }
Пример #25
0
    private void Update()
    {
        if (Time.frameCount == executeFrame)
        {
            using (StateEvent.From(keyboard, out InputEventPtr eventPtr))
            {
                keyboard[Key.A].WriteValueIntoEvent <float>(1, eventPtr);
                keyboard[Key.B].WriteValueIntoEvent <float>(1, eventPtr);
                InputSystem.QueueEvent(eventPtr);
            }

            //if (doA)
            //{
            //    using (StateEvent.From(keyboard, out InputEventPtr eventPtr))
            //    {
            //        keyboard[Key.A].WriteValueIntoEvent<float>(1, eventPtr);
            //        InputSystem.QueueEvent(eventPtr);
            //    }
            //}

            //if (doB)
            //{
            //    using (StateEvent.From(keyboard, out InputEventPtr eventPtr))
            //    {
            //        keyboard[Key.B].WriteValueIntoEvent<float>(1, eventPtr);
            //        InputSystem.QueueEvent(eventPtr);
            //    }
            //}
        }
        else if (Time.frameCount == executeFrame * 2)
        {
            using (StateEvent.From(keyboard, out InputEventPtr eventPtr))
            {
                keyboard[Key.A].WriteValueIntoEvent <float>(0, eventPtr);
                keyboard[Key.B].WriteValueIntoEvent <float>(0, eventPtr);
                InputSystem.QueueEvent(eventPtr);
            }

            //if (doA)
            //{
            //    using (StateEvent.From(keyboard, out InputEventPtr eventPtr))
            //    {
            //        keyboard[Key.A].WriteValueIntoEvent<float>(0, eventPtr);
            //        InputSystem.QueueEvent(eventPtr);
            //    }
            //}

            //if (doB)
            //{
            //    using (StateEvent.From(keyboard, out InputEventPtr eventPtr))
            //    {
            //        keyboard[Key.B].WriteValueIntoEvent<float>(0, eventPtr);
            //        InputSystem.QueueEvent(eventPtr);
            //    }
            //}
        }

        pressedA = keyboard[Key.A].ReadValue() > 0.1f;
        pressedB = keyboard[Key.B].ReadValue() > 0.1f;
    }
Пример #26
0
        /// <summary>
        /// Generates the code for a StateEvent node.
        /// </summary>
        /// <param name="se">The StateEvent node.</param>
        /// <param name="parentStateName">The name of the parent state.</param>
        /// <returns>String containing C# code for StateEvent se.</returns>
        private void GenerateStateEvent(StateEvent se, string parentStateName, StringBuilder sb)
        {
            // we need to separate the argument declaration list from other kids
            List <SYMBOL> argumentDeclarationListKids = new List <SYMBOL>();
            List <SYMBOL> remainingKids = new List <SYMBOL>();

            foreach (SYMBOL kid in se.kids)
            {
                if (kid is ArgumentDeclarationList)
                {
                    argumentDeclarationListKids.Add(kid);
                }
                else
                {
                    remainingKids.Add(kid);
                }
            }

            // "state" (function) declaration
            GenerateIndented(String.Format("public void {0}_event_{1}(", parentStateName, se.Name), se, sb);

            // print the state arguments, if any
            foreach (SYMBOL kid in argumentDeclarationListKids)
            {
                GenerateArgumentDeclarationList((ArgumentDeclarationList)kid, sb);
            }

            GenerateLine(")", sb);

            foreach (SYMBOL kid in remainingKids)
            {
                GenerateNodeToSB(se, kid, sb);
            }
        }
 /// <summary>
 /// 开启服务
 /// </summary>
 /// <returns></returns>
 public bool StartServer()
 {
     asynTcp.AsyncDataAcceptedEvent += AsynTcp_AsyncDataAcceptedEvent;
     asynTcp.AsyncSocketAcceptEvent += AsynTcp_AsyncSocketAcceptEvent;
     asynTcp.AsyncSocketClosedEvent += AsynTcp_AsyncSocketClosedEvent;
     MsgEvent?.Invoke();
     StateEvent?.Invoke(string.Format("服务端: {0}:{1} 开始监听!!!", address == "" ? "LocalHost" : address, point.ToString()));
     return(asynTcp.AsyncOpen());
 }
Пример #28
0
    public virtual void Awake()
    {
        if (onStateChange == null)
        {
            onStateChange = new StateEvent();
        }

        lastStateChange = Time.time;
    }
Пример #29
0
        public unsafe bool PreProcessEvent(InputEventPtr eventPtr)
        {
            if (eventPtr.type == DeltaStateEvent.Type)
            {
                // if someone queued delta state SPVS directly, just use as-is
                // otherwise skip all delta state events
                return(DeltaStateEvent.FromUnchecked(eventPtr)->stateFormat == SwitchProControllerHIDInputState.Format);
            }

            // use all other non-state/non-delta-state events
            if (eventPtr.type != StateEvent.Type)
            {
                return(true);
            }

            var stateEvent = StateEvent.FromUnchecked(eventPtr);
            var size       = stateEvent->stateSizeInBytes;

            if (stateEvent->stateFormat == SwitchProControllerHIDInputState.Format)
            {
                return(true); // if someone queued SPVS directly, just use as-is
            }
            if (stateEvent->stateFormat != SwitchHIDGenericInputReport.Format || size < sizeof(SwitchHIDGenericInputReport))
            {
                return(false); // skip unrecognized state events otherwise they will corrupt control states
            }
            var genericReport = (SwitchHIDGenericInputReport *)stateEvent->state;

            if (genericReport->reportId == SwitchSimpleInputReport.ExpectedReportId && size >= SwitchSimpleInputReport.kSize)
            {
                var data = ((SwitchSimpleInputReport *)stateEvent->state)->ToHIDInputReport();
                *((SwitchProControllerHIDInputState *)stateEvent->state) = data;
                stateEvent->stateFormat = SwitchProControllerHIDInputState.Format;
                return(true);
            }
            else if (genericReport->reportId == SwitchFullInputReport.ExpectedReportId && size >= SwitchFullInputReport.kSize)
            {
                var data = ((SwitchFullInputReport *)stateEvent->state)->ToHIDInputReport();
                *((SwitchProControllerHIDInputState *)stateEvent->state) = data;
                stateEvent->stateFormat = SwitchProControllerHIDInputState.Format;
                return(true);
            }
            else if (size == 8 || size == 9) // official accessories send 8 byte reports
            {
                // On Windows HID stack we somehow get 1 byte extra prepended, so if we get 9 bytes, subtract one, see ISX-993
                // This is written in such way that if we fix it in backend, we wont break the package (Unity will report 8 bytes instead of 9 bytes).
                var bugOffset = size == 9 ? 1 : 0;
                var data      = ((SwitchInputOnlyReport *)((byte *)stateEvent->state + bugOffset))->ToHIDInputReport();
                *((SwitchProControllerHIDInputState *)stateEvent->state) = data;
                stateEvent->stateFormat = SwitchProControllerHIDInputState.Format;
                return(true);
            }
            else
            {
                return(false); // skip unrecognized reportId
            }
        }
Пример #30
0
 /// <summary>
 /// Decrement the counter. Trigger the StateEvent if in the previous state the counter riched the maximum value.
 /// </summary>
 public static void Remove()
 {
     --count;
     if (full)
     {
         full = false;
         StateEvent?.Invoke(null, new BoolEventArgs(false));
     }
 }
Пример #31
0
 /// <summary>
 /// MOGA Controller state event
 /// </summary>
 /// <param name="e">State event args</param>
 public void OnStateEvent(StateEvent e)
 {
     Debug.WriteLine("Controller state changed event");
     // TODO
 }
	public State on_update_own(StateEvent evn)
	{
		update_own_actions.Add(evn);
		return this;
	}
Пример #33
0
		public bool shutdown() {
			if(state == State.Stopped) {
				state = State.UnInited;
				var s = new StateEvent(state);
				lock(queueLock) {
					queue.Enqueue(s);
					Monitor.PulseAll(queueLock);
				}
				s.Wait();
				return true;
			} else {
				return false;
			}
		}
 public static void FixEventName(string script, ref StateEvent evt)
 {
     if (evt.Name == "remote_data")
     {
         string[] lines = script.Split(new [] { '\n' });
         string line = lines[evt.Line-1];
         if (line.IndexOf('(') > 0)
         {
             line = line.Substring(0, line.IndexOf('(')).Trim();
             if(_newLSLEvents.Any((ev) => ev.Name == line))
                 evt.Name = line;
         }
     }
 }
Пример #35
0
		public bool start() {
			if(state == State.Stopped) {
				state = State.Running;
				var s = new StateEvent(state);
				lock(queueLock) {
					queue.Enqueue(s);
					Monitor.PulseAll(queueLock);
				}
				s.Wait();
				return true;
			} else if(state == State.Running){
				return true;
			} else {
				return false;
			}
		}
Пример #36
0
		public bool step() {
			if(state == State.Stopped) {
				var s = new StateEvent(State.Step);
				lock(queueLock) {
					queue.Enqueue(s);
					Monitor.PulseAll(queueLock);
				}
				s.Wait();
				return true;
			} else {
				return false;
			}
		}
Пример #37
0
        public void closedTradeChangeNotification(string pair, Dictionary<string, object> map, StateEvent e)
        {
            if (StateEvent.Create == e)
            {
                Dictionary<string, string> closedTradeMap = new Dictionary<string, string>();
                string closedTradeId = "1";
                if (closedTradeId != null)
                    //tradeMap["AccountID"] = otr.AccountID; ;
                    closedTradeMap["Amount"] = "" + map["amount"];
                //tradeMap["OfferID"] = otr.OfferID;
                //tradeMap["OrderID"] = otr.OpenOrderID;
                closedTradeMap["BuySell"] = "" + map["entry"];
                closedTradeMap["OpenRate"] = "" + map["openPrice"];
                closedTradeMap["Pair"] = pair;
                closedTradeId = "" + map["orderId"];

                string grossPL = "[" + map["grossPL"] + "]"; // init with base-currency PL
                double pips = (double)map["pips"];
                int amount = (int)map["amount"];
                double basePL = pips * amount * TransactionManager.getPoiintSize(pair);
                double rate = getSpotRate(pair);
                if (rate != 0.0)
                {
                    grossPL = ""+ basePL / rate;
                }

                log.debug("Close added\t{0}, amount={1}, entry={2}, orderID={3}, tradeID={4}, grossPL={5}, pips={6}, customId={7}, accountId={8}",
                pair, map["amount"], map["entry"], map["orderId"], map["tradeId"], grossPL, map["pips"], map["customId"], "simuated");
            }
            else if (StateEvent.Delete == e)
            {
                   // TODO--print a log entry

            }
        }
Пример #38
0
        /// <summary>
        ///     Generates the code for a StateEvent node.
        /// </summary>
        /// <param name="se">The StateEvent node.</param>
        /// <param name="parentStateName">The name of the parent state.</param>
        /// <returns>String containing C# code for StateEvent se.</returns>
        private string GenerateStateEvent(StateEvent se, string parentStateName)
        {
            StringBuilder retstr = new StringBuilder();

            // we need to separate the argument declaration list from other kids
            List<SYMBOL> argumentDeclarationListKids = new List<SYMBOL>();
            List<SYMBOL> remainingKids = new List<SYMBOL>();

            _currentLocalFunctionDeclaration = se;

            MethodVariables.Clear();
            VariablesToRename.Clear();

            foreach (SYMBOL kid in se.kids)
                if (kid is ArgumentDeclarationList)
                    argumentDeclarationListKids.Add(kid);
                else
                    remainingKids.Add(kid);

            // "state" (function) declaration
            retstr.Append(GenerateIndented(
                String.Format("public System.Collections.IEnumerator {0}_event_{1}(", parentStateName, se.Name), se));

            IsParentEnumerable = true;

            // print the state arguments, if any
            List<ArgumentDeclarationList> args = new List<ArgumentDeclarationList>();
            foreach (SYMBOL kid in argumentDeclarationListKids)
            {
                args.Add(((ArgumentDeclarationList) kid));
                retstr.Append(GenerateArgumentDeclarationList((ArgumentDeclarationList) kid));
            }

            m_allMethods.Add(String.Format("{0}_event_{1}", parentStateName, se.Name), args);
            retstr.Append(GenerateLine(")"));


            foreach (SYMBOL kid in remainingKids)
                retstr.Append(GenerateNode(kid));


            if (retstr[retstr.Length - 2] == '}')
                retstr.Insert(retstr.Length - 2, GenerateLine("    yield break;"));

            return retstr.ToString();
        }
Пример #39
0
 public void positionChangeNotification(string pair, Dictionary<string, object> map, StateEvent e)
 {
     if (StateEvent.Create == e)
     {
         Dictionary<string, object> tradeMap = new Dictionary<string, object>();
         string tradeId = "1";
         if (tradeId != null)
             lock (posnLockObject)
             {
                 //tradeMap["AccountID"] = otr.AccountID; ;
                 tradeMap["Amount"] = "" + map["amount"];
                 //tradeMap["OfferID"] = otr.OfferID;
                 //tradeMap["OrderID"] = otr.OpenOrderID;
                 tradeMap["BuySell"] = "" + map["entry"];
                 tradeMap["OpenRate"] = "" + map["price"];
                 tradeMap["Pair"] = pair;
                 tradeId = "" + map["tradeId"];
                 mapTrade.Add(tradeId, tradeMap);
                 if (!mapPairTrade.ContainsKey(pair))
                 {
                     mapPairTrade.Add(pair, new List<string>());
                 }
                 List<string> lt = mapPairTrade[pair];
                 lt.Add(tradeId);
                 log.debug("trade opened\t{0}, amount={1}, entry={2}, orderId={3}, tradeId={4}, customId={5}, accountId={6}",
                      pair, map["amount"], map["entry"], map["orderId"], map["tradeId"], map["customId"], "simulated");
             }
     } else if (StateEvent.Delete == e)
     {
         string tradeId = "" + map["tradeId"];
         if (tradeId != null)
             lock (posnLockObject)
             {
                 if (mapTrade.ContainsKey(tradeId))
                 {
                     mapTrade.Remove(tradeId);
                 }
                 if (mapPairTrade.ContainsKey(pair))
                 {
                     List<string> lt = mapPairTrade[pair];
                     lt.Remove(tradeId);
                     if (lt.Count == 0)
                         mapPairTrade.Remove(pair);
                 }
             }
         log.debug("trade closed\t{0}, amount={1}, entry={2}, tradeId={3}, openOrderID={4}, customId={5}, accountId={6}",
              pair, map["amount"], map["entry"], map["tradeId"], map["orderId"], map["customId"], "simulated");
     }
 }
Пример #40
0
 public void orderChangeNotification(string pair, Dictionary<string, object> map, StateEvent e)
 {
     if (StateEvent.Create == e)
     {
         Dictionary<string, string> orderMap = new Dictionary<string, string>();
         string orderId = "1";
         if (orderId != null)
                 //tradeMap["AccountID"] = otr.AccountID; ;
                 orderMap["Amount"] = "" + map["amount"];
                 //tradeMap["OfferID"] = otr.OfferID;
                 //tradeMap["OrderID"] = otr.OpenOrderID;
                 orderMap["BuySell"] = "" + map["entry"];
                 orderMap["OpenRate"] = "" + map["price"];
                 orderMap["Pair"] = pair;
                 orderId = "" + map["orderId"];
         log.debug("Order added\t{0}, amount={1}, entry={2}, orderId={3}, type={4}, contingencyType={5}, rate={6}, pegOffset={7}, customId={8}, accountId={9}",
             pair, map["amount"], map["entry"], map["orderId"], map["type"], "n/a", map["price"], "n/a", map["customId"], "simulated");
     }
     else if (StateEvent.Delete == e)
     {
         string orderId = "" + map["orderId"];
         if (orderId != null)
             log.debug("Order deleted\t{0}, amount={1}, entry={2}, orderId={3}, type={4}, contingencyType={5}, rate={6}, customId={7}, accountId={8}",
             pair, map["amount"], map["entry"], map["orderId"], map["type"], "n/a", map["price"], map["customId"], "simulated");
     }
 }
        /*
        // Subscribe Methods
        public virtual void Subscribe(StateEvent e, Method method)
        {

            // Update Events
            if (e == StateEvent.OnUpdate)
            {
                Instance.Updater.SubscribeUpdate(method);
            }
            else if (e == StateEvent.OnFixedUpdate)
            {
                Instance.Updater.SubscribeFixedUpdate(method);
            }
            else if (e == StateEvent.OnLateUpdate)
            {
                Instance.Updater.SubscribeLateUpdate(method);
            }

        }
        */
        internal virtual void Subscribe(StateEvent e, GameObject target, Method method)
        {
            // Update Events
            if (e == StateEvent.OnUpdate)
            {
                Instance.Updater.SubscribeUpdate(method);
                //Observable.Subscribe<BehaviourUpdate>(target, method);
            }
            else if (e == StateEvent.OnFixedUpdate)
            {
                Instance.Updater.SubscribeFixedUpdate(method);
                //Observable.Subscribe<BehaviourFixedUpdate>(target, method);
            }
            else if (e == StateEvent.OnLateUpdate)
            {
                Instance.Updater.SubscribeLateUpdate(method);
                //Observable.Subscribe<BehaviourLateUpdate>(target, method);
            }

            // Inspector Events
            else
            if (e == StateEvent.OnReset)
            {
                Observable.Subscribe<InspectorReset>(target, method);
            }

            // Application Events
            else if (e == StateEvent.OnResume)
            {
                Observable.Subscribe<AppResume>(target, method);
            }
            else if (e == StateEvent.OnPause)
            {
                Observable.Subscribe<AppPause>(target, method);
            }
            else if (e == StateEvent.OnQuit)
            {
                Observable.Subscribe<AppQuit>(target, method);
            }

            // Transform Events
            else if (e == StateEvent.OnTransformParentChanged)
            {
                Observable.Subscribe<TransformParentChange>(target, method);
            }
            else if (e == StateEvent.OnTransformChildrenChanged)
            {
                Observable.Subscribe<TransformChildrenChange>(target, method);
            }

            // Draw Events
            else if (e == StateEvent.OnDrawGizmos)
            {
                Observable.Subscribe<DrawGizmos>(target, method);
            }
            else if (e == StateEvent.OnDrawGizmosSelected)
            {
                Observable.Subscribe<DrawGizmosSelected>(target, method);
            }

            // Collision Events
            else if (e == StateEvent.OnCollisionEnter)
            {
                Observable<Collision>.Subscribe<CollisionEnter>(target, method);
            }
            else if (e == StateEvent.OnCollisionStay)
            {
                Observable<Collision>.Subscribe<CollisionStay>(target, method);
            }
            else if (e == StateEvent.OnCollisionExit)
            {
                Observable<Collision>.Subscribe<CollisionExit>(target, method);
            }

            // Collision 2D Events
            else if (e == StateEvent.OnCollisionEnter2D)
            {
                Observable<Collision2D>.Subscribe<CollisionEnter2D>(target, method);
            }
            else if (e == StateEvent.OnCollisionStay2D)
            {
                Observable<Collision2D>.Subscribe<CollisionStay2D>(target, method);
            }
            else if (e == StateEvent.OnCollisionExit2D)
            {
                Observable<Collision2D>.Subscribe<CollisionExit2D>(target, method);
            }

            // Trigger Events
            else if (e == StateEvent.OnTriggerEnter)
            {
                Observable<Collider>.Subscribe<TriggerEnter>(target, method);
            }
            else if (e == StateEvent.OnTriggerStay)
            {
                Observable<Collider>.Subscribe<TriggerStay>(target, method);
            }
            else if (e == StateEvent.OnTriggerExit)
            {
                Observable<Collider>.Subscribe<TriggerExit>(target, method);
            }

            // Trigger 2D Events
            else if (e == StateEvent.OnTriggerEnter2D)
            {
                Observable<Collider2D>.Subscribe<TriggerEnter2D>(target, method);
            }
            else if (e == StateEvent.OnTriggerStay2D)
            {
                Observable<Collider2D>.Subscribe<TriggerStay2D>(target, method);
            }
            else if (e == StateEvent.OnTriggerExit2D)
            {
                Observable<Collider2D>.Subscribe<TriggerExit2D>(target, method);
            }

            // Render Events
            else if (e == StateEvent.OnWillRenderObject)
            {
                Observable.Subscribe<WillRenderObject>(target, method);
            }
            else if (e == StateEvent.OnPreCull)
            {
                Observable.Subscribe<PreCull>(target, method);
            }
            else if (e == StateEvent.OnBecameVisible)
            {
                Observable.Subscribe<BecameVisible>(target, method);
            }
            else if (e == StateEvent.OnBecameInvisible)
            {
                Observable.Subscribe<BecameInvisible>(target, method);
            }
            else if (e == StateEvent.OnPreRender)
            {
                Observable.Subscribe<PreRender>(target, method);
            }
            else if (e == StateEvent.OnRenderObject)
            {
                Observable.Subscribe<RenderObject>(target, method);
            }
            else if (e == StateEvent.OnRenderImage)
            {
                Observable<RenderTexture, RenderTexture>.Subscribe<RenderImage>(target, method);
            }
            else if (e == StateEvent.OnPostRender)
            {
                Observable.Subscribe<PostRender>(target, method);
            }

            // Animator Events
            else if (e == StateEvent.OnAnimatorIK)
            {
                Observable<int>.Subscribe<AnimatorIK>(target, method);
            }
            else if (e == StateEvent.OnAnimatorMove)
            {
                Observable.Subscribe<AnimatorMove>(target, method);
            }
        }
	public State on_entry(StateEvent evn)
	{
		entry_actions.Add(evn);
		return this;
	}
	public State on_exit(StateEvent evn)
	{
		exit_actions.Add(evn);
		return this;
	}
Пример #44
0
 public void positionChangeNotification(string pair, Dictionary<string, object> map, StateEvent e)
 {
     if (e == StateEvent.Delete)
     {
         getOrder().closeOrders(pair, (string)map["entry"]);
     }
     else if (e == StateEvent.Create)
     {
     }
 }
Пример #45
0
 public void orderChangeNotification(string pair, Dictionary<string, object> map, StateEvent e)
 {
     throw new NotImplementedException();
 }