Ejemplo n.º 1
0
        /// <summary>
        /// Returns top speed in km/h
        /// </summary>
        /// <param name="sim"></param>
        /// <param name="car"></param>
        /// <returns></returns>
        public double TopSpeed(ISimulator sim, ICar car)
        {
            if (sim.Garage != null && sim.Garage.Available)
            {
                if (car == null)
                {
                    // Look up car.
                    try
                    {
                        car = sim.Garage.SearchCar(sim.Drivers.Player.CarClass, sim.Drivers.Player.CarModel);
                    }catch(Exception ex)
                    {

                    }
                    if (car == null)
                        return TopSpeed_Stock;

                    car.ScanAerodynamics();
                    car.ScanEngine();

                    if (car.Engine == null || car.Aerodynamics == null)
                        return TopSpeed_Stock;
                }

                double power = MaximumPower(sim, car);
                double aero = car.Aerodynamics.GetAerodynamicDrag(sim.Setup);

                return 3.6 * Math.Pow(power * 1000.0 / aero, 1 / 3.0);
            }
            else
            {
                return TopSpeed_Stock;
            }
        }
Ejemplo n.º 2
0
 internal ConwaysGameOfLife2D(IWorldViewer viewer, IWorldEditor editor, ISimulator simulator, ICoordinateConverter converter)
 {
     _viewer    = viewer ?? throw new ArgumentNullException(nameof(viewer));
     _editor    = editor ?? throw new ArgumentNullException(nameof(editor));
     _simulator = simulator ?? throw new ArgumentNullException(nameof(simulator));
     _converter = converter ?? throw new ArgumentNullException(nameof(converter));
 }
Ejemplo n.º 3
0
        public rFactor(ISimulator sim)
        {
            Simulator = sim;
            MMF = new rFactorMMF();

            if (Simulator.UseMemoryReader)
            {
                Game = new MemoryPolledReader(sim);
            }
            else
            {
                Game = null;
            }

            Garage = new rFactorGarage();
            Session = new Session();
            Drivers = new Drivers();

            Player = new DriverPlayer();

            Game.Diagnostic = true;
            var t = new Timer(1000);
            t.AutoReset = true;
            t.Elapsed += (a, b) => Debug.WriteLine("RPM: " + Game.ReadCalls);
            t.Start();
        }
Ejemplo n.º 4
0
 static void ExecuteMultipleCommands(ISimulator simulator, string[] commands)
 {
     foreach (var command in commands)
     {
         simulator.ExecuteCommand(command);
     }
 }
Ejemplo n.º 5
0
        public override void Process(ISimulator simulator, double tick)
        {
            foreach (var handle in simulator.GetHandlesForProcessor(Aspect))
            {
                if(Console.KeyAvailable)
                {
                    var key = Console.ReadKey(true);

                    switch(key.Key)
                    {
                        case ConsoleKey.UpArrow:
                            VelocityComponent.MoveByX[handle.Index] = 1;
                            break;
                        case ConsoleKey.DownArrow:
                            VelocityComponent.MoveByX[handle.Index] = -1;
                            break;
                        case ConsoleKey.LeftArrow:
                            VelocityComponent.MoveByY[handle.Index] = -1;
                            break;
                        case ConsoleKey.RightArrow:
                            VelocityComponent.MoveByY[handle.Index] = 1;
                            break;
                    }
                }
            }
        }
Ejemplo n.º 6
0
        public Track(ISimulator sim, string name)
        {
            if (name == null) return;
            Route = new RouteCollection();
            Apexes = new ApexCollection();
            Sections = new SectionsCollection();

            // TODO: Make possible without Telemetry.m.Sim available!
            if (sim.Garage != null && sim.Garage.Available
                 && sim.Garage.Available_Tracks)
            {
                ITrack track = sim.Garage.SearchTrack(name);
                if (track != null)
                {
                    track.Scan();
                    track.ScanRoute();
                    Location = track.Location;
                    Type = track.Type;
                    Name = track.Name;

                    Route = (RouteCollection) track.Route.Clone();
                }
            }
            LapLogger = new Timer();
            LapLogger.Interval = 2;
            LapLogger.Elapsed += LapLogger_Elapsed;
            LapLogger.AutoReset = true;
            LapLogger.Start();
        }
Ejemplo n.º 7
0
 //private readonly Client _client;
 public MrpController(ISimulator simulator, IProcessMrp processMrp, IMessageHub messageHub)
 {
     _processMrp = processMrp;
     _simulator  = simulator;
     _messageHub = messageHub;
     //_client = client;
 }
Ejemplo n.º 8
0
        public static void SetSimpleScene(ISimulator simulator)
        {
            #region Create a box

            //create a rigidBody
            var boxRigidBodyDescriptor = new RigidBodyDescriptor(MotionType.Dynamic, Matrices.Translate(0, 10, 0));
            var boxRigidBody           = simulator.ActorsFactory.CreateRigidBody(boxRigidBodyDescriptor);

            //create a simple fixture for the rigidBody
            var fixtureDescriptor = new FixtureDescriptor(Matrices.I);
            var simpleFixture     = boxRigidBody.FixtureFactory.CreateSimpleFixture(fixtureDescriptor);

            //define the shape for the simple fixture
            var boxShapeDescriptor = new BoxShapeDescriptor(3, 3, 3, _motionColor);
            simpleFixture.ShapeFactory.CreateBox(boxShapeDescriptor);

            //define the material for the simple fixture
            var materialDescriptor = new MaterialDescriptor(friction: 0.5f, restitution: 0.6f);
            simpleFixture.MaterialFactory.CreateMaterial(materialDescriptor);
            boxRigidBody.MassFrame.UpdateFromShape();

            #endregion

            #region Create a plane for the ground

            var groundRigidBody =
                simulator.ActorsFactory.CreateRigidBody(new RigidBodyDescriptor(MotionType.Static, Matrices.I));
            var groundSimpleFixture =
                groundRigidBody.FixtureFactory.CreateSimpleFixture(new FixtureDescriptor(Matrices.I));
            groundSimpleFixture.ShapeFactory.CreatePlane(new PlaneShapeDescriptor(Vectors.YAxis, 0, _groundColor));
            groundSimpleFixture.MaterialFactory.CreateMaterial(materialDescriptor);

            #endregion
        }
Ejemplo n.º 9
0
        public static void SetFrictionScene(ISimulator simulator)
        {
            const int   maxI      = 8;
            const float alphaGrad = 33;

            for (int i = 0; i <= maxI; i++)
            {
                SetSimpleRigidBody <IBoxShape, BoxShapeDescriptor>(simulator,
                                                                   new RigidBodyDescriptor(MotionType.Dynamic,
                                                                                           GMath.mul(
                                                                                               Matrices.Translate(
                                                                                                   2 * i - maxI, 0.5f, 0),
                                                                                               Matrices.RotateZGrad(
                                                                                                   alphaGrad))),
                                                                   new BoxShapeDescriptor(1, 1, 1, _motionColor),
                                                                   new MaterialDescriptor(friction: (maxI - i) * 1f / maxI,
                                                                                          restitution: 0.5f));
            }

            //create inclined ground
            var groundRigidBody =
                simulator.ActorsFactory.CreateRigidBody(new RigidBodyDescriptor(MotionType.Static, Matrices.I));
            var fixtureDescriptor = new FixtureDescriptor(Matrices.RotateZGrad(alphaGrad));
            var simpleFixture     = groundRigidBody.FixtureFactory.CreateSimpleFixture(fixtureDescriptor);

            simpleFixture.ShapeFactory.Create <IPlaneShape, PlaneShapeDescriptor>(new PlaneShapeDescriptor(
                                                                                      Vectors.YAxis, 0, _groundColor));
            simpleFixture.MaterialFactory.CreateMaterial(new MaterialDescriptor(friction: 0.0f, restitution: 0.5f));
            groundRigidBody.MassFrame.UpdateFromShape();
        }
Ejemplo n.º 10
0
        private static IRigidBody SetSnowman(ISimulator simulator, Matrix4x4 pose)
        {
            var rigidBody = simulator.ActorsFactory.CreateRigidBody(new RigidBodyDescriptor(MotionType.Dynamic, pose));

            var fixtureDescriptor = new FixtureDescriptor(Matrices.I);
            var compositeFixture  = rigidBody.FixtureFactory.CreateCompositeFixture(fixtureDescriptor);

            //head
            var simpleFixture = compositeFixture.FixtureFactory.CreateSimpleFixture(
                new FixtureDescriptor(Matrices.Translate(0, 4f, 0)));

            simpleFixture.ShapeFactory.CreateSphere(new SphereShapeDescriptor(0.7f));

            //body
            simpleFixture = compositeFixture.FixtureFactory.CreateSimpleFixture(
                new FixtureDescriptor(Matrices.Translate(0, 3, 0)));
            simpleFixture.ShapeFactory.CreateSphere(new SphereShapeDescriptor(1));

            //legs?
            simpleFixture = compositeFixture.FixtureFactory.CreateSimpleFixture(
                new FixtureDescriptor(Matrices.Translate(0, 1.5f, 0)));
            simpleFixture.ShapeFactory.CreateSphere(new SphereShapeDescriptor(1.5f));
            rigidBody.MassFrame.UpdateFromShape();
            return(rigidBody);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Refreshes the catalog and initializes all simulators with the host (Telemetry class).
        /// </summary>
        private void Refresh()
        {
            try
            {
                var catalog = new DirectoryCatalog(Telemetry.m.binaryDirectory + "simulators/", "SimTelemetry.Game.*.dll");
                catalog.Refresh();
                var container = new CompositionContainer(catalog);
                container.ComposeParts(this);

                foreach (ISimulator sim in Sims)
                {
                    sim.Host = Telemetry.m;
                    sim.Initialize();
                }

                if (Network != null)
                {
                    throw new Exception("Network already added");
                }
                Network = new NetworkGame {
                    Host = Telemetry.m
                };
                Network.Initialize();

                Sims.Add(Network);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed loading assemblies");
                Debug.WriteLine(ex.Message);
                Debug.WriteLine(ex.StackTrace);
            }
        }
Ejemplo n.º 12
0
        public async void Disable()
        {
            try
            {
                if (this.dispatcherTimer != null)
                {
                    dispatcherTimer.Stop();
                    dispatcherTimer = null;
                }

                if (this.core != null)
                {
                    await this.core.ZeroPneumatics();

                    this.core = null;
                }

                if (this.simulator != null)
                {
                    this.simulator.Dispose();
                    this.simulator = null;
                }

                if (this.relays != null)
                {
                    this.relays.Dispose();
                    this.relays = null;
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.ToString(), ex.Message);
            }
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Load new track. Specify location of gamedirectory and file.
 /// </summary>
 /// <param name="sim">Source simulator of track</param>
 /// <param name="track">Relative path from gamedirectory to track file OR track name.</param>
 public void Track_Load(ISimulator sim, string track)
 {
     if (Net == null || !Net.IsClient)
     {
         Track = new Track.Track(sim, track);
     }
 }
Ejemplo n.º 14
0
        public Track(ISimulator sim, string name)
        {
            if (name == null)
            {
                return;
            }
            Route    = new RouteCollection();
            Apexes   = new ApexCollection();
            Sections = new SectionsCollection();

            // TODO: Make possible without Telemetry.m.Sim available!
            if (sim.Garage != null && sim.Garage.Available &&
                sim.Garage.Available_Tracks)
            {
                ITrack track = sim.Garage.SearchTrack(name);
                if (track != null)
                {
                    track.Scan();
                    track.ScanRoute();
                    Location = track.Location;
                    Type     = track.Type;
                    Name     = track.Name;

                    Route = (RouteCollection)track.Route.Clone();
                }
            }
            LapLogger           = new Timer();
            LapLogger.Interval  = 2;
            LapLogger.Elapsed  += LapLogger_Elapsed;
            LapLogger.AutoReset = true;
            LapLogger.Start();
        }
Ejemplo n.º 15
0
        public static void SetBulletScene(ISimulator simulator)
        {
            //base
            SetSimpleRigidBody <IBoxShape, BoxShapeDescriptor>(
                simulator,
                new RigidBodyDescriptor(MotionType.Dynamic, Matrices.Translate(0, 0.5f, 0), _motionColor),
                new BoxShapeDescriptor(1, 1, 1),
                new MaterialDescriptor(0.5f, 0.5f));

            //board
            SetSimpleRigidBody <IBoxShape, BoxShapeDescriptor>(
                simulator,
                new RigidBodyDescriptor(MotionType.Dynamic, Matrices.Translate(3, 0.5f + 0.0001f / 2, 0), _motionColor),
                new BoxShapeDescriptor(10, 0.00005f, 1),
                new MaterialDescriptor(0.5f, 0.5f));

            //bullet
            var bullet = SetSimpleRigidBody <ISphereShape, SphereShapeDescriptor>(simulator,
                                                                                  new RigidBodyDescriptor(MotionType.Dynamic, Matrices.Translate(-1, 200f, 0), _motionColor),
                                                                                  new SphereShapeDescriptor(0.1f), new MaterialDescriptor(0.5f, 0.5f));

            //simulator.Configurator.Set(new SimulatorCcdConfiguration(true));
            //bullet.Configurator.Set(new RigidBodyCcdConfiguration(true));

            SetGround(simulator, new MaterialDescriptor(0.5f, 0.5f));
        }
Ejemplo n.º 16
0
        public rFactor(ISimulator sim)
        {
            Simulator = sim;
            MMF       = new rFactorMMF();

            if (Simulator.UseMemoryReader)
            {
                Game = new MemoryPolledReader(sim);
            }
            else
            {
                Game = null;
            }

            Garage  = new rFactorGarage();
            Session = new Session();
            Drivers = new Drivers();

            Player = new DriverPlayer();



            Game.Diagnostic = true;
            var t = new Timer(1000);

            t.AutoReset = true;
            t.Elapsed  += (a, b) => Debug.WriteLine("RPM: " + Game.ReadCalls);
            t.Start();
        }
Ejemplo n.º 17
0
        public SettingsVM(ISimulator simulator)
        {
            this._simulator = simulator;
            SynchronizationContext uiContext = SynchronizationContext.Current;

            // start threads for async operations with UI-Context
            Stations = new ObservableCollection <StationVM>();
            Task.Run(() => LoadStationsAsync(uiContext));

            MeasurementTypes = new ObservableCollection <MeasurementType>();
            Task.Run(() => LoadTypesAsync(uiContext));

            // register event handlers to watch for simulation status changes
            simulator.IsSimulatingChanged += value => IsSimulating = value;

            simulator.StationIsInSimulationChanged += (added, station) => {
                if (added)
                {
                    SelectedStations.Add(station);
                }
                else
                {
                    for (int i = 0; i < SelectedStations.Count; i++)
                    {
                        if (SelectedStations[i].Id == station.Id)
                        {
                            SelectedStations.RemoveAt(i);
                        }
                    }
                }

                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedStations)));
                UpdateSimulationReady();
            };
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Returns power in HP
        /// </summary>
        /// <param name="sim"></param>
        /// <param name="car"></param>
        /// <returns></returns>
        public double MaximumPower(ISimulator sim, ICar car)
        {
            if (sim.Garage == null)
            {
                return(0);
            }

            if (car == null)
            {
                // Look up car.
                car = sim.Garage.SearchCar(sim.Drivers.Player.CarClass, sim.Drivers.Player.CarModel);

                if (car == null)
                {
                    return(0);
                }

                car.ScanEngine();

                if (car.Engine == null)
                {
                    return(0);
                }
            }

            return(car.Engine.GetMaximumPower());
        }
        public TracingDecoratorSimulator(ITraceLogger logger, ISimulator sim, string name)
        {
            this.logger = logger;
            this.sim    = sim;

            simulatorName = name;
        }
Ejemplo n.º 20
0
        public static void SetForceEffectScene(ISimulator simulator)
        {
            int echelonCount = 7;
            var chain        = new IRigidBody[echelonCount];

            for (int i = 0; i < echelonCount; i++)
            {
                chain[i] = SetSimpleRigidBody <ISphereShape, SphereShapeDescriptor>(simulator, new RigidBodyDescriptor(i == 0 ? MotionType.Static : MotionType.Dynamic, Matrices.Translate(-i, 10, 0), _motionColor), new SphereShapeDescriptor(0.4f), new MaterialDescriptor(0.5f, 0.5f));
                if (i > 0)
                {
                    simulator.ConstraintsFactory.CreateSphericalJoint(
                        new SphericalJointDescriptor(
                            new Vector3(1f, 0, 0), new Vector3(), chain[i], chain[i - 1]));
                }
            }

            for (int i = 0; i < 2 * echelonCount; i++)
            {
                SetSimpleRigidBody <IBoxShape, BoxShapeDescriptor>(simulator, new RigidBodyDescriptor(MotionType.Dynamic, Matrices.Translate(-i, (i + 1) * 0.1f / 2, 10), _motionColor), new BoxShapeDescriptor((i + 1) * 0.1f, (i + 1) * 0.1f, (i + 1) * 0.1f), new MaterialDescriptor(0.5f, 0.5f));
            }

            simulator.AddForceEffect(new AttractionForceEffect(chain[echelonCount - 1]));

            SetGround(simulator, new MaterialDescriptor(0.5f, 0.5f));
        }
Ejemplo n.º 21
0
 /// <summary>
 /// Fire Sim Stop event.
 /// </summary>
 /// <param name="me">Simulator stopped</param>
 internal void Report_SimStop(ISimulator me)
 {
     Debug.WriteLine("SimStop fired");
     if (Sim_Stop != null)
     {
         Sim_Stop(me);
     }
 }
        public ToySimulatorIntegrationTests()
        {
            var placeParameterParser = new PlaceParameterParser();

            simulator = new ToyRobotSimulator(new ToyRobot(), new CommandParser(new List <IParameterParser> {
                placeParameterParser
            }), new ToyTabletop(5, 5));
        }
Ejemplo n.º 23
0
 /// <summary>
 /// Fire Session Stop event.
 /// </summary>
 /// <param name="me">Simulator of which session stopped</param>
 internal void Report_SessionStop(ISimulator me)
 {
     Debug.WriteLine("SessionStop fired");
     if (Session_Stop != null)
     {
         Session_Stop(me);
     }
 }
Ejemplo n.º 24
0
 /// <summary>
 /// Fire Lap event.
 /// </summary>
 /// <param name="me">Simulator of which session stopped</param>
 internal void Report_Laps(ISimulator me, ILap lap)
 {
     Debug.WriteLine("Laps fired");
     if (Lap != null)
     {
         Lap(me, lap);
     }
 }
Ejemplo n.º 25
0
 //[GLswitchSimulators]
 public void SwitchSimulator()
 {
     _simulators.Enqueue(_simulator);
     _simulator = _simulators.Dequeue();
     Description();
     _frameCounter = 0;
     _stopwatch.Restart();
 }
Ejemplo n.º 26
0
 /// <summary>
 /// Fire Driving Stop event.
 /// </summary>
 /// <param name="sim">Simulator with drive session stopped</param>
 private void Report_DrivingStop(ISimulator sim)
 {
     Debug.WriteLine("DrivingStop fired");
     if (Driving_Stop != null)
     {
         Driving_Stop(sim);
     }
 }
Ejemplo n.º 27
0
 public RunForTicks()
 {
     _simulator = new Simulator(_sectorGenerator.Object, _simulationRepository.Object, _empireGenerator.Object, _economicSimulator.Object, _militarySimulator.Object, _diplomacySimulator.Object, _deltaApplier.Object);
     _simulationRepository.Setup(x => x.GetSimulation(It.IsAny <ObjectId>()))
     .Returns(new Simulation {
         EmpireIds = new ObjectId[0]
     });
 }
Ejemplo n.º 28
0
        /// <summary>
        /// Calculates(approximation) the engine power for a given throttle position at a given RPM
        /// It always needs a combination of both ISimulator and Car. Car value can be null, and it will search for the Player car.
        /// </summary>
        /// <param name="sim">Simulator for the garage plug-in to search in</param>
        /// <param name="car">Direct car to search in</param>
        /// <param name="engineRpm">Engine RPM</param>
        /// <param name="pedalsThrottle">Throttle position 0.0-1.0</param>
        /// <returns>Engine power (kW)</returns>
        public double GetPower(ISimulator sim, ICar car, double engineRpm, double pedalsThrottle)
        {
            if (sim.Garage != null && sim.Garage.Available)
            {
                if (car == null)
                {
                    // Look up car.
                    try
                    {
                        car = sim.Garage.SearchCar(sim.Drivers.Player.CarClass, sim.Drivers.Player.CarModel);
                    }
                    catch (Exception ex)
                    {
                    }
                    if (car == null)
                    {
                        return(0);
                    }
                    car.ScanEngine();
                    if (car.Engine == null)
                    {
                        return(0);
                    }
                }

                // We got engine info:
                var engineCurve = car.Engine.GetPowerCurve(0, pedalsThrottle, 0);

                double engineRpmBefore = 0, engineRpmAfter = 0, enginePowerBefore = 0, enginePowerAfter = 0;

                foreach (var engineCurveKvp in engineCurve)
                {
                    if (engineRpmBefore < engineRpm && engineCurveKvp.Key >= engineRpm)
                    {
                        engineRpmAfter   = engineCurveKvp.Key;
                        enginePowerAfter = engineCurveKvp.Value;
                        break;
                    }

                    engineRpmBefore   = engineCurveKvp.Key;
                    enginePowerBefore = engineCurveKvp.Value;
                }
                if (engineRpmAfter == 0) // didn't find our RPM in the curve:
                {
                    return(enginePowerBefore);
                }

                double engineRpmDutyCycle = (engineRpm - engineRpmBefore) / (engineRpmAfter - engineRpmBefore);
                double enginePowerSlope   = (enginePowerAfter - enginePowerBefore);

                double enginePower = engineRpmDutyCycle * enginePowerSlope + enginePowerBefore;
                return(Power.HP_KW(enginePower));
            }
            else
            {
                return(0);
            }
        }
Ejemplo n.º 29
0
        public void Add_AddsSimulator()
        {
            ISimulation simulation = Simulation.Create();
            ISimulator  simulator  = Substitute.For <ISimulator>();

            ((IAddSimulator)simulation).Add(simulator);

            simulation.Simulators.Single().ShouldBeSameAs(simulator);
        }
 public void ReleaseExclusiveKeyboardAccess()
 {
     if (exclusiveAccess != TW.Internal.ActiveSimulator)
     {
         throw new InvalidOperationException("Does not have exclusive access");
     }
     exclusiveAccess = null;
     SpectaterCamera.EnableUserInput = true;
 }
 public void RequestExclusiveKeyboardAccess()
 {
     if (exclusiveAccess != null)
     {
         throw new InvalidOperationException("Another sim has exclusive keyboard access: " + exclusiveAccess);
     }
     exclusiveAccess = TW.Internal.ActiveSimulator;
     SpectaterCamera.EnableUserInput = false;
 }
Ejemplo n.º 32
0
 private void m_Lap(ISimulator sim, ILap lap)
 {
     if (Telemetry.m.Sim != null)
     {
         Time_Start = Telemetry.m.Sim.Session.Time; // TODO: add local timing if not supported.
         // Get the last lap from the game.
         PreviousRecords = false;
         _mUpdateBestLap.Start();
     }
 }
Ejemplo n.º 33
0
        public MainWindow()
        {
            InitializeComponent();

            _simulator = new Simulator();

            _timeControl.SimulatorTimer = _simulator;
            _acceleratorControl.SimulatorAccelerator = _simulator;
            _speedControl.SimulatorSpeed             = _simulator;
            _distanceControl.SimulatorDistance       = _simulator;
        }
Ejemplo n.º 34
0
        public void Dispose_DoesNotThrow_WhenSimulatorDoesNotImplementIDisposable()
        {
            ISimulator  simulator  = Substitute.For <ISimulator>();
            ISimulation simulation = Simulation.Create();

            ((IAddSimulator)simulation).Add(simulator);

            Action action = () => simulation.Dispose();

            action.ShouldNotThrow();
        }
Ejemplo n.º 35
0
        public rFactor(ISimulator sim)
        {
            Simulator = sim;
            Game = new MemoryPolledReader(sim);

            Garage = new rFactorGarage();
            Session = new Session();
            Drivers = new Drivers();

            Player = new DriverPlayer();
        }
Ejemplo n.º 36
0
        private void renderedControl1_InitializeRender(object sender, RenderEventArgs e)
        {
            _render = e.Render;
            _renderingVisitor = new RenderingVisitor(_render);
            _simulator = new DigitalRuneSimulator();
            _simulator.AddForceEffect(new GravityForceEffect());

            Samples.SetSimpleScene(_simulator);

            _previousTickCount = Environment.TickCount;
            _startTickCount = _previousTickCount;
        }
Ejemplo n.º 37
0
        public override void Process(ISimulator simulator, double tick)
        {
            foreach (var handle in simulator.GetHandlesForProcessor(Aspect))
            {
                Console.BackgroundColor = RenderComponent.Color[handle.Index];
                Console.Clear();

                var x = TransformComponent.X[handle.Index];
                var y = TransformComponent.Y[handle.Index];
                Console.SetCursorPosition(x, y);

                Console.Write(RenderComponent.Text[handle.Index]);
            }
        }
Ejemplo n.º 38
0
        public MemoryPolledReader(ISimulator sim)
            : base()
        {
            this.sim = sim;
            Active = true;

            // Start up thread
            ProcessName = sim.ProcessName;

            Poller = new Thread(Polling);
            Activate();

            Triton.TritonBase.PreExit += new Triton.AnonymousSignal(TritonBase_PreExit);
        }
Ejemplo n.º 39
0
        public Program(
			IInput input,
			IOutput output,
			IMessageBoard messageBoard,
			IDispatcher dispatcher,
			ISimulator simulator)
        {
            this.input = input;
            this.output = output;
            this.dispatcher = dispatcher;
            this.simulator = simulator;

            messageBoard.Receive<QuitCommand>(OnQuit);
        }
Ejemplo n.º 40
0
        public override void Process(ISimulator simulator, double tick)
        {
            foreach(var handle in simulator.GetHandlesForProcessor(Aspect))
            {
                if(VelocityComponent.MoveByX[handle.Index] != 0)
                {
                    TransformComponent.X[handle.Index] += VelocityComponent.MoveByX[handle.Index];
                    VelocityComponent.MoveByX[handle.Index] = 0;
                }

                if (VelocityComponent.MoveByY[handle.Index] != 0)
                {
                    TransformComponent.Y[handle.Index] += VelocityComponent.MoveByY[handle.Index];
                    VelocityComponent.MoveByY[handle.Index] = 0;
                }
            }
        }
        /// <summary>
        /// Generates Voltage Sensitivities to changes in P and Q at each load bus on
        /// the network.
        /// </summary>
        /// <remarks>
        /// This is a convenience class that uses the functionality supplied by
        /// <see cref="SensitivityGenerator{T}"/> and <see cref="PerturbAndObserveRunner{T}"/>.
        /// For other kinds of sensitivities, you may wish to use these classes directly.</remarks>
        /// <param name="Simulator">The simulator to use for the generation of sensitivities.</param>
        /// <param name="NetworkMasterFile">The file path of the Network to calculate sensitivities for.</param>
        /// <param name="CommandString">A command for issuing perturbations. The command should be
        /// compatible with <see cref="String.Format(String,Object[])"/>-style format strings, and should
        /// use <c>{0}</c> to represent a random ID, <c>{1}</c> to represent the bus that perturbation should occur
        /// on, <c>{2}</c> to represent a kW quantity to perturb by and <c>{3}</c> to represent a kVAr quantity to
        /// perturb by.
        /// <example>
        /// As an example, the following string specifies a new generator for perturbation in OpenDSS syntax:
        /// <code>
        /// "new Generator.{0} bus1={1} phases=3 model=1 status=fixed kV=11 Vminpu=0.9 Vmaxpu=1.1 kW={2} kvAR={3}"</code></example></param>
        /// <param name="PerturbationFrac">The fraction of average load size to perturb by.</param>
        /// <returns>A 2-axis dictionary, in which the X-axis represents the source bus, the Y-axis represents the affected bus,
        /// and the values are an index of sensitivity information.</returns>
        public static TwinKeyDictionary<String, String, VoltageSensitivityToPQDataSet> GetVoltageSensitivityToComplexPower(ISimulator Simulator, String NetworkMasterFile, String CommandString, double PerturbationFrac)
        {
            PerturbAndObserveRunner<Complex> perturbAndObserve = new PerturbAndObserveRunner<Complex>(Simulator);
            NetworkController controller = new NetworkController(Simulator);
            controller.NetworkFilename = NetworkMasterFile;
            controller.Execute();
            var avgLoad = controller.Network.Loads.Select(load=>load.ActualKVA).Aggregate((seed,elem) => seed+elem);
            avgLoad /= controller.Network.Loads.Count;
            perturbAndObserve.NetworkFilename = NetworkMasterFile;
            perturbAndObserve.ObserveElementSelector = network => network.Buses.Values.Where(bus => bus.ConnectedTo.OfType<Load>().Any());
            perturbAndObserve.PerturbElementSelector = perturbAndObserve.ObserveElementSelector;
            perturbAndObserve.PerturbCommands = new []{CommandString};
            perturbAndObserve.ObserveElementValuesSelector = elem => ((Bus)elem).Voltage;

            SensitivityGenerator<Complex> generator = new SensitivityGenerator<Complex>();

            //real
            perturbAndObserve.PerturbElementValuesSelector = bus => new Object[] {"inject-"+bus.ID,bus.ID,PerturbationFrac * avgLoad.Real, 0};
            perturbAndObserve.PerturbValuesToRecord = vars => vars[2];
            perturbAndObserve.RunPerturbAndObserve();

            generator.RecordedPerturbationSelector = x => x;
            generator.ResultSelector = x => x.Magnitude;

            var MagnitudeDictionaryReal = generator.GenerateSensitivities(perturbAndObserve);

            generator.ResultSelector = x => x.Phase;
            var PhaseDictionaryReal = generator.GenerateSensitivities(perturbAndObserve);

            //imaginary
            perturbAndObserve.PerturbElementValuesSelector = bus => new Object[] { "inject-" + bus.ID, bus.ID, 0, PerturbationFrac * avgLoad.Imaginary };
            perturbAndObserve.PerturbValuesToRecord = vars => vars[3];
            perturbAndObserve.RunPerturbAndObserve();

            generator.RecordedPerturbationSelector = x => x;
            generator.ResultSelector = x => x.Magnitude;

            var MagnitudeDictionaryImag = generator.GenerateSensitivities(perturbAndObserve);

            generator.ResultSelector = x => x.Phase;
            var PhaseDictionaryImag = generator.GenerateSensitivities(perturbAndObserve);

            // now merge all the dictionaries.
            return TwinKeyDictionaryMerge(MagnitudeDictionaryReal, MagnitudeDictionaryImag, PhaseDictionaryReal, PhaseDictionaryImag);
        }
Ejemplo n.º 42
0
        public override void Process(ISimulator simulator, double tick)
        {
            var transform = simulator.GetComponent<TransformComponent>();
              var velocity = simulator.GetComponent<VelocityComponent>();

              foreach (var handle in simulator.GetHandlesForProcessor(Aspect))
              {
            if (velocity.MoveByX[handle.Index] != 0)
            {
              transform.X[handle.Index] += velocity.MoveByX[handle.Index];
              velocity.MoveByX[handle.Index] = 0;
            }

            if (velocity.MoveByY[handle.Index] != 0)
            {
              transform.Y[handle.Index] += velocity.MoveByY[handle.Index];
              velocity.MoveByY[handle.Index] = 0;
            }
              }
        }
Ejemplo n.º 43
0
        /// <summary>
        /// Returns power in HP
        /// </summary>
        /// <param name="sim"></param>
        /// <param name="car"></param>
        /// <returns></returns>
        public double MaximumPower(ISimulator sim, ICar car)
        {
            if (sim.Garage == null)
                return 0;

            if (car == null)
            {
                // Look up car.
                car = sim.Garage.SearchCar(sim.Drivers.Player.CarClass, sim.Drivers.Player.CarModel);

                if (car == null)
                    return 0;

                car.ScanEngine();

                if (car.Engine == null )
                    return 0;
            }

            return car.Engine.GetMaximumPower();
        }
Ejemplo n.º 44
0
        //[/LockPositions]

        public SimWindow() : base(800, 600, GraphicsMode.Default, "Gravitational n-body simulation")
        {
            _numBodies = 256*64;
            const float clusterScale = 1.0f;
            const float velocityScale = 1.0f;
            _deltaTime = 0.001f;
            _softeningSquared = 0.00125f;
            _damping = 0.9995f;
            //[CreateWorker]
            _worker = Worker.CreateByFunc(Generate);
            //[/CreateWorker]

            _stopwatch = Stopwatch.StartNew();
            _fpsCalcLag = 128;
            _frameCounter = 0;

            //[CreateSimulatros]
            _simulators = new Queue<ISimulator>();
            var target = GPUModuleTarget.Worker(_worker);

            var simulatorGpuDynamicBlockSizeModule = new GpuDynamicSimulatorModule(target);         // need dispose
            var simulatorGpuDynamicBlockSize64 = simulatorGpuDynamicBlockSizeModule.Create(64);
            var simulatorGpuDynamicBlockSize128 = simulatorGpuDynamicBlockSizeModule.Create(128);
            var simulatorGpuDynamicBlockSize256 = simulatorGpuDynamicBlockSizeModule.Create(256);
            var simulatorGpuDynamicBlockSize512 = simulatorGpuDynamicBlockSizeModule.Create(512);

            var simulatorGpuStaticBlockSizeModule64 = new GpuStaticSimulatorModule64(target);       // need dispose
            var simulatorGpuStaticBlockSizeModule128 = new GpuStaticSimulatorModule128(target);     // need dispose
            var simulatorGpuStaticBlockSizeModule256 = new GpuStaticSimulatorModule256(target);     // need dispose
            var simulatorGpuStaticBlockSizeModule512 = new GpuStaticSimulatorModule512(target);     // need dispose

            // First, enquene one simulator which is 256 blocksize so we can compare with C code for performance.
            _simulators.Enqueue(simulatorGpuStaticBlockSizeModule256);

            // Enqueue several dynamic block size simulators.
            _simulators.Enqueue(simulatorGpuDynamicBlockSize64);
            _simulators.Enqueue(simulatorGpuDynamicBlockSize128);
            _simulators.Enqueue(simulatorGpuDynamicBlockSize256);
            _simulators.Enqueue(simulatorGpuDynamicBlockSize512);

            // Enqueue several static block size simulators.
            _simulators.Enqueue(simulatorGpuStaticBlockSizeModule64);
            _simulators.Enqueue(simulatorGpuStaticBlockSizeModule128);
            _simulators.Enqueue(simulatorGpuStaticBlockSizeModule256);
            _simulators.Enqueue(simulatorGpuStaticBlockSizeModule512);

            // We do not enqueue any cpu simulator as it is much too slow.
            //_simulators.Enqueue(new CpuSimulator(_worker, _numBodies));

            _disposeSimulators = () =>
            {
                simulatorGpuDynamicBlockSizeModule.Dispose();
                simulatorGpuStaticBlockSizeModule64.Dispose();
                simulatorGpuStaticBlockSizeModule128.Dispose();
                simulatorGpuStaticBlockSizeModule256.Dispose();
                simulatorGpuStaticBlockSizeModule512.Dispose();
            };

            _simulator = _simulators.Dequeue();
            //[/CreateSimulatros]

            //[CreateBuffers]
            _buffers = new uint[2];
            for (var i = 0; i < _buffers.Length; i++)
            {
                _buffers[i] = 0;
            }
            GL.GenBuffers(_buffers.Length, _buffers);
            foreach (var buffer in _buffers)
            {
                GL.BindBuffer(BufferTarget.ArrayBuffer, buffer);
                GL.BufferData(BufferTarget.ArrayBuffer,
                              (IntPtr) (Microsoft.FSharp.Core.Operators.SizeOf<float4>()*_numBodies), 
                              IntPtr.Zero, BufferUsageHint.DynamicDraw);
                var size = 0;
                unsafe
                {
                    GL.GetBufferParameter(BufferTarget.ArrayBuffer, BufferParameterName.BufferSize, &size);
                }
                if (size != Microsoft.FSharp.Core.Operators.SizeOf<float4>()*_numBodies)
                {
                    throw new Exception("Pixel Buffer Object allocation failed!");
                }
                GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
                CUDAInterop.cuSafeCall(CUDAInterop.cuGLRegisterBufferObject(buffer));
            }

            _resources = new IntPtr[_buffers.Length];
            for (var i = 0; i < _buffers.Length; i++)
            {
                var res = IntPtr.Zero;
                unsafe
                {
                    CUDAInterop.cuSafeCall(CUDAInterop.cuGraphicsGLRegisterBuffer(&res, _buffers[i], 0u));
                }
                _resources[i] = res;
            }
            //[/CreateBuffers]

            //[FinalizeGL]
            _vel = _worker.Malloc<float4>(_numBodies);

            float4[] hpos, hvel;
            BodyInitializer.Initialize(new BodyInitializer3(), clusterScale, velocityScale, _numBodies, 
                                       out hpos, out hvel);
            _worker.Scatter(hvel, _vel.Ptr, Microsoft.FSharp.Core.FSharpOption<int>.None,
                Microsoft.FSharp.Core.FSharpOption<int>.None);
            LockPos(
                (pos0, pos1) =>
                    _worker.Scatter(hpos, pos1, Microsoft.FSharp.Core.FSharpOption<int>.None,
                        Microsoft.FSharp.Core.FSharpOption<int>.None));

            Help();
            Description();
            //[/FinalizeGL]
        }
Ejemplo n.º 45
0
 public void AddedToSimulator(ISimulator simulator)
 {
     _simulator = simulator;
 }
Ejemplo n.º 46
0
 private static void StartSimulator(ISimulator simulator)
 {
     Console.WriteLine($"Starting Simulator: {simulator.Name}");
     if (s_simThread != null)
     {
         s_simThread.Abort();
         s_simThread.Join();
     }
     simulator.Initialize();
     s_simThread = new Thread(simulator.Start);
     s_simThread.Start();
 }
Ejemplo n.º 47
0
 //[GLswitchSimulators]
 public void SwitchSimulator()
 {
     _simulators.Enqueue(_simulator);
     _simulator = _simulators.Dequeue();
     Description();
     _frameCounter = 0;
     _stopwatch.Restart();
 }
Ejemplo n.º 48
0
        void ucGame_Chosen(object sim)
        {
            Sim = Telemetry.m.Sims.Sims.Find(delegate(ISimulator s) { return s.Name.Equals(sim.ToString()); });
            if (Sim.Garage == null)
                // TODO: Display errors.
                // TODO: Check if sim is installed.
                Window = GarageWindow.GameSelect;
            else
            {
                Window = GarageWindow.TrackCars;
                Sim.Garage.Scan();
            }

            Redraw();
        }
Ejemplo n.º 49
0
 public void RemovedFromSimulator(ISimulator simulator)
 {
     _simulator = null;
 }
Ejemplo n.º 50
0
 public abstract void Process(ISimulator space, double time);
Ejemplo n.º 51
0
 /// <summary>
 /// Fire Sim Stop event.
 /// </summary>
 /// <param name="me">Simulator stopped</param>
 internal void Report_SimStop(ISimulator me)
 {
     Debug.WriteLine("SimStop fired");
     if (Sim_Stop != null)
         Sim_Stop(me);
 }
Ejemplo n.º 52
0
 /// <summary>
 /// Load new track. Specify location of gamedirectory and file.
 /// </summary>
 /// <param name="sim">Source simulator of track</param>
 /// <param name="track">Relative path from gamedirectory to track file OR track name.</param>
 public void Track_Load(ISimulator sim, string track)
 {
     if (Net == null || !Net.IsClient)
     {
         Track = new Track.Track(sim, track);
     }
 }
Ejemplo n.º 53
0
 /// <summary>
 /// Fire Lap event.
 /// </summary>
 /// <param name="me">Simulator of which session stopped</param>
 internal void Report_Laps(ISimulator me, ILap lap)
 {
     Debug.WriteLine("Laps fired");
     if (Lap != null)
         Lap(me , lap);
 }
Ejemplo n.º 54
0
 public void setSimulator(ISimulator sim)
 {
     this.sim = sim;
         /*this.maxHeight = sim.maxHeight;
         this.mapSize = sim.mapSize;
         this.objects = sim.map.elements;
         this.action = sim.action;*/
         ready = true;
         SetupViewport();
 }
Ejemplo n.º 55
0
 public ZigzagPatternEA3()
 {
     m_simulator = new TickSimulator(this); //new RateSimulator()
 }
Ejemplo n.º 56
0
        private void ActionBack()
        {
            switch(Window)
            {
                case GarageWindow.GameSelect:
                    this.Close();
                    break;

                case GarageWindow.TrackCars:
                    Window = GarageWindow.GameSelect;
                    break;

                case GarageWindow.Mod:
                    Window = GarageWindow.TrackCars;
                    break;
            }
            if (Window == GarageWindow.GameSelect)
                Sim = null;
            Redraw();
        }
Ejemplo n.º 57
0
 /// <summary>
 /// Instantiates a <see cref="NetworkController"/> using the provided simulator.
 /// </summary>
 /// <param name="sim">The simulator object to use for simulations.</param>
 public NetworkController(ISimulator sim)
 {
     simulator = sim;
     CacheNetwork = true;
 }
Ejemplo n.º 58
0
 /// <summary>
 /// Fire Driving Stop event.
 /// </summary>
 /// <param name="sim">Simulator with drive session stopped</param>
 private void Report_DrivingStop(ISimulator sim)
 {
     Debug.WriteLine("DrivingStop fired");
     if (Driving_Stop != null)
         Driving_Stop(sim);
 }
Ejemplo n.º 59
0
 /// <summary>
 /// Fire Session Stop event.
 /// </summary>
 /// <param name="me">Simulator of which session stopped</param>
 internal void Report_SessionStop(ISimulator me)
 {
     Debug.WriteLine("SessionStop fired");
     if (Session_Stop != null)
         Session_Stop(me);
 }
Ejemplo n.º 60
0
 private void m_Lap(ISimulator sim, ILap lap)
 {
     if (Telemetry.m.Sim != null)
     {
         Time_Start = Telemetry.m.Sim.Session.Time; // TODO: add local timing if not supported.
         // Get the last lap from the game.
         PreviousRecords = false;
         _mUpdateBestLap.Start();
     }
 }