Beispiel #1
0
 public static void Initialize(         
  IConsole console,
  ISurface surface,
  IStyle style,
  IDrawings drawing,
  IShapes shapes,
  IImages images,
  IControls controls,
  ISounds sounds,         
  IKeyboard keyboard,
  IMouse mouse,
  ITimer timer,
  IFlickr flickr,
  ISpeech speech,
  CancellationToken token)
 {
     TextWindow.Init(console);
      Desktop.Init(surface);
      GraphicsWindow.Init(style, surface, drawing, keyboard, mouse);
      Shapes.Init(shapes);
      ImageList.Init(images);
      Turtle.Init(surface, drawing, shapes);
      Controls.Init(controls);
      Sound.Init(sounds);
      Timer.Init(timer);
      Stack.Init();
      Flickr.Init(flickr);
      Speech.Init(speech);
      Program.Init(token);
 }
Beispiel #2
0
        public World(IControls controls)
        {
            _controls = controls;

            _start = new State
            {
                Update = StartUpdate,
                Draw = StartDraw
            };
            _alive = new State
            {
                Update = AliveUpdate,
                Draw = AliveDraw
            };
            _dead = new State
            {
                Update = DeadUpdate,
                Draw = DeadDraw
            };
            _gameOver = new State
            {
                Update = GameOverUpdate,
                Draw = GameOverDraw
            };

            _state = _start;
            _viewer = new Viewer();
            _bird = new Bird(controls);
            _pipeCollection = new PipeCollection();
        }
        public FaceDetectionService(
            IDatabaseService databaseService,
            IControls controls,
            IParameters parameters,
            IFileDirectoryService fileDirectoryService,
            ILocalStorageService localStorageService, IFaceRecogntionService faceRecogntionService)
        {
            _controls              = controls;
            _parameters            = parameters;
            _fileDirectoryService  = fileDirectoryService;
            _localStorageService   = localStorageService;
            _faceRecogntionService = faceRecogntionService;
            _databaseService       = databaseService;

            _faces = new List <Rectangle>();
            _eyes  = new List <Rectangle>();

            StartServices();

            _saveWorker = new BackgroundWorker
            {
                WorkerSupportsCancellation = true
            };

            _saveWorker.DoWork             += _saveWorker_DoWork;
            _saveWorker.RunWorkerCompleted += _saveWorker_RunWorkerCompleted;
        }
    // Update is called once per frame
    void Update()
    {
        isGrounded = Physics2D.OverlapCircle(groundCheckTransform.position, 0.1f, groundCheckLayerMask);

        if (health.currentValue <= 0 && isAlive)
        {
            Debug.Log("Player died!");
            die();
        }

        if (gameState.getState() == GameState.GameStateEnum.Running)
        {
            handleControls();
        }

        if (vehicleState == VehicleStateEnum.Ground)
        {
            currentControls = car;
        }
        else if (vehicleState == VehicleStateEnum.Fly)
        {
            currentControls = fly;
        }

        helicopterEnergyHandler();
        IndicateHeart();
    }
Beispiel #5
0
        public World(IControls controls)
        {
            _controls = controls;

            _start = new State
            {
                Update = StartUpdate,
                Draw   = StartDraw
            };
            _alive = new State
            {
                Update = AliveUpdate,
                Draw   = AliveDraw
            };
            _dead = new State
            {
                Update = DeadUpdate,
                Draw   = DeadDraw
            };
            _gameOver = new State
            {
                Update = GameOverUpdate,
                Draw   = GameOverDraw
            };

            _state          = _start;
            _viewer         = new Viewer();
            _bird           = new Bird(controls);
            _pipeCollection = new PipeCollection();
        }
Beispiel #6
0
 public static void Initialize(
     IConsole console,
     ISurface surface,
     IStyle style,
     IDrawings drawing,
     IShapes shapes,
     IImages images,
     IControls controls,
     ISounds sounds,
     IKeyboard keyboard,
     IMouse mouse,
     ITimer timer,
     IFlickr flickr,
     ISpeech speech,
     CancellationToken token)
 {
     TextWindow.Init(console);
     Desktop.Init(surface);
     GraphicsWindow.Init(style, surface, drawing, keyboard, mouse);
     Shapes.Init(shapes);
     ImageList.Init(images);
     Turtle.Init(surface, drawing, shapes);
     Controls.Init(controls);
     Sound.Init(sounds);
     Timer.Init(timer);
     Stack.Init();
     Flickr.Init(flickr);
     Speech.Init(speech);
     Program.Init(token);
 }
Beispiel #7
0
        public CarService(IEngineService engineService, IBrakeService brakeService, IControls controls)
        {
            _engineService = engineService;
            _brakeService  = brakeService;
            _controls      = controls;

            Name = $"Car: {Guid.NewGuid().ToString()}";
        }
Beispiel #8
0
 void Start()
 {
     controller           = new PythonControls(maxTorque, "Assets/Scripts/robot.py");
     sensors              = new Dictionary <string, GetSensorValISensor>();
     sensors["rightProx"] = new GetSensorValISensor(transform.Find("robot_body").Find("RightProxSensor").gameObject.GetComponent <ISensor>().getSensorValue);
     sensors["leftProx"]  = new GetSensorValISensor(transform.Find("robot_body").Find("LeftProxSensor").gameObject.GetComponent <ISensor>().getSensorValue);
     sensorData           = new Dictionary <string, float>();
 }
Beispiel #9
0
        public virtual void initialize(Game game, InputHandler inputHandler, ControlType controlType)
        {
            input = inputHandler;

            input.Initialize();
            hud.Initialize();

            switch (controlType)
            {
            case ControlType.buttons:
                controls = new ButtonControls();
                break;

            case ControlType.motion:
                controls = new TapControls();
                break;
            }

            level = 1;
            score = 0;
            bonus = 1;

            ColorData.setColors();
            TextureData.setTexture();

            mainGrid    = new GridType(new Vector2(36, 14), new Vector2(20), 10, 19);
            previewGrid = new GridType(new Vector2(12, 426), new Vector2(20), 4, 2);

            mainGrid.initialize();
            previewGrid.initialize();

            random = new Random();

            mainBlock    = randomize();
            previewBlock = randomize();

            controls.initializeInput(input);
            input.addMotion("Pause", new Press(new Rectangle(52, 0, 160, 10)));

            initializeHUD(game.GraphicsDevice);

            fallCounter = new CounterType(data.StartSpeed);
            fallCounter.setEvent(Drop);

            accelFallCounter = new CounterType(5);
            accelFallCounter.setEvent(AccelDrop);

            movementCounter = new CounterType(5);
            movementCounter.setEvent(Move);

            updateCounter = new CounterType(30);
            updateCounter.setEvent(Update);

            bonusCounter = new CounterType(900);
            bonusCounter.setEvent(ReduceBonus);

            game.Components.Add(hud);
        }
    void transformToFly()
    {
        playerAnimator.SetBool("isGroundVehicle", false);
        car.disable();
        fly.enable();
        vehicleState = VehicleStateEnum.Fly;

        currentControls = fly;
    }
 //todo: przerobic na serwis
 public static void ResestStatus(IControls controls)
 {
     Task.Delay(700).ContinueWith(_ =>
     {
         controls.StatusText  = StatusTypes.Ready.GetDesciption();
         controls.IsNewUpdate = false;
     }
                                  );
 }
Beispiel #12
0
 public void Init()
 {
     shipSystem                   = SystemController.Instance.ShipSystems.FirstOrDefault(x => x.SystemType == systemType);
     powerButton.onToggle        += ToggleSystemPower;
     depressurizeButton.onToggle += ToggleDepressurise;
     lockButton.onToggle         += ToggleLock;
     specificControl              = specificControlPrefab.GetComponent <IControls>();
     specificControl.Init();
 }
Beispiel #13
0
 /// <summary>
 /// Met deze constructor wordt een Button aangemaakt die een toets representeert.
 /// </summary>
 /// <param name="Eresys.Controls">Controls object dat zal worden gebruikt om de status van de toets op te vragen.</param>
 /// <param name="key">karakter v/d toets</param>
 /// <param name="type">type van de toets (key of trigger)</param>
 public Button(Key key, ButtonType type, IControls controls)
 {
     _controls      = controls;
     this.enabled   = true;
     this.mouse     = false;
     this.key       = key;
     this.type      = type;
     this.wasActive = false;
 }
    void transformToCar()
    {
        playerAnimator.SetBool("isGroundVehicle", true);
        fly.disable();
        car.enable();
        vehicleState = VehicleStateEnum.Ground;

        currentControls = car;
    }
 public FaceRecognitionService(IDatabaseService databaseService,
                               IControls controls, IParameters parameters,
                               IFileDirectoryService directoryService, ILocalStorageService localStorageService)
 {
     _databaseService     = databaseService;
     _parameters          = parameters;
     _controls            = controls;
     _directoryService    = directoryService;
     _localStorageService = localStorageService;
 }
Beispiel #16
0
        public Bird(IControls controls)
        {
            _controls = controls;

            _body = new Body()
            {
                InitialPosition = new Vector2(200.0f, 200.0f),
                InitialVelocity = new Vector2(300.0f, 0.0f)
            };
        }
Beispiel #17
0
        public Bird(IControls controls)
        {
            _controls = controls;

            _body = new Body()
            {
                InitialPosition = new Vector2(200.0f, 200.0f),
                InitialVelocity = new Vector2(300.0f, 0.0f)
            };
        }
 public ControlUpdater(IStateProvider stateProvider, IControls controls)
 {
     if (stateProvider == null)
     {
         throw new ArgumentNullException(nameof(stateProvider));
     }
     if (controls == null)
     {
         throw new ArgumentNullException(nameof(controls));
     }
     _stateProvider = stateProvider;
     _controls      = controls;
 }
Beispiel #19
0
        public virtual void initializeControls(ControlType controlType)
        {
            switch (controlType)
            {
            case ControlType.buttons:
                controls = new ButtonControls();
                break;

            case ControlType.motion:
                controls = new TapControls();
                break;
            }
        }
Beispiel #20
0
 public MainMenuState(IControls controls, IStateManager stateManager)
 {
     _controls     = controls;
     _stateManager = stateManager;
     Children      = new IRenderable[] {
         new TextComponent("Stupid Princess!", new Position(1, 1))
         {
             RenderedColor = ConsoleColor.Magenta
         },
         new TextComponent("Controls:", new Position(1 + 4, 3)),
         new TextComponent("Arrow Keys - Move Cursor", new Position(1 + 4 * 2, 4)),
         new TextComponent("[Press Any Key to Begin!]", new Position(1, 6))
         {
             RenderedColor = ConsoleColor.Yellow
         },
     };
 }
        // Use this for initialization
        private void Start()
        {
            _CharacterController = GetComponent <CharacterController>();
            _AudioSource         = GetComponent <AudioSource>();
            _Controls            = GameObject.FindGameObjectWithTag(Tags.GameController).GetComponent <IControls>();
            _Camera   = Camera.main;
            _Animator = GetComponent <Animator>();


            _OriginalCameraPosition = _Camera.transform.localPosition;
            _FovKick.Setup(_Camera);
            _HeadBob.Setup(_Camera, _StepInterval);
            _MouseLook.Init(transform, _Camera.transform);

            _StepCycle       = 0f;
            _NextStep        = _StepCycle / 2f;
            _Jumping         = false;
            _CharacterHeight = _CharacterController.height;
        }
    // Use this for initialization
    void Start()
    {
        float height = 2.0f * Camera.main.orthographicSize;

        screenWidthInPoints = height * Camera.main.aspect;

        spawner                = GetComponent <SpawnHandler>();
        playerAudio            = GetComponent <AudioSource>();
        car                    = GetComponent <CarControls>();
        fly                    = GetComponent <FlyControls>();
        gameState              = GetComponent <GameState>();
        playerRenderer         = GetComponent <SpriteRenderer>();
        playerAnimator         = GetComponent <Animator>();
        heartIndicatorRenderer = heartIndicator.GetComponent <SpriteRenderer>();

        // Start on ground
        vehicleState    = VehicleStateEnum.Ground;
        currentControls = car;
    }
Beispiel #23
0
 internal static void Init(IControls controls)
 {
     _controls = controls;
 }
Beispiel #24
0
 protected DependentActions()
 {
     _controls = IoC.Resolve <IControls>(Configuration.BrowserName);
 }
 protected DependentActions()
 {
     _controls = IoC.Resolve<IControls>(Configuration.BrowserName);
 }
Beispiel #26
0
 public Cursor(IControls controls)
 {
     _controls = controls;
 }
Beispiel #27
0
        public void Setup(int cx, int cy)
        {
            this._cx = cx;
            this._cy = cy;

            // Version strings
            _version.Retrieve();

            // Get OpenGL extensions
            _extensions.Retrieve();

            // Debug callback
            _debug_callback.Init();

            // create Vertex Array Object, Array Buffer Object and Element Array Buffer Object

            (float[] attributes, uint[] indices) = new Cube().Create();
            TVertexFormat[] format =
            {
                new TVertexFormat(0, 0, 3, 0, false),
                new TVertexFormat(0, 1, 3, 3, false),
                //new TVertexFormat(0, ?, 2, 6, false),
                new TVertexFormat(0, 2, 4, 8, false),
            };

            _test_vao = openGLFactory.NewVertexArrayObject();
            _test_vao.AppendVertexBuffer(0, 12, attributes);
            _test_vao.Create(format, indices);
            _test_vao.Bind();

            // Create shader program

            string vert_shader = @"#version 460 core
            layout (location = 0) in vec4 a_pos;
            layout (location = 1) in vec3 a_nv;
            layout (location = 2) in vec4 a_color;
      
            layout (location = 0) out TVertexData
            {
                vec3 pos;
                vec3 nv;
                vec4 col;
            } outData;

            layout(std430, binding = 1) buffer MVP
            {
                mat4 proj;
                mat4 view;
                mat4 model;
            } mvp;

            void main()
            {
                mat4 mv_mat     = mvp.view * mvp.model;
                mat3 normal_mat = inverse(transpose(mat3(mv_mat))); 

                outData.nv   = normalize(normal_mat * a_nv);
                outData.col  = a_color;
                vec4 viewPos = mv_mat * a_pos;
                outData.pos  = viewPos.xyz / viewPos.w;
                gl_Position  = mvp.proj * viewPos;
            }";

            string frag_shader = @"#version 460 core
            out vec4 frag_color;
            
            layout (location = 0) in TVertexData
            {
                vec3 pos;
                vec3 nv;
                vec4 col;
            } inData;

            layout(std430, binding = 2) buffer TLight
            {
                vec4  u_lightDir;
                float u_ambient;
                float u_diffuse;
                float u_specular;
                float u_shininess;
            } light_data;
      
            void main()
            {
                vec3 color = inData.col.rgb;

                // ambient part
                vec3 lightCol = light_data.u_ambient * color;
                vec3 normalV  = normalize( inData.nv );
                vec3 eyeV     = normalize( -inData.pos );
                vec3 lightV   = normalize( -light_data.u_lightDir.xyz );

                // diffuse part
                float NdotL   = max( 0.0, dot( normalV, lightV ) );
                lightCol     += NdotL * light_data.u_diffuse * color;

                // specular part
                vec3  halfV     = normalize( eyeV + lightV );
                float NdotH     = max( 0.0, dot( normalV, halfV ) );
                float kSpecular = ( light_data.u_shininess + 2.0 ) * pow( NdotH, light_data.u_shininess ) / ( 2.0 * 3.14159265 );
                lightCol       += kSpecular * light_data.u_specular * color;

                frag_color = vec4( lightCol.rgb, inData.col.a );
            }";

            this._test_prog = openGLFactory.VertexAndFragmentShaderProgram(vert_shader, frag_shader);
            this._test_prog.Generate();

            // Model view projection shader storage block objects and buffers
            TMVP mvp = new TMVP(Matrix4.Identity, Matrix4.Identity, Matrix4.Identity);

            this._mvp_ssbo = openGLFactory.NewStorageBuffer();
            this._mvp_ssbo.Create(ref mvp);
            this._mvp_ssbo.Bind(1);

            TLightSource light_source = new TLightSource(new Vector4(-1.0f, -0.5f, -2.0f, 0.0f), 0.2f, 0.8f, 0.8f, 10.0f);

            this._light_ssbo = openGLFactory.NewStorageBuffer();
            this._light_ssbo.Create(ref light_source);
            this._light_ssbo.Bind(2);

            this._depth_pack_buffer = openGLFactory.NewPixelPackBuffer();
            this._depth_pack_buffer.Create <float>();

            // states

            GL.Viewport(0, 0, this._cx, this._cy);
            //GL.ClearColor(System.Drawing.Color.Beige);
            GL.ClearColor(0.2f, 0.3f, 0.3f, 1.0f);
            GL.Enable(EnableCap.DepthTest);
            GL.Enable(EnableCap.CullFace);
            GL.FrontFace(FrontFaceDirection.Ccw);
            GL.CullFace(CullFaceMode.Back);

            // matrices and controller

            this._view = Matrix4.LookAt(0.0f, -4.0f, 0.0f, 0, 0, 0, 0, 0, 1);

            float angle  = 90.0f * (float)Math.PI / 180.0f;
            float aspect = (float)this._cx / (float)this._cy;

            this._projection = Matrix4.CreatePerspectiveFieldOfView(angle, aspect, 0.1f, 100.0f);

            _controls = new NavigationControls(
                () => { return(new float[] { 0, 0, (float)this._cx, (float)this._cy }); },
                () => { return(this._view); },
                () => { return(this._projection); },
                this.GetDepth,
                (cursor_pos) => { return(new Vector3(0, 0, 0)); },
                (Matrix4 view) => { this._view = view; }
                );
        }
Beispiel #28
0
 public void Awake()
 {
     controls = gameObject.GetComponent <IControls>();
 }
Beispiel #29
0
 private void Start()
 {
     _controls = GameObject.FindGameObjectWithTag(Tags.GameController).GetComponent <IControls>();
 }
 public GamePadController(IControls controls)
 {
     buttonMappings = controls.RetrieveGamePadControls();
     prevState = GamePad.GetState(PlayerIndex.One);
 }
Beispiel #31
0
        /********************************************************
         * CLASS METHODS
         *********************************************************/
        /// <summary>
        /// Primary Analysis Thread:
        /// </summary>
        public static void Main(string[] args)
        {
            //Initialize:
            AlgorithmNodePacket job = null;
            var timer     = Stopwatch.StartNew();
            var algorithm = default(IAlgorithm);

            //Name thread for the profiler:
            Thread.CurrentThread.Name = "Algorithm Analysis Thread";
            Log.Trace("Engine.Main(): Started " + DateTime.Now.ToShortTimeString());
            Log.Trace("Engine.Main(): Memory " + OS.ApplicationMemoryUsed + "Mb-App  " + +OS.TotalPhysicalMemoryUsed + "Mb-Used  " + OS.TotalPhysicalMemory + "Mb-Total");

            //Import external libraries specific to physical server location (cloud/local)
            var catalog = new AggregateCatalog();

            catalog.Catalogs.Add(new DirectoryCatalog(@"../../Extensions"));
            var container = new CompositionContainer(catalog);

            try
            {
                // grab the right export based on configuration
                Notify   = container.GetExportedValueByTypeName <IMessagingHandler>(Config.Get("messaging-handler"));
                Tasks    = container.GetExportedValueByTypeName <ITaskHandler>(Config.Get("task-handler"));
                Controls = container.GetExportedValueByTypeName <IControls>(Config.Get("controls-handler"));
            }
            catch (CompositionException compositionException)
            { Log.Error("Engine.Main(): Failed to load library: " + compositionException); }

            //Setup packeting, queue and controls system: These don't do much locally.
            Controls.Initialize();
            Notify.Initialize();
            Tasks.Initialize(_liveMode);

            //Start monitoring the backtest active status:
            var statusPingThread = new Thread(StateCheck.Ping.Run);

            statusPingThread.Start();

            do
            {
                try
                {
                    //Clean up cache directories:
                    CleanUpDirectories();

                    //Reset algo manager internal variables preparing for a new algorithm.
                    AlgorithmManager.ResetManager();

                    //Reset thread holders.
                    var    initializeComplete = false;
                    Thread threadFeed         = null;
                    Thread threadTransactions = null;
                    Thread threadResults      = null;
                    Thread threadRealTime     = null;

                    //-> Pull job from QuantConnect job queue, or, pull local build:
                    var algorithmPath = "";
                    job = Tasks.NextTask(out algorithmPath); // Blocking.

                    //-> Initialize messaging system
                    Notify.SetChannel(job.Channel);

                    //-> Reset the backtest stopwatch; we're now running the algorithm.
                    timer.Restart();

                    //-> Create SetupHandler to configure internal algorithm state:
                    SetupHandler = GetSetupHandler(job.SetupEndpoint);

                    //-> Set the result handler type for this algorithm job, and launch the associated result thread.
                    ResultHandler = GetResultHandler(job);
                    threadResults = new Thread(ResultHandler.Run, 0)
                    {
                        Name = "Result Thread"
                    };
                    threadResults.Start();

                    try
                    {
                        // Save algorithm to cache, load algorithm instance:
                        algorithm = SetupHandler.CreateAlgorithmInstance(algorithmPath);

                        //Initialize the internal state of algorithm and job: executes the algorithm.Initialize() method.
                        initializeComplete = SetupHandler.Setup(algorithm, out _brokerage, job);

                        //If there are any reasons it failed, pass these back to the IDE.
                        if (!initializeComplete || algorithm.ErrorMessages.Count > 0 || SetupHandler.Errors.Count > 0)
                        {
                            initializeComplete = false;
                            //Get all the error messages: internal in algorithm and external in setup handler.
                            var errorMessage = String.Join(",", algorithm.ErrorMessages);
                            errorMessage += String.Join(",", SetupHandler.Errors);
                            throw new Exception(errorMessage);
                        }
                    }
                    catch (Exception err)
                    {
                        ResultHandler.RuntimeError("Algorithm.Initialize() Error: " + err.Message, err.StackTrace);
                    }

                    //-> Using the job + initialization: load the designated handlers:
                    if (initializeComplete)
                    {
                        //Set algorithm as locked; set it to live mode if we're trading live, and set it to locked for no further updates.
                        algorithm.SetAlgorithmId(job.AlgorithmId);
                        algorithm.SetLiveMode(LiveMode);
                        algorithm.SetLocked();

                        //Load the associated handlers for data, transaction and realtime events:
                        ResultHandler.SetAlgorithm(algorithm);
                        DataFeed           = GetDataFeedHandler(algorithm, _brokerage, job);
                        TransactionHandler = GetTransactionHandler(algorithm, _brokerage, ResultHandler, job);
                        RealTimeHandler    = GetRealTimeHandler(algorithm, _brokerage, DataFeed, ResultHandler, job);

                        //Set the error handlers for the brokerage asynchronous errors.
                        SetupHandler.SetupErrorHandler(ResultHandler, _brokerage);

                        //Send status to user the algorithm is now executing.
                        ResultHandler.SendStatusUpdate(job.AlgorithmId, AlgorithmStatus.Running);

                        //Launch the data, transaction and realtime handlers into dedicated threads
                        threadFeed = new Thread(DataFeed.Run, 0)
                        {
                            Name = "DataFeed Thread"
                        };
                        threadTransactions = new Thread(TransactionHandler.Run, 0)
                        {
                            Name = "Transaction Thread"
                        };
                        threadRealTime = new Thread(RealTimeHandler.Run, 0)
                        {
                            Name = "RealTime Thread"
                        };

                        //Launch the data feed, result sending, and transaction models/handlers in separate threads.
                        threadFeed.Start();         // Data feed pushing data packets into thread bridge;
                        threadTransactions.Start(); // Transaction modeller scanning new order requests
                        threadRealTime.Start();     // RealTime scan time for time based events:
                                                    // Result manager scanning message queue: (started earlier)

                        try
                        {
                            // Execute the Algorithm Code:
                            var complete = Isolator.ExecuteWithTimeLimit(SetupHandler.MaximumRuntime, () =>
                            {
                                try
                                {
                                    //Run Algorithm Job:
                                    // -> Using this Data Feed,
                                    // -> Send Orders to this TransactionHandler,
                                    // -> Send Results to ResultHandler.
                                    AlgorithmManager.Run(job, algorithm, DataFeed, TransactionHandler, ResultHandler, SetupHandler, RealTimeHandler);
                                }
                                catch (Exception err)
                                {
                                    //Debugging at this level is difficult, stack trace needed.
                                    Log.Error("Engine.Run(): Error in Algo Manager: " + err.Message + " ST >> " + err.StackTrace);
                                }

                                Log.Trace("Engine.Run(): Exiting Algorithm Manager");
                            }, MaximumRamAllocation);

                            if (!complete)
                            {
                                Log.Error("Engine.Main(): Failed to complete in time: " + SetupHandler.MaximumRuntime.ToString("F"));
                                throw new Exception("Failed to complete algorithm within " + SetupHandler.MaximumRuntime.ToString("F") + " seconds. Please make it run faster.");
                            }

                            // Algorithm runtime error:
                            if (AlgorithmManager.RunTimeError != null)
                            {
                                throw AlgorithmManager.RunTimeError;
                            }
                        }
                        catch (Exception err)
                        {
                            //Log:
                            Log.Error("Engine.Run(): Breaking out of parent try-catch: " + err.Message + " " + err.StackTrace);
                            //Error running the user algorithm: purge datafeed.
                            if (DataFeed != null)
                            {
                                DataFeed.Exit();
                            }
                            //Send the error message:
                            if (ResultHandler != null)
                            {
                                ResultHandler.RuntimeError("Runtime Error: " + err.Message, err.StackTrace);
                            }
                        }

                        //Send result data back: this entire code block could be rewritten.
                        // todo: - Split up statistics class, its enormous.
                        // todo: - Make a dedicated Statistics.Benchmark class.
                        // todo: - Elegently manage failure scenarios where no equity present.
                        // todo: - Move all creation and transmission of statistics out of primary engine loop.
                        // todo: - Statistics.Generate(algorithm, resulthandler, transactionhandler);

                        try
                        {
                            var charts     = new Dictionary <string, Chart>(ResultHandler.Charts);
                            var orders     = new Dictionary <int, Order>(TransactionHandler.Orders);
                            var holdings   = new Dictionary <string, Holding>();
                            var statistics = new Dictionary <string, string>();
                            var banner     = new Dictionary <string, string>();

                            try
                            {
                                //Generates error when things don't exist (no charting logged, runtime errors in main algo execution)
                                var equity      = charts["Strategy Equity"].Series["Equity"].Values;
                                var performance = charts["Daily Performance"].Series["Performance"].Values;
                                var profitLoss  = new SortedDictionary <DateTime, decimal>(algorithm.Transactions.TransactionRecord);
                                statistics = Statistics.Statistics.Generate(equity, profitLoss, performance, SetupHandler.StartingCapital, 252);
                            }
                            catch (Exception err) {
                                Log.Error("Algorithm.Node.Engine(): Error generating result packet: " + err.Message);
                            }

                            //Diagnostics Completed:
                            ResultHandler.DebugMessage("Algorithm Id:(" + job.AlgorithmId + ") completed analysis in " + timer.Elapsed.TotalSeconds.ToString("F2") + " seconds");

                            //Send the result packet:
                            ResultHandler.SendFinalResult(job, orders, algorithm.Transactions.TransactionRecord, holdings, statistics, banner);
                        }
                        catch (Exception err)
                        {
                            Log.Error("Engine.Main(): Error sending analysis result: " + err.Message + "  ST >> " + err.StackTrace);
                        }

                        //Before we return, send terminate commands to close up the threads
                        timer.Stop();               //Algorithm finished running.
                        TransactionHandler.Exit();
                        DataFeed.Exit();
                        RealTimeHandler.Exit();
                        AlgorithmManager.ResetManager();
                    }

                    //Close result handler:
                    ResultHandler.Exit();

                    //Wait for the threads to complete:
                    Log.Trace("Engine.Main(): Waiting for threads to deactivate...");
                    var ts = Stopwatch.StartNew();
                    while ((ResultHandler.IsActive || (TransactionHandler != null && TransactionHandler.IsActive) || (DataFeed != null && DataFeed.IsActive)) && ts.ElapsedMilliseconds < 60 * 1000)
                    {
                        Thread.Sleep(100);
                        DataFeed.Exit();
                        Log.Trace("WAITING >> Result: " + ResultHandler.IsActive + " Transaction: " + TransactionHandler.IsActive + " DataFeed: " + DataFeed.IsActive + " RealTime: " + RealTimeHandler.IsActive);
                    }

                    Log.Trace("Engine.Main(): Closing Threads...");
                    if (threadFeed != null && threadFeed.IsAlive)
                    {
                        threadFeed.Abort();
                    }
                    if (threadTransactions != null && threadTransactions.IsAlive)
                    {
                        threadTransactions.Abort();
                    }
                    if (threadResults != null && threadResults.IsAlive)
                    {
                        threadResults.Abort();
                    }
                    Log.Trace("Engine.Main(): Analysis Completed and Results Posted.");
                }
                catch (Exception err)
                {
                    Log.Error("Engine.Main(): Error running algorithm: " + err.Message + " >> " + err.StackTrace);
                }
                finally
                {
                    //Delete the message from the queue before another worker picks it up:
                    Tasks.AcknowledgeTask(job);
                    Log.Trace("Engine.Main(): Packet removed from queue: " + job.AlgorithmId);
                    GC.Collect();
                }

                //If we're running locally will execute just once.
            } while (!IsLocal);

            // Send the exit signal and then kill the thread
            StateCheck.Ping.Exit();

            // Make the console window pause so we can read log output before exiting and killing the application completely
            System.Console.ReadKey();

            //Finally if ping thread still not complete, kill.
            if (statusPingThread != null && statusPingThread.IsAlive)
            {
                statusPingThread.Abort();
            }
        }
 public bool Equals(IControls other)
 {
     return(Equals(other as SafeComWrapper <VB.SelectedVBControls>));
 }
 public ControlsParserContext(IControls controls, string promptPrefix)
 {
     _promptPrefix = promptPrefix;
     Commands      = new[]
     {
         new CommandInformation()
         {
             ArgumentCount         = 1,
             CommandText           = "clear",
             CommandImplementation = (args, parserContextManager) =>
             {
                 controls.Clear();
                 return(false);
             }
         },
         new CommandInformation()
         {
             ArgumentCount         = 1,
             CommandText           = "print",
             CommandImplementation = (args, parserContextManager) =>
             {
                 controls.ToList().ForEach(control => Console.WriteLine(control.Name));
                 return(false);
             }
         },
         new CommandInformation()
         {
             ArgumentCount         = 2,
             CommandText           = "add",
             CommandImplementation = (args, parserContextManager) =>
             {
                 if (controls.Any(control => control.Name == args[1]))
                 {
                     Console.WriteLine($"Duplicate control ignored: {args[1]}");
                 }
                 else
                 {
                     var control = new TestCases.PublicObjects.Control()
                     {
                         Name = args[1]
                     };
                     controls.Add(control);
                     parserContextManager.PushContext(new StatesParserContext(control.States, control.Name));
                 }
                 return(false);
             }
         },
         new CommandInformation()
         {
             ArgumentCount         = 3,
             CommandText           = "reference",
             CommandImplementation = (args, parserContextManager) =>
             {
                 if (controls.Any(control => control.Name == args[1]))
                 {
                     Console.WriteLine($"Duplicate control ignored: {args[1]}");
                 }
                 else
                 {
                     var control = new TestCases.PublicObjects.ControlReference()
                     {
                         Name = args[1], ReferenceName = args[2]
                     };
                     controls.Add(control);
                     parserContextManager.PushContext(new StatesParserContext(control.States, control.Name));
                 }
                 return(false);
             }
         },
         new CommandInformation()
         {
             ArgumentCount         = 2,
             CommandText           = "delete",
             CommandImplementation = (args, parserContextManager) =>
             {
                 var item = controls.SingleOrDefault(control => control.Name == args[1]);
                 if (item == default(IControl))
                 {
                     Console.WriteLine($"Missing control not deleted: {args[1]}");
                 }
                 else
                 {
                     controls.Remove(item);
                 }
                 return(false);
             }
         },
         new CommandInformation()
         {
             ArgumentCount         = 2,
             CommandText           = "select",
             CommandImplementation = (args, parserContextManager) =>
             {
                 var item = controls.SingleOrDefault(control => control.Name == args[1]);
                 if (item == default(IControl))
                 {
                     Console.WriteLine($"Missing control not selected: {args[1]}");
                 }
                 else
                 {
                     parserContextManager.PushContext(new StatesParserContext(item.States, item.Name));
                 }
                 return(false);
             }
         },
     };
 }
Beispiel #34
0
        private static (DeclarationType, string Name) GetSelectedName(IVBComponent component, IControls selectedControls, int selectedCount)
        {
            // Cannot use DeclarationType.UserForm, parser only assigns UserForms the ClassModule flag
            if (selectedCount == 0)
            {
                return(DeclarationType.ClassModule, component.Name);
            }

            using (var firstSelectedControl = selectedControls[0])
            {
                return(DeclarationType.Control, firstSelectedControl.Name);
            }
        }
Beispiel #35
0
 public Level01(IControls controls)
 {
     _maze = MazeLoader.Load("Game/MainGame/level01.txt");
     _maze.AddEntity(new Cursor(controls));
     _statusBar = new StatusBar();
 }
Beispiel #36
0
 public bool Equals(IControls other)
 {
     return(Equals(other as SafeComWrapper <VB.Forms.Controls>));
 }
 public KeyboardController(IControls controls)
 {
     keyMappings = controls.RetrieveKeyboardControls();
     prevPressedKeys = Keyboard.GetState().GetPressedKeys();
 }