コード例 #1
0
    static public void Main()
    {
        var agent     = new Agent();
        var server    = new Server();
        var processor = new Proccessor();

        agent.Proccessor = processor;
        agent.Server     = server;
        processor.Server = server;
        agent.SendPacket();
    }
コード例 #2
0
ファイル: Program.cs プロジェクト: immmdreza/TBH
        private static async void On_Update(object sender, Telegram.Bot.Args.UpdateEventArgs e)
        {
            var     Client     = (TelegramBotClient)sender;
            iUpdate finder     = null;
            var     customdata = new Dictionary <string, object>();

            switch (e.Update.Type)
            {
            case UpdateType.Message:
            {
                finder = TBH.Variables.UpdatesList
                         .Where(x => x.Trigger.UpdateType == UpdateType.Message)
                         .FirstOrDefault(x => x.Trigger.TextTriggers.Any(c => c == e.Update.Message.Text.ToLower()));

                customdata.Add("LangCode", e.Update.Message.From.LanguageCode);
                break;
            }

            case UpdateType.CallbackQuery:
            {
                finder = TBH.Variables.UpdatesList
                         .Where(x => x.Trigger.UpdateType == UpdateType.CallbackQuery)
                         .FirstOrDefault(x => e.Update.CallbackQuery.Data.StartsWith(x.Trigger.TextTriggers[0]));

                customdata.Add("LangCode", e.Update.CallbackQuery.From.LanguageCode);
                break;
            }

            default:
                break;
            }

            using (Proccessor proccessor = new Proccessor(finder, Client, e.Update, customdata))
            {
                if (finder is null)
                {
                    return;
                }

                await proccessor.Proccess().ConfigureAwait(false);
            }
        }
コード例 #3
0
        public override void UpdateBeforeSimulation()
        {
            try
            {
                //
                // Finish work from last frame
                //
                DsUtil.Start("projectiles2");
                Projectiles.Stage2();
                DsUtil.Complete("projectiles2", true);

                DsUtil.Start("damage");
                if (_effectedCubes.Count > 0)
                {
                    ApplyGridEffect();
                }

                if (Tick60)
                {
                    GridEffects();
                }

                if (Hits.Count > 0)
                {
                    ProcessHits();
                }
                DsUtil.Complete("damage", true);

                if (MpActive)
                {
                    DsUtil.Start("network1");
                    if (WeaponsToSync.Count > 0)
                    {
                        Proccessor.Proccess();
                    }
                    if (UiInput.InputChanged && ActiveControlBlock != null)
                    {
                        SendMouseUpdate(ActiveControlBlock);
                    }
                    if (ClientGridResyncRequests.Count > 0)
                    {
                        ProccessGridResyncRequests();
                    }

                    Proccessor.AddPackets();

                    if (PacketsToClient.Count > 0)
                    {
                        ProccessServerPacketsForClients();
                    }
                    if (PacketsToServer.Count > 0)
                    {
                        ProccessClientPacketsForServer();
                    }
                    if (ClientSideErrorPktList.Count > 0)
                    {
                        ReproccessClientErrorPackets();
                    }
                    DsUtil.Complete("network1", true);
                }

                DsUtil.Start("av");
                if (!DedicatedServer)
                {
                    Av.End();
                }
                DsUtil.Complete("av", true);
                //
                // Finished last frame
                //
                Timings();

                if (!WeaponAmmoRemoveQueue.IsEmpty && CTask.IsComplete)
                {
                    if (CTask.valid && CTask.Exceptions != null)
                    {
                        TaskHasErrors(ref CTask, "CTask");
                    }

                    CTask = MyAPIGateway.Parallel.StartBackground(AmmoToRemove, RemoveAmmo);
                }

                if (!WeaponAmmoPullQueue.IsEmpty && ITask.IsComplete)
                {
                    if (ITask.valid && ITask.Exceptions != null)
                    {
                        TaskHasErrors(ref ITask, "ITask");
                    }

                    ITask = MyAPIGateway.Parallel.StartBackground(AmmoPull, MoveAmmo);
                }

                if (!CompsToStart.IsEmpty)
                {
                    StartComps();
                }

                if (Tick120 && CompsDelayed.Count > 0)
                {
                    DelayedComps();
                }

                if (CompReAdds.Count > 0)
                {
                    ChangeReAdds();
                }

                if (Tick3600 && MpActive)
                {
                    NetReport();
                }

                if (Tick180)
                {
                    ProfilePerformance();
                }

                FutureEvents.Tick(Tick);

                if (!DedicatedServer && ActiveControlBlock != null && !InMenu)
                {
                    WheelUi.UpdatePosition();
                }
            }
            catch (Exception ex) { Log.Line($"Exception in SessionBeforeSim: {ex}"); }
        }
コード例 #4
0
    static void Main(string[] args)
    {
        int simulationLength = 2 * 60 * 60; // simulation length is seconds
        int M = 20;                         // set mean job arrival time
        int P = 5;                          // set max number of processors
        int T = 20;                         // set mean exicution time

        // declare needed variables
        waitingQueue <Pevent>  wQueue = new waitingQueue <Pevent>(5000);
        PriorityQueue <Pevent> pQueue = new PriorityQueue <Pevent>(5000);
        Random     r     = new Random();
        Proccessor cores = new Proccessor(P);
        int        time  = 0;
        Job        nextJob;
        Pevent     newEvent, currentEvent;
        int        jobnum = 0;
        double     regJob = 0;
        double     intJob = 0;
        int        AvailabelCore;
        double     waitTime = 0;
        Random     random   = new Random();

        // creation of event list ( doesnt say to do this in assignment but its better and common practice for discrete event simulation


        // https://www.cs.cmu.edu/~music/cmsip/readings/intro-discrete-event-sim.html
        //        Implementation of Discrete Event Simulation

        //Operationally, a discrete -event simulation is a chronologically nondecreasing sequence of event occurrences.

        //event record:
        //a pairing of an event with its event time
        //future event list (FEL) (or just event list):
        //a list ordered by nondecreasing simulation time (e.g., in a priority queue)
        //event (list) driven simulation:
        //simulation where time is advanced to the time given by the first event record from the event list
        //Requirements for support of discrete-event simulation:

        //maintain a future event list
        //enable event record creation and insertion into and deletion from event list
        //maintain simulation clock
        //(for stochastic simulations) provide utilities to generate random numbers from common probability distributions
        while (true)
        {
            time = time + Convert.ToInt32(Math.Round(-M * Math.Log(r.NextDouble())));
            if (time > simulationLength)
            {
                break;
            }
            jobnum++;

            if (r.NextDouble() < 0.9)
            {
                nextJob = new Job(jobnum, T, P, random);
                regJob++;
                for (int i = 0; i < nextJob.processors; i++)
                {
                    newEvent = new Pevent(nextJob, Pevent.Jobtype.Arrival, time);
                    pQueue.Add(newEvent);
                }
            }
            else
            {
                nextJob  = new Job(0, T, P, random);
                newEvent = new Pevent(nextJob, Pevent.Jobtype.IArrival, time, nextJob.processors);
                pQueue.Add(newEvent);
                intJob++;
            }
        }
        // TEST SCINARIO

        //nextJob = new Job(1, T, P,random);
        //nextJob.time = 30;
        //nextJob.processors = 5;
        //time = 30;
        //for (int i = 0; i < nextJob.processors; i++)
        //{
        //    newEvent = new Pevent(nextJob, Pevent.Jobtype.Arrival, time);
        //    pQueue.Add(newEvent);
        //}
        //nextJob = new Job(2, T, P,random);
        //nextJob.time = 60;
        //nextJob.processors = 3;
        //time = 40;
        //for (int i = 0; i < nextJob.processors; i++)
        //{
        //    newEvent = new Pevent(nextJob, Pevent.Jobtype.Arrival, time);
        //    pQueue.Add(newEvent);
        //}
        //nextJob = new Job(0, T, P,random);
        //nextJob.time = 35;
        //nextJob.processors = 4;
        //time = 45;
        //newEvent = new Pevent(nextJob, Pevent.Jobtype.IArrival, time);
        //pQueue.Add(newEvent);

        //nextJob = new Job(0, T, P, random);
        //nextJob.time = 35;
        //nextJob.processors = 4;
        //time = 60;
        //newEvent = new Pevent(nextJob, Pevent.Jobtype.IArrival, time);
        //pQueue.Add(newEvent);

        //nextJob = new Job(3, T, P,random);
        //nextJob.time = 40;
        //nextJob.processors = 4;
        //time = 115;
        //for (int i = 0; i < nextJob.processors; i++)
        //{
        //    newEvent = new Pevent(nextJob, Pevent.Jobtype.Arrival, time);
        //    pQueue.Add(newEvent);
        //}
        //nextJob = new Job(4, T, P,random);
        //nextJob.time = 50;
        //nextJob.processors = 3;
        //time = 125;
        //for (int i = 0; i < nextJob.processors; i++)
        //{
        //    newEvent = new Pevent(nextJob, Pevent.Jobtype.Arrival, time);
        //    pQueue.Add(newEvent);
        //}

        //regJob = 4;
        //intJob = 2;
        // processing of events


        while (!pQueue.Empty())
        {
            currentEvent = pQueue.Front();             // get next event
            pQueue.Remove();                           // remove it from the priority queue
            time = currentEvent.time;                  // update simulation clock

            Console.WriteLine(currentEvent.getTime()); // display time



            // proccess Arrival event
            if (currentEvent.type == Pevent.Jobtype.Arrival)
            {
                Console.WriteLine("arrival"); // display job type
                if (!cores.IsFull())          // check if all processors are active
                {
                    // if not
                    AvailabelCore = cores.NextAvailable();                                                                               // get first available processor
                    newEvent      = new Pevent(currentEvent.job, Pevent.Jobtype.Departure, time + currentEvent.job.time, AvailabelCore); // create new departure
                    cores.Activate(AvailabelCore);                                                                                       // activate the core
                    pQueue.Add(newEvent);                                                                                                // add departure
                    Console.WriteLine("Job " + newEvent.job.number + " Arrives and is assigned to proccesor " + AvailabelCore);          // display update
                }
                else
                {
                    // if full
                    wQueue.Add(currentEvent);                                                                             // add event to waiting queue
                    Console.WriteLine("job " + currentEvent.job.number + " Arrives and is assigned to the waitingQueue"); // display update
                }
            }


            // process departure event
            if (currentEvent.type == Pevent.Jobtype.Departure)
            {
                Console.WriteLine("departure");                                                                                                               // display status type
                cores.DeActivate(currentEvent.processor);                                                                                                     // deactivate processor
                Console.WriteLine("Job " + currentEvent.job.number + " has finished exicution on proccessor " + currentEvent.processor);
                if (!wQueue.IsEmpty())                                                                                                                        // if a event is in waiting queue
                {
                    waitTime = waitTime + currentEvent.time - wQueue.Front().time;                                                                            // caculate how long it waited and add it to total wait time
                    newEvent = new Pevent(wQueue.Front().job, Pevent.Jobtype.Departure, time + wQueue.Front().job.time, currentEvent.processor);              // create new departure event
                    cores.Activate(newEvent.processor);                                                                                                       // activate processor
                    wQueue.Remove();                                                                                                                          // remove from waiting queue
                    pQueue.Add(newEvent);                                                                                                                     // add departure to priority queue
                    Console.WriteLine("Job " + newEvent.job.number + " is removed form the waiting que and assigned to proccesor " + currentEvent.processor); // update status
                }
            }

            // process Inturupt Event

            if (currentEvent.type == Pevent.Jobtype.IArrival)
            {
                Console.WriteLine("interupt");                                                                                                                           // display event type
                if (cores.getStatus(currentEvent.job.processors) != Proccessor.Status.Interrupted)                                                                       // if processor is exicuting a inturupt
                {
                    if (cores.getStatus(currentEvent.job.processors) == Proccessor.Status.Active)                                                                        // if a process is exicuting on the processor
                    {
                        newEvent = pQueue.RemoveItem(currentEvent);                                                                                                      // remove the departure event
                        Console.WriteLine("Inturupt for Proccesor " + currentEvent.job.processors + " exicuted job " + newEvent.job.number + " is placed in waiting Q"); // display status
                        newEvent.job.time = newEvent.time - currentEvent.time;                                                                                           // decrease exicution time by time it has been exicuting
                        newEvent.type     = Pevent.Jobtype.Arrival;                                                                                                      // change job type back to arrival
                        newEvent.time     = currentEvent.time;                                                                                                           // set its arrival time to current time
                        wQueue.Add(newEvent);                                                                                                                            // add it back to waiting queue
                        cores.Inturupt(newEvent.processor);                                                                                                              // make processor status inturupted
                        newEvent = new Pevent(currentEvent.job, Pevent.Jobtype.Departure, time + currentEvent.job.time, currentEvent.job.processors);                    // create inturupt departure
                        pQueue.Add(newEvent);                                                                                                                            // add it to priority queue
                    }
                    else // no event is being exicuted
                    {
                        Console.WriteLine("interupt begins on proccesor " + currentEvent.job.processors);                                             // update status
                        cores.Inturupt(currentEvent.processor);                                                                                       // set core status
                        newEvent = new Pevent(currentEvent.job, Pevent.Jobtype.Departure, time + currentEvent.job.time, currentEvent.job.processors); // create departure
                        pQueue.Add(newEvent);                                                                                                         // add it to priority queue
                    }
                }
                else // processor is exicuting a intureupt  ignore the inturupt
                {
                    Console.WriteLine("Inturupt for proccessor " + currentEvent.job.processors + "Ignored");
                }
            }

            cores.Print(); // print cores status
            Console.WriteLine();
        }


        Console.WriteLine();
        Console.WriteLine(regJob + ": regular jobs arrived " + intJob + ": inturupt jobs occured"); // display number or reg jobs and inturupt jobs


        double totaltime = waitTime / regJob;       // average waittime in seconds
        // convert to hours min seconds
        double h = Math.Floor(Convert.ToDouble(totaltime / 3600));
        double m = Math.Floor(Convert.ToDouble((totaltime - (h * 3600)) / 60));
        double s = Math.Floor(Convert.ToDouble(totaltime % 60));

        Console.WriteLine("average wait time: " + h + ":" + m + ":" + s); // display average waittime
        Console.ReadLine();
    }
コード例 #5
0
ファイル: SessionRun.cs プロジェクト: Coreman230/WeaponCore
        public override void UpdateAfterSimulation()
        {
            try
            {
                if (Placer != null)
                {
                    UpdatePlacer();
                }
                if (!DedicatedServer)
                {
                    ProcessAnimations();
                }

                /*
                 * DsUtil.Start("projectiles");
                 * if (!DedicatedServer && false)
                 * {
                 *  if (!PTask.IsComplete)
                 *      PTask.Wait();
                 *
                 *  if (PTask.IsComplete && PTask.valid && PTask.Exceptions != null)
                 *      TaskHasErrors(ref PTask, "PTask");
                 * }
                 * else Projectiles.Update();
                 *
                 * DsUtil.Complete("projectiles", true);
                 */
                if (_effectedCubes.Count > 0)
                {
                    ApplyGridEffect();
                }

                if (Tick60)
                {
                    GridEffects();
                }

                if (GridTask.IsComplete)
                {
                    CheckDirtyGrids();
                }

                DsUtil.Start("damage");
                if (Hits.Count > 0)
                {
                    ProcessHits();
                }
                DsUtil.Complete("damage", true);

                if (IsClient)
                {
                    if (!MTask.IsComplete)
                    {
                        MTask.Wait();
                    }

                    if (MTask.IsComplete && MTask.valid && MTask.Exceptions != null)
                    {
                        TaskHasErrors(ref MTask, "MTask");
                    }
                }

                /*
                 * DsUtil.Start("network");
                 * if (!DedicatedServer)
                 * {
                 *  if (!NTask.IsComplete)
                 *      NTask.Wait();
                 *
                 *  if (NTask.IsComplete && NTask.valid && NTask.Exceptions != null)
                 *      TaskHasErrors(ref NTask, "NTask");
                 * }
                 * else if (WeaponsToSync.Count > 0) Proccessor.Proccess();
                 */

                DsUtil.Start("network2");
                Proccessor.AddPackets();

                if (MpActive && !HandlesInput)
                {
                    if (PacketsToClient.Count > 0)
                    {
                        ProccessServerPacketsForClients();
                    }
                    if (PacketsToServer.Count > 0)
                    {
                        ProccessClientPacketsForServer();
                    }
                }
                DsUtil.Complete("network2", true);
            }
            catch (Exception ex) { Log.Line($"Exception in SessionAfterSim: {ex}"); }
        }
コード例 #6
0
ファイル: SessionRun.cs プロジェクト: Coreman230/WeaponCore
        public override void Simulate()
        {
            try
            {
                if (!DedicatedServer)
                {
                    EntityControlUpdate();
                    CameraMatrix = Session.Camera.WorldMatrix;
                    CameraPos    = CameraMatrix.Translation;
                    PlayerPos    = Session.Player?.Character?.WorldAABB.Center ?? Vector3D.Zero;
                }

                if (GameLoaded)
                {
                    DsUtil.Start("ai");
                    AiLoop();
                    DsUtil.Complete("ai", true);

                    DsUtil.Start("charge");
                    if (ChargingWeapons.Count > 0)
                    {
                        UpdateChargeWeapons();
                    }
                    DsUtil.Complete("charge", true);

                    DsUtil.Start("acquire");
                    if (AcquireTargets.Count > 0)
                    {
                        CheckAcquire();
                    }
                    DsUtil.Complete("acquire", true);

                    DsUtil.Start("shoot");
                    if (ShootingWeapons.Count > 0)
                    {
                        ShootWeapons();
                    }
                    DsUtil.Complete("shoot", true);
                }

                if (!DedicatedServer && !WheelUi.WheelActive && !InMenu)
                {
                    UpdateLocalAiAndCockpit();
                    if (UiInput.PlayerCamera && ActiveCockPit != null)
                    {
                        TargetSelection();
                    }
                }

                if (FragmentsNeedingEntities.Count > 0)
                {
                    Projectiles.PrepFragmentEntities();
                }

                DsUtil.Start("projectiles");
                Projectiles.Update();
                DsUtil.Complete("projectiles", true);

                DsUtil.Start("network1");
                if (WeaponsToSync.Count > 0)
                {
                    Proccessor.Proccess();
                }
                DsUtil.Complete("network1", true);

                /*
                 * if (!DedicatedServer)
                 * {
                 *  //PTask = MyAPIGateway.Parallel.StartBackground(Projectiles.Update);
                 *  if (WeaponsToSync.Count > 0) NTask = MyAPIGateway.Parallel.StartBackground(Proccessor.Proccess);
                 * }
                 */
            }
            catch (Exception ex) { Log.Line($"Exception in SessionSim: {ex}"); }
        }
コード例 #7
0
    public async static void ReadCallback(IAsyncResult ar)
    {
        String content = String.Empty;
        // Retrieve the state object and the handler socket
        // from the asynchronous state object.
        StateObject state   = (StateObject)ar.AsyncState;
        Socket      handler = state.workSocket;

        // Read data from the client socket.
        int bytesRead = handler.EndReceive(ar);

        //Console.WriteLine("AsyncEngine@ReadCallback | readed bytes {0}", bytesRead);

        // catch every exception on server and send 500 if exception occured
        try  {
            if (bytesRead > 0)
            {
                // There  might be more data, so store the data received so far.
                state.sb.Append(Encoding.ASCII.GetString(
                                    state.buffer, 0, bytesRead));

                // Check for end-of-file tag. If it is not there, read
                // more data.
                content = state.sb.ToString();
                //Console.WriteLine("Content | {0}", content);

                // if readed bytes >= BUFFER_SIZE -> read more bytes
                if (bytesRead != 1024)
                {
                    // All the data has been read from the
                    // client. Display it on the console.


                    logger.info("AsyncEngine@ReadCallback | Read {0} bytes from socket",
                                content.Length);
                    logger.info("AsyncEngine@ReadCallback | Raw Request \n{0}", content);



                    IgniteRequest        request = requestParser.Parse(content);
                    IgniteResponseStatus status  = IgniteRequestValidatorService.validate(request);

                    if (status.getCode() != HttpStatus.OK)
                    {
                        logger.warn("AsyncEngine@ReadCallback | request not valid {0}:{1}", status.getCode(), status.getMessage());
                        IgniteResponse failedResponse = IgniteResponseFactory.getInstance(status);
                        String         rawResponse    = responseParser.stringify(failedResponse);

                        logger.info("\n\nAsyncEngine@ReadCallback | raw response \n {0}", rawResponse);

                        Send(handler, rawResponse);
                    }
                    else
                    {
                        //Console.WriteLine("AsyncEngine@ReadCallback | request valid");
                        //Console.WriteLine("AsyncEngine@ReadCallback | Parsed request {0}", request);
                        Proccessor     proccessor = ProccessorFactory.getInstance();
                        IgniteResponse response   = await proccessor.proccess(request);

                        String rawResponse = responseParser.stringify(response);

                        logger.info("AsyncEngine@ReadCallback | raw response \n{0}", rawResponse);

                        Send(handler, rawResponse);
                    }
                }
                else
                {
                    // Not all data received. Get more.
                    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                                         new AsyncCallback(ReadCallback), state);
                }
            }
        } catch (Exception e) {
            logger.error("AsyncEngine@ReadCallback | Server erorr occured {0}", e);
            IgniteResponse failedResponse = IgniteResponseFactory.getInstance(new IgniteResponseStatus(HttpStatus.SERVER_ERROR, HttpStatus.SERVER_ERROR_MESSAGE));
            String         rawResponse    = responseParser.stringify(failedResponse);

            logger.info("AsyncEngine@ReadCallback | raw response \n", rawResponse);


            Send(handler, rawResponse);
        }
    }