public void ItShouldHandleStart() { var sampleGuid = Guid.NewGuid(); var sampleCommand = new Start { Id = sampleGuid }; var expectedEvent = new Started { Id = sampleGuid }; sut.Publish(sampleCommand); publishedEvent.ShouldBeEquivalentTo(expectedEvent); }
public void ItShouldHandleStart() { var sampleGuid = Guid.NewGuid(); var sampleCommand = new Start { Id = sampleGuid }; var expectedEvent = new Started { Id = sampleGuid }; sut.Publish(sampleCommand); var publishedEvent = publishedEvents.Single(@event => @event.GetType() == typeof(Started)); publishedEvent.Should().BeOfType<Started>(); publishedEvent.ShouldBeEquivalentTo(expectedEvent); }
/// <summary> /// Perform a one-time startup of the application connecting to Wayland and getting access to any required resources. /// </summary> public void Startup() { // Ensure we have not already started up if (IsStarted) { throw new Exception("Cannot start the application more than once"); } // Connect to the Wayland display if (_display == null) // Check for zero incase previous partial startup { _display = Display.Connect(); } // Now hookup to the registry if (Registry == null) // Check for zero incase previous partial startup { Registry = Registry.Get(_display); } // Ensure our compositor and shell interfaces Registry.EnsureCoreGlobals(); // Mark us as started IsStarted = true; // If we had an initial window show it now and remove our handle to it if (_initialWindow != null) { _initialWindow.Show(); _initialWindow = null; } // We are ready so trigger the Started event Started?.Invoke(this, new EventArgs()); }
private void Run() { _isRunning = true; #if DEBUG Started?.Invoke(this, EventArgs.Empty); #endif while (!_terminated) { long elapsedMilliseconds = Interlocked.Exchange(ref _uiElapsedMilliseconds, 0); // Perform a simulation tick if (elapsedMilliseconds > 0) { IMap map = _mapProvider.Current(); _actors.SimulationUpdate(map); } _gate.WaitOne(); } _isRunning = false; #if DEBUG Stopped?.Invoke(this, EventArgs.Empty); #endif }
public void StartServer(int port, ushort maxClients) { if (!IsRunning) { if (_server == null) { Initalize(); } Debug.Log("Starting Server"); Action serverTicker = _server.Start(port, maxClients); IsRunning = true; if (_updater == null) { GameObject updaterInstance = Instantiate(_updaterPrefab); DontDestroyOnLoad(updaterInstance); _updater = updaterInstance.GetComponent <FixedUpdater>(); } _updater.UpdateAction = serverTicker; _updater.enabled = true; _server.ClientConnected += OnClientConnected; _server.ClientDisconnected += OnClientDisconnect; Started?.Invoke(); } }
/// <summary> /// Create a stage program. /// </summary> /// <param name="clock">Clock for timing</param> /// <param name="stageProvider">Stage provider that providing stages</param> /// <param name="preferPreloaded">Prefer pre-loaded stages if possible</param> public StageProgram([NotNull] IClock clock, [NotNull] IStageProvider stageProvider, bool preferPreloaded = true) { if (stageProvider == null) { throw new ArgumentNullException(nameof(stageProvider)); } OriginalClock = clock ?? throw new ArgumentNullException(nameof(clock)); FreezableClock = new FreezableClock(clock.As(TimeUnit.Millisecond)); FreezableClock.Frozen += (sender, e) => _pausedEvent.Set(); FreezableClock.Unfrozen += (sender, e) => _pausedEvent.Reset(); _stageProvider = preferPreloaded && stageProvider.TryPreload(out var preloaded) ? preloaded : stageProvider; _cyclicExecutor = new AsyncCyclicExecutor("StageProgram Worker", DoWork, true, ThreadPriority.Highest, null, StoppingAction.Abort); _cyclicExecutor.Starting += (sender, e) => { CurrentStage = null; _pausedEvent.Set(); StartTime = Time; _nextUpdateTime = 0; }; _cyclicExecutor.Started += (sender, e) => Started?.Invoke(this, EventArgs.Empty); _cyclicExecutor.Stopped += (sender, e) => Stopped?.Invoke(this, EventArgs.Empty); _stageSkipped = new AtomicBool(false); _pausedEvent = new ManualResetEvent(false); }
/// <summary> /// Called on algorithm start. /// </summary> /// <param name="args"><see cref="EventArgs.Empty"/>.</param> protected virtual void OnStarted([NotNull] EventArgs args) { Debug.Assert(args != null); Started?.Invoke(this, args); }
public void Start() { Begin = DateTime.Now; Started?.Invoke(this, Begin); }
public Task Start(WindowCreateInfo wci, GraphicsDeviceOptions graphicsDeviceOptions) { //return Task.Factory.StartNew(() => //{ AddRenderer(new Renderer() { RenderWireframes = false }); _window = VeldridStartup.CreateWindow(ref wci); //Window.CursorVisible = false; //Window.SetMousePosition(Window.Width / 2, Window.Height / 2); _window.Resized += () => _windowResized = true; _graphicsDevice = VeldridStartup.CreateGraphicsDevice(_window, graphicsDeviceOptions); _commandList = _graphicsDevice.ResourceFactory.CreateCommandList(); _renderers.ForEach(r => r.Initialize(_graphicsDevice, _commandList, _window.Width, _window.Height)); var imGuiRenderer = new ImGuiRenderer(_graphicsDevice, _graphicsDevice.MainSwapchain.Framebuffer.OutputDescription, _window.Width, _window.Height); Started?.Invoke(); var frameWatch = Stopwatch.StartNew(); var targetFrameTime = 0.13f; while (_window.Exists) { var inputSnapshot = _window.PumpEvents(); if (!_window.Exists) { break; } InputTracker.UpdateFrameInput(_window, inputSnapshot); if (InputTracker.WasKeyDowned(Key.Escape)) { break; } if (InputTracker.WasKeyDowned(Key.Tilde)) { InputTracker.LockMouse = !InputTracker.LockMouse; } if (InputTracker.WasKeyDowned(Key.T)) { StackedTiming.Enabled = !StackedTiming.Enabled; Timing.Enabled = !Timing.Enabled; } if (_windowResized) { _windowResized = false; _graphicsDevice.ResizeMainWindow((uint)_window.Width, (uint)_window.Height); _renderers.ForEach(r => r.WindowResized(_window.Width, _window.Height)); imGuiRenderer.WindowResized(_window.Width, _window.Height); } var frameTime = (float)frameWatch.Elapsed.TotalSeconds; frameWatch.Restart(); imGuiRenderer.Update(frameTime, InputTracker.LockMouse ? new EmptyInputSnapshot() : InputTracker.FrameSnapshot); Tick?.Invoke(); if (NextScene != null) { if (CurrentScene != null) { CurrentScene.SceneStopped(); } CurrentScene = NextScene; NextScene = null; CurrentScene.SceneStarted(this); } if (CurrentScene != null) { StackedTiming.PushFrameTimer("Scene Update"); CurrentScene.Update(frameTime); StackedTiming.PopFrameTimer(); } _commandList.Begin(); _commandList.SetFramebuffer(_graphicsDevice.MainSwapchain.Framebuffer); //commandList.ClearColorTarget(0, new RgbaFloat(25f / 255, 25f / 255, 112f / 255, 1.0f)); _commandList.ClearColorTarget(0, RgbaFloat.CornflowerBlue); _commandList.ClearDepthStencil(1f); StackedTiming.PushFrameTimer("Render"); if (Camera != null) { _renderers.ForEach(r => r.Render(Camera, _graphicsDevice, _commandList, RenderWireframes.SOLID)); } StackedTiming.PopFrameTimer(); StackedTiming.Render(frameTime); Timing.Render(frameTime); imGuiRenderer.Render(_graphicsDevice, _commandList); _commandList.End(); _graphicsDevice.SubmitCommands(_commandList); _graphicsDevice.SwapBuffers(_graphicsDevice.MainSwapchain); _graphicsDevice.WaitForIdle(); bool jobsRemain = true; while (jobsRemain && frameWatch.Elapsed.TotalSeconds < targetFrameTime) { jobsRemain = BestEffortFrameQueue.ConsumeActions(1); } } //}, TaskCreationOptions.LongRunning); return(Task.CompletedTask); }
private void OnStarted() { Started?.Invoke(this, new GameControllerEventArgs(this)); }
public int CompareTo(HistoryEntry other) { return(Started.CompareTo(other.Started)); }
private void DeviceWorker() { Console.WriteLine("Starting worker thread for {0}", _Device.ToString()); // Open HID device to read input from the gamepad _Device.OpenDevice(DeviceMode.Overlapped, DeviceMode.Overlapped, ShareMode.ShareRead | ShareMode.ShareWrite); // Init Xiaomi Gamepad vibration _Device.WriteFeatureData(new byte[] { 0x20, 0x00, 0x00 }); // Connect the virtual Xbox360 gamepad try { _Target.Connect(); } catch (VigemAlreadyConnectedException e) { _Target.Disconnect(); _Target.Connect(); } Started?.Invoke(this, EventArgs.Empty); HidReport hidReport; while (!_CTS.Token.IsCancellationRequested) { // Is device has been closed, exit the loop if (!_Device.IsOpen) { break; } // Otherwise read a report hidReport = _Device.ReadReport(1000); if (hidReport.ReadStatus == HidDeviceData.ReadStatus.WaitTimedOut) { continue; } else if (hidReport.ReadStatus != HidDeviceData.ReadStatus.Success) { Console.WriteLine("Device {0}: error while reading HID report, {1}", _Device.ToString(), hidReport.ReadStatus.ToString()); break; } var data = hidReport.Data; /* * [0] Buttons state, 1 bit per button * [1] Buttons state, 1 bit per button * [2] 0x00 * [3] D-Pad * [4] Left thumb, X axis * [5] Left thumb, Y axis * [6] Right thumb, X axis * [7] Right thumb, Y axis * [8] 0x00 * [9] 0x00 * [10] L trigger * [11] R trigger * [12] Accelerometer axis 1 * [13] Accelerometer axis 1 * [14] Accelerometer axis 2 * [15] Accelerometer axis 2 * [16] Accelerometer axis 3 * [17] Accelerometer axis 3 * [18] Battery level * [19] MI button */ lock (_Report) { _Report.SetButtonState(Xbox360Buttons.A, GetBit(data[0], 0)); _Report.SetButtonState(Xbox360Buttons.B, GetBit(data[0], 1)); _Report.SetButtonState(Xbox360Buttons.X, GetBit(data[0], 3)); _Report.SetButtonState(Xbox360Buttons.Y, GetBit(data[0], 4)); _Report.SetButtonState(Xbox360Buttons.LeftShoulder, GetBit(data[0], 6)); _Report.SetButtonState(Xbox360Buttons.RightShoulder, GetBit(data[0], 7)); _Report.SetButtonState(Xbox360Buttons.Back, GetBit(data[1], 2)); _Report.SetButtonState(Xbox360Buttons.Start, GetBit(data[1], 3)); _Report.SetButtonState(Xbox360Buttons.LeftThumb, GetBit(data[1], 5)); _Report.SetButtonState(Xbox360Buttons.RightThumb, GetBit(data[1], 6)); // Reset Hat switch status, as is set to 15 (all directions set, impossible state) _Report.SetButtonState(Xbox360Buttons.Up, false); _Report.SetButtonState(Xbox360Buttons.Left, false); _Report.SetButtonState(Xbox360Buttons.Down, false); _Report.SetButtonState(Xbox360Buttons.Right, false); if (data[3] < 8) { var btns = HatSwitches[data[3]]; // Hat Switch is a number from 0 to 7, where 0 is Up, 1 is Up-Left, etc. _Report.SetButtons(btns); } // Analog axis _Report.SetAxis(Xbox360Axes.LeftThumbX, MapAnalog(data[4])); _Report.SetAxis(Xbox360Axes.LeftThumbY, MapAnalog(data[5], true)); _Report.SetAxis(Xbox360Axes.RightThumbX, MapAnalog(data[6])); _Report.SetAxis(Xbox360Axes.RightThumbY, MapAnalog(data[7], true)); // Triggers _Report.SetAxis(Xbox360Axes.LeftTrigger, data[10]); _Report.SetAxis(Xbox360Axes.RightTrigger, data[11]); // Logo ("home") button if (GetBit(data[19], 0)) { _Report.SetButtonState((Xbox360Buttons)0x0400, true); Task.Delay(200).ContinueWith(DelayedReleaseGuideButton); } // Update battery level BatteryLevel = data[18]; _Target.SendReport(_Report); } } // Disconnect the virtual Xbox360 gamepad // Let Dispose handle that, otherwise it will rise a NotPluggedIn exception //_Target.Disconnect(); // Close the HID device _Device.CloseDevice(); Console.WriteLine("Exiting worker thread for {0}", _Device.ToString()); Ended?.Invoke(this, EventArgs.Empty); }
private static async Task <Game.Result> StartAsync_Ui(Game.StartProperties properties, GameMode mode) { using (var ui = _uiFactory.Create()) { Logging.Write($"Starting game: {properties.GetDescription()}"); ui.Show(properties, mode); CancellationTokenSource linked = null; IsInGame = true; try { FileUtils.TryToDelete(AcPaths.GetLogFilename()); Game.Result result; using (ReplaysExtensionSetter.OnlyNewIfEnabled()) using (ScreenshotsConverter.OnlyNewIfEnabled()) { Started?.Invoke(null, new GameStartedArgs(properties, mode)); if (mode == GameMode.Race) { properties.SetAdditional(new RaceCommandExecutor(properties)); properties.SetAdditional(new DBoxIntegration()); if (SettingsHolder.Drive.ContinueOnEscape) { properties.SetAdditional(new ContinueRaceHelper()); } } else if (mode == GameMode.Replay) { properties.SetAdditional(new ReplayCommandExecutor(properties)); } var cancellationToken = ui.CancellationToken; if (SettingsHolder.Drive.ImmediateCancel) { var cancelHelper = new ImmediateCancelHelper(); linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, cancelHelper.GetCancellationToken()); cancellationToken = linked.Token; properties.SetAdditional(cancelHelper); properties.SetKeyboardListener = true; } if (mode == GameMode.Replay) { await PrepareReplay(properties, ui, cancellationToken); } if (SettingsHolder.Drive.LoadPatchDataAutomatically && PatchHelper.IsActive()) { var trackId = string.IsNullOrWhiteSpace(properties.BasicProperties?.TrackConfigurationId) ? properties.BasicProperties?.TrackId : properties.BasicProperties?.TrackId + @"/" + properties.BasicProperties?.TrackConfigurationId; using (var cancellation = new CancellationTokenSource()) { ui.OnProgress("Loading data for Custom Shaders Patch…", AsyncProgressEntry.Indetermitate, () => { cancellation.Cancel(); }); var carName = properties.BasicProperties?.CarId == null ? null : CarsManager.Instance.GetById(properties.BasicProperties?.CarId); var trackName = trackId == null ? null : TracksManager.Instance.GetById(trackId)?.Name ?? trackId; await PatchTracksDataUpdater.Instance.TriggerAutoLoadAsync(trackId, PatchSubProgress($"Config for track {trackName}"), cancellation.Token); await PatchTracksVaoDataUpdater.Instance.TriggerAutoLoadAsync(trackId, PatchSubProgress($"Ambient occlusion patch for track {trackName}"), cancellation.Token); await PatchBackgroundDataUpdater.Instance.TriggerAutoLoadAsync(trackId, PatchSubProgress($"Backgrounds for track {trackName}"), cancellation.Token); await PatchCarsDataUpdater.Instance.TriggerAutoLoadAsync(properties.BasicProperties?.CarId, PatchSubProgress($"Config for car {carName}"), cancellation.Token); await PatchCarsVaoDataUpdater.Instance.TriggerAutoLoadAsync(properties.BasicProperties?.CarId, PatchSubProgress($"Ambient occlusion patch for car {carName}"), cancellation.Token); ui.OnProgress("Final preparations…"); IProgress <AsyncProgressEntry> PatchSubProgress(string target) { return(new Progress <AsyncProgressEntry>(p => ui.OnProgress("Loading data for Custom Shaders Patch…", new AsyncProgressEntry($"{target}\n{p.Message ?? @"…"}", p.IsReady || p.Progress == null ? 0d : p.Progress), () => cancellation.Cancel()))); } } } result = await Game.StartAsync(CreateStarter(properties), properties, new ProgressHandler(ui), cancellationToken); } Logging.Write($"Result: {result?.GetDescription() ?? @"<NULL>"}"); if (ui.CancellationToken.IsCancellationRequested) { ui.OnError(new UserCancelledException()); return(null); } var whatsGoingOn = mode != GameMode.Race || result == null?AcLogHelper.TryToDetermineWhatsGoingOn() : null; if (whatsGoingOn != null) { properties.SetAdditional(whatsGoingOn); } if (mode == GameMode.Race) { var param = new GameEndedArgs(properties, result); Ended?.Invoke(null, param); /* TODO: should set result to null if param.Cancel is true? */ var replayHelper = new ReplayHelper(properties, result); (result == null || param.Cancel ? Cancelled : Finished)?.Invoke(null, new GameFinishedArgs(properties, result)); ui.OnResult(result, replayHelper); } else { ui.OnResult(null, null); } return(result); } catch (Exception e) when(e.IsCancelled()) { // ui.OnError(new UserCancelledException()); ui.OnResult(null, null); return(null); } catch (Exception e) { Logging.Warning(e); ui.OnError(e); return(null); } finally { linked?.Dispose(); IsInGame = false; } } }
public string Serialize(Started message) { return(JsonSerializer.SerializeToString <Started>(message)); }
private void OnStarted(Started ev) { _startedTime = ev.StartedTime; }
public void method_23() { foreach (Control control in this.panel1.Controls) { control.Dispose(); } this.panel1.Controls.Clear(); Started started = new Started { TopLevel = false, FormBorderStyle = FormBorderStyle.None, Visible = true }; this.panel1.Controls.Add(started); }
private void StartGuessing(Started _) { Console.WriteLine("Game: Now we can start guessing"); enquirer.Tell(new Start()); }
public string Serialize(Started message) { return JsonSerializer.SerializeToString<Started>(message); }
private void OnStarted(EventArgs e) { Started?.Invoke(this, e); }
public async Task <VideoCacheDownloadOperationCompleteState> DownloadAsync() { IRandomAccessStream downloadStream = null; try { var uri = await _dmcVideoStreamingSession.GetDownloadUrlAndSetupDownloadSession(); downloadStream = await HttpRandomAccessStream.CreateAsync(_dmcVideoStreamingSession.NiconicoSession.ToolkitContext.HttpClient, uri); } catch { downloadStream?.Dispose(); throw; } Started?.Invoke(this, EventArgs.Empty); _cancelAwaitTcs = new TaskCompletionSource <bool>(); _cancellationTokenSource = new CancellationTokenSource(); _onwerShipReturnedCancellationTokenSource = new CancellationTokenSource(); _pauseCancellationTokenSource = new CancellationTokenSource(); _linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(_cancellationTokenSource.Token, _onwerShipReturnedCancellationTokenSource.Token, _pauseCancellationTokenSource.Token); _dmcVideoStreamingSession.StopStreamingFromOwnerShipReturned += _dmcVideoStreamingSession_StopStreamingFromOwnerShipReturned; try { var ct = _linkedCancellationTokenSource.Token; await Task.Run(async() => await _videoCacheDownloadOperationOutput.CopyStreamAsync(downloadStream.AsStreamForRead(), new _Progress(x => Progress?.Invoke(this, x)), ct), ct); } catch (OperationCanceledException) { // 削除操作、または視聴権を喪失した場合 if (_cancellationTokenSource.IsCancellationRequested) { return(VideoCacheDownloadOperationCompleteState.DownloadCanceledWithUser); } else if (_pauseCancellationTokenSource.IsCancellationRequested) { return(VideoCacheDownloadOperationCompleteState.DownloadPaused); } else if (_onwerShipReturnedCancellationTokenSource.IsCancellationRequested) { return(VideoCacheDownloadOperationCompleteState.ReturnDownloadSessionOwnership); } else { throw; } } catch (FileLoadException) { throw; } catch (Exception) { // ニコ動サーバー側からタイムアウトで切られた場合は一時停止扱い return(VideoCacheDownloadOperationCompleteState.DownloadPaused); } finally { _cancelAwaitTcs.TrySetResult(true); _dmcVideoStreamingSession.StopStreamingFromOwnerShipReturned -= _dmcVideoStreamingSession_StopStreamingFromOwnerShipReturned; downloadStream.Dispose(); _onwerShipReturnedCancellationTokenSource.Dispose(); _pauseCancellationTokenSource.Dispose(); _cancellationTokenSource.Dispose(); _linkedCancellationTokenSource.Dispose(); _cancellationTokenSource = null; Completed?.Invoke(this, EventArgs.Empty); } return(VideoCacheDownloadOperationCompleteState.Completed); }
protected bool Equals(ReplicationPerformanceStats other) { return(BatchSize == other.BatchSize && Duration.Equals(other.Duration) && Started.Equals(other.Started)); }
private void StartAppCenter() { if (Settings == null) { Debug.LogError("App Center isn't configured!"); return; } var services = Settings.Services; PrepareEventHandlers(services); InvokeInitializingServices(); AppCenter.SetWrapperSdk(); AppCenter.CacheStorageSize(Settings.MaxStorageSize.Size); if (Settings.CustomLogUrl.UseCustomUrl) { AppCenter.CacheLogUrl(Settings.CustomLogUrl.Url); } var appSecret = AppCenter.ParseAndSaveSecretForPlatform(Settings.AppSecret); var advancedSettings = GetComponent <AppCenterBehaviorAdvanced>(); if (IsStartFromAppCenterBehavior(advancedSettings)) { AppCenter.LogLevel = Settings.InitialLogLevel; if (Settings.CustomLogUrl.UseCustomUrl) { AppCenter.SetLogUrl(Settings.CustomLogUrl.Url); } if (Settings.MaxStorageSize.UseCustomMaxStorageSize && Settings.MaxStorageSize.Size > 0) { AppCenterInternal.SetMaxStorageSize(Settings.MaxStorageSize.Size); } var startupType = GetStartupType(advancedSettings); if (startupType != StartupType.Skip) { var transmissionTargetToken = GetTransmissionTargetToken(advancedSettings); var appSecretString = GetAppSecretString(appSecret, transmissionTargetToken, startupType); if (string.IsNullOrEmpty(appSecretString)) { AppCenterInternal.Start(services); } else { AppCenterInternal.Start(appSecretString, services); } } } #if UNITY_IOS || UNITY_ANDROID else { foreach (var service in services) { #if UNITY_IOS || UNITY_ANDROID // On iOS and Android we start crash service here, to give app an opportunity to assign handlers after crash and restart in Awake method var startCrashes = service.GetMethod("StartCrashes"); if (startCrashes != null) { startCrashes.Invoke(null, null); } #endif } } #endif InvokeInitializedServices(); if (Started != null) { Started.Invoke(); } }
private void OnStarted() { Started?.Invoke(this, EventArgs.Empty); }
private async Task StartCoreAsync(ChromiumProcess p) { var output = new StringBuilder(); void OnProcessDataReceivedWhileStarting(object sender, DataReceivedEventArgs e) { if (e.Data != null) { output.AppendLine(e.Data); var match = Regex.Match(e.Data, "^DevTools listening on (ws:\\/\\/.*)"); if (match.Success) { p._startCompletionSource.TrySetResult(match.Groups[1].Value); } } } void OnProcessExitedWhileStarting(object sender, EventArgs e) => p._startCompletionSource.TrySetException(new ChromiumProcessException($"Failed to launch Chromium! {output}")); void OnProcessExited(object sender, EventArgs e) => Exited.EnterFrom(p, p._currentState); p.Process.ErrorDataReceived += OnProcessDataReceivedWhileStarting; p.Process.Exited += OnProcessExitedWhileStarting; p.Process.Exited += OnProcessExited; CancellationTokenSource cts = null; try { p.Process.Start(); await Started.EnterFromAsync(p, this).ConfigureAwait(false); p.Process.BeginErrorReadLine(); var timeout = p._options.Timeout; if (timeout > 0) { cts = new CancellationTokenSource(timeout); cts.Token.Register(() => p._startCompletionSource.TrySetException( new ChromiumProcessException($"Timed out after {timeout} ms while trying to connect to Chromium!"))); } try { await p._startCompletionSource.Task.ConfigureAwait(false); await Started.EnterFromAsync(p, this).ConfigureAwait(false); } catch { await Killing.EnterFromAsync(p, this).ConfigureAwait(false); throw; } } finally { cts?.Dispose(); p.Process.Exited -= OnProcessExitedWhileStarting; p.Process.ErrorDataReceived -= OnProcessDataReceivedWhileStarting; } }
private static async Task <Game.Result> StartAsync_Ui(Game.StartProperties properties, GameMode mode) { using (var ui = _uiFactory.Create()) { Logging.Write($"Starting game: {properties.GetDescription()}"); ui.Show(properties, mode); CancellationTokenSource linked = null; IsInGame = true; try { Game.Result result; using (ReplaysExtensionSetter.OnlyNewIfEnabled()) using (ScreenshotsConverter.OnlyNewIfEnabled()) { Started?.Invoke(null, new GameStartedArgs(properties, mode)); if (mode == GameMode.Race) { properties.SetAdditional(new RaceCommandExecutor(properties)); properties.SetAdditional(new DBoxIntegration()); if (SettingsHolder.Drive.ContinueOnEscape) { properties.SetAdditional(new ContinueRaceHelper()); } } else if (mode == GameMode.Replay) { properties.SetAdditional(new ReplayCommandExecutor(properties)); } var cancellationToken = ui.CancellationToken; if (SettingsHolder.Drive.ImmediateCancel) { var cancelHelper = new ImmediateCancelHelper(); linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, cancelHelper.GetCancellationToken()); cancellationToken = linked.Token; properties.SetAdditional(cancelHelper); properties.SetKeyboardListener = true; } if (mode == GameMode.Replay) { await PrepareReplay(properties, ui, cancellationToken); } ui.OnProgress("Loading data for Custom Shaders Patch…"); var trackId = string.IsNullOrWhiteSpace(properties.BasicProperties?.TrackConfigurationId) ? properties.BasicProperties?.TrackId : properties.BasicProperties?.TrackId + @"/" + properties.BasicProperties?.TrackConfigurationId; await PatchTracksDataUpdater.Instance.TriggerAutoLoadAsync(trackId); await PatchTracksVaoDataUpdater.Instance.TriggerAutoLoadAsync(trackId); await PatchBackgroundDataUpdater.Instance.TriggerAutoLoadAsync(trackId); await PatchCarsDataUpdater.Instance.TriggerAutoLoadAsync(properties.BasicProperties?.CarId); result = await Game.StartAsync(CreateStarter(properties), properties, new ProgressHandler(ui), cancellationToken); } Logging.Write($"Result: {result?.GetDescription() ?? @"<NULL>"}"); if (ui.CancellationToken.IsCancellationRequested) { ui.OnError(new UserCancelledException()); return(null); } var whatsGoingOn = mode != GameMode.Race || result == null?AcLogHelper.TryToDetermineWhatsGoingOn() : null; if (whatsGoingOn != null) { properties.SetAdditional(whatsGoingOn); } if (mode == GameMode.Race) { var param = new GameEndedArgs(properties, result); Ended?.Invoke(null, param); /* TODO: should set result to null if param.Cancel is true? */ var replayHelper = new ReplayHelper(properties, result); (result == null || param.Cancel ? Cancelled : Finished)?.Invoke(null, new GameFinishedArgs(properties, result)); ui.OnResult(result, replayHelper); } else { ui.OnResult(null, null); } return(result); } catch (Exception e) when(e.IsCancelled()) { // ui.OnError(new UserCancelledException()); ui.OnResult(null, null); return(null); } catch (Exception e) { Logging.Warning(e); ui.OnError(e); return(null); } finally { linked?.Dispose(); IsInGame = false; } } }
// Raise the Started event (see above). private void OnStarted(DateTime startTime) => Started?.Invoke(this, new PyRunnerStartedEventArgs(startTime));
internal static void InvokeServerStartup() { Started?.Invoke(); }
public void Start() { Thread = new Thread(Flow); Thread.Start(); Started?.Invoke(this, new ThreadStartedEventArgs()); }
private void Player_Start(object sender, EventArgs e) { Started?.Invoke(this, e); }
// // Start the driver service // public void Start(string processPath, string arguments) { if (App.exp_no_vmulti) { ConfigurationManager.Current.OutputMode = Configuration.OutputModes.SendInput; arguments += " -r"; } if (!File.Exists(processPath)) { throw new FileNotFoundException(processPath + " not found!"); } // Try to start the driver try { // Create process start info ProcessStartInfo startInfo = new ProcessStartInfo { FileName = processPath, Arguments = arguments, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, RedirectStandardInput = true, CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Normal }; // Create process processService = new Process { StartInfo = startInfo }; processService.OutputDataReceived += ProcessService_OutputDataReceived; processService.ErrorDataReceived += ProcessService_ErrorDataReceived; processService.Exited += ProcessService_Exited; processService.Disposed += ProcessService_Disposed; // Start process if (processService.Start()) { processService.BeginOutputReadLine(); // Set process priority try { processService.PriorityClass = ProcessPriorityClass.High; } catch (Exception) { } running = true; timerWatchdog.Start(); Started?.Invoke(this, new EventArgs()); } // Start failed else { throw new Exception("Can't start the driver service!"); } } // Start failed catch (Exception e) { throw e; } }
protected virtual void OnStarted() { Started?.Invoke(this, EventArgs.Empty); }
public void Start() { if (socket_ != null) { throw new InvalidOperationException("Network is already running"); } socket_ = new Socket(broadcastEndpoint_.AddressFamily, SocketType.Dgram, ProtocolType.Udp); // Bind to the broadcast port. socket_.Bind(new IPEndPoint(localAddress_, broadcastEndpoint_.Port)); // Optionally join a multicast group if (IsMulticast(broadcastEndpoint_.Address)) { if (broadcastEndpoint_.AddressFamily == AddressFamily.InterNetwork) { MulticastOption mcastOption; mcastOption = new MulticastOption(broadcastEndpoint_.Address, localAddress_); socket_.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, mcastOption); } else if (broadcastEndpoint_.AddressFamily == AddressFamily.InterNetworkV6) { IPv6MulticastOption mcastOption; if (localAddress_ != IPAddress.IPv6Any) { var ifaceIdx = GetIfaceIdxFromAddress(localAddress_); mcastOption = new IPv6MulticastOption(broadcastEndpoint_.Address, ifaceIdx); } else { mcastOption = new IPv6MulticastOption(broadcastEndpoint_.Address); } socket_.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, mcastOption); } else { // Should never happen throw new NotSupportedException($"Invalid address family: {broadcastEndpoint_.AddressFamily}"); } } else { // Assume this is a broadcast address. socket_.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); } // Start the cleanup thread. deleteExpiredCts_ = new CancellationTokenSource(); var token = deleteExpiredCts_.Token; deleteExpiredTask_ = Task.Run(() => CleanupExpired(token), token); // Start the receiving thread. recvTask_ = Task.Run(ReceiveLoop); Started?.Invoke(this); }
public async Task Run() { // Build the C# script if not in CSharp mode if (config.Mode != ConfigMode.CSharp) { config.CSharpScript = config.Mode == ConfigMode.Stack ? Stack2CSharpTranspiler.Transpile(config.Stack, config.Settings) : Loli2CSharpTranspiler.Transpile(config.LoliCodeScript, config.Settings); } if (options.UseProxy && !options.TestProxy.Contains(':')) { throw new InvalidProxyException(options.TestProxy); } if (!options.PersistLog) { logger.Clear(); } // Close any previously opened browser if (lastBrowser != null) { await lastBrowser.CloseAsync(); } options.Variables.Clear(); IsRunning = true; cts = new CancellationTokenSource(); var sw = new Stopwatch(); var wordlistType = RuriLibSettings.Environment.WordlistTypes.First(w => w.Name == options.WordlistType); var dataLine = new DataLine(options.TestData, wordlistType); var proxy = options.UseProxy ? Proxy.Parse(options.TestProxy, options.ProxyType) : null; var providers = new Bots.Providers(RuriLibSettings) { RNG = RNGProvider }; if (!RuriLibSettings.RuriLibSettings.GeneralSettings.UseCustomUserAgentsList) { providers.RandomUA = RandomUAProvider; } // Build the BotData var data = new BotData(providers, config.Settings, logger, dataLine, proxy, options.UseProxy) { CancellationToken = cts.Token }; using var httpClient = new HttpClient(); data.SetObject("httpClient", httpClient); var runtime = Python.CreateRuntime(); var pyengine = runtime.GetEngine("py"); var pco = (PythonCompilerOptions)pyengine.GetCompilerOptions(); pco.Module &= ~ModuleOptions.Optimized; data.SetObject("ironPyEngine", pyengine); data.AsyncLocker = new(); dynamic globals = new ExpandoObject(); var script = new ScriptBuilder() .Build(config.CSharpScript, config.Settings.ScriptSettings, PluginRepo); logger.Log($"Sliced {dataLine.Data} into:"); foreach (var slice in dataLine.GetVariables()) { var sliceValue = data.ConfigSettings.DataSettings.UrlEncodeDataAfterSlicing ? Uri.EscapeDataString(slice.AsString()) : slice.AsString(); logger.Log($"{slice.Name}: {sliceValue}"); } // Initialize resources Dictionary <string, ConfigResource> resources = new(); // Resources will need to be disposed of foreach (var opt in config.Settings.DataSettings.Resources) { try { resources[opt.Name] = opt switch { LinesFromFileResourceOptions x => new LinesFromFileResource(x), RandomLinesFromFileResourceOptions x => new RandomLinesFromFileResource(x), _ => throw new NotImplementedException() }; } catch { logger.Log($"Could not create resource {opt.Name}", LogColors.Tomato); } } // Add resources to global variables globals.Resources = resources; var scriptGlobals = new ScriptGlobals(data, globals); // Set custom inputs foreach (var input in config.Settings.InputSettings.CustomInputs) { (scriptGlobals.input as IDictionary <string, object>).Add(input.VariableName, input.DefaultAnswer); } try { sw.Start(); Started?.Invoke(this, EventArgs.Empty); var state = await script.RunAsync(scriptGlobals, null, cts.Token); foreach (var scriptVar in state.Variables) { try { var type = DescriptorsRepository.ToVariableType(scriptVar.Type); if (type.HasValue && !scriptVar.Name.StartsWith("tmp_")) { var variable = DescriptorsRepository.ToVariable(scriptVar.Name, scriptVar.Type, scriptVar.Value); variable.MarkedForCapture = data.MarkedForCapture.Contains(scriptVar.Name); options.Variables.Add(variable); } } catch { // The type is not supported, e.g. it was generated using custom C# code and not blocks // so we just disregard it } } } catch (OperationCanceledException) { data.STATUS = "ERROR"; logger.Log($"Operation canceled", LogColors.Tomato); } catch (Exception ex) { data.STATUS = "ERROR"; var logErrorMessage = RuriLibSettings.RuriLibSettings.GeneralSettings.VerboseMode ? ex.ToString() : ex.Message; logger.Log($"[{data.ExecutionInfo}] {ex.GetType().Name}: {logErrorMessage}", LogColors.Tomato); IsRunning = false; throw; } finally { sw.Stop(); logger.Log($"BOT ENDED AFTER {sw.ElapsedMilliseconds} ms WITH STATUS: {data.STATUS}"); // Save the browser for later use lastBrowser = data.TryGetObject <Browser>("puppeteer"); // Dispose stuff in data.Objects data.DisposeObjectsExcept(new[] { "puppeteer", "puppeteerPage", "puppeteerFrame" }); // Dispose resources foreach (var resource in resources.Where(r => r.Value is IDisposable) .Select(r => r.Value).Cast <IDisposable>()) { resource.Dispose(); } data.AsyncLocker.Dispose(); } IsRunning = false; Stopped?.Invoke(this, EventArgs.Empty); }
public void GetEncounters(string playerName, string region, string playerServer = "", int areaId = 0, int bossId = 0) { Task.Run(() => { if (_requestInProgress) { return; } Started?.Invoke(); _requestInProgress = true; var results = new List <IMoongourdEncounter>(); using var webClient = Nostrum.MiscUtils.GetDefaultWebClient(); try { var strResp = webClient.DownloadString(BuildSearchUrl(region, playerServer, playerName)); var jResp = JArray.Parse(strResp)[1]; //[0] is { count: 0 }, [1] is log array var count = 0; foreach (var jEntry in jResp) { if (count >= MAX_ENCOUNTERS) { break; } if (jEntry["playerName"] !.Value <string>() != playerName) { continue; } var logId = long.Parse((jEntry["logId"]) !.Value <string>() !); var logZoneId = jEntry["zoneId"] !.Value <int>(); var logBossId = jEntry["bossId"] !.Value <int>(); var logUrl = BuildLogUrl(region, logZoneId, logBossId, logId); var strLog = webClient.DownloadString(logUrl); var jLog = JObject.Parse(strLog); var dps = int.Parse(jLog["members"] !.FirstOrDefault(y => y["playerName"] !.Value <string>() == playerName) !["playerDps"] !.Value <string>() !); var deaths = int.Parse(jLog["members"] !.FirstOrDefault(y => y["playerName"] !.Value <string>() == playerName) !["playerDeaths"] !.Value <string>() !); var encounter = new MoongourdEncounter() { PlayerName = playerName, AreaId = logZoneId, BossId = logBossId, LogId = logId, PlayerDps = dps, PlayerDeaths = deaths }; results.Add(encounter); count++; } } catch (Exception e) { Log.CW(e.ToString()); Failed?.Invoke(e.ToString()); _requestInProgress = false; return; } Finished?.Invoke(results); _requestInProgress = false; }); }
public void Run(bool cluster) { // TODO: /* * + Переименовать классы и интерфейсы * + Внести шедулер внутрь джоба * - Добавить листенеры на мисфаер, ошибки и прочее * - Написать тесты * - Добавить синхронизацию между машинами */ ISchedulerFactory schedulerFactory; if (cluster) { if (propertiesDB != null) { schedulerFactory = new StdSchedulerFactory(propertiesDB); } else { throw new Exception("Нет настроек DB"); } } else { schedulerFactory = new StdSchedulerFactory(); } IJobFactory customJobFactory = new CustomJobFactory(type => _getJobInstance(type)); // NB: GetScheduler() возвращает Singleton - один и тот же инстанс IScheduler IScheduler scheduler = schedulerFactory.GetScheduler(); scheduler.JobFactory = customJobFactory; List <SingleCallCronJob> jobs = _jobTypes.Select(x => _getJobInstance(x)).ToList(); foreach (SingleCallCronJob job in jobs) { try { Type jobType = job.GetType(); job.Scheduler = scheduler; IJobDetail jobDetail = JobBuilder.Create(jobType) .WithIdentity(jobType.Name, jobType.Namespace) .RequestRecovery() .Build(); job.JobDetail = jobDetail; ITrigger trigger = TriggerBuilder.Create() .WithIdentity(jobType.Name, jobType.Namespace) .StartAt(DateBuilder.FutureDate(1, IntervalUnit.Second)) .WithCronSchedule(job.CronExpression) .Build(); job.Trigger = trigger; // Если задача уже добавлена, то не добавляем ее if (scheduler.GetJobDetail(jobDetail.Key) == null) { scheduler.ScheduleJob(jobDetail, trigger); } } //в DB не добавлены нужные таблицы catch (JobPersistenceException exc) { throw; } } // Ставим всё на паузу, если мы не из кластерного решения: для GUI ждём ручного запуска, для службы ждём вызова OnStart() if (!cluster) { scheduler.PauseAll(); } if (Environment.UserInteractive || Debugger.IsAttached) { var viewModel = new MainViewModel(); viewModel.SetJobs(jobs, cluster); var window = new MainWindow { DataContext = viewModel }; window.Show(); window.Closed += (sender, args) => { if (!cluster) { foreach (var job in viewModel.Jobs) { job.StopCommand.Execute(null); } } scheduler.Shutdown(); Stopped?.Invoke(); }; if (!cluster) { scheduler.Start(); } Started?.Invoke(); } else { var jobService = new JobService(jobs, cluster); jobService.Started += () => { scheduler.Start(); Started?.Invoke(); }; jobService.Stopped += () => { scheduler.Shutdown(); Stopped?.Invoke(); }; ServiceBase.Run(new ServiceBase[] { jobService }); } }
/// <summary>Fires the event: <see cref="Started"/></summary> private void OnStarted() { Log.Info(this, "Started: " + this); Started?.Invoke(); }