private void OnComponentAdded(GameObject gameObject, Component component) { bool didUpdate = false; AddCallbacksFrom(component); didUpdate = true; if (component is Rigidbody newRigidbody) { Assert.IsNull(rigidbody); rigidbody = newRigidbody; didUpdate = true; } else if (component is Collider collider) { Assert.IsFalse(_colliders.Contains(collider)); _colliders.Add(collider); didUpdate = true; } if (didUpdate) { OnUpdate?.Invoke(this); } }
// main loop public void Update(int ms) { if (!_isValid || !_isRunning) { return; } #if UNITY_EDITOR if (UnityEditor.EditorApplication.isCompiling) { ScriptEngine.Shutdown(); _logger?.Write(LogLevel.Warn, "assembly reloading, shutdown script engine immediately"); return; } #endif if (_pendingActions.Count != 0) { ExecutePendingActions(); } OnUpdate?.Invoke(); //TODO: optimize ExecutePendingJob(); // poll here; _timerManager.Update(ms); if (_autorelease != null) { _autorelease.Drain(); } }
private void Update() { // Cheat codes // * * * * * * * if (Keyboard.current.lKey.isPressed) { ReloadScene(); } if (Paused) { if (Keyboard.current.numpad1Key.isPressed) { StartGame("Keyboard"); } if (Keyboard.current.numpad2Key.isPressed) { StartGame("Controller"); } if (Keyboard.current.numpad3Key.isPressed) { StartGame("Both"); } } // * * * * * * * // Invoke the main Update of the game if it is not paused if (!Paused) { OnUpdate?.Invoke(); } }
private void Timer_Tick(object sender, EventArgs e) { Task.Run(() => { if (TcpClient is null) { return; } NetworkStream stream = TcpClient.GetStream(); if (!isRegistered) { Register(stream); isRegistered = true; return; } byte[] data = new byte[1024]; StringBuilder builder = new StringBuilder(); int bytes = 0; do { bytes = stream.Read(data, 0, data.Length); builder.Append(Encoding.Unicode.GetString(data, 0, bytes)); }while (stream.DataAvailable); var update = builder.ToString(); OnUpdate?.Invoke(this, new UpdateArgs(update, this)); }); }
protected void SendEvent(string eventName, string data) { switch (eventName) { case "update": var status = JsonConvert.DeserializeObject <Status>(data); OnUpdate?.Invoke(this, new StreamUpdateEventArgs(status)); break; case "notification": var notification = JsonConvert.DeserializeObject <Notification>(data); OnNotification?.Invoke(this, new StreamNotificationEventArgs(notification)); break; case "delete": var statusId = (data); OnDelete?.Invoke(this, new StreamDeleteEventArgs(statusId)); break; case "filters_changed": OnFiltersChanged?.Invoke(this, new StreamFiltersChangedEventArgs()); break; case "conversation": var conversation = JsonConvert.DeserializeObject <Conversation>(data); OnConversation?.Invoke(this, new StreamConversationEvenTargs(conversation)); break; } }
public void Update(float delta) { if (!active) { return; } if (resync) { accumulator = 0; delta = timestep; resync = false; } if (Mathf.Abs(delta - timestepClampUpper) < .0002) { delta = timestepClampUpper; } if (Mathf.Abs(delta - timestep) < .0002) { delta = timestep; } if (Mathf.Abs(delta - timestepClampLower) < .0002) { delta = timestepClampLower; } accumulator += delta * timescale; while (accumulator >= timestep) { OnUpdate?.Invoke(timestep); accumulator -= timestep; } }
private void EditorAppUpdateCallback() { if (!Application.isPlaying) { OnUpdate?.Invoke(); } }
/// <summary> /// Process a timer event /// </summary> async private void onTimer(object sender, System.Timers.ElapsedEventArgs e) { string hostname = Workflow.State.HostName; List <Project> enabledProjects = Workflow.GetProjectsToUpdate(); IWorkflowDetails oldDetails = Cache.Details.Clone(); try { await Cache.UpdateAsync(); } catch (OperatorException ex) { ExceptionHandlers.Handle(ex, "Auto-update failed"); return; } MergeRequestUpdates updates = WorkflowDetailsChecker.CheckForUpdates(hostname, enabledProjects, oldDetails, Cache.Details); ProjectWatcher.ProcessUpdates(updates, Workflow.State.HostName, Cache.Details); Trace.TraceInformation( String.Format("[UpdateManager] Merge Request Updates: New {0}, Updated {1}, Closed {2}", updates.NewMergeRequests.Count, updates.UpdatedMergeRequests.Count, updates.ClosedMergeRequests.Count)); OnUpdate?.Invoke(updates); }
private void ProcessUpdateTask(object sender, DoWorkEventArgs e) { var worker = sender as BackgroundWorker; var prevTime = Stopwatch.StartNew(); while (!e.Cancel) { if (worker.CancellationPending) { e.Cancel = true; break; } prevTime.Restart(); if (!IsRunning & !_lastUpdateBeforePausing) { goto FrameLimitStreamUpdate; } _lastUpdateBeforePausing = false; int timeToWait; if (!RefreshRam()) { goto FrameLimitStreamUpdate; } OnUpdate?.Invoke(this, new EventArgs()); FrameLimitStreamUpdate: // Calculate delay to match correct FPS prevTime.Stop(); timeToWait = (int)RefreshRateConfig.RefreshRateInterval - (int)prevTime.ElapsedMilliseconds; timeToWait = Math.Max(timeToWait, 0); // Calculate Fps lock (_fpsQueueLocker) { if (_fpsTimes.Count() >= 10) { _fpsTimes.Dequeue(); } _fpsTimes.Enqueue(prevTime.ElapsedMilliseconds + timeToWait); } FpsUpdated?.Invoke(this, new EventArgs()); if (timeToWait > 0) { Thread.Sleep(timeToWait); } else { Thread.Yield(); } } OnClose?.BeginInvoke(this, new EventArgs(), null, null); }
private IEnumerator UpdateCoroutine() { while (timeLeft > 0 && !isComplete) { yield return(null); _preTime = timeLeft; timeLeft = GetTimeLeft(); if (_preTime != timeLeft) { OnUpdate?.Invoke(timeLeft); } } if (isComplete) { yield break; } Debug.Log(GameTimers.TIMER + id + " Completed!"); isComplete = true; GameTimers.RemoveTimer(id); OnComplete?.Invoke(this); }
public void DeleteItem(Item item, int quantity) { for (int i = 0; i < itemSlots.Count; i++) { InventorySlot invSlot = itemSlots[i]; if (invSlot == null) { continue; } if (invSlot.item == null) { continue; } if (invSlot.ItemID == item.ItemID) { invSlot.quantity -= quantity; if (invSlot.quantity <= 0) { itemSlots[i].item = null; } OnUpdate?.Invoke(); return; } } OnUpdate?.Invoke(); }
protected virtual void Update() { if (GameManager.playing) { OnUpdate?.Invoke(); } }
public void Update(GameTime gameTime) { if (Enabled) { OnUpdate?.Invoke(this, new EventArgs()); } }
private void OnComponentRemoved(GameObject gameObject, Component component) { bool didUpdate = false; RemoveCallbacksFrom(component); didUpdate = true; if (component is Rigidbody) { Assert.IsNotNull(rigidbody); rigidbody = null; didUpdate = true; } else if (component is Collider collider) { Assert.IsTrue(_colliders.Contains(collider)); _colliders.Remove(collider); didUpdate = true; } if (didUpdate) { OnUpdate?.Invoke(this); } }
public void Add(string value) { (ValidationResult, MarkupString)? validation = _validator?.Invoke(value); if (validation?.Item1 == ValidationResult.Invalid) { return; } string?transformed = _transformer?.Invoke(value); if (transformed != null) { value = transformed; } if (_preventDuplicates && _values.Contains(value)) { if (_moveDuplicatesToEnd) { _values.Remove(value); _values.Add(value); } return; } _values.Add(value); OnAdd?.Invoke(value); OnUpdate?.Invoke(_values); }
private void ProcessableBusiness_OnUpdate(object sender, ProcessorEventArgs e) { var process = sender as IProcessable; Value = e.Progress; OnUpdate?.Invoke(process, e); }
public override void FromJson(JObject data) { Data = data["Data"].ToObject <byte[]>(); // TODO: cleanup callbacks OnUpdate?.Invoke(this, EventArgs.Empty); }
void UpdateDatabase() { cityAutocomplete = new AutoCompleteStringCollection(); cityAutocomplete.AddRange(GetAllCities().Select(c => c.Name).ToArray()); OnUpdate?.Invoke(this, null); }
private void Validate_Click(object sender, RoutedEventArgs e) { if (podcast.Category == null) { podcast.Category = Category.Text; podcast.AddToLibrary(); CloseFlyout(); if (NavigateOnSuccess) { GlobalStateManager.CurrentShell.Navigate(typeof(LibraryPage)); } } else { CloseFlyout(); if (podcast.Category == Category.Text) { return; } podcast.Category = Category.Text; } OnUpdate?.Invoke(); }
public void Listen() { if (_cts == null) { _cts = new CancellationTokenSource(); CancellToken = _cts.Token; Task.Factory.StartNew(() => OnStart?.Invoke(this, CancellToken)); while (!CancellToken.IsCancellationRequested) { JToken jtoken = RequestLongPoll(); if (Convert.ToInt32(jtoken["failed"]) == 1) { Ts = jtoken["ts"].ToString(); } else if (Convert.ToInt32(jtoken["failed"]) == 2 || Convert.ToInt32(jtoken["failed"]) == 3) { GetInfoLongPoll(); } else { Ts = jtoken["ts"].ToString(); foreach (JToken response in ((IEnumerable <JToken>)jtoken["updates"])) { UpdateEventArgs update = new UpdateEventArgs(response); Task.Factory.StartNew(() => OnUpdate?.Invoke(this, update)); } } } } else { Api.SendException(this, new ApiException("The task cannot be started because it is already running", ExceptionCode.System)); } }
internal virtual void UpdateSubTree() { transformationDelay = 0; //todo: this should be moved to after the IsVisible condition once we have TOL for transformations (and some better logic). updateTransformations(); if (!IsVisible) { return; } Update(); OnUpdate?.Invoke(); // This check is conservative in the sense, that autosize containers do not impose // any masking on children. This is valid under the assumption, that autosize // will always adjust its size such that it does not mask children away. // todo: Fix for AlwaysDraw == false (never get to UpdateResult.Discard case below) //if (IsMaskedOut()) // return updateResult = UpdateResult.ShouldNotDraw; updateDepthChanges(); internalChildren.Update(Time); foreach (Drawable child in internalChildren.Current) { child.UpdateSubTree(); } UpdateLayout(); }
public void Update() { float change = 0.0f; if (InputManager.Manager.IsKeyPressed(PositiveKey)) { change += 1; } if (InputManager.Manager.IsKeyPressed(NegativeKey)) { change -= 1; } change *= speed; if (Statics.IsNearlyEqual(change, 0.0f) && !Statics.IsNearlyEqual(Value, 0.0f)) { change = gravity * Math.Sign(Value) * -1; } float newValue = MathHelper.Clamp(Value + change, -1f, 1f); if (Statics.IsNearlyEqual(Value, newValue, speed / 2)) { return; } Value = newValue; if (Statics.IsNearlyEqual(Value, 0.0f)) { Value = 0.0f; } OnUpdate?.Invoke(Value); }
/// <summary> /// Save the preferences object and invoke the required event handlers. /// </summary> public void Save() { OnPreSave?.Invoke(this, Preferences); Save(PrefPath, Preferences); OnSave?.Invoke(this, Preferences); OnUpdate?.Invoke(this, Preferences); }
internal void Update(long dt) { this.Time += dt; #if !DEBUG try { #endif var count = this.Lives.Count; for (var i = 0; i < count && i < this.Lives.Count; i++) { var life = this.Lives[i]; life.Update(dt); } OnUpdate?.Invoke(this, new EventArgs()); #if !DEBUG } catch (ThreadAbortException) { return; } catch (Exception ex) { this.OnError?.Invoke(this, new UnhandledExceptionEventArgs(ex, false)); } #endif }
private void BtnAdd_Click(object sender, EventArgs e) { try { //if (!this.validator1.Validate()) { // return; } this.user.FirstName = this.txtFirstName.Text; this.user.LastName = this.txtLastName.Text; this.user.Email = this.txtEmail.Text; this.user.Privilege = this.privilegeControl1.Selecteds; this.user.Enable = this.ckbEnable.Checked; string message = "¿Seguro que desea Agregar este nuevo Usuario?"; DialogResult dialogResult = Helpers.ShowDialog(message, MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { var updated = this.repository.Update(this.user); if (updated != null) { OnUpdate?.Invoke(updated, new EventArgs()); } this.Close(); } } catch (Exception ex) { ex.ShowDialog(); } }
/// <summary> /// Start the game update and render loops /// </summary> public static void Begin(string title, Vector2 size) { Console.Title = title; Size = size; Render.Start(); Input.Start(); OnStart?.Invoke(); while (true) { currentTime = DateTime.Now; DeltaTime = (float)currentTime.Subtract(lastTime).TotalSeconds; lastTime = currentTime; frameRate++; if (currentTime >= nextFrameRateUpdate) { nextFrameRateUpdate = currentTime.AddSeconds(1); Console.Title = $"{title} - {frameRate}"; frameRate = 0; } Input.Update(); OnUpdate?.Invoke(); Render.Update(); } }
/// <summary> /// Updates this drawable, once every frame. /// </summary> /// <returns>False if the drawable should not be updated.</returns> protected internal virtual bool UpdateSubTree() { if (Parent != null) //we don't want to update our clock if we are at the top of the stack. it's handled elsewhere for us. { customClock?.ProcessFrame(); } if (LoadState < LoadState.Alive) { if (!loadComplete()) { return(false); } } transformationDelay = 0; //todo: this should be moved to after the IsVisible condition once we have TOL for transformations (and some better logic). updateTransforms(); if (!IsVisible) { return(true); } Update(); OnUpdate?.Invoke(); return(true); }
private void ParseField(string rawField) { rawField = rawField.Substring(6); int size = (int)Math.Sqrt(rawField.Length); if (MapSize != size) { Map = new Elements[size, size]; MapSize = size; } int rawPosition = 0; for (int j = 0; j < size; j++) { for (int i = 0; i < size; i++) { Map[i, j] = CharToBlock(rawField[rawPosition]); if (IsPlayerCoords(Map[i, j])) { PlayerX = i; PlayerY = j; } rawPosition++; } } OnUpdate?.Invoke(); }
private void Recalculate() { _value = _evaluateAsPercent ? _curve.EvaluateFactor(_x.Value, _useZeroBaseline) : _curve.Value.Evaluate(_x.Value); OnUpdate?.Invoke(); }
public void ProcessQueue() { Dictionary <Guid, ToDoItem> items = new Dictionary <Guid, ToDoItem>(); ToDoItem toDoItem; while (queue.TryDequeue(out toDoItem)) { items[toDoItem.EditId] = toDoItem; } foreach (var item in items) { ToDoItemEventArgs args = new ToDoItemEventArgs { Item = item.Value }; if (item.Value.MarkedForRemoval) { // TODO: Remove from database here OnRemove?.Invoke(this, args); continue; } // TODO: Database Update Here // TEMP if (item.Value.Id == 0) { item.Value.Id = rd.Next(1, 9999); OnCreate?.Invoke(this, args); } OnUpdate?.Invoke(this, args); } }