// the perception is created and generated here
    public Percept(SimulationState state, int agentID, bool inProlog = true)
    {
        //SimulationEngineComponentScript.ss.stdout.Send("entro al constructor de Percept");

        if (inProlog){
            auxList = new List<string>();
            auxList.Add("time("+SimulationState.getInstance().gameTime+")");
            if (state.agents.ContainsKey(agentID)) {
                state.agents[agentID].agentController.perceive(this);
                foreach(IPerceivableEntity e in elements){
                    aux = e.toProlog();
                    auxList.Add(aux);
                }
                //auxList.Add(state.agents[agentID].agentController.selfProperties());
                p = PrologList.AtomList<string>(auxList);
            }
            else {
                Debug.LogError("Percept creation fail.");
            }
        }
        else{
            // xml
            throw new NotImplementedException();
        }
    }
Exemple #2
0
        public string Serialize(SimulationState state)
        {
            States.Add(state);

            var average = state.Individuals.Select(a => a.Fitness).Average();

            return string.Format("{{ \"average_fitness\": {0}, \"processing_time\": {1} }}", average, state.ProcessingTime);
        }
Exemple #3
0
    static void Start()
    {
        quit = false;

        ss = new SimulationState("config.xml");
        se = new SimulationEngine(ss);

        Console.WriteLine("Press press any key to stop the simulation engine.");
        Console.WriteLine("Note: there is no ANY key on your keyboard.");

        se.start();
    }
    public override void Start()
    {
        base.Start();
        this._type = "inn";
        this.ss    = (GameObject.FindGameObjectWithTag("GameController").
            GetComponent(typeof(SimulationEngineComponentScript))
            as SimulationEngineComponentScript).engine as SimulationState;

        this.ss.addInn(this);

        forbiddenEntry = new Dictionary<Agent, Interval>();
    }
Exemple #5
0
        public GameLoop(int idleTimer)
        {
            playBehaviour = new PlayBehaviour();
            deathBehaviour = new DeathBehaviour();

            this.idleTimer = idleTimer;
            this.defaultIdleTimer = idleTimer;

            InputQueue = new Queue<Command>();

            simulationState = SimulationState.Idling;
        }
    public override void Start()
    {
        SimulationState.getInstance().stdout.Send("entro Start");
        base.Start();
        this._type = "home";
        this.ss    = (GameObject.FindGameObjectWithTag("GameController").
            GetComponent(typeof(SimulationEngineComponentScript))
            as SimulationEngineComponentScript).engine as SimulationState;

        this.ss.addHome(this);
        gameObject.renderer.material.color = color;
        texture = Agent.MakeTex(2, 2, color);
    }
    public ConnectionHandler(SimulationState ss)
    {
        // NETWORK & OPERATION
        tcpListener             = new TcpListener(IPAddress.Parse("127.0.0.1"), 8888);
        connectionHandlerThread = new Thread(new ThreadStart(this.run));
        connectionHandlerThread.IsBackground = true;

        // SIMULATION
        quit                    = false;
        simulationState         = ss;
        agentConnections        = new List<AgentConnection>();
        instantiationResults    = new MailBox<bool>(false);
    }
    public AgentConnection(SimulationState ss, TcpClient tcpc)
    {
        // NETWORK & OPERATION
        tcpClient              = tcpc;
        networkStream          = tcpc.GetStream();
        streamReader           = new StreamReader(networkStream);
        streamWriter           = new StreamWriter(networkStream);
        agentConnectionThread  = new Thread(new ThreadStart(this.run));

        agentConnectionThread.IsBackground = true;

        // SIMULATION
        quit                   = false;
        simulationState        = ss;
    }
    // Use this for initialization
    void Awake()
    {
        ss = new SimulationState("C:\\config.xml", goldPrefab, potionPrefab);
        SimulationState.getInstance().stdout.Send("entro Awake Sim Engine");
        se = new SimulationEngine(ss);

        //ss.initialize();

        InvokeRepeating( "DoWork", 0, 0.1f );

        // Instantiate dummy agent for testing purposes
        /*
        se.instantiateDummyAgent("dummy1", agentPrefab);
        AgentState dummy1AgState = se.simulationState.agents[se.simulationState.agentIDs["dummy1"]];
        dummy1AgState.agentController.pickupPosCon(Gold.Create(new Vector3(0,0,0)));
        dummy1AgState.agentController.pickupPosCon(Gold.Create(new Vector3(0,0,0)));
        dummy1AgState.agentController.pickupPosCon(Potion.Create(new Vector3(0,0,0)));
        dummy1AgState.agentController.pickupPosCon(Potion.Create(new Vector3(0,0,0)));
        dummy1AgState.agentController.pickupPosCon(Potion.Create(new Vector3(0,0,0)));
        //se.instantiateDummyAgent("dummy2", agentPrefab);
        */
        se.start();
    }
 public void CreatingState(ref SimulationState simulationState)
 {
 }
Exemple #11
0
        /// <summary>
        /// Writes a new state to the stream.
        /// </summary>
        /// <param name="state">New state</param>
        public void Write(SimulationState state)
        {
            serializer.Write(BlockType.FrameStart);
            int[] keys;

            #region Framestart

            // The first call creates the frame
            if (frame == null)
            {
                // Create new frame
                frame = new Frame(state);
                serializer.Write(BlockType.Frame, frame);
            }
            else
            {
                // Send frame-update
                FrameUpdate update = frame.GenerateUpdate(state);
                if (update != null)
                {
                    serializer.Write(BlockType.FrameUpdate, update);
                }
            }

            #endregion

            #region Teams and ColonyStates

            #region ant-reset

            // reset alive-flag
            foreach (Ant ant in antList.Values)
            {
                ant.IsAlive = false;
            }

            #endregion

            #region marker-reset

            // reset alive-flag
            foreach (Marker marker in markerList.Values)
            {
                marker.IsAlive = false;
            }

            #endregion

            // Teams are static and need no update

            // enumerate all teams
            foreach (TeamState teamState in state.TeamStates)
            {
                // Check, if team is known
                if (teamList.ContainsKey(teamState.Id))
                {
                    // No Teamupdate needed
                }
                else
                {
                    Team team = new Team(teamState);
                    serializer.Write(BlockType.Team, team);
                    teamList.Add(teamState.Id, team);
                }

                // ColonyStates are static and need no update

                // enumerate all colonies
                foreach (ColonyState colonyState in teamState.ColonyStates)
                {
                    // Check, if colony is known
                    if (colonyList.ContainsKey(colonyState.Id))
                    {
                        // colony-update
                        ColonyUpdate update = colonyList[colonyState.Id].GenerateUpdate(colonyState);
                        if (update != null)
                        {
                            serializer.Write(BlockType.ColonyUpdate, update);
                        }
                        colonyList[colonyState.Id].Interpolate();
                    }
                    else
                    {
                        // new colony
                        Colony colony = new Colony(colonyState, teamState.Id);
                        serializer.Write(BlockType.Colony, colony);
                        colonyList.Add(colonyState.Id, colony);
                        casteList.Add(colonyState.Id, new Dictionary <int, Caste>());

                        #region Castes

                        // Casts are static and need no update

                        Dictionary <int, Caste> castes = casteList[colonyState.Id];

                        // enumerate casts
                        for (ushort i = 0; i < colonyState.CasteStates.Count; i++)
                        {
                            // Check, if caste is known
                            if (!castes.ContainsKey(i))
                            {
                                // add caste
                                Caste caste = new Caste(colonyState.CasteStates[i]);
                                serializer.Write(BlockType.Caste, caste);
                            }
                        }

                        #endregion

                        #region Anthills

                        // Anthills are static and need no update

                        // enumerate anthills
                        foreach (AnthillState anthill in colonyState.AnthillStates)
                        {
                            if (!anthillList.ContainsKey(anthill.Id))
                            {
                                Anthill hill = new Anthill(anthill);
                                serializer.Write(BlockType.Anthill, hill);
                                anthillList.Add(anthill.Id, hill);
                            }
                        }

                        #endregion
                    }

                    #region Ants

                    // enumerate ants
                    foreach (AntState antState in colonyState.AntStates)
                    {
                        // Check, if ant is known
                        if (antList.ContainsKey(antState.Id))
                        {
                            // ant-update
                            AntUpdate update = antList[antState.Id].GenerateUpdate(antState);
                            if (update != null)
                            {
                                serializer.Write(BlockType.AntUpdate, update);
                            }
                            antList[antState.Id].Interpolate();
                        }
                        else
                        {
                            // create ant
                            Ant ant = new Ant(antState);
                            serializer.Write(BlockType.Ant, ant);
                            antList.Add(ant.Id, ant);
                        }

                        antList[antState.Id].IsAlive = true;
                    }

                    #endregion

                    #region Marker

                    // enumerate marker
                    foreach (MarkerState markerState in colonyState.MarkerStates)
                    {
                        // Check, if marker is known
                        if (markerList.ContainsKey(markerState.Id))
                        {
                            // marker-update
                            MarkerUpdate update = markerList[markerState.Id].GenerateUpdate(markerState);
                            if (update != null)
                            {
                                serializer.Write(BlockType.MarkerUpdate, update);
                            }
                            markerList[markerState.Id].Interpolate();
                        }
                        else
                        {
                            // create marker
                            Marker marker = new Marker(markerState);
                            serializer.Write(BlockType.Marker, marker);
                            markerList.Add(markerState.Id, marker);
                        }

                        markerList[markerState.Id].IsAlive = true;
                    }

                    #endregion
                }
            }

            #region Ant-Cleanup

            // remove dead ants
            keys = new int[antList.Keys.Count];
            antList.Keys.CopyTo(keys, 0);
            for (int i = 0; i < keys.Length; i++)
            {
                if (!antList[keys[i]].IsAlive)
                {
                    serializer.Write(BlockType.AntLost, new Lost(keys[i]));
                    antList.Remove(keys[i]);
                }
            }

            #endregion

            #region Marker-Cleanup

            // remove dead marker
            keys = new int[markerList.Keys.Count];
            markerList.Keys.CopyTo(keys, 0);
            for (int i = 0; i < keys.Length; i++)
            {
                if (!markerList[keys[i]].IsAlive)
                {
                    serializer.Write(BlockType.MarkerLost, new Lost(keys[i]));
                    markerList.Remove(keys[i]);
                }
            }

            #endregion

            #endregion

            #region Fruit

            // reset alive-flag
            foreach (Fruit fruit in fruitList.Values)
            {
                fruit.IsAlive = false;
            }

            // enumerate fruit
            foreach (FruitState fruitState in state.FruitStates)
            {
                // Check, if fruit is known
                if (fruitList.ContainsKey(fruitState.Id))
                {
                    // fruit-update
                    FruitUpdate update = fruitList[fruitState.Id].GenerateUpdate(fruitState);
                    if (update != null)
                    {
                        serializer.Write(BlockType.FruitUpdate, update);
                    }
                    fruitList[fruitState.Id].Interpolate();
                }
                else
                {
                    // create fruit
                    Fruit fruit = new Fruit(fruitState);
                    serializer.Write(BlockType.Fruit, fruit);
                    fruitList.Add(fruitState.Id, fruit);
                }

                fruitList[fruitState.Id].IsAlive = true;
            }

            // remove dead fruits
            keys = new int[fruitList.Keys.Count];
            fruitList.Keys.CopyTo(keys, 0);
            for (int i = 0; i < keys.Length; i++)
            {
                if (!fruitList[keys[i]].IsAlive)
                {
                    serializer.Write(BlockType.FruitLost, new Lost(keys[i]));
                    fruitList.Remove(keys[i]);
                }
            }

            #endregion

            #region Sugar

            // reset alive-flag
            foreach (Sugar sugar in sugarList.Values)
            {
                sugar.IsAlive = false;
            }

            // enumerate sugar
            foreach (SugarState sugarState in state.SugarStates)
            {
                // Check, if sugar is known
                if (sugarList.ContainsKey(sugarState.Id))
                {
                    // sugar-update
                    SugarUpdate update = sugarList[sugarState.Id].GenerateUpdate(sugarState);
                    if (update != null)
                    {
                        serializer.Write(BlockType.SugarUpdate, update);
                    }
                    sugarList[sugarState.Id].Interpolate();
                }
                else
                {
                    // create sugar
                    Sugar sugar = new Sugar(sugarState);
                    serializer.Write(BlockType.Sugar, sugar);
                    sugarList.Add(sugarState.Id, sugar);
                }

                sugarList[sugarState.Id].IsAlive = true;
            }

            // remove dead sugar
            keys = new int[sugarList.Keys.Count];
            sugarList.Keys.CopyTo(keys, 0);
            for (int i = 0; i < keys.Length; i++)
            {
                if (!sugarList[keys[i]].IsAlive)
                {
                    serializer.Write(BlockType.SugarLost, new Lost(keys[i]));
                    sugarList.Remove(keys[i]);
                }
            }

            #endregion

            #region Bugs

            // reset alive-flag
            foreach (Bug bug in bugList.Values)
            {
                bug.IsAlive = false;
            }

            // enumerate bugs
            foreach (BugState bugState in state.BugStates)
            {
                // Check, if bug is known
                if (bugList.ContainsKey(bugState.Id))
                {
                    // bug-update
                    BugUpdate update = bugList[bugState.Id].GenerateUpdate(bugState);
                    if (update != null)
                    {
                        serializer.Write(BlockType.BugUpdate, update);
                    }
                    bugList[bugState.Id].Interpolate();
                }
                else
                {
                    // create bug
                    Bug bug = new Bug(bugState);
                    serializer.Write(BlockType.Bug, bug);
                    bugList.Add(bugState.Id, bug);
                }

                bugList[bugState.Id].IsAlive = true;
            }

            // remove dead bugs
            keys = new int[bugList.Keys.Count];
            bugList.Keys.CopyTo(keys, 0);
            for (int i = 0; i < keys.Length; i++)
            {
                if (!bugList[keys[i]].IsAlive)
                {
                    serializer.Write(BlockType.BugLost, new Lost(keys[i]));
                    bugList.Remove(keys[i]);
                }
            }

            #endregion

            serializer.Write(BlockType.FrameEnd);
        }
        private void callback_OnSimulationChanged(SimulationState state, byte framerate)
        {
            // Server State changed from running to stopped
            if (_serverState != SimulationState.Stopped && state == SimulationState.Stopped)
            {
                // Trash Deserializer
                if (_deserializer != null)
                {
                    _deserializer.Dispose();
                    _deserializer = null;
                }

                // Remove last State
                _currentState = null;
            }

            //// Server State changed from stopped to running
            //if (_serverState == SimulationState.Stopped && state != SimulationState.Stopped)
            //{
            //    if (_deserializer == null)
            //    {
            //        _deserializer = new StateDeserializer();
            //    }
            //}

            // Set local Properties
            _serverState = state;
            _rate = framerate;

            // Drop Event
            if (OnSimulationChanged != null)
                OnSimulationChanged(this, state, framerate);
        }
Exemple #13
0
        /// <summary>
        /// Reads a new simulation-state out of stream.
        /// </summary>
        /// <returns>New simulation-state or null, if stream is over</returns>
        public SimulationState Read()
        {
            // if stream is at his end, return null
            if (complete)
            {
                return(null);
            }

            // first block have to be a frame-start
            ISerializable block;
            BlockType     blockType = serializer.Read(out block);

            // detect stream-end
            if (blockType == BlockType.StreamEnd)
            {
                complete = true;
                return(null);
            }

            // unexpected block-type
            if (blockType != BlockType.FrameStart)
            {
                throw new InvalidOperationException(
                          string.Format(
                              CultureInfo.CurrentCulture,
                              Resource.AntvideoReaderInvalidBlockType, blockType));
            }

            // block-loop
            while (blockType != BlockType.FrameEnd)
            {
                blockType = serializer.Read(out block);
                switch (blockType)
                {
                case BlockType.Ant:
                    Ant ant = (Ant)block;
                    antList.Add(ant.Id, ant);
                    break;

                case BlockType.Anthill:
                    Anthill anthill = (Anthill)block;
                    anthillList.Add(anthill.Id, anthill);
                    break;

                case BlockType.AntLost:
                    Lost antLost = (Lost)block;
                    antList.Remove(antLost.Id);
                    break;

                case BlockType.AntUpdate:
                    AntUpdate antUpdate = (AntUpdate)block;
                    antList[antUpdate.Id].Update(antUpdate);
                    break;

                case BlockType.Bug:
                    Bug bug = (Bug)block;
                    bugList.Add(bug.Id, bug);
                    break;

                case BlockType.BugLost:
                    Lost bugLost = (Lost)block;
                    bugList.Remove(bugLost.Id);
                    break;

                case BlockType.BugUpdate:
                    BugUpdate bugUpdate = (BugUpdate)block;
                    bugList[bugUpdate.Id].Update(bugUpdate);
                    break;

                case BlockType.Caste:
                    Caste caste = (Caste)block;
                    casteList[caste.ColonyId].Add(caste.Id, caste);
                    break;

                case BlockType.Team:
                    Team team = (Team)block;
                    teamList.Add(team.Id, team);
                    colonyList.Add(team.Id, new Dictionary <int, Colony>());
                    break;

                case BlockType.Colony:
                    Colony colony = (Colony)block;
                    colonyList[colony.TeamId].Add(colony.Id, colony);
                    casteList.Add(colony.Id, new Dictionary <int, Caste>());
                    break;

                case BlockType.ColonyUpdate:
                    ColonyUpdate colonyUpdate = (ColonyUpdate)block;
                    colonyList[colonyUpdate.TeamId][colonyUpdate.Id].Update(colonyUpdate);
                    break;

                case BlockType.Frame:
                    frame = (Frame)block;
                    break;

                case BlockType.FrameUpdate:
                    FrameUpdate frameUpdate = (FrameUpdate)block;
                    frame.Update(frameUpdate);
                    break;

                case BlockType.Fruit:
                    Fruit fruit = (Fruit)block;
                    fruitList.Add(fruit.Id, fruit);
                    break;

                case BlockType.FruitLost:
                    Lost fruitLost = (Lost)block;
                    fruitList.Remove(fruitLost.Id);
                    break;

                case BlockType.FruitUpdate:
                    FruitUpdate fruitUpdate = (FruitUpdate)block;
                    fruitList[fruitUpdate.Id].Update(fruitUpdate);
                    break;

                case BlockType.Marker:
                    Marker marker = (Marker)block;
                    markerList.Add(marker.Id, marker);
                    break;

                case BlockType.MarkerLost:
                    Lost markerLost = (Lost)block;
                    markerList.Remove(markerLost.Id);
                    break;

                case BlockType.MarkerUpdate:
                    MarkerUpdate markerUpdate = (MarkerUpdate)block;
                    markerList[markerUpdate.Id].Update(markerUpdate);
                    break;

                case BlockType.Sugar:
                    Sugar sugar = (Sugar)block;
                    sugarList.Add(sugar.Id, sugar);
                    break;

                case BlockType.SugarLost:
                    Lost sugarLost = (Lost)block;
                    sugarList.Remove(sugarLost.Id);
                    break;

                case BlockType.SugarUpdate:
                    SugarUpdate sugarUpdate = (SugarUpdate)block;
                    sugarList[sugarUpdate.Id].Update(sugarUpdate);
                    break;
                }
            }

            // Detect streamend
            if ((BlockType)serializer.Peek() == BlockType.StreamEnd)
            {
                complete = true;
            }

            // Interpolate all elements and buildup state
            frame.Interpolate();
            SimulationState state = frame.GenerateState();

            foreach (Bug bug in bugList.Values)
            {
                bug.Interpolate();
                state.BugStates.Add(bug.GenerateState());
            }
            foreach (Fruit fruit in fruitList.Values)
            {
                fruit.Interpolate();
                state.FruitStates.Add(fruit.GenerateState());
            }
            foreach (Sugar sugar in sugarList.Values)
            {
                sugar.Interpolate();
                state.SugarStates.Add(sugar.GenerateState());
            }

            foreach (Team team in teamList.Values)
            {
                TeamState teamState = team.GenerateState();
                state.TeamStates.Add(teamState);

                foreach (Colony colony in colonyList[team.Id].Values)
                {
                    colony.Interpolate();
                    ColonyState colonyState = colony.GenerateState();
                    teamState.ColonyStates.Add(colonyState);

                    foreach (Caste caste in casteList[colony.Id].Values)
                    {
                        colonyState.CasteStates.Add(caste.GenerateState());
                    }

                    foreach (Anthill anthill in anthillList.Values)
                    {
                        if (anthill.ColonyId == colony.Id)
                        {
                            colonyState.AnthillStates.Add(anthill.GenerateState());
                        }
                    }

                    foreach (Ant ant in antList.Values)
                    {
                        if (ant.ColonyId == colony.Id)
                        {
                            ant.Interpolate();
                            colonyState.AntStates.Add(ant.GenerateState());
                        }
                    }
                    foreach (Marker marker in markerList.Values)
                    {
                        if (marker.ColonyId == colony.Id)
                        {
                            marker.Interpolate();
                            colonyState.MarkerStates.Add(marker.GenerateState());
                        }
                    }
                }
            }

            // deliver
            return(state);
        }
        /// <summary>
        /// Called at the end of every attempt.
        /// </summary>
        private void EndAttempt()
        {
            // Stop the ball.
              _ball.Stop(_world);

              // Don't load a new ball if the player ran out of balls.
              if (_attemptsLeft > 0) {
            _launcher.LoadBall(Ball);
              } else {
            _currentState = SimulationState.Failed;
            Console.WriteLine("You lose!");

            // Do anything that needs to be done when the level is failed.
            if (OnFailure != null) {
              OnFailure();
            }
              }
        }
        //UI thread
        /// <summary>
        /// Starts simulation for specified number of steps.
        /// </summary>
        /// <param name="stepCount">How many steps of simulation shall be performed (0 means unlimited).</param>
        public void StartSimulation(uint stepCount)
        {
            bool doFixedNumberOfSteps = (stepCount > 0);

            if (State == SimulationState.STOPPED)
            {
                MyLog.INFO.WriteLine("Scheduling...");
                Simulation.Schedule(Project);

                MyLog.INFO.WriteLine("Initializing tasks...");
                Simulation.Init();

                MyLog.INFO.WriteLine("Allocating memory...");
                Simulation.AllocateMemory();
                PrintMemoryInfo();

                MyLog.INFO.WriteLine("Starting simulation...");
            }
            else
            {
                MyLog.INFO.WriteLine("Resuming simulation...");
            }

            State = doFixedNumberOfSteps ? SimulationState.RUNNING_STEP : SimulationState.RUNNING;
            m_stepsToPerform = stepCount;
            m_lastProgressChangedStep = 0;

            // Clean up breakpoints.
            Simulation.CleanTemporaryBlockData();

            MyKernelFactory.Instance.SetCurrent(MyKernelFactory.Instance.DevCount - 1);

            m_workedCompleted.Reset();
            m_worker.RunWorkerAsync();
        }
Exemple #16
0
 /// <summary>
 /// Updates UI
 /// </summary>
 /// <param name="state">current state of simulation</param>
 public void UpdateUI(SimulationState state)
 {
 }
Exemple #17
0
 public SessionSendSimulationStatePacket(SimulationState simulationState, ulong playerUID)
 {
     SimulationState = simulationState;
     PlayerUID       = playerUID;
 }
Exemple #18
0
        public void Or(string input, string regex, SimulationState expectedResult)
        {
            SimulationState result = RegexEngine.Simulate(regex, input);

            Assert.AreEqual(expectedResult, result);
        }
        /// <summary>
        /// Just run the sim
        /// </summary>
        public void RunSimulation()
        {
            // running
            this.SimulationState = SimulationState.Running;

            // notify
            SimulatorOutput.WriteLine("Simulation Started");

            // start thread
            Thread d = new Thread(Simulate);
            d.Priority = ThreadPriority.AboveNormal;
            d.IsBackground = true;
            d.Start();

            // state
            this.simulationMain.SimulationModeLabel.Text = "Simulation Running";
            this.simulationMain.SimulationModeLabel.Image = global::Simulator.Properties.Resources.Light_Bulb_On_16_n_p;
        }
        /// <summary>
        /// End simulation
        /// </summary>
        public void EndSimulation()
        {
            // stop sim
            this.SimulationState = SimulationState.Stopped;

            // notify
            SimulatorOutput.WriteLine("Simulation Stopped");

            // state
            this.simulationMain.SimulationModeLabel.Text = "Simulation Stopped";
            this.simulationMain.SimulationModeLabel.Image = global::Simulator.Properties.Resources.Light_Bulb_Off_16_n_p;
        }
 //UI thread
 void m_worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
 {
     if (e.Cancelled && !doPause)
     {
         DoStop();
     }
     else
     {
         MyLog.INFO.WriteLine("Paused.");
         State = SimulationState.PAUSED;
         Project.World.DoPause();
     }
 }
        private void DoStop()
        {
            MyLog.INFO.WriteLine("Cleaning up world...");
            Project.World.Cleanup();

            MyLog.INFO.WriteLine("Freeing memory...");
            Simulation.FreeMemory();
            PrintMemoryInfo();

            MyKernelFactory.Instance.RecoverContexts();

            MyLog.INFO.WriteLine("Clearing simulation...");
            Simulation.Clear();

            MyLog.INFO.WriteLine("Stopped after "+this.SimulationStep+" steps.");
            State = SimulationState.STOPPED;
        }
    public override void Start()
    {
        SimulationState.getInstance().stdout.Send("entro Start");
        base.Start();
        this._type = "grave";
        this.ss    = (GameObject.FindGameObjectWithTag("GameController").
            GetComponent(typeof(SimulationEngineComponentScript))
            as SimulationEngineComponentScript).engine as SimulationState;

        this.ss.addGrave(this);
        initializeContent();
    }
        /// <summary>
        /// Restarts the simulation phase.
        /// </summary>
        public void Restart()
        {
            // Reset the number of attempts, the various statistics, and lets the user provide input again.
              _attemptsLeft = _startingAttempts;
              _elapsedTime = 0f;
              _collectedTreasures = 0;
              _bounces = 0;
              _currentState = SimulationState.Active;

              // Restore all breakable platforms and treasures.
              foreach (Platform platform in _platforms) {
            platform.Reset();
              }
              foreach (Platform platform in _moveablePlatforms) {
            platform.Reset();
              }
              foreach (Treasure treasure in _treasures) {
            treasure.Reset();
              }

              // If the ball happens to be moving, stop it and put it back into
              // the launcher.
              if (!_launcher.Movable) {
            _ball.Stop(_world);
            _launcher.LoadBall(Ball);
              }
        }
 void SimulationStateChangedHandler(object sender, SimulationState newState)
 {
     CheckSimulationState();
 }
Exemple #26
0
        /// <summary>
        /// Executes one single step in simulation and returns hostState.
        /// </summary>
        /// <returns>Summery of the executed simulationStep</returns>
        public SimulatorHostState Step(ref SimulationState simulationState)
        {
            if (environment == null)
            {
                throw new InvalidOperationException(Resource.SimulationCoreHostEnvironmentNotInit);
            }

            // Reset of times
            stepWatch.Reset();
            foreach (TeamInfo team in configuration.Teams)
            {
                foreach (PlayerInfo spieler in team.Player)
                {
                    playerTimes[spieler.Guid] = 0;
                }
            }

            // Init Step-Thread
            exception           = null;
            lastSimulationState = simulationState;
            Thread stepThread = new Thread(step);

            stepWatch.Start();
            stepThread.Start();
            if (configuration.IgnoreTimeouts)
            {
                // Wait without any timeout
                stepThread.Join();
            }
            else
            {
                // Wait for thread with timeout
                if (!stepThread.Join(configuration.RoundTimeout))
                {
                    throw new TimeoutException(Resource.SimulationCoreHostRoundTimeout);
                }
            }
            stepWatch.Stop();

            // Bei Exceptions null zurück liefern, um Fehler zu signalisieren
            if (exception != null)
            {
                return(null);
            }

            // Add player-times
            lastHostState.ElapsedRoundTime = stepWatch.ElapsedTicks;
            for (int i = 0; i < configuration.Teams.Count; i++)
            {
                for (int j = 0; j < configuration.Teams[i].Player.Count; j++)
                {
                    Guid guid = configuration.Teams[i].Player[j].Guid;
                    if (!lastHostState.ElapsedPlayerTimes.ContainsKey(guid))
                    {
                        lastHostState.ElapsedPlayerTimes.Add(guid, playerTimes[guid]);
                    }
                }
            }

            // deliver host-state
            return(lastHostState);
        }
Exemple #27
0
        private void OnFinishedSimulation(GameStateManager gameStateManager, IGameTime gameTime)
        {
            this.simulationState = SimulationState.Idling;
            gameStateManager.CreateTimestamp(gameTime.TotalGameTime.TotalMilliseconds);

            EventArgs e = new EventArgs();
            if(FinishedSimulation != null)
            {
                FinishedSimulation(this, e);
            }
        }
 public StateEventArgs(SimulationState oldState, SimulationState newState)
 {
     OldState = oldState;
     NewState = newState;
 }
        // NOT UI thread
        void m_worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (ProgressChanged != null && m_lastProgressChangedStep != SimulationStep)
            {
                ProgressChanged(this, null);
            }

            if (e.Cancelled && !doPause)
            {
                DoStop();
            }
            else
            {
                // This means we're either pausing, or this was a single simulation step.
                MyLog.INFO.WriteLine("Paused.");
                State = SimulationState.PAUSED;
            }

            m_workedCompleted.Set();
        }
Exemple #30
0
        private static IEnumerable <bool> AddPatch(VesselState startingState)
        {
            if (null == Trajectories.AttachedVessel.patchedConicSolver)
            {
                Util.LogWarning("patchedConicsSolver is null, Skipping.");
                yield break;
            }

            CelestialBody body = startingState.ReferenceBody;

            Patch patch = new Patch
            {
                StartingState = startingState,
                IsAtmospheric = false,
                SpaceOrbit    = startingState.StockPatch ?? CreateOrbitFromState(startingState)
            };

            patch.EndTime = patch.StartingState.Time + patch.SpaceOrbit.period;

            // the flight plan does not always contain the first patches (before the first maneuver node),
            // so we populate it with the current orbit and associated encounters etc.
            List <Orbit> flightPlan = new List <Orbit>();

            for (Orbit orbit = Trajectories.AttachedVessel.orbit; orbit != null && orbit.activePatch; orbit = orbit.nextPatch)
            {
                if (Trajectories.AttachedVessel.patchedConicSolver.flightPlan.Contains(orbit))
                {
                    break;
                }
                flightPlan.Add(orbit);
            }

            foreach (Orbit orbit in Trajectories.AttachedVessel.patchedConicSolver.flightPlan)
            {
                flightPlan.Add(orbit);
            }


            Orbit nextPatch = null;

            if (startingState.StockPatch == null)
            {
                nextPatch = patch.SpaceOrbit.nextPatch;
            }
            else
            {
                int planIdx = flightPlan.IndexOf(startingState.StockPatch);
                if (planIdx >= 0 && planIdx < flightPlan.Count - 1)
                {
                    nextPatch = flightPlan[planIdx + 1];
                }
            }

            if (nextPatch != null)
            {
                patch.EndTime = nextPatch.StartUT;
            }

            double maxAtmosphereAltitude = RealMaxAtmosphereAltitude(body);

            if (!body.atmosphere)
            {
                maxAtmosphereAltitude = body.pqsController.mapMaxHeight;
            }

            double minAltitude = patch.SpaceOrbit.PeA;

            if (patch.SpaceOrbit.timeToPe < 0 || patch.EndTime < startingState.Time + patch.SpaceOrbit.timeToPe)
            {
                minAltitude = Math.Min(
                    patch.SpaceOrbit.getRelativePositionAtUT(patch.EndTime).magnitude,
                    patch.SpaceOrbit.getRelativePositionAtUT(patch.StartingState.Time + 1.0).magnitude
                    ) - body.Radius;
            }
            if (minAltitude < maxAtmosphereAltitude)
            {
                double entryTime;
                if (startingState.Position.magnitude <= body.Radius + maxAtmosphereAltitude)
                {
                    // whole orbit is inside the atmosphere
                    entryTime = startingState.Time;
                }
                else
                {
                    entryTime = FindOrbitBodyIntersection(
                        patch.SpaceOrbit,
                        startingState.Time, startingState.Time + patch.SpaceOrbit.timeToPe,
                        body.Radius + maxAtmosphereAltitude);
                }

                if (entryTime > startingState.Time + 0.1 || !body.atmosphere)
                {
                    if (body.atmosphere)
                    {
                        // add the space patch before atmospheric entry

                        patch.EndTime = entryTime;
                        patchesBackBuffer_.Add(patch);
                        AddPatch_outState = new VesselState
                        {
                            Position      = Util.SwapYZ(patch.SpaceOrbit.getRelativePositionAtUT(entryTime)),
                            ReferenceBody = body,
                            Time          = entryTime,
                            Velocity      = Util.SwapYZ(patch.SpaceOrbit.getOrbitalVelocityAtUT(entryTime))
                        };
                        yield break;
                    }
                    else
                    {
                        // the body has no atmosphere, so what we actually computed is the entry
                        // inside the "ground sphere" (defined by the maximal ground altitude)
                        // now we iterate until the inner ground sphere (minimal altitude), and
                        // check if we hit the ground along the way
                        double groundRangeExit = FindOrbitBodyIntersection(
                            patch.SpaceOrbit,
                            startingState.Time, startingState.Time + patch.SpaceOrbit.timeToPe,
                            body.Radius - maxAtmosphereAltitude);

                        if (groundRangeExit <= entryTime)
                        {
                            groundRangeExit = startingState.Time + patch.SpaceOrbit.timeToPe;
                        }

                        double iterationSize = (groundRangeExit - entryTime) / 100.0;
                        double t;
                        bool   groundImpact = false;
                        for (t = entryTime; t < groundRangeExit; t += iterationSize)
                        {
                            Vector3d pos            = patch.SpaceOrbit.getRelativePositionAtUT(t);
                            double   groundAltitude = GetGroundAltitude(body, CalculateRotatedPosition(body, Util.SwapYZ(pos), t))
                                                      + body.Radius;
                            if (pos.magnitude < groundAltitude)
                            {
                                t           -= iterationSize;
                                groundImpact = true;
                                break;
                            }
                        }

                        if (groundImpact)
                        {
                            patch.EndTime           = t;
                            patch.RawImpactPosition = Util.SwapYZ(patch.SpaceOrbit.getRelativePositionAtUT(t));
                            patch.ImpactPosition    = CalculateRotatedPosition(body, patch.RawImpactPosition.Value, t);
                            patch.ImpactVelocity    = Util.SwapYZ(patch.SpaceOrbit.getOrbitalVelocityAtUT(t));
                            patchesBackBuffer_.Add(patch);
                            AddPatch_outState = null;
                            yield break;
                        }
                        else
                        {
                            // no impact, just add the space orbit
                            patchesBackBuffer_.Add(patch);
                            if (nextPatch != null)
                            {
                                AddPatch_outState = new VesselState
                                {
                                    Position      = Util.SwapYZ(patch.SpaceOrbit.getRelativePositionAtUT(patch.EndTime)),
                                    Velocity      = Util.SwapYZ(patch.SpaceOrbit.getOrbitalVelocityAtUT(patch.EndTime)),
                                    ReferenceBody = nextPatch == null ? body : nextPatch.referenceBody,
                                    Time          = patch.EndTime,
                                    StockPatch    = nextPatch
                                };
                                yield break;
                            }
                            else
                            {
                                AddPatch_outState = null;
                                yield break;
                            }
                        }
                    }
                }
                else
                {
                    if (patch.StartingState.ReferenceBody != Trajectories.AttachedVessel.mainBody)
                    {
                        // currently, we can't handle predictions for another body, so we stop
                        AddPatch_outState = null;
                        yield break;
                    }

                    // simulate atmospheric flight (drag and lift), until impact or atmosphere exit
                    // (typically for an aerobraking maneuver) assuming a constant angle of attack
                    patch.IsAtmospheric            = true;
                    patch.StartingState.StockPatch = null;

                    // lower dt would be more accurate, but a trade-off has to be found between performances and accuracy
                    double dt = Settings.IntegrationStepSize;

                    // some shallow entries can result in very long flight. For performances reasons,
                    // we limit the prediction duration
                    int maxIterations = (int)(60.0 * 60.0 / dt);

                    int chunkSize = 128;

                    // time between two consecutive stored positions (more intermediate positions are computed for better accuracy),
                    // also used for ground collision checks
                    double trajectoryInterval = 10.0;

                    List <Point[]> buffer = new List <Point[]>
                    {
                        new Point[chunkSize]
                    };
                    int nextPosIdx = 0;

                    SimulationState state;
                    state.position = Util.SwapYZ(patch.SpaceOrbit.getRelativePositionAtUT(entryTime));
                    state.velocity = Util.SwapYZ(patch.SpaceOrbit.getOrbitalVelocityAtUT(entryTime));

                    // Initialize a patch with zero acceleration
                    Vector3d currentAccel = new Vector3d(0.0, 0.0, 0.0);


                    double   currentTime               = entryTime;
                    double   lastPositionStoredUT      = 0;
                    Vector3d lastPositionStored        = new Vector3d();
                    bool     hitGround                 = false;
                    int      iteration                 = 0;
                    int      incrementIterations       = 0;
                    int      minIterationsPerIncrement = maxIterations / Settings.MaxFramesPerPatch;

                    #region Acceleration Functor

                    // function that calculates the acceleration under current parameters
                    Func <Vector3d, Vector3d, Vector3d> accelerationFunc = (position, velocity) =>
                    {
                        Profiler.Start("accelerationFunc inside");

                        // gravity acceleration
                        double   R_      = position.magnitude;
                        Vector3d accel_g = position * (-body.gravParameter / (R_ * R_ * R_));

                        // aero force
                        Vector3d vel_air = velocity - body.getRFrmVel(body.position + position);

                        double aoa = DescentProfile.GetAngleOfAttack(body, position, vel_air) ?? 0d;

                        Profiler.Start("GetForces");
                        Vector3d force_aero = aerodynamicModel_.GetForces(body, position, vel_air, aoa);
                        Profiler.Stop("GetForces");

                        Vector3d accel = accel_g + force_aero / aerodynamicModel_.Mass;

                        Profiler.Stop("accelerationFunc inside");
                        return(accel);
                    };
                    #endregion


                    #region Integration Loop

                    while (true)
                    {
                        ++iteration;
                        ++incrementIterations;

                        if (incrementIterations > minIterationsPerIncrement && incrementTime_.ElapsedMilliseconds > MaxIncrementTime)
                        {
                            yield return(false);

                            incrementIterations = 0;
                        }


                        double R               = state.position.magnitude;
                        double altitude        = R - body.Radius;
                        double atmosphereCoeff = altitude / maxAtmosphereAltitude;
                        if (hitGround ||
                            atmosphereCoeff <= 0.0 || atmosphereCoeff >= 1.0 ||
                            iteration == maxIterations || currentTime > patch.EndTime)
                        {
                            //Util.PostSingleScreenMessage("atmo force", "Atmospheric accumulated force: " + accumulatedForces.ToString("0.00"));

                            if (hitGround || atmosphereCoeff <= 0.0)
                            {
                                patch.RawImpactPosition = state.position;
                                patch.ImpactPosition    = CalculateRotatedPosition(body, patch.RawImpactPosition.Value, currentTime);
                                patch.ImpactVelocity    = state.velocity;
                            }

                            patch.EndTime = Math.Min(currentTime, patch.EndTime);

                            int totalCount = (buffer.Count - 1) * chunkSize + nextPosIdx;
                            patch.AtmosphericTrajectory = new Point[totalCount];
                            int outIdx = 0;
                            foreach (Point[] chunk in buffer)
                            {
                                foreach (Point p in chunk)
                                {
                                    if (outIdx == totalCount)
                                    {
                                        break;
                                    }
                                    patch.AtmosphericTrajectory[outIdx++] = p;
                                }
                            }

                            if (iteration == maxIterations)
                            {
                                ScreenMessages.PostScreenMessage("WARNING: trajectory prediction stopped, too many iterations");
                                patchesBackBuffer_.Add(patch);
                                AddPatch_outState = null;
                                yield break;
                            }
                            else if (atmosphereCoeff <= 0.0 || hitGround)
                            {
                                patchesBackBuffer_.Add(patch);
                                AddPatch_outState = null;
                                yield break;
                            }
                            else
                            {
                                patchesBackBuffer_.Add(patch);
                                AddPatch_outState = new VesselState
                                {
                                    Position      = state.position,
                                    Velocity      = state.velocity,
                                    ReferenceBody = body,
                                    Time          = patch.EndTime
                                };
                                yield break;
                            }
                        }

                        Vector3d        lastAccel = currentAccel;
                        SimulationState lastState = state;

                        Profiler.Start("IntegrationStep");

                        // Verlet integration (more precise than using the velocity)
                        // state = VerletStep(state, accelerationFunc, dt);
                        state = RK4Step(state, accelerationFunc, dt, out currentAccel);

                        currentTime += dt;

                        // KSP presumably uses Euler integration for position updates. Since RK4 is actually more precise than that,
                        // we try to reintroduce an approximation of the error.

                        // The local truncation error for euler integration is:
                        // LTE = 1/2 * h^2 * y''(t)
                        // https://en.wikipedia.org/wiki/Euler_method#Local_truncation_error
                        //
                        // For us,
                        // h is the time step of the outer simulation (KSP), which is the physics time step
                        // y''(t) is the difference of the velocity/acceleration divided by the physics time step
                        state.position += 0.5 * TimeWarp.fixedDeltaTime * currentAccel * dt;
                        state.velocity += 0.5 * TimeWarp.fixedDeltaTime * (currentAccel - lastAccel);

                        Profiler.Stop("IntegrationStep");

                        // calculate gravity and aerodynamic force
                        Vector3d gravityAccel     = lastState.position * (-body.gravParameter / (R * R * R));
                        Vector3d aerodynamicForce = (currentAccel - gravityAccel) / aerodynamicModel_.Mass;

                        // acceleration in the vessel reference frame is acceleration - gravityAccel
                        maxAccelBackBuffer_ = Math.Max(
                            (float)(aerodynamicForce.magnitude / aerodynamicModel_.Mass),
                            maxAccelBackBuffer_);

                        #region Impact Calculation

                        Profiler.Start("AddPatch#impact");

                        double interval = altitude < 10000.0 ? trajectoryInterval * 0.1 : trajectoryInterval;
                        if (currentTime >= lastPositionStoredUT + interval)
                        {
                            double groundAltitude = GetGroundAltitude(body, CalculateRotatedPosition(body, state.position, currentTime));
                            if (lastPositionStoredUT > 0)
                            {
                                // check terrain collision, to detect impact on mountains etc.
                                Vector3 rayOrigin         = lastPositionStored;
                                Vector3 rayEnd            = state.position;
                                double  absGroundAltitude = groundAltitude + body.Radius;
                                if (absGroundAltitude > rayEnd.magnitude)
                                {
                                    hitGround = true;
                                    float coeff = Math.Max(0.01f, (float)((absGroundAltitude - rayOrigin.magnitude)
                                                                          / (rayEnd.magnitude - rayOrigin.magnitude)));
                                    state.position = rayEnd * coeff + rayOrigin * (1.0f - coeff);
                                    currentTime    = currentTime * coeff + lastPositionStoredUT * (1.0f - coeff);
                                }
                            }

                            lastPositionStoredUT = currentTime;
                            if (nextPosIdx == chunkSize)
                            {
                                buffer.Add(new Point[chunkSize]);
                                nextPosIdx = 0;
                            }
                            Vector3d nextPos = state.position;
                            if (Settings.BodyFixedMode)
                            {
                                nextPos = CalculateRotatedPosition(body, nextPos, currentTime);
                            }
                            buffer.Last()[nextPosIdx].aerodynamicForce = aerodynamicForce;
                            buffer.Last()[nextPosIdx].orbitalVelocity  = state.velocity;
                            buffer.Last()[nextPosIdx].groundAltitude   = (float)groundAltitude;
                            buffer.Last()[nextPosIdx].time             = currentTime;
                            buffer.Last()[nextPosIdx++].pos            = nextPos;
                            lastPositionStored = state.position;
                        }

                        Profiler.Stop("AddPatch#impact");

                        #endregion
                    }

                    #endregion
                }
            }
            else
            {
                // no atmospheric entry, just add the space orbit
                patchesBackBuffer_.Add(patch);
                if (nextPatch != null)
                {
                    AddPatch_outState = new VesselState
                    {
                        Position      = Util.SwapYZ(patch.SpaceOrbit.getRelativePositionAtUT(patch.EndTime)),
                        Velocity      = Util.SwapYZ(patch.SpaceOrbit.getOrbitalVelocityAtUT(patch.EndTime)),
                        ReferenceBody = nextPatch == null ? body : nextPatch.referenceBody,
                        Time          = patch.EndTime,
                        StockPatch    = nextPatch
                    };
                    yield break;
                }
                else
                {
                    AddPatch_outState = null;
                    yield break;
                }
            }
        }
Exemple #31
0
 /// <summary>
 /// Create new game scene based on given simulation state
 /// </summary>
 public GameScene(SceneStack sceneStack, InputManager inputManager, ResourceManager resourceManager, SimulationState state)
     : base(sceneStack, inputManager, resourceManager)
 {
     this.Initialize(state);
 }
Exemple #32
0
        public void OnFrame(Bot bot)
        {
            List <Unit> simulatedUnits = new List <Unit>();

            foreach (Task task in bot.TaskManager.Tasks)
            {
                task.AddCombatSimulationUnits(simulatedUnits);
            }

            foreach (Unit unit in bot.EnemyManager.LastSeen.Values)
            {
                if (unit.UnitType == UnitTypes.SIEGE_TANK_SIEGED || unit.UnitType == UnitTypes.WIDOW_MINE_BURROWED)
                {
                    continue;
                }
                if (bot.EnemyManager.LastSeen.ContainsKey(unit.Tag) && bot.Frame - bot.EnemyManager.LastSeenFrame[unit.Tag] > 112)
                {
                    continue;
                }
                if (UnitTypes.CombatUnitTypes.Contains(unit.UnitType))
                {
                    simulatedUnits.Add(unit);
                }
            }
            foreach (UnitLocation unit in bot.EnemyMineManager.Mines)
            {
                if (bot.EnemyManager.LastSeen.ContainsKey(unit.Tag))
                {
                    simulatedUnits.Add(bot.EnemyManager.LastSeen[unit.Tag]);
                }
            }
            foreach (UnitLocation unit in bot.EnemyTankManager.Tanks)
            {
                if (bot.EnemyManager.LastSeen.ContainsKey(unit.Tag))
                {
                    simulatedUnits.Add(bot.EnemyManager.LastSeen[unit.Tag]);
                }
            }

            List <List <Unit> > simulationGroups = GroupUnits(simulatedUnits);

            HashSet <uint> myUpgrades = new HashSet <uint>();

            if (bot.Observation.Observation.RawData.Player.UpgradeIds != null)
            {
                foreach (uint upgrade in bot.Observation.Observation.RawData.Player.UpgradeIds)
                {
                    myUpgrades.Add(upgrade);
                }
            }
            HashSet <uint> enemyUpgrades = new HashSet <uint>();

            bool logSimulation = bot.Frame % 22 == 0 && simulationGroups.Count > 0 && Debug;

            if (ShowStats)
            {
                bot.DrawText("Simulations: " + simulationGroups.Count);
            }
            if (logSimulation)
            {
                FileUtil.Debug("Simulations: " + simulationGroups.Count);
            }


            bool printState = false;

            if (Bot.Debug && bot.Observation.Chat != null && bot.Observation.Chat.Count > 0)
            {
                foreach (ChatReceived message in bot.Observation.Chat)
                {
                    if (message.Message == "s")
                    {
                        printState = true;
                        break;
                    }
                }
            }

            MyStartResources    = 0;
            MyFinalResources    = 0;
            EnemyStartResources = 0;
            EnemyFinalResources = 0;
            int i = 0;

            foreach (List <Unit> simulationGroup in simulationGroups)
            {
                SimulationState state = GetState(bot, simulationGroup, myUpgrades, enemyUpgrades, false);
                if (printState)
                {
                    state.SafeToFile("SimulationState-" + bot.Frame + "-" + i + ".txt");
                }
                float myResources    = GetResources(state, true);
                float enemyResources = GetResources(state, false);
                if (printState)
                {
                    TestCombatSim.TestCombat(state, SimulationLength);
                }
                else
                {
                    state.Simulate(SimulationLength);
                }

                float myNewResources    = GetResources(state, true);
                float enemyNewResources = GetResources(state, false);
                if (ShowStats)
                {
                    bot.DrawText("SimulationResult me: " + myResources + " -> " + myNewResources + " his: " + enemyResources + " -> " + enemyNewResources);
                }
                if (logSimulation)
                {
                    FileUtil.Debug("SimulationResult me: " + myResources + " -> " + myNewResources + " his: " + enemyResources + " -> " + enemyNewResources);
                }

                if (myResources > 0 &&
                    enemyResources > 0)
                {
                    MyStartResources    += myResources;
                    MyFinalResources    += myNewResources;
                    EnemyStartResources += enemyResources;
                    EnemyFinalResources += enemyNewResources;
                }

                MakeDecision(simulationGroup, state, myResources, myNewResources, enemyResources, enemyNewResources, myUpgrades, enemyUpgrades);
                i++;
            }

            if (logSimulation)
            {
                FileUtil.Debug("");
            }
        }
 public void MakeMove(SimulationState state)
 {
     _children[state.PlayerPosition[state.ActivePlayer]].MakeMove(state);
 }
Exemple #34
0
        private void MakeDecision(List <Unit> simulationGroup, SimulationState state, float myResources, float myNewResources, float enemyResources, float enemyNewResources, HashSet <uint> myUpgrades, HashSet <uint> enemyUpgrades)
        {
            if (myResources == 0)
            {
                return;
            }
            if (enemyResources == 0)
            {
                ApplyDecision(simulationGroup, CombatSimulationDecision.None);
                return;
            }

            int prevProceed  = 0;
            int prevFallBack = 0;

            foreach (Unit unit in simulationGroup)
            {
                if (Bot.Main.UnitManager.Agents.ContainsKey(unit.Tag) && Bot.Main.Frame - Bot.Main.UnitManager.Agents[unit.Tag].CombatSimulationDecisionFrame < 10)
                {
                    if (Bot.Main.UnitManager.Agents[unit.Tag].CombatSimulationDecision == CombatSimulationDecision.Proceed)
                    {
                        prevProceed++;
                    }
                    else if (Bot.Main.UnitManager.Agents[unit.Tag].CombatSimulationDecision == CombatSimulationDecision.FallBack)
                    {
                        prevFallBack++;
                    }
                }
            }

            float partProceed;

            if (prevFallBack + prevProceed == 0)
            {
                partProceed = 0;
            }
            else
            {
                partProceed = (float)prevProceed / (prevProceed + prevFallBack);
            }
            if (ShowStats)
            {
                Bot.Main.DrawText("Proceed: " + partProceed);
            }
            if (enemyResources - enemyNewResources >= (myResources - myNewResources) * (1.1 - 0.3 * partProceed))
            {
                ApplyDecision(simulationGroup, CombatSimulationDecision.Proceed);
            }
            else
            {
                SimulationState fleeState = GetState(Bot.Main, simulationGroup, myUpgrades, enemyUpgrades, true);
                state.Simulate(100);
                float myFleeResources = GetResources(fleeState, true);
                if (enemyResources - enemyNewResources >= (myFleeResources - myNewResources) * (1.1 - 0.3 * partProceed))
                {
                    ApplyDecision(simulationGroup, CombatSimulationDecision.Proceed);
                }
                else
                {
                    ApplyDecision(simulationGroup, CombatSimulationDecision.FallBack);
                }
            }
        }
Exemple #35
0
 /// <summary>
 /// Call for user-interface-updates.
 /// </summary>
 /// <param name="state">current state</param>
 public void UpdateUI(SimulationState state)
 {
     renderForm.SimulationState = state;
 }
        public GameState GetCurrentState()
        {
            this.SimState = SimulationState.PAUSED;
            ulong[] loopsDone = new ulong[regionManagers.Length];
            List <EntityOnMap <HealthyEntity> >[] populationHealthy = new List <EntityOnMap <HealthyEntity> > [regionManagers.Length];
            List <EntityOnMap <SickEntity> >[]    populationSick    = new List <EntityOnMap <SickEntity> > [regionManagers.Length];
            pipelines.ForEach(x => x.updateTimeScale(timeScale));
            for (int i = 0; i < regionManagers.Length; ++i)
            {
                regionManagers[i].SimState = SimulationState.PAUSED;
            }

            // Asynchronously extract the current state from each running task
            Task[] waitingData = new Task[regionManagers.Length];
            for (int i = 0; i < regionManagers.Length; ++i)
            {
                int procIndex = i;
                waitingData[procIndex] = new Task(() =>
                {
                    var item = regionManagers[procIndex].getEntities();
                    populationSick[procIndex]    = item.Item1;
                    populationHealthy[procIndex] = item.Item2;
                    loopsDone[procIndex]         = item.Item3;
                });
                waitingData[procIndex].Start();
            }
            Task.WaitAll(waitingData);

            outOfBoundsLock.WaitOne();
            var populationHealthyList = populationHealthy
                                        .Aggregate(
                new List <EntityOnMap <HealthyEntity> >(),
                (current, next) =>
            {
                current.AddRange(next);
                return(current);
            }
                )
                                        .Concat(outOfBoundsPopulationHealthy)
                                        .ToList();
            var populationSickList = populationSick
                                     .Aggregate(
                new List <EntityOnMap <SickEntity> >(),
                (current, next) =>
            {
                current.AddRange(next);
                return(current);
            }
                )
                                     .Concat(outOfBoundsPopulationSick)
                                     .ToList();

            outOfBoundsLock.ReleaseMutex();

            this.SimState = SimulationState.RUNNING;
            for (int i = 0; i < regionManagers.Length; ++i)
            {
                regionManagers[i].SimState = SimulationState.RUNNING;
            }

            var sickPeople    = (ushort)populationSickList.Count();
            var healthyPeople = (ushort)populationHealthyList.Count();

            return(new GameState
            {
                loopsDone = loopsDone,
                items = (populationSickList, populationHealthyList),
                sickPeople = sickPeople,
                healthyPeople = healthyPeople,
            });
        /// <summary>
        /// Completes the level.
        /// </summary>
        private void Complete()
        {
            // Stop the ball and don't accept any more input for the simulation.
              _currentState = SimulationState.Completed;
              _ball.Stop(_world);

              // Do anything that needs to be done when the level is completed.
              if (OnCompletion != null) {
            OnCompletion(CreateScoreData());
              }
        }
        public override void act(SimulationState state)
        {
            MovementVetorX = 0;
            MovementVetorY = 0;

            if (State == VehicleState.NoIntersection)
            {
                spawnFromEdgeWithNoIntersectionToNewEdge(state.intersections.SelectMany(ip => ip.intersectionPipes).ToList(), state.edgePipes);
                rotateTexture();
            }
            else if (NextEdge != null && State == VehicleState.OnIntersection)
            {
                moveToNewConnectors();
                rotateTexture();
                return;
            }

            var restEdges = state.edgePipes
                            .Where(e => e.ID == CurrentEdge.PipeID)
                            .FirstOrDefault().Edges
                            .Where(e => e.ID != CurrentEdge.ID);

            foreach (var vehicle in state.vehicles)
            {
                if (State == VehicleState.InIntersectionQueue || State == VehicleState.NoIntersection || !restEdges.Where(re => re.PipeID == vehicle.CurrentEdge.PipeID).Any())
                {
                    continue;
                }

                setCloserPositionToOutrunNewPosition();

                bool isOnIntersection = isVehicleOnIntersection();

                CurrentConnectorY = CurrentEdge.To.Y;
                CurrentConnectorX = CurrentEdge.To.X;

                if (isOnIntersection)
                {
                    OldVelocity = Velocity;
                    Velocity    = 0;

                    bool noIntersection = !state.intersections
                                          .Any(ip => ip.intersectionPipes
                                               .Any(p => p.EdgeRoad.ID == CurrentEdge.ID && p.IntersectionType == IntersectionPipeType.In));

                    if (noIntersection)
                    {
                        State = VehicleState.NoIntersection;
                    }
                    else
                    {
                        CurrentIntersectionID = state.intersections.SingleOrDefault(ip => ip.intersectionPipes.Any(p => p.EdgeRoad.ID == CurrentEdge.ID && p.IntersectionType == IntersectionPipeType.In)).ID;
                        State = VehicleState.InIntersectionQueue;
                    }

                    continue;
                }

                if (vehicle.ID == ID)
                {
                    continue;
                }

                if (vehicle.CurrentEdge.ID == CurrentEdge.ID && isVehicleInFront(vehicle) && isVehicleNCarWidthInFrontAtLeast(2, vehicle))
                {
                    Velocity = vehicle.Velocity;

                    if (restEdges.Count() == 0)
                    {
                        continue;
                    }

                    EdgeRoad closestEdge = null;
                    setClosestEdgeRoad(ref closestEdge, restEdges);

                    if (isNextLaneFreeForOutrun(closestEdge, state.vehicles))
                    {
                        setNewPositionForOutrun(ref closestEdge);
                        CurrentEdge = closestEdge;
                        Velocity   += 1;
                    }
                }
            }

            prepareMovementVector();

            Position.X += MovementVetorX;
            Position.Y += MovementVetorY;
        }
Exemple #39
0
 public void UpdateUI(SimulationState state)
 {
     window.Update(state);
 }
Exemple #40
0
 public virtual void OnFrame(SimulationState state, CombatUnit unit)
 {
 }
 /// <summary>
 /// Load settings from SimulationState.
 /// </summary>
 /// <param name="state">TState to load from.</param>
 public void LoadSettings(SimulationState state)
 {
     Paused           = state.Paused;
     BackgroundColour = state.BackgroundColour;
     Projectile.GravitationalAcceleration = state.Gravity;
 }
        /// <summary>
        /// Setzt eine pausierte Simulation wieder fort.
        /// </summary>
        public void ResumeSimulation()
        {
            // Nur reagieren, falls der Pause-Mode aktiv ist
            if (state != SimulationState.Paused)
                return;

            // state melden und setzen
            state = SimulationState.Running;
            if (OnSimulationState != null)
                OnSimulationChanged(this, state, rate);
        }
Exemple #43
0
        /// <summary>
        /// Calculates the next step and deliver through parameter.
        /// </summary>
        /// <param name="simulationState">empty <see cref="SimulationState"/></param>
        public void Step(ref SimulationState simulationState)
        {
            lastSimulationState = simulationState;
            switch (state)
            {
            case SimulatorState.Ready:
            case SimulatorState.Simulating:

                // Create proxy
                if (proxy == null)
                {
                    proxy = new SimulatorProxy();
                    proxy.Init(configuration);
                    currentLoop++;
                    currentRound = 0;
                    loopTime     = 0;
                    for (int i = 0; i < configuration.Teams.Count; i++)
                    {
                        for (int j = 0; j < configuration.Teams[i].Player.Count; j++)
                        {
                            totalPlayerTime[configuration.Teams[i].Player[j]] = 0;
                        }
                    }
                    state = SimulatorState.Simulating;
                }

                // Calculate step
                currentRound++;
                lastHostState   = proxy.Step(ref lastSimulationState);
                simulationState = lastSimulationState;

                // Calculate times
                roundTime  = lastHostState.ElapsedRoundTime;
                loopTime  += lastHostState.ElapsedRoundTime;
                totalTime += lastHostState.ElapsedRoundTime;
                for (int i = 0; i < configuration.Teams.Count; i++)
                {
                    for (int j = 0; j < configuration.Teams[i].Player.Count; j++)
                    {
                        // TODO: Fix Dictionary-Problem with time-list
                        PlayerInfo info = configuration.Teams[i].Player[j];
                        //totalPlayerTime[info] += lastHostState.ElapsedPlayerTimes[info];
                    }
                }

                // After one loop, unload appdomain
                if (currentRound >= configuration.RoundCount)
                {
                    proxy.Unload();
                    proxy = null;
                    GC.Collect();
                }

                // Mark Simulator as finished after all loops
                if (currentRound >= configuration.RoundCount &&
                    currentLoop >= configuration.LoopCount)
                {
                    state = SimulatorState.Finished;
                }
                break;

            case SimulatorState.Finished:

                // Throw exception, if step was called on a finished simulator
                throw new InvalidOperationException(
                          Resource.SimulationCoreSimulatorRestartFailed);
            }
            lastSimulationState = null;
        }
        /// <summary>
        /// Stoppt eine laufende Anwendung.
        /// </summary>
        public void StopSimulation()
        {
            // Nicht reagieren, falls ohnehin eine Simulation läuft.
            if (state == SimulationState.Stopped)
                return;

            // State ändern und kurz auf den Thread warten.
            state = SimulationState.Stopped;
            if (thread.Join(2000))
                thread.Abort();

            if (OnSimulationChanged != null)
                OnSimulationChanged(this, state, rate);
        }
Exemple #45
0
        public double[] Simulate(double t, double[] values)
        {
            SimulationState st = new SimulationState
            {
                VX       = values[3],
                VY       = values[4],
                VZ       = values[5],
                Phi      = values[6],
                Theta    = values[7],
                PhiDot   = values[8],
                ThetaDot = values[9],
                GammaDot = values[10],
                Gamma    = values[11],
            };

            //double CLo, CLa, CDo, CDa, CMo, CMa;
            //double CL_data, CD_data, CM_data;

            double[] CRr_rad = new[] { -0.0873, -0.0698, -0.0524, -0.0349, -0.0175, 0.0000, 0.0175, 0.0349, 0.0524, 0.0698, 0.0873, 0.1047, 0.1222, 0.1396, 0.1571, 0.1745, 0.1920, 0.2094, 0.2269, 0.2443, 0.2618, 0.5236 };

            double[] CRr_AdvR = new[] { 2, 1.04, 0.69, 0.35, 0.17, 0 };

            double[,] CRr_data = new [, ]
            {
                { -0.0172, -0.0192, -0.018, -0.0192, -0.018, -0.0172, -0.0172, -0.0168, -0.0188, -0.0164, -0.0136, -0.01, -0.0104, -0.0108, -0.0084, -0.008, -0.008, -0.006, -0.0048, -0.0064, -0.008, -0.003 },
                { -0.0112, -0.0132, -0.012, -0.0132, -0.012, -0.0112, -0.0112, -0.0108, -0.0128, -0.0104, -0.0096, -0.0068, -0.0072, -0.0076, -0.0052, -0.0048, -0.0048, -0.0028, -0.0032, -0.0048, -0.0064, -0.003 },
                { -0.0056, -0.0064, -0.0064, -0.0068, -0.0064, -0.0064, -0.0052, -0.0064, -0.0028, -0.0028, -0.004, -0.002, -0.004, -0.002, -0.0016, 0, 0, 0, 0, -0.002, -0.0048, -0.003 },
                { -0.0012, -0.0016, -0.0004, -0.0028, -0.0016, -0.0016, -0.0004, 0.0004, 0.0004, 0.0008, 0.0004, 0.0008, 0.0012, 0.0008, 0.002, 0.0028, 0.0032, 0.0024, 0.0028, 0.0004, -0.0012, -0.003 },
                { -0.0012, -0.0012, -0.0016, -0.0016, -0.0012, -0.0004, 0.0004, 0.0008, 0.0008, 0.0016, 0.0004, 0.002, 0.0004, 0.0016, 0.002, 0.002, 0.002, 0.0012, 0.0012, 0, -0.0012, -0.003 },
                { -0.0012, -0.0012, -0.0004, -0.0008, -0.0008, -0.0008, 0.0004, 0.0004, 0.0004, 0.0008, 0.0004, 0.0008, -0.0004, 0, 0, 0.0004, 0, 0, 0.0004, -0.002, -0.0012, -0.003 }
            };

            const double CMq = -0.005;
            const double CRp = -0.0055;
            const double CNr = 0.0000071;

            double diameter = 2 * Math.Sqrt(Area / Math.PI);

            //  Rotation matrix: http://s-mat-pcs.oulu.fi/~mpa/matreng/eem1_3-7.htm
            //                           y
            //  ------------------> x                        ^
            //  |\                       |
            //  | \                      |
            //  |  \                     |
            //  |   \ theta = pitch      |   gamma = yaw
            //  |                        |
            //  v                        --------------------> x
            //  z
            //  z
            //  ^
            //  |
            //  |
            //  |
            //  |  phi = roll
            //  |
            //  ------------------> y
            //
            // 3D homogenous transformation matrix
            //
            // g = gamma = yaw
            // t = theta = pitch
            // p = phi   = roll
            //
            // http://en.wikipedia.org/wiki/Rotation_matrix
            // http://www.gregslabaugh.name/publications/euler.pdf
            //       --                                                                                   --
            //      | cos(g)*cos(t), cos(g)*sin(t)*sin(p)-sin(g)*cos(p), cos(g)*sin(t)*cos(p)+sin(g)*sin(p) |
            //      |                                                                                       |
            //  T = | sin(g)*cos(t), sin(g)*sin(t)*sin(p)-cos(g)*cos(p), sin(g)*sin(t)*cos(p)+cos(g)*sin(p) |
            //      |                                                                                       |
            //      |    -sin(t)   ,          cos(t)*sin(p)            ,          cos(t)*cos(p)             |
            //       --                                                                                   --
            //
            // With g = yaw = 0 and sin(t) = -sin(t) since z is positive downward
            //
            //       --                                      --
            //      | cos(t)  , sin(t)*sin(p)  , sin(t)*cos(p) |
            //      |                                          |
            //  T = |   0     ,     cos(p)     ,     sin(p)    |
            //      |                                          |
            //      | -sin(t) , cos(t)*sin(p)  , cos(t)*cos(p) |
            //       --                                      --



            Matrix <double> transformation = new SparseMatrix(new [, ]
            {
                { st.CosTheta, st.SinTheta * st.SinPhi, -st.SinTheta * st.CosPhi },
                { 0, st.CosPhi, st.SinPhi },
                { st.SinTheta, -st.CosTheta * st.SinPhi, st.CosTheta * st.CosPhi }
            });

            // Eigenvector & eigenvalue
            //       --
            //      | x1
            //  X = | x2
            //      | x3
            //       --
            //
            //       --
            //      | a11, a12, a13
            //  A = | a21, a22, a23
            //      | a31, a32, a33
            //       --
            //
            //
            // Usually, the multiplication of a vector x by a square matrix A changes both the magnitude and the direction
            // of the vector upon which it acts; but in the special case where it changes only the scale (magnitude) of the
            // vector and leaves the direction unchanged, or switches the vector to the opposite direction, then that vector
            // is called an eigenvector of that matrix (the term "eigenvector" is meaningless except in relation to some
            // particular matrix). When multiplied by a matrix, each eigenvector of that matrix changes its magnitude by a
            // factor, called the eigenvalue corresponding to that eigenvector.
            //
            //
            // See local frame vs global frame:
            //

            Evd evd = new UserEvd(transformation);
            //Matrix<double> eigenVectors = evd.EigenVectors();
            Vector <Complex> temp        = evd.EigenValues();
            Vector <double>  eigenValues = new SparseVector(3);

            eigenValues[0] = temp[0].Real;
            eigenValues[1] = temp[1].Real;
            eigenValues[1] = temp[1].Real;

            //eigenValues.Norm

            //
            // If you have Theta and Phi = 0 you have a transformation matrix like this:
            //
            // | 1, 0, 0 |
            // | 0, 1, 0 |
            // | 0, 0, 1 |
            //
            // So each row represents the rotated X, Y or Z axis expressed as N-Frame coordinates. In this case,
            // there is no rotation so you have the axis (1,0,0), (0,1,0), (0,0,1).
            // For example, the first row represents the X Axis after the rotation. Since the rotation is 0,
            // the X axis is a vector (1,0,0) in the N-Frame.
            //
            //
            //
            //
            //SparseVector c1 = new SparseVector(transformation.Row(0));
            //SparseVector c2 = new SparseVector(transformation.Row(1));
            SparseVector c3 = new SparseVector(transformation.Row(2));

            SparseVector velocity          = new SparseVector(new [] { st.VX, st.VY, st.VZ });
            double       velocityMagnitude = velocity.Norm(2);

            double velocityC3 = velocity.DotProduct(c3);

            Vector <double> vp          = velocity.Subtract(c3.Multiply(velocityC3));
            double          vpMagnitude = vp.Norm(2);


            double alpha = Math.Atan(velocityC3 / vp.Norm(2));
            double adp   = Area * Rho * velocityMagnitude * velocityMagnitude / 2;

            Vector <double> unitVelocity = velocity.Divide(velocityMagnitude);
            Vector <double> unitVp       = vp.Divide(vpMagnitude);

            //c3.
            Vector <double> unitLat = ConvertVector(Vector3D.CrossProduct(ConvertVector(c3), ConvertVector(unitVp)));

            Matrix <double> omegaD_N_inC = new SparseMatrix(new [, ] {
                { st.PhiDot *st.CosTheta, st.ThetaDot, st.PhiDot *st.SinTheta + st.GammaDot }
            });                                                                                                     // expressed in c1,c2,c3
            Vector <double> omegaD_N_inN = transformation.Transpose().Multiply(omegaD_N_inC.Transpose()).Column(0); // expressed in c1,c2,c3
            double          omegaVp      = omegaD_N_inN.DotProduct(unitVp);
            double          omegaLat     = omegaD_N_inN.DotProduct(unitLat);
            double          omegaSpin    = omegaD_N_inN.DotProduct(c3);

            double aDvR = diameter * omegaSpin / 2 / vpMagnitude;

            LinearSplineInterpolation interpolation = new LinearSplineInterpolation(m_xCL, m_yCL);
            double CL = interpolation.Interpolate(alpha);

            interpolation = new LinearSplineInterpolation(m_xCD, m_yCD);
            double CD = interpolation.Interpolate(alpha);

            interpolation = new LinearSplineInterpolation(m_xCM, m_yCM);
            double CM = interpolation.Interpolate(alpha);


            alglib.spline2d.spline2dinterpolant interpolant = new alglib.spline2d.spline2dinterpolant();
            alglib.spline2d.spline2dbuildbilinear(CRr_rad, CRr_AdvR, CRr_data, 6, 22, interpolant);
            double CRr = alglib.spline2d.spline2dcalc(interpolant, alpha, aDvR);

            Vector <double> mvp = unitVp.Multiply(adp * diameter * (CRr * diameter * omegaSpin / 2 / velocityMagnitude + CRp * omegaVp)); // Roll moment, expressed in N

            double lift = CL * adp;
            double drag = CD * adp;

            Vector <double> unitLift = -ConvertVector(Vector3D.CrossProduct(ConvertVector(unitVelocity), ConvertVector(unitLat)));
            Vector <double> unitDrag = -unitVelocity;

            Vector <double> forceAerodynamic = unitLift.Multiply(lift).Add(unitDrag.Multiply(drag));
            Vector <double> gravityForceN    = new SparseVector(new[] { 0, 0, m * g });

            Vector <double> force = forceAerodynamic.Add(gravityForceN);

            Vector <double> mLat    = unitLat.Multiply(adp * diameter * (CM + CMq * omegaLat));
            Vector <double> mSpin   = new SparseVector(new [] { 0, 0, CNr * omegaSpin }); // TODO: Check if missing element
            Vector <double> mvpInC  = transformation.Multiply(mvp);
            Vector <double> mLatInC = transformation.Multiply(mLat);

            Vector <double> moment = mvpInC.Add(mLatInC).Add(mSpin);

            Vector <double> acceleration = force.Divide(m);


            double[] result = new double[12];

            result[0] = velocity[0];
            result[1] = velocity[1];
            result[2] = velocity[2];
            result[3] = acceleration[0];
            result[4] = acceleration[1];
            result[5] = acceleration[2];
            result[6] = -st.PhiDot;
            result[7] = st.ThetaDot;
            result[8] = (moment[0] + Id * st.ThetaDot * st.PhiDot * st.SinTheta -
                         Ia * st.ThetaDot * (st.PhiDot * st.SinTheta + st.GammaDot) + Id * st.ThetaDot * st.PhiDot * st.SinTheta) / Id /
                        st.CosTheta;
            result[9]  = (moment[1] + Ia * st.PhiDot * st.CosTheta * (st.PhiDot * st.SinTheta + st.GammaDot) - Id * st.PhiDot * st.PhiDot * st.CosTheta * st.SinTheta) / Id;
            result[10] = (moment[2] - Ia * (result[9] * st.SinTheta + st.ThetaDot * st.PhiDot * st.CosTheta)) / Ia;
            result[11] = result[10];
            return(result);
        }
Exemple #46
0
        private void OnStartingSimulation()
        {
            this.simulationState = SimulationState.Simulating;

            EventArgs e = new EventArgs();

            if(StartingSimulation != null)
            {
                StartingSimulation(this, e);
            }
        }
Exemple #47
0
 /// <summary>
 /// Останавливает симуляцию.
 /// </summary>
 public void Stop()
 {
     State = SimulationState.Stopped;
     ResetLevelTo(_initialLevel);
 }
Exemple #48
0
 private void PauseSimulation(object sender, EventArgs e)
 {
     _simulationState = SimulationState.Paused;
     _computing       = false;
     EnableButtons();
 }
Exemple #49
0
 public void CreatedState(ref SimulationState state)
 {
 }
        //UI thread
        /// <summary>
        /// Starts simulation
        /// </summary>
        /// <param name="oneStepOnly">Only one step of simulation is performed when true</param>
        public void StartSimulation(bool oneStepOnly)
        {
            if (State == SimulationState.STOPPED)
            {
                MyLog.INFO.WriteLine("Scheduling...");
                Simulation.Schedule(Project);

                MyLog.INFO.WriteLine("Initializing tasks...");
                Simulation.Init();

                MyLog.INFO.WriteLine("Allocating memory...");
                Simulation.AllocateMemory();
                PrintMemoryInfo();

                MyLog.INFO.WriteLine("Starting simulation...");
            }
            else
            {
                MyLog.INFO.WriteLine("Resuming simulation...");
            }

            State = oneStepOnly ? SimulationState.RUNNING_STEP : SimulationState.RUNNING;

            MyKernelFactory.Instance.SetCurrent(MyKernelFactory.Instance.DevCount - 1);

            m_worker.RunWorkerAsync();
        }
 /// <summary>
 /// Pausiert eine laufende Anwendung oder tut nichts, falls gestoppt.
 /// </summary>
 public void PauseSimulation()
 {
     // Nicht reagieren, falls die Simulation nicht läuft.
     if (state == SimulationState.Running)
     {
         state = SimulationState.Paused;
         if (OnSimulationState != null)
             OnSimulationChanged(this, state, rate);
     }
 }
Exemple #52
0
        /// <summary>
        /// Constructor for the PreferencesEditor.
        /// </summary>
        /// <param name="preferences">The preferences for the Editor.</param>
        /// <param name="showSimulationProperties">Should the form show properties about the simulation.</param>
        /// <param name="simulationState">The state of the simulation.</param>
        public PreferencesEditor(EditorPreferences preferences, bool showSimulationProperties, SimulationState simulationState = default)
        {
            InitializeComponent();

            Preferences = preferences;

            propertiesPanel.Visible = showSimulationProperties;

            if (showSimulationProperties)
            {
                propertyGrid.SelectedObject = simulationState;
            }
        }
        /// <summary>
        /// Startet die Simulation, sofern alle Daten vollständig sind.
        /// </summary>
        /// <param name="result">Eventuelle Fehlermeldung</param>
        /// <returns>Erfolgsmeldung</returns>
        public bool StartSimulation()
        {
            // Im Falle des Pause-Modes wird einfach fortgesetzt
            if (state == SimulationState.Paused)
            {
                ResumeSimulation();
                return true;
            }

            // Simulation läuft bereits
            if (state == SimulationState.Running)
            {
                return true;
            }

            // Prüfen, ob ein Level vorhanden ist
            if (level == null)
            {
                throw new Exception("There is not Level set");
            }

            // Player zählen
            int count = 0;
            for (int i = 0; i < AntMe.Level.MAX_SLOTS; i++)
            {
                if (players[i] != null)
                {
                    // Prüfen, ob player bereit ist
                    if (!slots[i].ReadyState)
                    {
                        throw new Exception("Player " + (i + 1) + " is not ready");
                    }

                    // Prüfen, ob Faction Filter aktiv ist
                    var filter = level.FactionFilter.Where(f => f.SlotIndex == i);
                    if (filter.Count() > 0)
                    {
                        if (filter.Where(f => f.Type.TypeName == players[i].FactionType).Count() == 0)
                        {
                            throw new Exception("Player " + i + " does not match the Faction filter");
                        }
                    }

                    count++;
                }
            }

            // prüfen, ob genügend Player vorhanden sind
            if (count < level.LevelDescription.MinPlayerCount)
            {
                throw new Exception("Not enougth player");
            }

            if (count > level.LevelDescription.MaxPlayerCount)
            {
                throw new Exception("Too many player");
            }

            // State ändern
            state = SimulationState.Running;
            if (OnSimulationChanged != null)
                OnSimulationChanged(this, state, rate);

            // Thread erzeugen
            thread = new Thread(SimulationLoop);
            thread.IsBackground = true;
            thread.Priority = ThreadPriority.Lowest;
            thread.Start();

            return true;
        }
 public void OnSimulationStateChanged(SimulationState simulationState)
 {
     SetInactiveMsgState(simulationState == SimulationState.Disabled);
 }
        private void SimulationLoop()
        {
            try
            {
                InitSimulation(0, level, players, slots);
            }
            catch (Exception ex)
            {
                // Event werfen
                if (OnError != null)
                    OnError(this, ex.Message);

                // Simulation stoppen
                StopSimulation();
            }

            while (state != SimulationState.Stopped)
            {
                // Pausemodus skippen
                if (state == SimulationState.Paused || rate <= 0)
                {
                    Thread.Sleep(1);
                    continue;
                }

                // Messung starten
                watch.Restart();

                // State erzeugen
                currentState = UpdateSimulation();

                // Das EventLog füttern
                log.Update(currentState);

                if (currentState.Mode > LevelMode.Running)
                {
                    state = SimulationState.Stopped;
                    continue;
                }

                if (OnSimulationState != null)
                    OnSimulationState(this, currentState);

                // Wartezeit zwischen Frames
                while (state != SimulationState.Stopped &&
                    watch.ElapsedMilliseconds < (int)(1000 / rate))
                {
                    Thread.Sleep(1);
                }
            }

            FinalizeSimulation();
        }
Exemple #56
0
 private void CurrentClient_OnSimulationChanged(ISimulationClient client, SimulationState simulationState, byte frames)
 {
     framesToolButton.Text = string.Format("{0} fps", frames);
     // throw new NotImplementedException();
 }
        private void DoStop()
        {
            // TODO(HonzaS): This is hacky, it needs to be redone properly.
            // 1) Stop the simulation if needed.
            // 2) Set the state to STOPPED => notifies the nodes to clean up.
            // 3) Clear everything else if we're quitting.
            var stopping = false;
            if (State != SimulationState.STOPPED)
            {
                stopping = true;
                MyLog.INFO.WriteLine("Cleaning up world...");
                Project.World.Cleanup();

                MyLog.INFO.WriteLine("Freeing memory...");
                Simulation.FreeMemory();
                PrintMemoryInfo();

                MyKernelFactory.Instance.RecoverContexts();

                // This needs to be set before Clear is called so that nodes can be notified about the state change.
                State = SimulationState.STOPPED;
            }

            if (m_closeCallback != null)
                Simulation.Finish();

            if (stopping)
            {
                MyLog.INFO.WriteLine("Clearing simulation...");
                // This will destroy the collection that holds the nodes, so it has to be the last thing.
                Simulation.Clear();
                MyLog.INFO.WriteLine("Stopped after "+this.SimulationStep+" steps.");

                if (SimulationStopped != null)
                {
                    var args = new SimulationStoppedEventArgs
                    {
                        Exception = m_simulationStoppedException,
                        StepCount = SimulationStep
                    };
                    SimulationStopped(this, args);
                }
            }

            // Cleanup and invoke the callback action.
            if (m_closeCallback != null)
                m_closeCallback();
        }
 public abstract void MakeMove(SimulationState state);
 public StateEventArgs(SimulationState oldState, SimulationState newState)
 {
     OldState = oldState;
     NewState = newState;
 }
Exemple #60
0
 /// <summary>
 /// Create new game scene based on given simulation state
 /// </summary>
 public GameScene(Scene parent, SimulationState state)
     : base(parent)
 {
     this.Initialize(state);
 }