Exemplo n.º 1
0
        private void subElaButton_Down(object sender, MouseEventArgs e)
        {
            if (Validator.ValidateSpeedTextOnly(speedTextBox.Text))
            {
                double speed = Convert.ToDouble(speedTextBox.Text);
                if (Validator.ValidateSpeed(speed))
                {
                    // Start CW Jog
                    MovementResult result = rtController.StartRadioTelescopeJog(speed, RadioTelescopeDirectionEnum.ClockwiseOrNegative, RadioTelescopeAxisEnum.ELEVATION);

                    if (result == MovementResult.Success)
                    {
                        logger.Info($"{Utilities.GetTimeStamp()}: Successfully started elevation negative jog.");
                    }
                    else if (result == MovementResult.StoppingCurrentMove)
                    {
                        logger.Info($"{Utilities.GetTimeStamp()}: Stopping current movement. Please wait until that movement has finished ending and try to jog again.");
                    }
                    else if (result == MovementResult.AlreadyMoving)
                    {
                        logger.Info($"{Utilities.GetTimeStamp()}: Elevation negative jog BLOCKED. Another manual script is already running.");
                    }
                }
                else
                {
                    MessageBox.Show("Speed is not in valid range, 0.0-2.0 RPMs. Please try again");
                }
            }
            else
            {
                MessageBox.Show("Invalid speed. Must be in RPMs between 0.0 and 2.0");
            }
        }
Exemplo n.º 2
0
        private void ExecuteCorrectStop()
        {
            MovementResult result = MovementResult.None;

            if (ControlledButtonRadio.Checked)
            {
                result = rtController.ExecuteRadioTelescopeStopJog(MCUCommandType.ControlledStop);
                formData.immediateStopBool  = false;
                formData.controlledStopBool = true;

                if (result == MovementResult.Success)
                {
                    logger.Info($"{Utilities.GetTimeStamp()}: Successfully stopped jog with a controlled stop.");
                }
            }
            else if (immediateRadioButton.Checked)
            {
                result = rtController.ExecuteRadioTelescopeStopJog(MCUCommandType.ImmediateStop);
                formData.immediateStopBool  = true;
                formData.controlledStopBool = false;

                if (result == MovementResult.Success)
                {
                    logger.Info($"{Utilities.GetTimeStamp()}: Successfully stopped jog with an immediate stop.");
                }
            }
            else
            {
                logger.Info(Utilities.GetTimeStamp() + ": Invalid Stop Selected");
                throw new Exception();
            }
        }
Exemplo n.º 3
0
        private void timerSnakeGame_Tick(object sender, EventArgs e)
        {
            MovementResult movementResult = this.snake.Move(
                this.pictureBoxSnakeGame.Width,
                this.pictureBoxSnakeGame.Height,
                this.apple);

            if (movementResult == MovementResult.Wall ||
                movementResult == MovementResult.SelfBite)
            {
                timerSnakeGame.Stop();

                // Game is over
                MessageBox.Show(string.Format("Game over!!! Your points: {0}", snake.Length));
                this.Close();
            }

            if (movementResult == MovementResult.OnApple)
            {
                do
                {
                    this.apple = this.appleGenerator.CreateApple();
                }while (this.snake.IsOn(apple));
            }

            this.Invalidate(true);
        }
Exemplo n.º 4
0
        public void TestRoverIncidentObstacle()
        {
            Rover rover = new Rover("Lolly", new MapPlanet()
            {
                Length = 10, Height = 10
            });

            rover.SetPosition(1, 1);
            rover.SetDirection(DirectionEnum.Est);

            Obstacle obstacle = new Obstacle()
            {
                Position = new Position(2, 1)
            };

            MovementResult result = rover.MoveForward(new List <Obstacle>()
            {
                obstacle
            });

            Position expeted = new Position()
            {
                X = 1,
                Y = 1
            };

            Assert.IsTrue(
                expeted.X == result.Position.X &&
                expeted.Y == result.Position.Y &&
                obstacle.Position.X == result.Obstacle.Position.X &&
                obstacle.Position.Y == result.Obstacle.Position.Y &&
                !result.Result);
        }
        public void TestGetCurrentOrientation()
        {
            // Create an Orientation object with an azimuth of 311 and elevation of 42
            Orientation Orientation = new Orientation(311.0, 42.0);
            // Set the RadioTelescope's CurrentOrientation field
            MovementResult response = TestRadioTelescopeController.MoveRadioTelescopeToOrientation(Orientation, MovementPriority.Appointment);
            // Call the GetCurrentOrientationMethod
            Orientation CurrentOrientation = TestRadioTelescopeController.GetCurrentOrientation();

            // Ensure the objects are identical
            Assert.AreEqual(response, MovementResult.Success);
            Assert.AreEqual(Orientation.Azimuth, CurrentOrientation.Azimuth, 0.001);
            Assert.AreEqual(Orientation.Elevation, CurrentOrientation.Elevation, 0.001);


            Orientation = new Orientation(28.0, 42.0);
            // Set the RadioTelescope's CurrentOrientation field
            response = TestRadioTelescopeController.MoveRadioTelescopeToOrientation(Orientation, MovementPriority.Appointment);
            // Call the GetCurrentOrientationMethod
            CurrentOrientation = TestRadioTelescopeController.GetCurrentOrientation();
            Assert.AreEqual(response, MovementResult.Success);
            Assert.AreEqual(Orientation.Azimuth, CurrentOrientation.Azimuth, 0.001);
            Assert.AreEqual(Orientation.Elevation, CurrentOrientation.Elevation, 0.001);


            Orientation = new Orientation(310.0, 42.0);
            // Set the RadioTelescope's CurrentOrientation field
            response = TestRadioTelescopeController.MoveRadioTelescopeToOrientation(Orientation, MovementPriority.Appointment);
            // Call the GetCurrentOrientationMethod
            CurrentOrientation = TestRadioTelescopeController.GetCurrentOrientation();
            // Ensure the objects are identical
            Assert.AreEqual(response, MovementResult.Success);
            Assert.AreEqual(Orientation.Azimuth, CurrentOrientation.Azimuth, 0.001);
            Assert.AreEqual(Orientation.Elevation, CurrentOrientation.Elevation, 0.001);
        }
        public void TestThermalCalibrateRadioTelescope_TriesThermalCalibrateRadioTelescopeWithAnotherCommandRunning_AlreadyMoving()
        {
            MovementResult   result0  = MovementResult.None;
            MovementResult   result1  = MovementResult.None;
            MovementPriority priority = MovementPriority.Manual;

            // This is running two commands at the same time. One of them should succeed, while
            // the other is rejected

            Thread t0 = new Thread(() =>
            {
                result0 = TestRadioTelescopeController.ThermalCalibrateRadioTelescope(priority);
            });

            Thread t1 = new Thread(() =>
            {
                result1 = TestRadioTelescopeController.ThermalCalibrateRadioTelescope(priority);
            });

            t0.Start();
            t1.Start();

            t0.Join();
            t1.Join();

            Assert.IsTrue(result0 == MovementResult.Success || result1 == MovementResult.Success);
            Assert.IsTrue(result0 == MovementResult.AlreadyMoving || result1 == MovementResult.AlreadyMoving);
        }
Exemplo n.º 7
0
        private void AutomaticSnowDumpInterval(Object source, ElapsedEventArgs e)
        {
            double      DELTA = 0.01;
            Orientation currentOrientation = GetCurrentOrientation();

            // Check if we need to dump the snow off of the telescope
            if (RadioTelescope.WeatherStation.GetOutsideTemp() <= 30.00 && RadioTelescope.WeatherStation.GetTotalRain() > 0.00)
            {
                // We want to check stow position precision with a 0.01 degree margin of error
                if (Math.Abs(currentOrientation.Azimuth - MiscellaneousConstants.Stow.Azimuth) <= DELTA && Math.Abs(currentOrientation.Elevation - MiscellaneousConstants.Stow.Elevation) <= DELTA)
                {
                    Console.WriteLine("Time threshold reached. Running snow dump...");

                    MovementResult result = SnowDump(MovementPriority.Appointment);

                    if (result != MovementResult.Success)
                    {
                        logger.Info($"{Utilities.GetTimeStamp()}: Automatic snow dump FAILED with error message: {result.ToString()}");
                        pushNotification.sendToAllAdmins("Snow Dump Failed", $"Automatic snow dump FAILED with error message: {result.ToString()}");
                        EmailNotifications.sendToAllAdmins("Snow Dump Failed", $"Automatic snow dump FAILED with error message: {result.ToString()}");
                    }
                    else
                    {
                        Console.WriteLine("Snow dump completed");
                    }
                }
            }
        }
Exemplo n.º 8
0
    protected virtual void ExecuteInput(Vector2Int?direction = null)
    {
        Vector2Int actionDirection;

        if (!direction.HasValue)
        {
            actionDirection = _currentInput;
        }
        else
        {
            actionDirection = direction.Value;
        }

        // If the direction is null/zero return
        if (actionDirection == Vector2Int.zero)
        {
            return;
        }

        // Try to move to the target position
        var            targetPosition = _gridObject.m_GridPosition + actionDirection;
        MovementResult movementResult = _gridMovement.TryMoveToNeighborInPosition(targetPosition, m_AnimateMovement, m_RotateTowardsDirection);

        // Queue the desired input if the movement is currently in cooldown
        if (movementResult == MovementResult.Cooldown)
        {
            _queuedInput = _currentInput;
            return;
        }

        // If movement was succesful or failed for some other reason we remove the current input
        _currentInput = Vector2Int.zero;
    }
Exemplo n.º 9
0
        private static void Main()
        {
            // The snake speed
            double sleepTime = 100;

            ConsoleAppleGenerator appleGenerator = new ConsoleAppleGenerator(Console.WindowWidth, Console.WindowHeight);

            ConsoleSnake snake = new ConsoleSnake(5, '#', ConsoleColor.Green, Direction.Right);
            ConsoleApple apple;

            do
            {
                apple = appleGenerator.CreateApple();
            }while (snake.IsOn(apple));

            FixConsole();

            apple.Draw();

            while (true)
            {
                // Read user input
                if (Console.KeyAvailable)
                {
                    ConsoleKeyInfo pressedKey = Console.ReadKey();
                    snake.ChangeDirection(pressedKey);
                }

                MovementResult movementResult = snake.Move(Console.WindowWidth, Console.WindowHeight, apple);

                if (movementResult == MovementResult.Wall ||
                    movementResult == MovementResult.SelfBite)
                {
                    // Game is over
                    Console.SetCursorPosition(0, 0);
                    Console.ForegroundColor = ConsoleColor.Gray;
                    Console.WriteLine("Game over!!! Your points: {0}", snake.Length);
                    return;
                }

                if (movementResult == MovementResult.OnApple)
                {
                    do
                    {
                        apple = appleGenerator.CreateApple();
                    }while (snake.IsOn(apple));

                    apple.Draw();
                }

                snake.Draw();

                // Slow the motion
                Thread.Sleep((int)sleepTime);

                // Change the speed
                sleepTime -= 0.05;
            }
        }
        public void TestMoveRadioTelescopeToOrientation_AllStatusesOK_Success()
        {
            Orientation o = new Orientation();

            MovementResult result = TestRadioTelescopeController.MoveRadioTelescopeToOrientation(o, MovementPriority.Manual);

            Assert.AreEqual(MovementResult.Success, result);
        }
        public void TestMoveRadioTelescopeToCoordinate_AllStatusesOK_Success()
        {
            Coordinate c = new Coordinate();

            MovementResult result = TestRadioTelescopeController.MoveRadioTelescopeToCoordinate(c, MovementPriority.Manual);

            Assert.AreEqual(MovementResult.Success, result);
        }
        public void TestHomeTelescope_ElevationEncoderOKAndOverridden_Success()
        {
            TestRadioTelescopeController.overrides.setElevationAbsEncoder(true);

            MovementResult result = TestRadioTelescopeController.HomeTelescope(MovementPriority.Manual);

            Assert.AreEqual(MovementResult.Success, result);
        }
        public void TestHomeTelescope_AzimuthAbsoluteEncoderOff_IncorrectPosition()
        {
            SensorNetworkServer.CurrentAbsoluteOrientation.Azimuth = 1;

            MovementResult result = TestRadioTelescopeController.HomeTelescope(MovementPriority.Manual);

            Assert.AreEqual(MovementResult.IncorrectPosition, result);
        }
    internal static void FleeKinematic(InputParameters inputData, ref MovementResult result)
    {
        Vector3 directionToTarget = inputData.currentTransform.position - inputData.targetTransform.position;

        directionToTarget.Normalize();

        result.newPosition = inputData.currentTransform.position + (directionToTarget * inputData.maxSpeed * inputData.currentUpdateDuration);
    }
        public void TestHomeTelescope_ElevationAbsoluteEncoderOffButOverridden_Success()
        {
            SensorNetworkServer.CurrentAbsoluteOrientation.Elevation = 1;
            TestRadioTelescopeController.overrides.setElevationAbsEncoder(true);

            MovementResult result = TestRadioTelescopeController.HomeTelescope(MovementPriority.Manual);

            Assert.AreEqual(MovementResult.Success, result);
        }
Exemplo n.º 16
0
    internal static void AttackCooldown(InputParameters inputData, ref MovementResult result)
    {
        //Debug.Log("AttackCooldown");
        Vector3 directionToTarget = inputData.currentTransform.position - inputData.targetTransform.position;

        directionToTarget.Normalize();

        result.newPosition   = inputData.currentTransform.position + (directionToTarget * inputData.maxSpeed * inputData.currentUpdateDuration);
        result.newPosition.y = inputData.currentTransform.position.y;
    }
Exemplo n.º 17
0
        /// <summary>
        /// Ends an appointment by returning the RT to the stow position.
        /// </summary>
        public void EndAppointment()
        {
            logger.Info(Utilities.GetTimeStamp() + ": Ending Appointment");
            endAppt = true;
            MovementResult result = RTController.MoveRadioTelescopeToOrientation(new Orientation(0, 90), MovementPriority.Appointment);

            if (result != MovementResult.Success)
            {
                logger.Error("Stowing telescope failed with message " + result);
            }
        }
Exemplo n.º 18
0
    private void MoveForward()
    {
        Debug.Log(">>> Move forward");

        Coordinate     destination = ARPB2.Location + OrientationToCoords(ARPB2.Orientation);
        MovementResult result      = Board.MoveElement(ARPB2, destination);

        if (result.Equals(MovementResult.Success))
        {
            ARPB2.MoveForward();
        }
    }
        public void TestThermalCalibrateRadioTelescope_SensorDataUnsafe_SensorsNotSafe()
        {
            TestRadioTelescopeController.overrides.setElevationMotTemp(false);
            SensorNetworkServer.CurrentElevationMotorTemp[0].temp        = 3000;
            SensorNetworkServer.CurrentElevationMotorTemp[0].location_ID = (int)SensorLocationEnum.EL_MOTOR;

            Thread.Sleep(2000);

            MovementResult result = TestRadioTelescopeController.ThermalCalibrateRadioTelescope(MovementPriority.Manual);

            Assert.AreEqual(MovementResult.SensorsNotSafe, result);
        }
    internal static void SeekKinematic(InputParameters inputData, ref MovementResult result)
    {
        Vector3 directionToTarget = inputData.targetTransform.position - inputData.currentTransform.position;

        directionToTarget.Normalize();
        if ((inputData.targetTransform.position - inputData.currentTransform.position).magnitude < arrivalRadius)
        {
            inputData.maxSpeed = inputData.maxSpeed - (((inputData.targetTransform.position - inputData.currentTransform.position).magnitude) / arrivalRadius * inputData.maxSpeed);
        }

        result.newPosition = inputData.currentTransform.position + (directionToTarget * inputData.maxSpeed * inputData.currentUpdateDuration);
    }
Exemplo n.º 21
0
 static void dele1(MovementResult res)
 {
     if (res.Collisions.Any())
     {
         //collisionCount++;
         Console.WriteLine("Collision");
         foreach (var act in res.Collisions)
         {
             Console.Write(act.AgentGuid+"  and  ");
         }
         Console.WriteLine();
     }
 }
Exemplo n.º 22
0
        /// <summary>
        /// Method used to request to start jogging the Radio Telescope's elevation
        /// at a speed (in RPM), in either the clockwise or counter-clockwise direction.
        /// </summary>
        public MovementResult StartRadioTelescopeJog(double speed, RadioTelescopeDirectionEnum direction, RadioTelescopeAxisEnum axis)
        {
            MovementResult result = MovementResult.None;

            // Return if incoming priority is equal to or less than current movement
            if ((MovementPriority.Jog - 1) <= RadioTelescope.PLCDriver.CurrentMovementPriority)
            {
                return(MovementResult.AlreadyMoving);
            }

            // We only want to do this if it is safe to do so. Return false if not
            if (!AllSensorsSafe)
            {
                return(MovementResult.SensorsNotSafe);
            }

            // If a lower-priority movement was running, safely interrupt it.
            if (RadioTelescope.PLCDriver.InterruptMovementAndWaitUntilStopped())
            {
                return(MovementResult.StoppingCurrentMove);
            }

            // If the thread is locked (two moves coming in at the same time), return
            if (Monitor.TryEnter(MovementLock))
            {
                RadioTelescope.PLCDriver.CurrentMovementPriority = MovementPriority.Jog;

                double azSpeed = 0;
                double elSpeed = 0;

                if (axis == RadioTelescopeAxisEnum.AZIMUTH)
                {
                    azSpeed = speed;
                }
                else
                {
                    elSpeed = speed;
                }

                result = RadioTelescope.PLCDriver.StartBothAxesJog(azSpeed, direction, elSpeed, direction);

                Monitor.Exit(MovementLock);
            }
            else
            {
                result = MovementResult.AlreadyMoving;
            }

            return(result);
        }
Exemplo n.º 23
0
        private static void Movement(Board myBoard, int x1, int y1, int x2, int y2)
        {
            Console.Clear();
            MovementResult myRes = myBoard.move(x1, y1, x2, y2);

            myBoard.drawChessBoard();
            Console.WriteLine(myRes);
            System.Threading.Thread.Sleep(500);

            if ((myRes == MovementResult.LegalMove) || (myRes == MovementResult.Hit))
            {
                ChangeTurn();
            }
        }
        public void TestHomeTelescope_FinalOffsetBelowAz0_NormalizesAzOffset()
        {
            Orientation expectedOrientation = new Orientation(359.5, 20);

            TestRadioTelescopeController.RadioTelescope.CalibrationOrientation = new Orientation(-0.5, 20);;

            MovementResult result = TestRadioTelescopeController.HomeTelescope(MovementPriority.Manual);

            Orientation resultMotorEncoderOrientation    = TestRadioTelescopeController.GetCurrentOrientation();
            Orientation resultAbsoluteEncoderOrientation = TestRadioTelescopeController.GetAbsoluteOrientation();

            Assert.AreEqual(MovementResult.Success, result);
            Assert.IsTrue(expectedOrientation.Equals(resultMotorEncoderOrientation));
            Assert.IsTrue(expectedOrientation.Equals(resultAbsoluteEncoderOrientation));
        }
    internal static void WanderKinematic(InputParameters inputData, ref MovementResult result)
    {
        int range = 15;

        wanderCounter += inputData.currentUpdateDuration;
        if (wanderCounter > maxWanderDuration)
        {
            Vector3 randomTarget = inputData.targetTransform.position;
            randomTarget.x += (float)(r.NextDouble() - 0.5f) * range;
            randomTarget.z += (float)(r.NextDouble() - 0.5f) * range;
            inputData.targetTransform.position = randomTarget;
            wanderCounter = 0.0f;
        }

        SeekKinematic(inputData, ref result);
    }
Exemplo n.º 26
0
 void Update()
 {
     if (currentPlatform == null)
     {
         currentPlatform = GetPlayerSpawnerPlatform();
     }
     if (test)
     {
         test = false;
         MovementResult res = TryMoveToNextPlatform(EntityManager.GetPlayer().transform.forward);
         if (res.success)
         {
             EntityManager.GetPlayer().GetComponent <NavMeshAgent>().SetDestination(res.result.transform.position);
         }
     }
 }
Exemplo n.º 27
0
    // Try to move using a target tile in the grid
    public virtual MovementResult TryMoveTo(GridTile targetGridTile, bool animate = true, bool andRotate = true, bool checkMovementCooldown = true)
    {
        // Set the current and target tile
        m_StartGridTile  = _gridObject.m_CurrentGridTile;
        m_TargetGridTile = targetGridTile;
        // Current position and position we'd like to move to
        Vector2Int fromGridPos = _gridObject.m_GridPosition;
        Vector2Int toGridPos   = targetGridTile.m_GridPosition;


        // Checks for the cooldown or if it is moving
        if (checkMovementCooldown && (m_IsMoving || Cooldown.InProgress))
        {
            return(MovementResult.Cooldown);
        }

        // Rotation
        if (andRotate)
        {
            // Try to rotate the object in the direction
            var rotated = TryRotateTo(toGridPos, animate);
            // Return the correct movementresult if we actually turned and triggered the cooldown
            if (rotated && _rotationCausesMovementCooldown && Cooldown.InProgress)
            {
                return(MovementResult.Turned);
            }
        }

        // Declare a new local variable to store wether the movement was succesful or not
        MovementResult movementResult = MovementResult.Moved;

        // Move if possible else return the failed result
        if (_gridObject.m_CurrentGridTile != null && targetGridTile.CanMoveToTile())
        {
            var moved = MoveTo(targetGridTile, animate);
            if (!moved)
            {
                movementResult = MovementResult.Failed;
            }
        }
        else
        {
            movementResult = MovementResult.Failed;
        }

        return(movementResult);
    }
Exemplo n.º 28
0
    internal static void Idle(InputParameters inputData, ref MovementResult result)
    {
        // Debug.Log("Idle");
        int range = 5;

        wanderCounter += inputData.currentUpdateDuration;
        if (wanderCounter > maxWanderDuration)
        {
            Vector3 randomTarget = inputData.targetTransform.position;
            randomTarget.x += (float)r.NextDouble() * range;
            randomTarget.z += (float)r.NextDouble() * range;
            inputData.targetTransform.position = randomTarget;
            wanderCounter = 0.0f;
        }

        Attack(inputData, ref result);
    }
        public void TestMoveRadioTelescope_SlipRing_359degrees()
        {
            // Set the Telescope Type to SLIP RING
            TestRTPLC.setTelescopeType(RadioTelescopeTypeEnum.SLIP_RING);

            // Create an Orientation object with an azimuth of 311 and elevation of 0
            Orientation TargetOrientation = new Orientation(359.0, 0);

            // Set the RadioTelescope's CurrentOrientation field
            MovementResult response = TestRadioTelescopeController.MoveRadioTelescopeToOrientation(TargetOrientation, MovementPriority.Appointment);

            // Call the GetCurrentOrientationMethod
            Orientation CurrentOrientation = TestRadioTelescopeController.GetCurrentOrientation();

            // Ensure the objects are identical
            Assert.AreEqual(response, MovementResult.Success);
            Assert.AreEqual(TargetOrientation.Azimuth, CurrentOrientation.Azimuth, 0.001);
            Assert.AreEqual(TargetOrientation.Elevation, CurrentOrientation.Elevation, 0.001);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Ship tries to move in the ocean.
        /// </summary>
        /// <param name="prevPosition"></param>
        /// <param name="newPosition"></param>
        /// <returns></returns>
        public MovementResult TryMove(Coords?prevPosition, Coords newPosition)
        {
            MovementResult result = MovementResult.Success;

            if ((newPosition.XCoord < 0) ||
                (newPosition.XCoord >= _xSize) ||
                (newPosition.YCoord < 0) ||
                (newPosition.YCoord >= _ySize))
            {
                if ((prevPosition.HasValue) && _warnings.Contains(prevPosition.Value))
                {
                    result = MovementResult.Warning;
                }
                else
                {
                    result = MovementResult.Lost;
                }
            }

            return(result);
        }
Exemplo n.º 31
0
        public Extract Handle(IFormFile file)
        {
            if (file.Length > 0)
            {
                var extract = new Extract();
                extract.pagamentos   = new List <MovementResult>();
                extract.recebimentos = new List <MovementResult>();
                using (var reader = new StreamReader(file.OpenReadStream()))
                {
                    while (reader.Peek() >= 0)
                    {
                        var item = reader.ReadLine().Split(";");

                        var movement = new MovementResult()
                        {
                            data      = item[0],
                            descricao = item[1],
                            moeda     = "R$",
                            valor     = item[2],
                            categoria = item.Length > 2 ? item[3] : null
                        };

                        var valor = Convert.ToDecimal(movement.valor);

                        if (valor <= 0)
                        {
                            extract.pagamentos.Add(movement);
                        }
                        else
                        {
                            extract.recebimentos.Add(movement);
                        }
                    }
                }
                return(extract);
            }

            throw new System.Exception("file not found");
        }
Exemplo n.º 32
0
        public void Commit()
        {
            var before = DateTime.Now;
            // Block all incoming requests until the calculation
            gpuActive = true;
            // Wait till the processing add and move operations finished
            while (m_ActiveOperationCount > 0)
            {
                Thread.Sleep(5);
            }

            // Total number of elements to calculate
             constants.numTotalElements = envActEnvObjs.Count + envExploreObjs.Count + envFreshAddedObjs.Count;
            /*
             constants.numTotalElements--;
             constants.numTotalElements |=  constants.numTotalElements >> 1;
             constants.numTotalElements |=  constants.numTotalElements >> 2;
             constants.numTotalElements |=  constants.numTotalElements >> 4;
             constants.numTotalElements |=  constants.numTotalElements >> 8;
             constants.numTotalElements |=  constants.numTotalElements >> 16;
             constants.numTotalElements++;
            */

            if (DEBUG)
            {
                debugReadInput = new long[constants.numTotalElements];
                debugCollisionList = new long[constants.numTotalElements * 8];
            }
            cellPosList = new CollisionCell[constants.numTotalElements * 8];
            tupelList = new CollisionTupel[constants.numTotalElements * 8];
            readCellData = new long[constants.numTotalElements * 8];
            readCellIdList = new int[constants.numTotalElements * 8];

            clShapeArray = envActEnvObjs.Values.ToList();
            clShapeArray.AddRange(envExploreObjs.Values.ToList());
            clShapeArray.AddRange(envFreshAddedObjs.Values.ToList());
              //  int fillCount =  constants.numTotalElements - clShapeArray.Count;
            /*long[] dummys = new long[fillCount];
            dummys.i*/

            //shapes.
            clObjArray = envActEnvObjs.Keys.ToList();
            clObjArray.AddRange(envExploreObjs.Keys.ToList());
            clObjArray.AddRange(envFreshAddedObjs.Keys.ToList());
            constants.numTotalElements = clObjArray.Count;

            #region CreateBuffers
            // Create the Buffers
            CreateBuffers();
            #endregion

            Console.WriteLine("Execution time Create Buffers =" + (DateTime.Now - before).TotalMilliseconds);
            before = DateTime.Now;

            #region createCellList
            CreateCellId();
            #endregion

            Console.WriteLine("Execution time CreateCellIdArray =" + (DateTime.Now - before).TotalMilliseconds);
            before = DateTime.Now;

            #region RadixSort
            // Radix Sort
            sort.sortKeysValue(cellIds, cellData, constants.numTotalElements * 8);
            //sort.sortKeysValue();
            ErrorCode error;
            Event eve;

            error = Cl.EnqueueReadBuffer(cqCommandQueue, cellData, Bool.True, IntPtr.Zero, (IntPtr)(constants.numTotalElements * 8 * 8),
            readCellData, 0, null, out eve);
            CheckErr(error, "Cl.EnqueueReadBuffer");

            if (DEBUG)
            {
                error = Cl.EnqueueReadBuffer(cqCommandQueue, cellIds, Bool.True, IntPtr.Zero, (IntPtr)(constants.numTotalElements * 4 * 8),
                readCellIdList, 0, null, out eve);
                CheckErr(error, "Cl.EnqueueReadBuffer");

                for (int i = 0; i < readCellIdList.Count(); i++)
                {
                    if (cellMap.ContainsKey(readCellIdList[i]))
                    {
                        cellPosList[i] = cellMap[readCellIdList[i]];
                    }
                    else
                    {
                        cellPosList[i] = new CollisionCell();
                    }
                }

                DebugHelper.PrintCellIdBufferExtended(debugReadInput, readCellIdList, readCellData, cellPosList, "Sorted Keys", constants.numTotalElements);

            }

            #endregion

            Console.WriteLine("Execution time RadixSort =" + (DateTime.Now - before).TotalMilliseconds);
            before = DateTime.Now;

            #region CollisionList
            CreateCollisionList();
            #endregion

            Console.WriteLine("Execution time CreateCollisionList =" + (DateTime.Now - before).TotalMilliseconds);
            before = DateTime.Now;

            #region CreateCollisionTuples
            CreateCollsionTuples();
            #endregion
            Console.WriteLine("Execution time CreateCollisionTuples =" + (DateTime.Now - before).TotalMilliseconds);
            before = DateTime.Now;
            #region CheckCollisions
            if (sharedIdx[0] > 0)
            {
                CheckCollsions();
                Console.WriteLine("Execution time CheckCollisions =" + (DateTime.Now - before).TotalMilliseconds);
                before = DateTime.Now;

                //TODO: MAybe do this threadwise to get some more performance.
                for (int i = 0; i < sharedIdx[0]; i++)
                {
                    if (collisionMap.ContainsKey(tupelList[i].obj1))
                    {
                        collisionMap[tupelList[i].obj1].Add(tupelList[i].obj2);
                    }
                    else
                    {
                        HashSet<int> tmp = new HashSet<int>();
                        tmp.Add(tupelList[i].obj2);
                        collisionMap.Add(tupelList[i].obj1, tmp);
                    }
                    if (collisionMap.ContainsKey(tupelList[i].obj2))
                    {
                        collisionMap[tupelList[i].obj2].Add(tupelList[i].obj1);
                    }
                    else
                    {
                        HashSet<int> tmp = new HashSet<int>();
                        tmp.Add(tupelList[i].obj1);
                        collisionMap.Add(tupelList[i].obj2, tmp);
                    }
                }

                // Check Results
            }

            // RemoveSet
            var itemsToRemove = new HashSet<int>();
            // Call all delegates
            foreach (var actDele in m_AddDelegates)
            {
                int tmpId = (int) (actDele.Item1 & 0xFFFFFFFF);
                if (collisionMap.ContainsKey(tmpId))
                {
                    // Add collided -> dont add item to environment
                    List<ISpatialEntity> deleList = new List<ISpatialEntity>();//collisionMap[tmpId].Select(actObj => objIdSpatialMap[actObj]).ToList();
                    foreach (var actobjId in collisionMap[tmpId].ToList())
                    {
                        deleList.Add(objIdSpatialMap[actobjId]);
                    }
                    var ret = new MovementResult(deleList);
                    actDele.Item2.Invoke(ret);
                    itemsToRemove.Add(tmpId);
                }
                else
                {
                    // Add successful -> Add Element to environment and invoke corresponding delegate
                    actDele.Item2.Invoke(new MovementResult());
                    envActEnvObjs.Add(((long)tmpId) | FLAG_MOVE,objIdClShapeMap[tmpId]);
                }
            }
            foreach (var actDele in m_MoveDelegates)
            {
                int tmpId = (int)(actDele.Item1 & 0xFFFFFFFF);
                if (collisionMap.ContainsKey(tmpId))
                {
                    List<ISpatialEntity> deleList = collisionMap[tmpId].Select(actObj => objIdSpatialMap[actObj]).ToList();
                    var ret = new MovementResult(deleList);
                    actDele.Item2.Invoke(ret);
                }
                else
                {
                    actDele.Item2.Invoke(new MovementResult());
                }
            }
            foreach (var actDele in m_ExploreDelegates)
            {
                int tmpId = (int)(actDele.Item1 & 0xFFFFFFFF);
                if (collisionMap.ContainsKey(tmpId))
                {
                    List<ISpatialEntity> deleList = collisionMap[tmpId].Select(actObj => objIdSpatialMap[actObj]).ToList();
                    actDele.Item2.Invoke(deleList);
                }
                else
                {
                    actDele.Item2.Invoke(new List<ISpatialEntity>());
                }
            }
            foreach (var act in itemsToRemove)
            {
                RemoveByObjId(act);
            }
            #endregion
            m_AddDelegates.Clear();
            m_MoveDelegates.Clear();
            m_ExploreDelegates.Clear();
            envFreshAddedObjs.Clear();
            envExploreObjs.Clear();
            layerTickWait.Set();
            Thread.Sleep(10);
            layerTickWait.Reset();
            gpuActive = false;

            gpuActiveWait.Set();
            Thread.Sleep(10);
            gpuActiveWait.Reset();
            Console.WriteLine("Execution time Call Delegates and Cleanup =" + (DateTime.Now - before).TotalMilliseconds);
               // before = DateTime.Now;
        }