コード例 #1
0
ファイル: TheDriver.cs プロジェクト: darkiri/TicTacToe
 private static void Pipe(ControllerState state)
 {
     if (state != ControllerState.Quit)
     {
         Pipe(_controller.DoUserInteraction(state));
     }
 }
コード例 #2
0
 void changeState(ControllerState state)
 {
     Event_TouchUp(new Vector3());
     isFirstTick = true;
     timeHold = 0;
     inputBeofreNum = 0;
     inputBefore = new Vector3();
     myState = state;
 }
コード例 #3
0
ファイル: Controller.cs プロジェクト: EraYaN/EV2020
 /// <summary>
 /// Initializes the Controller class
 /// </summary>
 public Controller()
 {
     Data.com.SerialDataEvent += com_SerialDataEvent;
     sendInstructions = new Timer(TimerPeriod);
     sendInstructions.Elapsed+=sendInstructions_Elapsed;
     sendInstructions.Start();
     _receivingBuffer = new StringBuilder();
     _replyStopwatch = new Stopwatch();
     state = ControllerState.Idle;
 }
コード例 #4
0
ファイル: Placer.cs プロジェクト: BigDub/HomePrototype
 public override void changeState(ControllerState newState)
 {
     if (ground != null)
     {
         Locator.getComponentManager().removeEntity(ground);
     }
     if (marker != null)
     {
         Locator.getComponentManager().removeEntity(marker);
     }
     base.changeState(newState);
 }
コード例 #5
0
	void Update()
	{
		var animator = GetComponent<Animator>();		
		var newState = animator.GetCurrentState(0);
		bool changed = newState!=PrevState;
		PrevState = CurrentState;
		CurrentState = newState;
		if(changed) 
		{
			OnStateChanged(this);
		}

		HandleOneShot(); 
	}
コード例 #6
0
    public void Awake()
    {
        HandleCollisions = true;
        State = new ControllerState();
        _transform = transform;
        _localScale = transform.localScale;
        _boxCollider = GetComponent<BoxCollider2D>();
        var colliderWidth = _boxCollider.size.x * Mathf.Abs(transform.localScale.x)-(2 * SkinWidth);

        _horizontalDistanceBetweenRays = colliderWidth / (TotVerticalRays - 1);

        var colliderHeight = _boxCollider.size.y * Mathf.Abs(transform.localScale.y) - (2 * SkinWidth);
        _verticalDistanceBetweenRays = colliderHeight / (TotHorizontalRays - 1);
    }
コード例 #7
0
 public BipedControllerComponent(Actor owner)
     : base(owner)
 {
     DesiredMovementActions = MovementActions.Neutral;
     OrientationChange = Quaternion.Identity;
     HorizontalMovement = Vector2.Zero;
     Controller = null;
     MaxTurnAnglePerTick = MathHelper.Pi / 8.0f;
     mAnimationStateMachine = null;
     mState = ControllerState.Neutral;
     mBooster = null;
     AimCheck = delegate() { return false; };
     mAttentionLock = new Object();
     IsAttentionAvailable = true;
     Owner.ActorInitialized += ActorInitializedHandler;
     WorldAim = null;
 }
コード例 #8
0
        protected override void ProcessController()
        {
            ControllerState newState = new ControllerState();
            JoystickState joyState = new JoystickState();

            if (this.padsList == null || !this.padsList.Any())
            {
                this.padsList = this.GetGamePads();
                if (!this.padsList.Any()) return;
            }

            if (this.device == null)
            {
                this.device = this.padsList[0];
            }

            if (this.pad == null)
            {
                this.Acquire();
            }

            if (this.pad == null || this.pad.Poll().IsFailure || this.pad.GetCurrentState(ref joyState).IsFailure)
            {
                newState.Active = false;
            }
            else
            {
                //var objs = pad.GetObjects();
                newState.Active = true;
                newState.X = (joyState.X / 5000d);
                newState.Y = (joyState.Y / 5000d);
                newState.Buttons = joyState.GetButtons();
            }

            if (!newState.Equals(this.State))
            {

                this.State = newState;

                if (this.OnUpdate != null)
                {
                    this.OnUpdate.Invoke(this.State);
                }
            }
        }
コード例 #9
0
 public void forceState(ControllerState newState)
 {
     state = newState;
 }
コード例 #10
0
ファイル: VRUIButton.cs プロジェクト: Pcat0/VRTD
 public override void OnHoverExit(Vector2 position, ControllerState controllerState)
 {
     image.color = normalColor;
 }
コード例 #11
0
 public static extern uint XInputGetState(uint controllerIndex, out ControllerState state);
コード例 #12
0
ファイル: Controller.cs プロジェクト: jadevlin/EDMSuite
        public void StartTCL()
        {
            TCLState = Controller.ControllerState.RUNNING;
            Thread.Sleep(2000);
            Thread mainThread = new Thread(new ThreadStart(mainLoop));
            ui.UpdateUIState(TCLState);

            mainThread.Start();
        }
コード例 #13
0
 /// <summary>
 /// Parks the laser on a resonance. Uses ScanMaster to scan the laser and fit to the spectrum  in order
 /// to locate the resonance. Then adjusts the laser frequency to park the laser on the resonance.
 /// Note that this method parks but doesn't lock the laser
 /// </summary>
 public void Park()
 {
     double[] fitresult;
     ui.AddToTextBox("Attempting to park..." + Environment.NewLine);
     status = ControllerState.busy;
     try
     {
         scanMaster.AcquireAndWait(ui.ScansPerPark);
         Scan scan = scanMaster.DataStore.AverageScan;
         if (scan.Points.Count != 0)
         {
             fitresult = FitSpectrum(scan);
             double centreVoltage = fitresult[2];
             double scanStart = (double)scanMaster.GetOutputSetting("start");
             double scanEnd = (double)scanMaster.GetOutputSetting("end");
             if (centreVoltage > scanStart && centreVoltage < scanEnd)
             {
                 if (!Environs.Debug)
                 {
                     RampToVoltage(centreVoltage);
                     ui.AddToTextBox("Parked at " + centreVoltage + " volts." + Environment.NewLine);
                     ui.SetControlVoltageNumericEditorValue(centreVoltage);
                 }
                 else ui.AddToTextBox("Ramping to " + centreVoltage + " volts. \n");
             }
             else ui.AddToTextBox("Failed - Unable to locate the resonance." + Environment.NewLine);
         }
         else ui.AddToTextBox("Failed - Nothing to fit." + Environment.NewLine);
     }
     catch (System.Net.Sockets.SocketException)
     {
         ui.AddToTextBox("The connection to ScanMaster was refused. Make sure that ScanMaster is running." + Environment.NewLine);
     }
     status = ControllerState.free;
 }
コード例 #14
0
ファイル: Controller.cs プロジェクト: ColdMatter/EDMSuite
 public void StopRamp()
 {
     State = ControllerState.STOPPED;
     ui.updateUIState(State);
 }
コード例 #15
0
 public void getPreviousState(ControllerState state)
 {
     pState.CopyTo(state);
 }
コード例 #16
0
 public void getCurrentState(ControllerState state)
 {
     cState.CopyTo(state);
 }
コード例 #17
0
 public void getExposedState(EAll4StateExposed expState, ControllerState state)
 {
     cState.CopyTo(state);
     //expState.Accel = accel;
     //expState.Gyro = gyro;
 }
コード例 #18
0
ファイル: SetCommand.cs プロジェクト: EmVerif/EmVerifPC
 public void Finally(ControllerState inState)
 {
 }
コード例 #19
0
ファイル: SetCommand.cs プロジェクト: EmVerif/EmVerifPC
 public void Boot(ControllerState ioState)
 {
     ExecSetVarSetting(ioState);
 }
コード例 #20
0
        public static void RaiseEvent(ControllerState state)
        {
            switch (state)
            {
            case ControllerState.None:
                break;

            case ControllerState.Up:
                //if(pointer == ControllerPointerState.Down || pointer == ControllerPointerState.Enter){
                RaiseOnClick();
                RaiseOnUp();
                //}
                break;

            case ControllerState.Down:
                //if(pointer == ControllerPointerState.Down || pointer == ControllerPointerState.Enter){
                RaiseOnClick();
                RaiseOnDown();
                // }
                break;

            case ControllerState.Left:

                // if(pointer == ControllerPointerState.Down || pointer == ControllerPointerState.Enter){
                RaiseOnClick();
                RaiseOnLeft();
                // }
                break;

            case ControllerState.Right:
                // if(pointer == ControllerPointerState.Down || pointer == ControllerPointerState.Enter){
                RaiseOnClick();
                RaiseOnRight();
                // }
                break;

            case ControllerState.Select:
                // if(pointer == ControllerPointerState.Down){
                RaiseOnClick();
                RaiseOnSelect();
                // }
                break;

            case ControllerState.Start:
                // if(pointer == ControllerPointerState.Down){
                RaiseOnClick();
                RaiseOnStart();
                // }
                break;

            case ControllerState.A:
                // if(pointer == ControllerPointerState.Down || pointer == ControllerPointerState.Enter){
                RaiseOnClick();
                RaiseOnA();
                // }
                break;

            case ControllerState.B:
                // if(pointer == ControllerPointerState.Down || pointer == ControllerPointerState.Enter){
                RaiseOnClick();
                RaiseOnB();
                // }
                break;
            }
        }
コード例 #21
0
        /// <summary>
        /// 处理状态装换
        /// </summary>
        private void HandleState(ref ControllerState _currentControllerState, ref float3 _movementum, bool _isGrounded)
        {
            var up = math.up();

            var _isRising  = IsRisingOrFalling(_movementum) && GetDotProduct(_movementum, up) > 0f;
            var _isSliding = false;

            var newState      = _currentControllerState;
            var newMovementum = _movementum;

            switch (_currentControllerState)
            {
            case ControllerState.Grounded:
                if (_isRising)
                {
                    newState = ControllerState.Rising;    //地面->上升
                    //当离开地面,重置移动惯性为只有竖直方向
                    OnGroundConcactLost(ref _movementum);
                    break;
                }
                if (!_isGrounded)
                {
                    newState = ControllerState.Falling;    //地面到->下落
                    //当离开地面,重置移动惯性为只有竖直方向
                    OnGroundConcactLost(ref _movementum);
                    break;
                }
                if (_isSliding)
                {
                    newState = ControllerState.Sliding;    //地面->滑动
                    break;
                }
                break;

            case ControllerState.Sliding:
                break;

            case ControllerState.Falling:
                if (_isRising)
                {
                    newState = ControllerState.Rising;
                    break;
                }
                if (_isGrounded)
                {
                    newState = ControllerState.Grounded;
                    //重新回到地面
                    OnGroundContactRegained(_movementum);
                }
                if (_isSliding)
                {
                    newState = ControllerState.Sliding;
                    //重新回到地面
                    OnGroundContactRegained(_movementum);
                }

                break;

            case ControllerState.Rising:
                if (!_isRising)
                {
                    if (_isGrounded && !_isSliding)
                    {
                        newState = ControllerState.Grounded;
                        OnGroundContactRegained(_movementum);
                        break;
                    }
                    if (_isSliding)
                    {
                        newState = ControllerState.Sliding;
                        OnGroundContactRegained(_movementum);
                        break;
                    }
                    if (_isGrounded)
                    {
                        newState = ControllerState.Falling;
                        break;
                    }
                }
                break;

            case ControllerState.Jumping:
                //这儿直接转成Rising状态,所以Jumping状态只持续一帧
                newState = ControllerState.Rising;
                break;

            default:
                break;
            }

            _currentControllerState = newState;
            _movementum             = newMovementum;
        }
        //        public override void OnStart(PartModule.StartState state)
        //        {
        //            base.OnStart(state);
        //            
        //            fiSelRes = Type.GetType("Kethane.KethaneController").GetField("SelectedResource");
        //        }
        public override void OnFixedUpdate()
        {
            //			base.OnFixedUpdate();
            if (HighLogic.LoadedScene != GameScenes.FLIGHT || KethaneData.Current == null) { return; }

            if (lastBody != vessel.orbit.referenceBody) { // thanks to The_Duck, Technogeeky and ian for helping me fix the orbit calculation
                lastBody = vessel.orbit.referenceBody;
            //				Debug.Log("GravParameter " + lastBody.gravParameter);
                Orbits = new List<float>();
                int y = 1;
                var u3 = Math.Pow(lastBody.gravParameter, 1.0 / 3.0);
                while (y > 0)
                {
                    var oP = lastBody.rotationPeriod * (y / 80f);
                    var alt = u3 * Math.Pow(oP / (2 * Math.PI), 2.0 / 3.0) - lastBody.Radius;
                    var msg = string.Format("Orbit {0} is at {1:F1} km", y, alt / 1000f);
                    if (y % 2 != 0 && y % 5 != 0 && alt > 0 && alt < lastBody.sphereOfInfluence && (lastBody.atmosphere ? alt > lastBody.RealMaxAtmosphereAltitude() : true))
                    {
                        msg += " added";
                        Orbits.Add((float)alt / 1000f);
            //						Debug.Log(msg);
                    }
                    y++;
                    if (alt >= lastBody.sphereOfInfluence) { break; }
                }
                Orbits.Sort();
                string str = "";
                foreach (var o in Orbits)
                {
                    str += o.ToString("#.0") + " km\n";
                }
                System.IO.File.WriteAllText(KSPUtil.ApplicationRootPath + "\\KethaneScanOrbits_" + lastBody.name + ".txt", str);
            }

            //			var scans = KethaneData.Current.Scans[(string)fiSelRes.GetValue(null)][vessel.mainBody.name];
            var scans = KethaneData.Current.Scans[MapOverlay.SelectedResource][vessel.mainBody.name];
            Coverage = (float)Math.Floor(ordered.Count(c => scans[c]) / (float)ordered.Length * 100f * 100f) / 100f;

            var cell = GetLowestUnscanned(scans);
            if (Coverage == 100 && Active) {
                print(vessel.mainBody.name + " completely scanned at " + vesselState.time);
                TimeWarp.SetRate(0, false);
                Active = false;
            }
            maxInc = CellToLonLat(cell).y;

            if (Active)
            {
                var curInc = Math.Abs(maxInc);
                var myInc = Math.Abs(vesselState.orbitInclination);
                var diff = Math.Abs(myInc - curInc);

                switch (Status)
                {
                    case ControllerState.Inactive:
                        Status = ControllerState.Idle;
                        break;

                    case ControllerState.Idle:
                        if (diff > IncChangeStep && curInc >= IncChangeLimit && vessel.patchedConicSolver.maneuverNodes.Count == 0) {
                            var planner = core.GetComputerModule<MechJebModuleManeuverPlanner>();

                            double newInc;
                            if (ChangeByStep) {
                                newInc = vesselState.orbitInclination - (IncChangeStep * (vesselState.orbitInclination < 0 ? -1 : 1));
                            }
                            else
                            {
                                newInc = (curInc * (vesselState.orbitInclination < 0 ? -1 : 1));
                            }
                            newInc = Math.Round(newInc, 2);

                            var result = planner.PlanNode(MechJebModuleManeuverPlanner.Operation.INCLINATION,
                                                          MechJebModuleManeuverPlanner.TimeReference.EQ_ASCENDING, 0, 0, 0, newInc, 0, 0, 0, false);

                            if (result.Success && core.node != null) {
                                core.node.ExecuteOneNode(this);
                            }
                            else {
                                Active = false;
                                Status = ControllerState.Inactive;
                                print("KSC node planning error: " + result.Error + "\ntime error: " + result.TimeError);
                            }

                            warp = TimeWarp.CurrentRateIndex;
                            TimeWarp.SetRate(0, true);
                            Status = ControllerState.Waiting;
                        }
                        break;

                    case ControllerState.Waiting:
                        if (vessel.patchedConicSolver.maneuverNodes.Count == 0 && vessel.ctrlState.mainThrottle == 0)
                        {
                            TimeWarp.SetRate(warp, false);
                            Status = ControllerState.Idle;
            //							if (myInc - IncChangeStep < IncChangeLimit) { Active = false; }
                        }
                        break;
                }

            //				if (!core.node.users.Contains(this)) { core.node.users.Add(this); }
            }
            else //if(!Active)
            {
                if (Status != ControllerState.Disabled && Status != ControllerState.Inactive) { Status = ControllerState.Inactive; }
            //				if (core.node.users.Contains(this)) { core.node.users.Remove(this); }
            }
        }
コード例 #23
0
        void reader_ControllerStateChanged(IControllerReader reader, ControllerState newState)
        {
            newState = _blinkFilter.Process(newState);

            foreach (var button in _buttonsWithImages)
            {
                if (!newState.Buttons.ContainsKey(button.Item1.Name))
                {
                    continue;
                }

                button.Item2.Visibility = newState.Buttons [button.Item1.Name] ? Visibility.Visible : Visibility.Hidden;
            }

            foreach (var button in _rangeButtonsWithImages)
            {
                if (!newState.Analogs.ContainsKey(button.Item1.Name))
                {
                    continue;
                }

                var value   = newState.Analogs [button.Item1.Name];
                var visible = button.Item1.From <= value && value <= button.Item1.To;

                button.Item2.Visibility = visible ? Visibility.Visible : Visibility.Hidden;
            }

            foreach (var stick in _sticksWithImages)
            {
                var skin  = stick.Item1;
                var image = stick.Item2;

                float xrange = (skin.XReverse ? -1 :  1) * skin.XRange;
                float yrange = (skin.YReverse ?  1 : -1) * skin.YRange;

                var x = newState.Analogs.ContainsKey(skin.XName)
                      ? skin.Config.X + xrange * newState.Analogs [skin.XName]
                      : skin.Config.X;

                var y = newState.Analogs.ContainsKey(skin.YName)
                      ? skin.Config.Y + yrange * newState.Analogs [skin.YName]
                      : skin.Config.Y;

                image.Margin = new Thickness(x, y, 0, 0);
            }

            foreach (var trigger in _triggersWithGridImages)
            {
                var skin = trigger.Item1;
                var grid = trigger.Item2;

                if (!newState.Analogs.ContainsKey(skin.Name))
                {
                    continue;
                }

                var val = newState.Analogs [skin.Name];
                if (skin.UseNegative)
                {
                    val *= -1;
                }
                if (skin.IsReversed)
                {
                    val = 1 - val;
                }
                if (val < 0)
                {
                    val = 0;
                }
                switch (skin.Direction)
                {
                case Skin.AnalogTrigger.DirectionValue.Right:
                    grid.Width = skin.Config.Width * val;
                    break;

                case Skin.AnalogTrigger.DirectionValue.Left:
                    var width = skin.Config.Width * val;
                    var offx  = skin.Config.Width - width;
                    grid.Margin = new Thickness(skin.Config.X + offx, skin.Config.Y, 0, 0);
                    grid.Width  = width;
                    break;

                case Skin.AnalogTrigger.DirectionValue.Down:
                    grid.Height = skin.Config.Height * val;
                    break;

                case Skin.AnalogTrigger.DirectionValue.Up:
                    var height = skin.Config.Height * val;
                    var offy   = skin.Config.Height - height;
                    grid.Margin = new Thickness(skin.Config.X, skin.Config.Y + offy, 0, 0);
                    grid.Height = height;
                    break;
                }
            }
        }
コード例 #24
0
        public virtual void Update(TimeSpan dt, List <Direction> limiters, ControllerState controller)
        {
            Limiters = limiters;
            C        = controller;

            bool canMoveDown  = !limiters.Contains(Direction.Down);
            bool canMoveUp    = !limiters.Contains(Direction.Up);
            bool canMoveLeft  = !limiters.Contains(Direction.Right);
            bool canMoveRight = !limiters.Contains(Direction.Left);

            bool cs1 = false;
            bool cs2 = false;
            bool cs3 = false;
            bool cs4 = false;

            if (Confused)
            {
                cs1 = Extensions.RandomBool();
                cs2 = Extensions.RandomBool();
                cs3 = Extensions.RandomBool();
                cs4 = Extensions.RandomBool();
            }

            _currentMovement = Movement.Idle;

            HealthBar.Value = Health;

            #region Vibrating Health
            if (_vibratingHealth)
            {
                if (Extensions.GetMS() - _lastVibrateTime > Health + 200)
                {
                    _lastVibrateTime    = Extensions.GetMS();
                    _lastVibrateStarted = Extensions.GetMS();
                    controller.StartVibrate(0.7f, 0.7f);
                }
                if (Extensions.GetMS() - _lastVibrateStarted > 100)
                {
                    controller.StopVibrate();
                }
            }
            #endregion

            #region Satus Updates
            if (Stunned && Extensions.GetMS() - _lastStunTime > _stunDuration)
            {
                Stunned = false;
            }
            if (Confused && Extensions.GetMS() - _lastConfuseTime > _confuseDuration)
            {
                Confused = false;
            }
            if (Extensions.GetMS() - _lastManaGain > _manaGainDelay)
            {
                if (Mana < 5)
                {
                    Mana += 1;
                }
            }
            #endregion

            #region Physics
            if (canMoveDown && !Flying && !Dead)
            {
                Position.Y += (int)_gravityAcceleration;
                if (Program.Game.InsideWall(this) != null)
                {
                    Position.Y          -= (int)_gravityAcceleration;
                    _gravityAcceleration = Program.Game.Gravity * 5;
                    Jumping = false;
                }
                _gravityAcceleration += Program.Game.Gravity;
                _currentMovement      = _gravityAcceleration > JumpStrength ? Movement.Fall : Movement.Jump;
            }
            else
            {
                _gravityAcceleration = 0;
                Jumping = false;
            }
            #endregion

            #region Controller Input

            if (controller.IsButtonDown(Microsoft.Xna.Framework.Input.Buttons.LeftShoulder))
            {
                Health -= 10;
                if (Health < 0)
                {
                    Health = 0;
                }
            }
            else
            {
                if (Health > MaxHealth)
                {
                    Health = MaxHealth;
                }
            }

            if (!ActionLocked)
            {
                if ((controller.WasButtonPressed(Microsoft.Xna.Framework.Input.Buttons.A)) && !Stunned && !Dead)
                {
                    if (!Jumping)
                    {
                        Jumping = true;
                    }
                }
                if (Jumping && !Flying && !Dead)
                {
                    if (canMoveUp)
                    {
                        Position.Y -= JumpStrength;
                        if (Program.Game.InsideWall(this) != null)
                        {
                            Position.Y += JumpStrength;
                            Jumping     = false;
                        }
                    }
                    else
                    {
                        Jumping = false;
                    }
                }

                if (($"{C.LeftThumbstickDirection}".Contains("Right") || cs1) && canMoveRight && !Stunned && !Dead)
                {
                    Position.X     += Speed;
                    FacingDirection = Direction.Right;
                    if (!FlipLocked)
                    {
                        FlipHorizontally = false;
                    }
                    if (!canMoveDown)
                    {
                        _currentMovement = Movement.Walk;
                    }
                }
                if (($"{C.LeftThumbstickDirection}".Contains("Left") || cs2) && canMoveLeft && !Stunned && !Dead)
                {
                    Position.X     -= Speed;
                    FacingDirection = Direction.Left;
                    if (!FlipLocked)
                    {
                        FlipHorizontally = true;
                    }
                    if (!canMoveDown)
                    {
                        _currentMovement = Movement.Walk;
                    }
                }
                if (Flying)
                {
                    if ($"{C.LeftThumbstickDirection}".Contains("Up") && canMoveUp && !Stunned && !Dead)
                    {
                        Position.Y -= Speed;
                    }
                    if ($"{C.LeftThumbstickDirection}".Contains("Down") && canMoveDown && !Stunned && !Dead)
                    {
                        Position.Y += Speed;
                    }
                }

                if (controller.WasButtonPressed(Microsoft.Xna.Framework.Input.Buttons.B) && !Stunned && !Dead && Mana >= Ability1Cost)
                {
                    Mana -= Ability1Cost;
                    Ability1();
                }

                if (controller.WasButtonPressed(Microsoft.Xna.Framework.Input.Buttons.X) && !Stunned && !Dead && Mana >= Ability2Cost)
                {
                    Mana -= Ability2Cost;
                    Ability2();
                }

                if (controller.WasButtonPressed(Microsoft.Xna.Framework.Input.Buttons.Y) && !Stunned && !Dead && Mana >= Ability3Cost)
                {
                    Mana -= Ability3Cost;
                    Ability3();
                }

                if (controller.IsButtonDown(Microsoft.Xna.Framework.Input.Buttons.LeftShoulder) && controller.IsButtonDown(Microsoft.Xna.Framework.Input.Buttons.RightShoulder) && UltimatePercent == 1.0 && !Stunned && !Dead)
                {
                    UltimatePercent = 1.0;
                    Ultimate();
                }

                if (controller.RightTriggerPower > 0 && !Stunned && !Dead)
                {
                    var tms = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
                    if (tms - _lastShotTime > ShotInterval)
                    {
                        Shoot();
                        _lastShotTime = tms;
                    }
                }
            }

            #endregion

            #region Movement Animation

            if (MovementAnimated)
            {
                if (_lastMovement != _currentMovement)
                {
                    //switch to current movement animation
                    switch (_currentMovement)
                    {
                    case Movement.Idle:
                        HardSetAnimation(IdleAnimation);
                        break;

                    case Movement.Fall:
                        HardSetAnimation(FallAnimation);
                        break;

                    case Movement.Jump:
                        HardSetAnimation(JumpAnimation);
                        break;

                    case Movement.Walk:
                        HardSetAnimation(WalkAnimation);
                        break;
                    }
                }
            }

            #endregion

            _previousPosition = Position;
            _lastMovement     = _currentMovement;
        }
コード例 #25
0
ファイル: Controller.cs プロジェクト: ColdMatter/EDMSuite
        /// <summary>
        /// The main loop. Scans the cavity, looks at photodiodes, corrects the cavity scan range for the next
        /// scan and locks the laser.
        /// It does a first scan of the data before starting.
        /// It then enters a loop where the next scan is prepared. The preparation varies depending on 
        /// the ControllerState. Once all the preparation is done, the next scan is started. And so on.
        /// </summary>
        private void rampLoop()
        {
            readParametersFromUI();
            ScanParameters sp = createInitialScanParameters();
            initializeHardware();
            CavityScanData scanData = scan(sp);

            double[] masterDataFit;
            double[] slaveDataFit;
            System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\cavityData.txt");
            while (State != ControllerState.STOPPED)
            {
                displayData(sp, scanData);

                masterDataFit = CavityScanFitHelper.FitLorenzianToMasterData(scanData, sp.Low, sp.High);
                saveFitData(file, masterDataFit[1]);
                displayMasterFit(sp, masterDataFit);
                slaveDataFit = CavityScanFitHelper.FitLorenzianToSlaveData(scanData, sp.Low, sp.High);
                saveFitData(file, slaveDataFit[1]);
                displaySlaveFit(sp, slaveDataFit);

                switch (State)
                {
                    case ControllerState.FREERUNNING:
                        releaseLaser();
                        break;

                    case ControllerState.CAVITYSTABILIZED:
                        ScanOffset = calculateNewScanCentre(sp, masterDataFit);
                        sp.High = ScanOffset + scanWidth;
                        sp.Low = ScanOffset - scanWidth;

                        setToLaserEngaged();
                        break;

                    case ControllerState.LASERLOCKING:
                        ScanOffset = calculateNewScanCentre(sp, masterDataFit);
                        sp.High = ScanOffset + scanWidth;
                        sp.Low = ScanOffset - scanWidth;

                        LaserSetPoint = CalculateLaserSetPoint(masterDataFit, slaveDataFit);

                        State = ControllerState.LASERLOCKED;
                        ui.updateUIState(State);
                        break;

                    case ControllerState.LASERLOCKED:
                        ScanOffset = calculateNewScanCentre(sp, masterDataFit);
                        sp.High = ScanOffset + scanWidth;
                        sp.Low = ScanOffset - scanWidth;

                        LaserSetPoint = tweakSetPoint(LaserSetPoint); //does nothing if not tweaked

                        /*Console.WriteLine("width=" + slaveDataFit[0].ToString() + ", centre =" + slaveDataFit[1].ToString()
                            + ", amp=" + slaveDataFit[2].ToString() + ", offset=" + slaveDataFit[3].ToString());*/

                        double shift = calculateDeviationFromSetPoint(LaserSetPoint, masterDataFit, slaveDataFit);
                        VoltageToLaser = calculateNewVoltageToLaser(VoltageToLaser, shift);

                        break;

                }
                if (lState == LaserState.BUSY)
                {
                    tcl.SetLaserVoltage(VoltageToLaser);
                }

                scanData = scan(sp);
            }
            file.Close();
            finalizeRamping();
        }
コード例 #26
0
ファイル: RealDoorState.cs プロジェクト: radtek/smartaccess
        private void AddWatchData(Controller ctrlr, bool connected, ControllerState state, bool doorstate, bool relaystate)
        {
            string cardNo = null;

            if (state != null)
            {
                cardNo = state.cardOrNoNumber;
                var card = _cards.Find(m => m.CARD_WG_NO == state.cardOrNoNumber);
                if (card != null)
                {
                    cardNo = card.CARD_NO;
                }
                else
                {
                    Maticsoft.BLL.SMT_CARD_INFO cardBll = new Maticsoft.BLL.SMT_CARD_INFO();
                    var c = cardBll.GetModelList("CARD_WG_NO='" + state.cardOrNoNumber + "'");
                    if (c.Count > 0)
                    {
                        _cards.Add(c[0]);
                        cardNo = c[0].CARD_NO;
                    }
                }
            }
            string staffname = "未知";
            string orgname   = "未知";

            Maticsoft.Model.SMT_STAFF_INFO sinfo = null;
            if (cardNo != null)
            {
                try
                {
                    Maticsoft.BLL.SMT_STAFF_INFO siBll = new Maticsoft.BLL.SMT_STAFF_INFO();
                    var ds   = siBll.GetListByCardNum(cardNo);
                    var list = siBll.DataTableToListWithDept(ds.Tables[0]);
                    if (list.Count > 0)
                    {
                        staffname = list[0].REAL_NAME;
                        orgname   = list[0].ORG_NAME;
                        sinfo     = list[0];
                    }
                }
                catch (Exception ex)
                {
                    log.Error("读取职员异常:", ex);
                }
            }
            this.Invoke(new Action(() =>
            {
                foreach (ListViewItem item in _lastDetectDoorItems)
                {
                    Maticsoft.Model.SMT_DOOR_INFO door = (Maticsoft.Model.SMT_DOOR_INFO)item.Tag;
                    if (door.IS_ENABLE && door.CTRL_ID != null && door.CTRL_DOOR_INDEX != null)
                    {
                        if (ctrlr.id != (decimal)door.CTRL_ID)
                        {
                            continue;
                        }
                        int doorIndex = (int)door.CTRL_DOOR_INDEX;
                        bool doorLock = false;
                        if (state != null)
                        {
                            //更新状态
                            switch (doorIndex)
                            {
                            case 1:
                                doorLock = state.isOpenDoorOfLock1;
                                break;

                            case 2:
                                doorLock = state.isOpenDoorOfLock2;
                                break;

                            case 3:
                                doorLock = state.isOpenDoorOfLock3;
                                break;

                            case 4:
                                doorLock = state.isOpenDoorOfLock4;
                                break;

                            default:
                                break;
                            }

                            //更新状态
                            item.ImageIndex = doorLock ? 1 : 0;
                            door.OPEN_STATE = doorLock ? 1 : 0;
                            DoorDataHelper.UpdateDoorSync(door);
                        }

                        if ((!connected || state == null) && !doorstate)
                        {
                            door.OPEN_STATE = 2;
                            DoorDataHelper.UpdateDoorSync(door);
                            item.ImageIndex = connected ? 0 : 2;

                            /*DataGridViewRow row = new DataGridViewRow();
                             * row.Tag = ctrlr;
                             * row.CreateCells(dgvRealLog, DateTime.Now, door.DOOR_NAME, string.Format("控制器:IP={0},SN={1} {2}!", ctrlr.ip, ctrlr.sn, connected ? "连接成功" : "无法连接"));
                             * row.DefaultCellStyle.BackColor = Color.Yellow;
                             * dgvRealLog.Rows.Insert(0, row);*/
                        }
                        else if ((byte)door.CTRL_DOOR_INDEX == state.doorNum)
                        {
                            DataGridViewRow row = new DataGridViewRow();
                            row.Tag             = state;
                            if (relaystate)
                            {
                                // row.CreateCells(dgvRealLog, state.recordTime, door.DOOR_NAME, string.Format("门禁:{0},卡号:{1},继电器状态改变!", door.DOOR_NAME, cardNo));
                                //dgvRealLog.Rows.Insert(0, row);
                            }
                            else
                            {
                                string actionname = AccessHelper.GetRecordReasonString(state.reasonNo);
                                if (!doorLock)
                                {
                                    actionname += ",锁状态:关";
                                }
                                else
                                {
                                    actionname += ",锁状态:开";
                                }
                                if (doorstate)
                                {
                                    row.CreateCells(dgvRealLog, state.recordTime, door.DOOR_NAME + (state.isEnterDoor ? "-进门" : "-出门"), string.Format("人员:{0},部门:{1},门禁:{2},卡号:{3},动作:{4}", staffname, orgname, door.DOOR_NAME, cardNo, actionname));
                                    dgvRealLog.Rows.Insert(0, row);
                                    row.Tag = new object[] { sinfo, state };
                                    ShowStaffInfo(row, row.Tag as object[]);
                                    while (dgvRealLog.Rows.Count > 2000)
                                    {
                                        dgvRealLog.Rows.RemoveAt(dgvRealLog.Rows.Count - 1);
                                    }
                                }
                                //else
                                //{
                                // row.CreateCells(dgvRealLog, state.recordTime, door.DOOR_NAME + (state.isEnterDoor ? "-进门" : "-出门"), string.Format("人员:{0},部门:{1},门禁:{2},卡号:{3},动作:当前状态=>{4}", staffname, orgname, door.DOOR_NAME, cardNo, actionname));
                                // }
                            }
                        }
                    }
                }
                foreach (DataGridViewRow item in dgvRealLog.SelectedRows)
                {
                    item.Selected = false;
                }
                if (dgvRealLog.Rows.Count > 0)
                {
                    dgvRealLog.Rows[0].Selected = true;
                }
            }));
        }
コード例 #27
0
 public ControllerStateRuleAttribute(string id, Type controllerType, string normalCriteria, string emptyCriteria, ControllerState state) : base(id, normalCriteria, emptyCriteria) {
     ControllerType = controllerType;
     ControllerState = state;
 }
コード例 #28
0
ファイル: RealDoorState.cs プロジェクト: radtek/smartaccess
 private void ShowStaffInfo(DataGridViewRow row, object[] infos)
 {
     if (infos == null)
     {
         return;
     }
     if (infos.Length >= 3)
     {
         ShowFaceStaffInfo((Maticsoft.Model.SMT_FACERECG_DEVICE)infos[0], (Maticsoft.Model.BST.staff_log)infos[1], (DateTime)infos[2]);
         return;
     }
     try
     {
         if (picBox.Image != null)
         {
             picBox.Image.Dispose();
             picBox.Image = null;
         }
         if (picBox2.Image != null)
         {
             picBox2.Image.Dispose();
             picBox2.Image = null;
         }
         Maticsoft.Model.SMT_STAFF_INFO sinfo = infos[0] as Maticsoft.Model.SMT_STAFF_INFO;
         ControllerState state = infos[1] as ControllerState;
         if (sinfo.PHOTO != null && sinfo.PHOTO.Length > 0)
         {
             MemoryStream ms     = new MemoryStream(sinfo.PHOTO);
             Image        bitmap = Image.FromStream(ms);
             picBox.Image = bitmap;
         }
         if (sinfo != null)
         {
             lbStaffName.Text = sinfo.REAL_NAME;
             lbDeptName.Text  = sinfo.ORG_NAME;
         }
         else
         {
             lbStaffName.Text = "----";
             lbDeptName.Text  = "----";
         }
         if (state != null)
         {
             lbTime.Text = state.recordTime.ToString("yyyy-MM-dd HH:mm:ss ddd");
             if (row.Cells[1].Value != null)
             {
                 lbDoorName.Text = (string)row.Cells[1].Value;
             }
             else
             {
                 lbDoorName.Text = "----";
             }
             lbAction.Text = AccessHelper.GetRecordReasonString(state.reasonNo).Replace(":", "\r\n");
         }
         else
         {
             lbTime.Text     = ((DateTime)row.Cells[0].Value).ToString("yyyy-MM-dd HH:mm:ss ddd");
             lbDoorName.Text = "----";
             lbAction.Text   = "----";
         }
     }
     catch (Exception ex)
     {
         log.Error("显示信息异常:", ex);
     }
 }
コード例 #29
0
        public void Initialize(OpenTK.GameWindow window)
        {
            game = window;

            int numKeys = (int)OpenTK.Input.Key.LastKey;
            int numMouseButtons = (int)OpenTK.Input.MouseButton.LastButton;

            prevKeysDown = new bool[numKeys];
            curKeysDown = new bool[numKeys];
            for (int i = 0; i < numKeys; ++i) {
                prevKeysDown[i] = curKeysDown[i] = false;
            }

            prevMouseDown = new bool[numMouseButtons];
            curMouseDown = new bool[numMouseButtons];
            for (int i = 0; i < numMouseButtons; ++i) {
                prevMouseDown[i] = curMouseDown[i] = false;
            }

            numJoysticks = game.Joysticks.Count;
            joyMapping = new ControllerMapping[numJoysticks];
            prevJoyDown = new ControllerState[numJoysticks];
            curJoyDown = new ControllerState[numJoysticks];
            joyDeadZone = new float[numJoysticks];
            for (int i = 0; i < numJoysticks; ++i) {
                joyMapping[i] = new ControllerMapping();
                prevJoyDown[i] = new ControllerState();
                curJoyDown[i] = new ControllerState();
                joyDeadZone[i] = 0.25f;
            }

            isInitialized = true;
        }
コード例 #30
0
ファイル: RealDoorState.cs プロジェクト: radtek/smartaccess
        private void biDetectCtrlr_Click(object sender, EventArgs e)
        {
            dgvRealLog.ClearSelection();
            List <Maticsoft.Model.SMT_DOOR_INFO> doors = GetSelectDoors();
            List <ListViewItem> items = new List <ListViewItem>();

            foreach (ListViewItem item in listDoors.SelectedItems)
            {
                items.Add(item);
            }

            if (doors.Count == 0)
            {
                WinInfoHelper.ShowInfoWindow(this, "请选择门禁!");
                return;
            }
            List <decimal> ctrIds  = GetSelectCtrlIDs(doors);
            CtrlWaiting    waiting = new CtrlWaiting(() =>
            {
                var models = GetSelectCtrls(ctrIds);
                if (models.Count == 0)
                {
                    WinInfoHelper.ShowInfoWindow(this, "未找到控制器!");
                    return;
                }
                List <ManualResetEvent> events = new List <ManualResetEvent>();
                foreach (var item in models)
                {
                    ManualResetEvent evt = new ManualResetEvent(false);
                    events.Add(evt);
                    ThreadPool.QueueUserWorkItem(new WaitCallback((o) =>
                    {
                        Maticsoft.Model.SMT_CONTROLLER_INFO cinfo = item;
                        Controller c          = ControllerHelper.ToController(item);
                        bool isconnect        = false;
                        ControllerState state = null;
                        try
                        {
                            IAccessCore acc = new Li.Access.Core.WGAccesses.WGAccess();
                            state           = acc.GetControllerState(c);
                            if (state == null)
                            {
                                throw new Exception("通信不上");
                            }
                            isconnect = true;
                        }
                        catch (Exception ex)
                        {
                            isconnect = false;
                        }
                        finally
                        {
                            lock (items)
                            {
                                this.Invoke(new Action(() =>
                                {
                                    foreach (var it in items)
                                    {
                                        Maticsoft.Model.SMT_DOOR_INFO door = (Maticsoft.Model.SMT_DOOR_INFO)it.Tag;
                                        if (door.CTRL_ID == null || !door.IS_ENABLE)
                                        {
                                            continue;
                                        }
                                        if (door.CTRL_ID == c.id)
                                        {
                                            if (state == null || !isconnect)
                                            {
                                                it.ImageIndex = 2;
                                            }
                                            else
                                            {
                                                it.ImageIndex = state.relayState[(int)door.CTRL_DOOR_INDEX - 1] ? 1 : 0;
                                            }
                                            DateTime dt         = DateTime.Now;
                                            DataGridViewRow row = new DataGridViewRow();
                                            row.CreateCells(dgvRealLog, dt, door.DOOR_NAME, string.Format("控制器通信{0}:IP={1},SN={2}", isconnect ? "正常" : "不上", cinfo.IP, cinfo.SN_NO));
                                            dgvRealLog.Rows.Insert(0, row);
                                            row.Selected = true;
                                        }
                                    }
                                }));
                            }
                            evt.Set();
                        }
                    }));
                }
                foreach (var item in events)
                {
                    item.WaitOne(15000);
                }
            });

            waiting.Show(this);
        }
コード例 #31
0
        public bool DpadHeld(int controllerIndex, DPadDir dir)
        {
            ControllerState state = _controllerStates[controllerIndex];

            return(DPadState.Held == state.DPadStates.ElementAt((int)dir));
        }
コード例 #32
0
    void DrawPath()
    {
        if (Input.GetButtonUp("Fire1"))
        {
            //We have let go, return to idle state
            state = ControllerState.idle;

            //All moves used?
            if (drawPathStack.Count - 1 == selectedUnit.GetMoveSpeed())
            {
                //Is this a valid path that leads to a destination tile?
                Node finalNode = drawPathStack.Peek();
                if (map.tiles[finalNode.pos.x, finalNode.pos.y].IsAvailable())
                {
                    //Feed our unit this path
                    Debug.Log("sending drawn path to unit");
                    List <Node> path = new List <Node>(drawPathStack);
                    path.Reverse();
                    selectedUnit.SetPath(path);
                }
            }
            else
            {
                map.ResetTileDrawPath();
            }
            ClearDrawPath();
            return;
        }

        Node       currentNode = drawPathStack.Peek();
        RaycastHit hit;

        //Check if we are hovering over tile
        if (MouseCast(out hit))
        {
            if (hit.transform.tag == "Tile")
            {
                ClickableTile tempTile = hit.transform.GetComponent <ClickableTile>();
                Node          tempNode = map.nodes[tempTile.pos.x, tempTile.pos.y];

                //Is the tile a walkable neighbor tile?
                if (NodeIsNeighbour(currentNode, tempNode) && map.UnitCanEnterTile(tempNode.pos, selectedUnit))
                {
                    //Is it the previous path node?
                    if (drawPathStack.Contains(tempNode))
                    {
                        //pop current position
                        Node          popped = drawPathStack.Pop();
                        ClickableTile tile   = map.tiles[popped.pos.x, popped.pos.y].GetComponent <ClickableTile>();
                        Debug.Log(tile.GetValue());
                        tile.DrawHighlight(false, .01f);
                        tile.SetValueText(tile.GetValue());

                        audioSource.volume = .4f;
                        audioSource.pitch  = 1.9f;
                        audioSource.clip   = sndClickUp;
                        audioSource.Play();

                        //adjust available tiles
                        var coordOptions = selectedUnit.GetAvailableTileOptions(tempNode, selectedUnit.GetMoveSpeed() - drawPathStack.Count + 1);
                        map.ResetTileAvailability();
                        List <Map.Coord> coordList = new List <Map.Coord>();
                        for (int i = 0; i < selectedUnit.coordOptions.Length; i++)
                        {
                            if (coordOptions.Contains(selectedUnit.coordOptions[i]))
                            {
                                coordList.Add(selectedUnit.coordOptions[i]);
                            }
                        }
                        map.MakeTilesAvailable(coordList.ToArray());
                    }
                    //If not, we can push this neighbor is we have remianing moves, one step closer to destination
                    else if (drawPathStack.Count - 1 < selectedUnit.GetMoveSpeed())
                    {
                        {
                            //adjust available tiles
                            var coordOptions = selectedUnit.GetAvailableTileOptions(tempNode, selectedUnit.GetMoveSpeed() - drawPathStack.Count);
                            map.ResetTileAvailability();
                            List <Map.Coord> coordList = new List <Map.Coord>();
                            for (int i = 0; i < selectedUnit.coordOptions.Length; i++)
                            {
                                if (coordOptions.Contains(selectedUnit.coordOptions[i]))
                                {
                                    coordList.Add(selectedUnit.coordOptions[i]);
                                }
                            }
                            map.MakeTilesAvailable(coordList.ToArray());

                            drawPathStack.Push(tempNode);
                            //highlight tempTile? show its part of path
                            tempTile.DrawHighlight(true, .02f);
                            tempTile.SetValueText(tempTile.GetValue() + drawPathStack.Count - 1);

                            audioSource.volume = .95f;
                            audioSource.pitch  = (((float)drawPathStack.Count - 1f) / (float)selectedUnit.GetMoveSpeed()) * .1f + .9f;
                            audioSource.clip   = sndClickDown;
                            audioSource.Play();
                        }
                    }
                }
            } //end MouseCast
        }
    }
コード例 #33
0
ファイル: VRUIButton.cs プロジェクト: Pcat0/VRTD
 public override void OnHoverEnter(Vector2 position, ControllerState controllerState)
 {
     image.color = hoverColor;
 }
コード例 #34
0
ファイル: XInInput.cs プロジェクト: nickmass/Emu-o-Tron
        //Listen I know this is stupid, it's just I don't use my gamepad much and I really want to get slimdx out of the main program NOW.
        public void MainLoop()
        {
            if (player1Controller.IsConnected)
            {
                Gamepad x360State = player1Controller.GetState().Gamepad;
                ControllerState newPlayer1;
                newPlayer1.A = ((x360State.Buttons & GamepadButtonFlags.A) != 0);
                newPlayer1.B = ((x360State.Buttons & GamepadButtonFlags.B) != 0);
                newPlayer1.X = ((x360State.Buttons & GamepadButtonFlags.X) != 0);
                newPlayer1.Y = ((x360State.Buttons & GamepadButtonFlags.Y) != 0);
                newPlayer1.Up = ((x360State.Buttons & GamepadButtonFlags.DPadUp) != 0) || (x360State.LeftThumbY > 15000);
                newPlayer1.Down = ((x360State.Buttons & GamepadButtonFlags.DPadDown) != 0) || (x360State.LeftThumbY < -15000);
                newPlayer1.Left = ((x360State.Buttons & GamepadButtonFlags.DPadLeft) != 0) || (x360State.LeftThumbX < -15000);
                newPlayer1.Right = ((x360State.Buttons & GamepadButtonFlags.DPadRight) != 0) || (x360State.LeftThumbX > 15000);
                newPlayer1.Start = ((x360State.Buttons & GamepadButtonFlags.Start) != 0);
                newPlayer1.Back = ((x360State.Buttons & GamepadButtonFlags.Back) != 0);
                newPlayer1.LBumper = ((x360State.Buttons & GamepadButtonFlags.LeftShoulder) != 0);
                newPlayer1.RBumper = ((x360State.Buttons & GamepadButtonFlags.RightShoulder) != 0);
                newPlayer1.LTrigger = (x360State.LeftTrigger > 100);
                newPlayer1.RTrigger = (x360State.RightTrigger > 100);

                if (newPlayer1.A != currentPlayer1.A)
                {
                    InputEvent(EmuKeys.Joy1, newPlayer1.A);
                }
                if (newPlayer1.B != currentPlayer1.B)
                {
                    InputEvent(EmuKeys.Joy2, newPlayer1.B);
                }
                if (newPlayer1.X != currentPlayer1.X)
                {
                    InputEvent(EmuKeys.Joy3, newPlayer1.X);
                }
                if (newPlayer1.Y != currentPlayer1.Y)
                {
                    InputEvent(EmuKeys.Joy4, newPlayer1.Y);
                }
                if (newPlayer1.Up != currentPlayer1.Up)
                {
                    InputEvent(EmuKeys.JoyUp, newPlayer1.Up);
                }
                if (newPlayer1.Down != currentPlayer1.Down)
                {
                    InputEvent(EmuKeys.JoyDown, newPlayer1.Down);
                }
                if (newPlayer1.Left != currentPlayer1.Left)
                {
                    InputEvent(EmuKeys.JoyLeft, newPlayer1.Left);
                }
                if (newPlayer1.Right != currentPlayer1.Right)
                {
                    InputEvent(EmuKeys.JoyRight, newPlayer1.Right);
                }
                if (newPlayer1.Start != currentPlayer1.Start)
                {
                    InputEvent(EmuKeys.Joy5, newPlayer1.Start);
                }
                if (newPlayer1.Back != currentPlayer1.Back)
                {
                    InputEvent(EmuKeys.Joy6, newPlayer1.Back);
                }
                if (newPlayer1.LBumper != currentPlayer1.LBumper)
                {
                    InputEvent(EmuKeys.Joy7, newPlayer1.LBumper);
                }
                if (newPlayer1.RBumper != currentPlayer1.RBumper)
                {
                    InputEvent(EmuKeys.Joy8, newPlayer1.RBumper);
                }
                if (newPlayer1.LTrigger != currentPlayer1.LTrigger)
                {
                    InputEvent(EmuKeys.Joy9, newPlayer1.LTrigger);
                }
                if (newPlayer1.RTrigger != currentPlayer1.RTrigger)
                {
                    InputEvent(EmuKeys.Joy10, newPlayer1.RTrigger);
                }
                currentPlayer1 = newPlayer1;
            }
            /*
            if (player2Controller.IsConnected)
            {
                Gamepad x360State = player2Controller.GetState().Gamepad;
                ControllerState newPlayer2;
                newPlayer2.A = ((x360State.Buttons & GamepadButtonFlags.A) != 0);
                newPlayer2.B = ((x360State.Buttons & GamepadButtonFlags.B) != 0);
                newPlayer2.X = ((x360State.Buttons & GamepadButtonFlags.X) != 0);
                newPlayer2.Y = ((x360State.Buttons & GamepadButtonFlags.Y) != 0);
                newPlayer2.Up = ((x360State.Buttons & GamepadButtonFlags.DPadUp) != 0) || (x360State.LeftThumbY > 15000);
                newPlayer2.Down = ((x360State.Buttons & GamepadButtonFlags.DPadDown) != 0) || (x360State.LeftThumbY < -15000);
                newPlayer2.Left = ((x360State.Buttons & GamepadButtonFlags.DPadLeft) != 0) || (x360State.LeftThumbX < -15000);
                newPlayer2.Right = ((x360State.Buttons & GamepadButtonFlags.DPadRight) != 0) || (x360State.LeftThumbX > 15000);
                newPlayer2.Start = ((x360State.Buttons & GamepadButtonFlags.Start) != 0);
                newPlayer2.Back = ((x360State.Buttons & GamepadButtonFlags.Back) != 0);
                newPlayer2.LBumper = ((x360State.Buttons & GamepadButtonFlags.LeftShoulder) != 0);
                newPlayer2.RBumper = ((x360State.Buttons & GamepadButtonFlags.RightShoulder) != 0);
                newPlayer2.LTrigger = (x360State.LeftTrigger > 100);
                newPlayer2.RTrigger = (x360State.RightTrigger > 100);

                if (newPlayer2.A != currentPlayer2.A)
                {
                    if (newPlayer2.A)
                        KeyDownEvent(this, Keys.NumPad1);
                    else
                        KeyUpEvent(this, Keys.NumPad1);
                }
                if (newPlayer2.B != currentPlayer2.B)
                {
                    if (newPlayer2.B)
                        KeyDownEvent(this, Keys.NumPad3);
                    else
                        KeyUpEvent(this, Keys.NumPad3);
                }
                if (newPlayer2.X != currentPlayer2.X)
                {
                    if (newPlayer2.X)
                        KeyDownEvent(this, Keys.Home);
                    else
                        KeyUpEvent(this, Keys.Home);
                }
                if (newPlayer2.Y != currentPlayer2.Y)
                {
                    if (newPlayer2.Y)
                        KeyDownEvent(this, Keys.End);
                    else
                        KeyUpEvent(this, Keys.End);
                }
                if (newPlayer2.Up != currentPlayer2.Up)
                {
                    if (newPlayer2.Up)
                        KeyDownEvent(this, Keys.NumPad8);
                    else
                        KeyUpEvent(this, Keys.NumPad8);
                }
                if (newPlayer2.Down != currentPlayer2.Down)
                {
                    if (newPlayer2.Down)
                        KeyDownEvent(this, Keys.NumPad5);
                    else
                        KeyUpEvent(this, Keys.NumPad5);
                }
                if (newPlayer2.Left != currentPlayer2.Left)
                {
                    if (newPlayer2.Left)
                        KeyDownEvent(this, Keys.NumPad4);
                    else
                        KeyUpEvent(this, Keys.NumPad4);
                }
                if (newPlayer2.Right != currentPlayer2.Right)
                {
                    if (newPlayer2.Right)
                        KeyDownEvent(this, Keys.NumPad6);
                    else
                        KeyUpEvent(this, Keys.NumPad6);
                }
                if (newPlayer2.Start != currentPlayer2.Start)
                {
                    if (newPlayer2.Start)
                        KeyDownEvent(this, Keys.NumPad7);
                    else
                        KeyUpEvent(this, Keys.NumPad7);
                }
                if (newPlayer2.Back != currentPlayer2.Back)
                {
                    if (newPlayer2.Back)
                        KeyDownEvent(this, Keys.NumPad9);
                    else
                        KeyUpEvent(this, Keys.NumPad9);
                }
                currentPlayer2 = newPlayer2;
            }*/
        }
コード例 #35
0
        public MSTSNotch(float v, int s, string type, STFReader stf)
        {
            Value  = v;
            Smooth = s == 0 ? false : true;
            Type   = ControllerState.Dummy; // Default to a dummy controller state if no valid alternative state used
            string lower = type.ToLower();

            if (lower.StartsWith("trainbrakescontroller"))
            {
                lower = lower.Substring(21);
            }
            if (lower.StartsWith("enginebrakescontroller"))
            {
                lower = lower.Substring(22);
            }
            if (lower.StartsWith("brakemanbrakescontroller"))
            {
                lower = lower.Substring(24);
            }
            switch (lower)
            {
            case "dummy": break;

            case ")": break;

            case "releasestart": Type = ControllerState.Release; break;

            case "fullquickreleasestart": Type = ControllerState.FullQuickRelease; break;

            case "runningstart": Type = ControllerState.Running; break;

            case "selflapstart": Type = ControllerState.SelfLap; break;

            case "holdstart": Type = ControllerState.Hold; break;

            case "holdlappedstart": Type = ControllerState.Lap; break;

            case "neutralhandleoffstart": Type = ControllerState.Neutral; break;

            case "graduatedselflaplimitedstart": Type = ControllerState.GSelfLap; break;

            case "graduatedselflaplimitedholdingstart": Type = ControllerState.GSelfLapH; break;

            case "applystart": Type = ControllerState.Apply; break;

            case "continuousservicestart": Type = ControllerState.ContServ; break;

            case "suppressionstart": Type = ControllerState.Suppression; break;

            case "fullservicestart": Type = ControllerState.FullServ; break;

            case "emergencystart": Type = ControllerState.Emergency; break;

            case "minimalreductionstart": Type = ControllerState.MinimalReduction; break;

            case "epapplystart": Type = ControllerState.EPApply; break;

            case "eponlystart": Type = ControllerState.EPOnly; break;

            case "epfullservicestart": Type = ControllerState.EPFullServ; break;

            case "epholdstart": Type = ControllerState.SelfLap; break;

            case "vacuumcontinuousservicestart": Type = ControllerState.VacContServ; break;

            case "vacuumapplycontinuousservicestart": Type = ControllerState.VacApplyContServ; break;

            case "manualbrakingstart": Type = ControllerState.ManualBraking; break;

            case "brakenotchstart": Type = ControllerState.BrakeNotch; break;

            case "overchargestart": Type = ControllerState.Overcharge; break;

            case "slowservicestart": Type = ControllerState.SlowService; break;

            default:
                STFException.TraceInformation(stf, "Skipped unknown notch type " + type);
                break;
            }
        }
コード例 #36
0
 public MSTSNotch(BinaryReader inf)
 {
     Value  = inf.ReadSingle();
     Smooth = inf.ReadBoolean();
     Type   = (ControllerState)inf.ReadInt32();
 }
コード例 #37
0
 public ControlManager(Point screen)
 {
     windows = new List<Window>();
     Locator.getMessageBoard().register(onPost);
     state = new Selector();
     screen_ = screen;
 }
コード例 #38
0
ファイル: Controller.cs プロジェクト: ColdMatter/EDMSuite
        public void Start()
        {
            ui = new MainForm();
            ui.controller = this;

            State = ControllerState.STOPPED;
            initializeControllerValues();
            Application.Run(ui);
        }
コード例 #39
0
ファイル: Controller.cs プロジェクト: ColdMatter/EDMSuite
        public void Start()
        {
            ui = new MainForm(config.Name);
            ui.controller = this;

            Dictionary<string, string> analogs = new Dictionary<string, string>();
            foreach(string key in config.Lasers.Keys)
            {
                analogs.Add(key, config.Lasers[key]);
            }
            analogs.Add("master", config.MasterLaser);
            analogs.Add("cavity", config.Cavity);

            initializeSlaveLaserControl(config.Lasers.Keys);
            initializeAIs(analogs.Values);

            TCLState = ControllerState.STOPPED;
            Application.Run(ui);
        }
コード例 #40
0
 public void Respawn(Vector3 position)
 {
     transform.position = position;
     _currentState      = new SpawnState(this);
 }
コード例 #41
0
ファイル: Controller.cs プロジェクト: ColdMatter/EDMSuite
 public void EngageLock()
 {
     State = ControllerState.LASERLOCKING;
     ui.updateUIState(State);
 }
コード例 #42
0
 public MSTSNotch(MSTSNotch other)
 {
     Value  = other.Value;
     Smooth = other.Smooth;
     Type   = other.Type;
 }
コード例 #43
0
ファイル: Controller.cs プロジェクト: ColdMatter/EDMSuite
 public void DisengageLock()
 {
     State = ControllerState.FREERUNNING;
     ui.updateUIState(State);
 }
コード例 #44
0
        unsafe public void OnHidEvent(object aSender, SharpLib.Hid.Event aHidEvent)
        {
            if (aHidEvent.IsStray)
            {
                //Stray event just ignore it
                return;
            }

            // Oculus Rift S Touch Controller report starts with 0x67
            if (aHidEvent.InputReport[0] != 0x67)
            {
                return;
                //Console.WriteLine(aHidEvent.InputReportString());
            }


            var size = aHidEvent.InputReport.Length;

            if (size < 62)
            {
                return;
            }

            iMutex.WaitOne();

            // Parse our raw input report into our controller report class.
            Utils.ParseControllerInputReport(aHidEvent.InputReport, iCtrlReport);

            // Check if we have a valid device ID
            if (iCtrlReport.device_id != 0)
            {
                // Check if we already meat this device
                ControllerState state;
                int             position = Console.WindowTop + iControllers.Count * 20;
                if (!iControllers.TryGetValue(iCtrlReport.device_id, out state))
                {
                    // That's a new device, create a state object for it then and add it to our collection
                    state           = new ControllerState();
                    state.device_id = iCtrlReport.device_id;
                    iControllers.Add(iCtrlReport.device_id, state);
                    //Console.WriteLine("Found new device: 0x" + report.device_id.ToString("X"));
                    iPosition.Add(iCtrlReport.device_id, position);
                }

                // Now that we have our state object for this device, we need to update it with the incoming input report
                Utils.UpdateControllerState(ref state, iCtrlReport);
            }


            // Do not update our prints too often to avoid lags
            bool updatePrints = iStopWatch.ElapsedMilliseconds >= 100;

            foreach (var ctrl in iControllers.Values)
            {
                // Quick and dirty mapping to keyboard input for MWO
                if (ctrl.device_id == 0xCE156735BF2F1676) // // Right controller
                {
                    var position = iPosition[ctrl.device_id];
                    if (updatePrints)
                    {
                        // Print our controller states in our console
                        Console.SetCursorPosition(Console.WindowLeft, position);
                        //Console.Clear();
                        string blank = "                                      ";
                        Console.WriteLine(ctrl.Dump());
                        if (isDownForward)
                        {
                            Console.WriteLine("Up");
                        }
                        else
                        {
                            Console.WriteLine(blank);
                        }

                        if (isDownBackward)
                        {
                            Console.WriteLine("Down");
                        }
                        else
                        {
                            Console.WriteLine(blank);
                        }


                        if (isDownLeft)
                        {
                            Console.WriteLine("Left");
                        }
                        else
                        {
                            Console.WriteLine(blank);
                        }

                        if (isDownRight)
                        {
                            Console.WriteLine("Right");
                        }
                        else
                        {
                            Console.WriteLine(blank);
                        }

                        iStopWatch.Restart();
                    }


                    // Throttle
                    if (ctrl.joystick_y > 10000)
                    {
                        // Moving forward
                        if (!isDownForward)
                        {
                            isDownForward  = true;
                            isDownBackward = false;
                            //
                            iInputSim.Keyboard.KeyDown(iUp);
                            iInputSim.Keyboard.KeyUp(iDown);
                        }
                    }
                    else if (ctrl.joystick_y < -10000)
                    {
                        // Moving backward
                        if (!isDownBackward)
                        {
                            isDownForward  = false;
                            isDownBackward = true;
                            //
                            iInputSim.Keyboard.KeyDown(iDown);
                            iInputSim.Keyboard.KeyUp(iUp);
                        }
                    }
                    else
                    {
                        if (isDownForward || isDownBackward)
                        {
                            isDownForward  = false;
                            isDownBackward = false;
                            //
                            iInputSim.Keyboard.KeyUp(iDown);
                            iInputSim.Keyboard.KeyUp(iUp);
                        }
                    }

                    // Rotation
                    if (ctrl.joystick_x > 15000)
                    {
                        // Moving right
                        if (!isDownRight)
                        {
                            isDownLeft  = false;
                            isDownRight = true;
                            //
                            iInputSim.Keyboard.KeyDown(iRight);
                            iInputSim.Keyboard.KeyUp(iLeft);
                        }
                    }
                    else if (ctrl.joystick_x < -15000)
                    {
                        // Moving left
                        if (!isDownLeft)
                        {
                            // We used those to measure our input lag by comparing the time the event is sent here and the time it is received in HidDemo
                            //Console.WriteLine("\nLeft down: " + aHidEvent.Time.ToString("HH:mm:ss:fff"));
                            isDownLeft  = true;
                            isDownRight = false;
                            //
                            iInputSim.Keyboard.KeyDown(iLeft);
                            iInputSim.Keyboard.KeyUp(iRight);
                        }
                    }
                    else
                    {
                        if (isDownRight)
                        {
                            // Use that to debug input lag
                            //Console.WriteLine("Right up: " + aHidEvent.Time.ToString("HH:mm:ss:fff"));
                            isDownRight = false;
                            iInputSim.Keyboard.KeyUp(iRight);
                        }

                        if (isDownLeft)
                        {
                            // Use that to debug input lag
                            //Console.WriteLine("Left up: " + aHidEvent.Time.ToString("HH:mm:ss:fff"));
                            isDownLeft = false;
                            iInputSim.Keyboard.KeyUp(iLeft);
                        }
                    }


                    //Target
                    if (ctrl.trigger < 3072)
                    {
                        if (!isDownTrigger)
                        {
                            isDownTrigger = true;
                            iInputSim.Keyboard.KeyDown(VirtualKeyCode.VK_R);
                        }
                    }
                    else if (isDownTrigger)
                    {
                        isDownTrigger = false;
                        iInputSim.Keyboard.KeyUp(VirtualKeyCode.VK_R);
                    }

                    // Push-to-talk
                    if (ctrl.grip < 512)
                    {
                        if (!isDownGrip)
                        {
                            //Console.WriteLine("down   ");
                            isDownGrip = true;
                            iInputSim.Keyboard.KeyDown(VirtualKeyCode.CAPITAL);
                        }
                    }
                    else if (isDownGrip)
                    {
                        //Console.WriteLine("up   ");
                        isDownGrip = false;
                        iInputSim.Keyboard.KeyUp(VirtualKeyCode.CAPITAL);
                    }

                    // Third weapon
                    if (ctrl.ButtonStick())
                    {
                        if (!isDownButtonStick)
                        {
                            //Console.WriteLine("down   ");
                            isDownButtonStick = true;
                            iInputSim.Keyboard.KeyDown(VirtualKeyCode.VK_3);
                        }
                    }
                    else if (isDownButtonStick)
                    {
                        //Console.WriteLine("up   ");
                        isDownButtonStick = false;
                        iInputSim.Keyboard.KeyUp(VirtualKeyCode.VK_3);
                    }

                    // Battlegrid
                    if (ctrl.ButtonMenu())
                    {
                        if (!isDownButtonMenu)
                        {
                            //Console.WriteLine("down   ");
                            isDownButtonMenu = true;
                            iInputSim.Keyboard.KeyDown(VirtualKeyCode.VK_B);
                        }
                    }
                    else if (isDownButtonMenu)
                    {
                        //Console.WriteLine("up   ");
                        isDownButtonMenu = false;
                        iInputSim.Keyboard.KeyUp(VirtualKeyCode.VK_B);
                    }
                }
            }



            iMutex.ReleaseMutex();
        }
コード例 #45
0
ファイル: Controller.cs プロジェクト: ColdMatter/EDMSuite
 public void StabilizeCavity()
 {
     State = ControllerState.CAVITYSTABILIZED;
     ui.updateUIState(State);
 }
コード例 #46
0
 public void ChangeState(ControllerState newState)
 {
     currentControllerState = newState;
     //Debug.Log("State Changed");
 }
コード例 #47
0
ファイル: Controller.cs プロジェクト: ColdMatter/EDMSuite
        public void StartRamp()
        {
            State = Controller.ControllerState.FREERUNNING;
            Thread.Sleep(2000);
            Thread rampThread = new Thread(new ThreadStart(rampLoop));
            ui.updateUIState(State);

            rampThread.Start();
        }
コード例 #48
0
    //Handle state transitions;
    //Determine current controller state based on current momentum and whether the controller is grounded (or not);
    void HandleState()
    {
        //Check if vertical momentum is pointing upwards;
        bool _isRising = IsRisingOrFalling() && (VectorMath.GetDotProduct(GetMomentum(), trans.up) > 0f);
        //Check if controller is sliding;
        bool _isSliding = mover.IsGrounded() && (Vector3.Angle(mover.GetGroundNormal(), trans.up) > slopeLimit);

        switch (currentControllerState)
        {
        case ControllerState.Grounded:

            if (_isRising)
            {
                currentControllerState = ControllerState.Rising;
                OnGroundContactLost();
                break;
            }
            if (!mover.IsGrounded())
            {
                currentControllerState = ControllerState.Falling;
                OnGroundContactLost();
                break;
            }
            if (_isSliding)
            {
                currentControllerState = ControllerState.Sliding;
                break;
            }
            break;

        case ControllerState.Falling:

            if (_isRising)
            {
                currentControllerState = ControllerState.Rising;
                break;
            }
            if (mover.IsGrounded() && !_isSliding)
            {
                currentControllerState = ControllerState.Grounded;
                OnGroundContactRegained(momentum);
                break;
            }
            if (_isSliding)
            {
                currentControllerState = ControllerState.Sliding;
                OnGroundContactRegained(momentum);
                break;
            }
            break;

        case ControllerState.Sliding:

            if (_isRising)
            {
                currentControllerState = ControllerState.Rising;
                OnGroundContactLost();
                break;
            }
            if (!mover.IsGrounded())
            {
                currentControllerState = ControllerState.Falling;
                break;
            }
            if (mover.IsGrounded() && !_isSliding)
            {
                OnGroundContactRegained(momentum);
                currentControllerState = ControllerState.Grounded;
                break;
            }
            break;

        case ControllerState.Rising:

            if (!_isRising)
            {
                if (mover.IsGrounded() && !_isSliding)
                {
                    currentControllerState = ControllerState.Grounded;
                    OnGroundContactRegained(momentum);
                    break;
                }
                if (_isSliding)
                {
                    currentControllerState = ControllerState.Sliding;
                    break;
                }
                if (!mover.IsGrounded())
                {
                    currentControllerState = ControllerState.Falling;
                    break;
                }
            }
            break;

        case ControllerState.Jumping:

            //Check for jump timeout;
            if ((Time.time - currentJumpStartTime) > jumpDuration)
            {
                currentControllerState = ControllerState.Rising;
            }

            //Check if jump key was let go;
            if (jumpKeyWasLetGo)
            {
                currentControllerState = ControllerState.Rising;
            }

            break;
        }
    }
コード例 #49
0
ファイル: Controller.cs プロジェクト: ColdMatter/EDMSuite
 public void UnlockCavity()
 {
     State = ControllerState.FREERUNNING;
     ui.updateUIState(State);
 }
コード例 #50
0
 public Daemon(TcpClient handler, ControllerState curstate)
 {
     Client = handler;
     state  = curstate;
 }
コード例 #51
0
        /// <summary>
        /// Locks the laser to a reference cavity. This method runs continuously until the laser is unlocked.
        /// When this method is called, the reference cavity is read in order to establish the lock point.
        /// The reference cavity is then read continuously and adjustments fed-back to the laser.
        /// </summary>
        public void Lock()
        {
            double singleValue;
            double singlerefValue;
            double averageValue = 0;
            int reads = 0;
            bool firstTime = true;
            DateTime oldCavityStamp = new DateTime();
            DateTime newCavityStamp = new DateTime();
            newCavityStamp = DateTime.Now;

            status = ControllerState.busy;
            ui.ControlVoltageEditorEnabledState(false);
            hardwareControl.LaserLocked = true;
            hardwareControl.SetAnalogOutputBlockedStatus("laser", true);

            while (status == ControllerState.busy)
            {
                if (!Environs.Debug)
                {
                    oldCavityStamp = newCavityStamp;
                    // read the cavity
                    if (hardwareControl.AnalogInputsAvailable)//scanmaster not running
                    {
                        singleValue = 0;
                        inputTask.Start();
                        latestData = cavityReader.ReadMultiSample(SAMPLES_PER_READ);
                        inputTask.Stop();

                        singlerefValue = 0;
                        inputrefTask.Start();
                        latestrefData = cavityrefReader.ReadMultiSample(SAMPLES_PER_READ);
                        inputrefTask.Stop();

                        foreach (double d in latestData) singleValue += d;
                        foreach (double e in latestrefData) singlerefValue += e;
                        singleValue = singleValue / SAMPLES_PER_READ;
                        singlerefValue = singlerefValue / SAMPLES_PER_READ;
                        if (singleValue > 4.7)
                        {
                            hardwareControl.diodeSaturationError();
                        }
                        else
                        {
                            hardwareControl.diodeSaturation();
                        }
                        singleValue = singleValue / singlerefValue;
                        newCavityStamp = DateTime.Now;
                        hardwareControl.UpdateLockCavityData(singleValue);
                        //hardwareControl.UpdateLockCavityData(singleValue / singlerefValue);
                    }
                    else
                    {
                        singleValue = hardwareControl.LastCavityData;
                        newCavityStamp = hardwareControl.LastCavityTimeStamp;
                    }

                    // provided the last cavity read is recent, do something with it
                    if (hardwareControl.TimeSinceLastCavityRead < LATENCY && newCavityStamp.CompareTo(oldCavityStamp) != 0)
                    {
                        // if this is the first read since throwing the lock, the result defines the set-point
                        if (firstTime)
                        {
                            integratedDeviation = 0;
                            // make sure we don't have a value that's out of range
                            if (singleValue > UPPER_SETPOINT_LIMIT) singleValue = UPPER_SETPOINT_LIMIT;
                            if (singleValue < LOWER_SETPOINT_LIMIT) singleValue = LOWER_SETPOINT_LIMIT;
                            setPoint = singleValue;
                            ui.SetSetPointNumericEditorValue(setPoint);
                            firstTime = false;
                        }
                        // otherwise, use the last read to update the running average
                        else
                        {
                            averageValue += singleValue;
                            reads++;
                            deviation = averageValue / reads - setPoint;
                            integratedDeviation = integratedDeviation + deviation * hardwareControl.TimeSinceLastCavityRead;
                        }
                        // is it time to feed-back to the laser
                        if (reads != 0 && (reads >= READS_PER_FEEDBACK || ui.SpeedSwitchState))
                        {
                            averageValue = averageValue / reads;
                            deviation = averageValue - setPoint;
                            LaserVoltage = LaserVoltage + SignOfFeedback * proportionalGain * deviation +
                                integralGain * integratedDeviation; //other terms to go here
                            // update the deviation plot
                            ui.DeviationPlotXYAppend(deviation);
                            // reset the variables
                            averageValue = 0;
                            reads = 0;
                        }
                    }
                }
                else
                {
                    // Debug mode
                    ui.DeviationPlotXYAppend(hardwareControl.LaserFrequencyControlVoltage - setPoint);
                }
                Thread.Sleep(SLEEPING_TIME);
            }
            // we're out of the while loop - revert to the unlocked state
            status = ControllerState.free;
            hardwareControl.LaserLocked = false;
            ui.ControlVoltageEditorEnabledState(true);
            hardwareControl.SetAnalogOutputBlockedStatus("laser", false);
        }
コード例 #52
0
        private void MaintaintHostConnection(Object Params)
        {
            TcpClient Connection = Params as TcpClient;

            try
            {
                Connection.Connect(Master);
                if (state != ControllerState.Suspending)
                {
                    state = ControllerState.Suspending;
                }
                UpdateData("Соединение с мастером установлено");
                Connection.ReceiveBufferSize = 10000;
                Connection.ReceiveTimeout    = 100;
                NetworkStream Stream = Connection.GetStream();
                bool          DataCollected;
                UInt32        oldHttpCount = 0;
                UInt32        oldUdpCount  = 0;
                UInt32        newHttpCount;
                UInt32        newUdpCount;
                while (Connection.Connected)
                {
                    DataCollected = false;
                    if (Connection.Available >= 1)
                    {
                        int code = Stream.ReadByte();
                        switch (code)
                        {
                        case 0:
                            while (Connection.Connected && !DataCollected)
                            {
                                if (Connection.Available >= 2)
                                {
                                    byte[] buuf = new byte[2];
                                    Stream.Read(buuf, 0, 2);                                  //df to add length in sendservicemsg
                                    UInt16 len = BitConverter.ToUInt16(buuf, 0);
                                    while (Connection.Connected && !DataCollected)
                                    {
                                        if (Connection.Available >= len)
                                        {
                                            byte[] buffer = new byte[len];
                                            Stream.Read(buffer, 0, len);
                                            InitParams(AttackParams.parseFromArray(buffer));
                                            state         = ControllerState.Suspending;
                                            DataCollected = true;
                                            UpdateData("Получены настройки от мастера");
                                        }
                                    }
                                }
                            }

                            break;

                        case 1:
                            AttackIsAllowed = true;
                            Start(); break;

                        case 2:
                            AttackIsAllowed = false;
                            Stop(); break;

                        case 3:
                            List <byte> msgs = new List <byte>();
                            msgs.Add(3);
                            newHttpCount = Core.HttpCounter;
                            newUdpCount  = Core.UdpCounter;
                            msgs.AddRange(BitConverter.GetBytes(newHttpCount - oldHttpCount));
                            msgs.AddRange(BitConverter.GetBytes(newUdpCount - oldUdpCount));
                            oldHttpCount = newHttpCount;
                            oldUdpCount  = newUdpCount;
                            Stream.Write(msgs.ToArray(), 0, msgs.Count);
                            //stats
                            break;
                        }
                    }
                }
                UpdateData("Соединение с мастером разорвано");
            }
            catch (SocketException err)
            {
                UpdateData("Невозможно подключиться к мастеру"); //1060 exception
                state = ControllerState.Error;
            }
            catch (ObjectDisposedException)
            {
                return;
            }
        }
コード例 #53
0
ファイル: Dualshock4.cs プロジェクト: Swizzy/ControllerTester
 private void WorkerThread(object sender, DoWorkEventArgs doWorkEventArgs)
 {
     while(Device.IsConnected && !Device.IsTimedOut) {
         try {
             SendOutputReport();
             var handler = Updated;
             var data = new byte[Device.Capabilities.InputReportByteLength];
             if(Device.ReadFile(data) != HidDevice.ReadStatus.Success)
                 continue;
             Device.FlushQueue();
             if(handler != null)
                 handler(this, new Ds4UpdateEventArgs(_lastState = new ControllerState(data, _isUsb)));
             CheckQuickDisconnect();
         }
         catch(Exception ex) {
             Console.WriteLine(ex);
         }
     }
 }
コード例 #54
0
 public TData GetData(ControllerState state)
 {
     return(ControllerStatesDataTemplate <TData> .GetData(this, state));
 }
コード例 #55
0
ファイル: Controller.cs プロジェクト: jadevlin/EDMSuite
        public void Start()
        {
            ui = new MainForm();
            ui.controller = this;

            string[] lockableLasers = (string[])Environs.Hardware.GetInfo("TCLLockableLasers");
            photodiodes = (string[])Environs.Hardware.GetInfo("TCLPhotodiodes");
            if ((double)Environs.Hardware.GetInfo("TCL_Default_VoltageToLaser") != null)
            {
                default_ScanPoints = (int)Environs.Hardware.GetInfo("TCL_Default_ScanPoints");
            }
            initializeSlaveLaserControl(lockableLasers);
            initializeAIs(photodiodes);
            makeLaserToAILookupTable();

            TCLState = ControllerState.STOPPED;
            Application.Run(ui);
        }
コード例 #56
0
 public TData GetData(ControllerState state)
 {
     return(GetData(this, state));
 }
コード例 #57
0
ファイル: Controller.cs プロジェクト: jadevlin/EDMSuite
 /// <summary>
 /// This will make the program exit the while loop in ramploop.
 /// Note: this will call 
 /// </summary>
 public void StopTCL()
 {
     TCLState = ControllerState.STOPPED;
     ui.UpdateUIState(TCLState);
 }
コード例 #58
0
        public EvalReturn Execute(string function, ref ControllerState cs)
        {
            // verify cog exists
            if (!functions.ContainsKey(function))
            {
                throw new ArgumentOutOfRangeException(function,
                                                      String.Format(cs.Config.strings["FunNotFound"], function));
            }

            IFunctionCog cog = functions[function];

            if (cog.NumArgs > 0) //Don't bother checking count & type of args if you take none.
            {
                // check number of arguments
                if (cs.stack.Count < cog.NumArgs)
                {
                    return(new EvalReturn(Response.Error,
                                          String.Format(cs.Config.strings["FunArgNumErr"], cog.FunctionName[0], cog.NumArgs),
                                          typeof(FunctionInstance)));
                }
                // Check the types of arguments
                Type[] argTypes = new Type[cog.NumArgs];
                int    topStack = cs.stack.Count;

                // Get all the types
                for (int i = 0; i < cog.NumArgs; i++)
                {
                    argTypes[i] = cs.stack.ElementAt(topStack - (topStack - i)).GetType();
                }

                bool allowed = false;
                foreach (Type[] t in cog.AllowedTypes)
                {
                    if (t.SequenceEqual(argTypes) || t.Contains(typeof(AnyType)))
                    {
                        allowed = true;
                        break;
                    }
                }

                if (!allowed)
                {
                    string argListString = "(";
                    foreach (Type t in argTypes)
                    {
                        argListString += t.ToString() + " ";
                    }
                    argListString += ")";

                    return(new EvalReturn(Response.Error,
                                          String.Format(cs.Config.strings["UnsupportedTypes"], argListString),
                                          typeof(FunctionInstance)));
                }
            }
            // call cog Execute
            ICalculonType retVal = cog.Execute(ref cs);

            if (retVal.GetType() == typeof(ErrorType))
            {
                return(new EvalReturn(Response.Error,
                                      retVal.Display, typeof(ErrorType)));
            }
            if (retVal.GetType() != typeof(EmptyType))
            {
                cs.stack.Push(retVal);
            }
            return(new EvalReturn(Response.Ok, retVal.Display, retVal.GetType()));
        }
コード例 #59
0
ファイル: BaseState.cs プロジェクト: BigDub/HomePrototype
 public virtual void changeState(ControllerState newState)
 {
     manager_.forceState(newState);
 }
コード例 #60
0
    protected virtual void FixedUpdate()
    {
        // check collisions
        // check the active collisions
        // ?

        if (m_activeStackedState != null)
        {
            InputManager.Instance.IgnoreInput = m_activeStackedState.ConsumesInputAndEffects;
        }

        foreach (ControllerState state in m_activeState.FutureStates)
        {
            bool entered = state.EnterOnCondition(/*m_activeState*/);
            if (entered)
            {
                m_activeState.Abort();
                state.LogicalEnter();

                if (m_activeStackedState == null || !m_activeStackedState.ConsumesInputAndEffects)
                {
                    state.EffectualEnter();
                }

                //m_lastState = m_activeState;
                m_stateStartedFrame = GameManager.Instance.Frame;

                Debug.Log("New active: " + state);
                m_activeState = state;
                break;
            }
        }

        if (m_activeStackedState != null)
        {
            foreach (ControllerState state in m_activeStackedState.StackedStates)
            {
                if (state.EnterOnCondition())
                {
                    m_activeStackedState?.Abort();
                    state.LogicalEnter();
                    state.EffectualEnter();

                    m_stateStartedStackedFrame = GameManager.Instance.Frame;
                    m_activeStackedState       = state;
                    break;
                }
            }
        }
        else
        {
            //DUNNO; Should the active state be able to still trigger stacked states?
            //DUNNO; Should I be able to add non stacked states to a stacked state

            foreach (ControllerState state in m_activeState.StackedStates)
            {
                if (state.EnterOnCondition())
                {
                    m_activeStackedState?.Abort();
                    state.LogicalEnter();
                    state.EffectualEnter();

                    m_stateStartedStackedFrame = GameManager.Instance.Frame;
                    m_activeStackedState       = state;
                    break;
                }
            }
        }

        m_activeState.HandleFixedUpdate();

        if (m_activeStackedState != null)
        {
            bool keep = m_activeStackedState.HandleFixedUpdate();
            if (!keep)
            {
                m_activeStackedState.Abort();
                m_activeStackedState = null;
                m_activeState.EffectualEnter();
            }
        }

        //TODO; For hold effects in special states; that won't work now
        //T** Therefore I should define better when stuff is blocked (maybe only in m_activeStates)
        InputManager.Instance.IgnoreInput = false;

        Move();
    }