private static Vector3 Truncate(Vector3 value, int decimals) { float power = MathF.Pow(10, decimals); value.X = float.IsNegative(value.X) ? MathF.Ceiling(value.X * power) / power : MathF.Floor(value.X * power) / power; value.Y = float.IsNegative(value.Y) ? MathF.Ceiling(value.Y * power) / power : MathF.Floor(value.Y * power) / power; value.Z = float.IsNegative(value.Z) ? MathF.Ceiling(value.Z * power) / power : MathF.Floor(value.Z * power) / power; return(value); }
/// <summary> /// Divide Width and Height as real numbers and return the Ceiling. /// </summary> public static Size DivideRoundUp(this Size originalSize, int divX, int divY) { var sizeVect = (Vector2)(SizeF)originalSize; sizeVect /= new Vector2(divX, divY); sizeVect.X = MathF.Ceiling(sizeVect.X); sizeVect.Y = MathF.Ceiling(sizeVect.Y); return(new Size((int)sizeVect.X, (int)sizeVect.Y)); }
public void DrawLine(int xStart, int yStart, int xEnd, int yEnd, byte r, byte g, byte b, byte a = 0) { if (Math.Abs(xEnd - xStart) > Math.Abs(yEnd - yStart)) { var direction = xEnd > xStart ? 1 : -1; for (var x = xStart; direction > 0 ? x <= xEnd : x >= xEnd; x += direction) { var y = (float)(x - xStart) / (xEnd - xStart) * (yEnd - yStart) + yStart; var yFloor = MathF.Floor(y); var yCeiling = MathF.Ceiling(y); var yCenter = y - yFloor > yCeiling - y ? yCeiling : yFloor; SetRGBA(x, yCenter, r, g, b, a); SetRGBA(x, yCenter + 1, r, g, b, a); SetRGBA(x, yCenter - 1, r, g, b, a); SetRGBA(x + 1, yCenter, r, g, b, a); SetRGBA(x - 1, yCenter, r, g, b, a); //if (yFloor == yCeiling) //{ // SetRGBA(x, yFloor, r, g, b, a); //} //else //{ // BlendRGBA(x, yFloor, MathF.Sqrt(yCeiling - y), r, g, b, a); // BlendRGBA(x, yCeiling, MathF.Sqrt(y - yFloor), r, g, b, a); //} } } else { var direction = yEnd > yStart ? 1 : -1; for (var y = yStart; direction > 0 ? y <= yEnd : y >= yEnd; y += direction) { var x = (float)(y - yStart) / (yEnd - yStart) * (xEnd - xStart) + xStart; var xFloor = MathF.Floor(x); var xCeiling = MathF.Ceiling(x); var xCenter = x - xFloor > xCeiling - x ? xCeiling : xFloor; SetRGBA(xCenter, y, r, g, b, a); SetRGBA(xCenter + 1, y, r, g, b, a); SetRGBA(xCenter - 1, y, r, g, b, a); SetRGBA(xCenter, y + 1, r, g, b, a); SetRGBA(xCenter, y - 1, r, g, b, a); //if (xFloor == xCeiling) //{ // SetRGBA(xFloor, y, r, g, b, a); //} //else //{ // BlendRGBA(xFloor, y, MathF.Sqrt(xCeiling - x), r, g, b, a); // BlendRGBA(xCeiling, y, MathF.Sqrt(x - xFloor), r, g, b, a); //} } } }
protected override void FrameUpdate(FrameEventArgs args) { base.FrameUpdate(args); _timeLeft -= args.DeltaSeconds; // Lerp to our new vertical offset if it's been modified. if (MathHelper.CloseToPercent(_verticalOffsetAchieved - VerticalOffset, 0, 0.1)) { _verticalOffsetAchieved = VerticalOffset; } else { _verticalOffsetAchieved = MathHelper.Lerp(_verticalOffsetAchieved, VerticalOffset, 10 * args.DeltaSeconds); } if (!_entityManager.GetComponent <TransformComponent>(_senderEntity).Coordinates.IsValid(_entityManager)) { Modulate = Color.White.WithAlpha(0); return; } if (_timeLeft <= FadeTime) { // Update alpha if we're fading. Modulate = Color.White.WithAlpha(_timeLeft / FadeTime); } else { // Make opaque otherwise, because it might have been hidden before Modulate = Color.White; } if (_entityManager.Deleted(_senderEntity) || _timeLeft <= 0) { // Timer spawn to prevent concurrent modification exception. Timer.Spawn(0, Die); return; } var worldPos = _entityManager.GetComponent <TransformComponent>(_senderEntity).WorldPosition; var scale = _eyeManager.MainViewport.GetRenderScale(); var offset = new Vector2(0, EntityVerticalOffset * EyeManager.PixelsPerMeter * scale); var lowerCenter = (_eyeManager.WorldToScreen(worldPos) - offset) / UIScale; var screenPos = lowerCenter - (Width / 2, ContentHeight + _verticalOffsetAchieved); // Round to nearest 0.5 screenPos = (screenPos * 2).Rounded() / 2; LayoutContainer.SetPosition(this, screenPos); var height = MathF.Ceiling(MathHelper.Clamp(lowerCenter.Y - screenPos.Y, 0, ContentHeight)); SetHeight = height; }
public SquareFormation(Vector3 goal, IPathReceiver <PotentialField>[] pathReceivers) { Goal = goal; var size = (int)MathF.Ceiling(MathF.Sqrt(pathReceivers.Length)); PathReceivers = new Array2D <IPathReceiver <PotentialField> >(size, size); for (int i = 0; i < pathReceivers.Length; i++) { PathReceivers[i] = pathReceivers[i]; } }
public int CalculatePrice() { if (this.quantity == 0) { return(this.baseCost); } float multiplier = 1.09f; //TODO: Move this to a global float price = this.baseCost * MathF.Pow(multiplier, this.quantity); return((int)MathF.Ceiling(price)); //The Math.ceil() function returns the smallest integer greater than or equal to a given number. }
public int CalculateIndexCount() { //Get number of probes var size = Grid.Max - Grid.Min; var stride = size / Grid.Step; stride.X = MathF.Ceiling(stride.X); stride.Y = MathF.Ceiling(stride.Y); stride.Z = MathF.Ceiling(stride.Z); return((int)(stride.X * stride.Y * stride.Z) * 8); //8 probes in each }
public AtlasGlyph(Glyph fontGlyph, float scale, float ascend) { CharIndex = (char)fontGlyph.CharIndex; Advance = MathF.Round(fontGlyph.AdvanceWidth * scale); XMin = MathF.Floor(fontGlyph.XMin * scale); Rectangle bbox = fontGlyph.GetBBox(scale); YBearing = bbox.Y + MathF.Ceiling(ascend * scale); YMin = MathF.Floor(fontGlyph.YMin * scale); Size = fontGlyph.GetDrawBox(scale).Size; }
/// <summary>Inflate the rectangle, snapping all 4 edges to integers.</summary> public static Rect inflateToIntegers(this Rect pixels) { Vector2 tl = pixels.topLeft; Vector2 br = pixels.bottomRight; tl.X = MathF.Floor(tl.X); tl.Y = MathF.Floor(tl.Y); br.X = MathF.Ceiling(br.X); br.Y = MathF.Ceiling(br.Y); return(new Rect(tl, br)); }
private static BigInteger CreateMask(int bits) { var mask = (BigInteger)0xff; var size = (int)MathF.Ceiling(bits / 8f); for (var i = 1; i < size; i++) { mask ^= 0xff << (8 * i); } return(mask); }
/// <summary> /// Allocates the frame component blocks. /// </summary> public void InitComponents() { this.McusPerLine = (int)MathF.Ceiling(this.SamplesPerLine / 8F / this.MaxHorizontalFactor); this.McusPerColumn = (int)MathF.Ceiling(this.Scanlines / 8F / this.MaxVerticalFactor); for (int i = 0; i < this.ComponentCount; i++) { JpegComponent component = this.Components[i]; component.Init(); } }
public static int Digits(this float self) { float i = RoundToNextSignificant(self); if (float.IsInfinity(i)) { return(0); } return((int)MathF.Ceiling(-MathF.Log10(i)) + 2); }
/// <summary> /// Initializes a new instance of the <see cref="ShapeRegion"/> class. /// </summary> /// <param name="shape">The shape.</param> public ShapeRegion(IPath shape) { this.Shape = shape.AsClosedPath(); int left = (int)MathF.Floor(shape.Bounds.Left); int top = (int)MathF.Floor(shape.Bounds.Top); int right = (int)MathF.Ceiling(shape.Bounds.Right); int bottom = (int)MathF.Ceiling(shape.Bounds.Bottom); this.Bounds = Rectangle.FromLTRB(left, top, right, bottom); }
private float GetSamplingRadius(int sourceSize, int destinationSize) { float scale = (float)sourceSize / destinationSize; if (scale < 1F) { scale = 1F; } return(MathF.Ceiling(scale * this.sampler.Radius)); }
protected override void FrameUpdate(FrameEventArgs args) { base.FrameUpdate(args); _timeLeft -= args.DeltaSeconds; if (_entityManager.Deleted(_senderEntity) || _timeLeft <= 0) { // Timer spawn to prevent concurrent modification exception. Timer.Spawn(0, Die); return; } // Lerp to our new vertical offset if it's been modified. if (MathHelper.CloseToPercent(_verticalOffsetAchieved - VerticalOffset, 0, 0.1)) { _verticalOffsetAchieved = VerticalOffset; } else { _verticalOffsetAchieved = MathHelper.Lerp(_verticalOffsetAchieved, VerticalOffset, 10 * args.DeltaSeconds); } if (!_entityManager.TryGetComponent <TransformComponent>(_senderEntity, out var xform) || xform.MapID != _eyeManager.CurrentMap) { Modulate = Color.White.WithAlpha(0); return; } if (_timeLeft <= FadeTime) { // Update alpha if we're fading. Modulate = Color.White.WithAlpha(_timeLeft / FadeTime); } else { // Make opaque otherwise, because it might have been hidden before Modulate = Color.White; } var offset = (-_eyeManager.CurrentEye.Rotation).ToWorldVec() * -EntityVerticalOffset; var worldPos = xform.WorldPosition + offset; var lowerCenter = _eyeManager.WorldToScreen(worldPos) / UIScale; var screenPos = lowerCenter - (ContentSize.X / 2, ContentSize.Y + _verticalOffsetAchieved); // Round to nearest 0.5 screenPos = (screenPos * 2).Rounded() / 2; LayoutContainer.SetPosition(this, screenPos); var height = MathF.Ceiling(MathHelper.Clamp(lowerCenter.Y - screenPos.Y, 0, ContentSize.Y)); SetHeight = height; }
public void UpdateStatsHungryAndUnhappyLimits() { Pet generatedPet = _petFactory.GetPet(); float minutesToSadness = MathF.Ceiling((generatedPet.Happiness - generatedPet.HAPPINESS_MIN) / MathF.Abs(generatedPet.HappinessRate)); float minutesToStarve = MathF.Ceiling((generatedPet.HUNGRINESS_MAX - generatedPet.Hungriness) / MathF.Abs(generatedPet.HungrinessRate)); float minutesElapsed = (minutesToSadness > minutesToStarve) ? minutesToSadness : minutesToStarve; generatedPet.LastUpdate = DateTime.UtcNow - TimeSpan.FromMinutes(minutesElapsed); generatedPet.UpdateMetrics(); Assert.Equal(generatedPet.Hungriness, generatedPet.HUNGRINESS_MAX); Assert.Equal(generatedPet.Happiness, generatedPet.HAPPINESS_MIN); }
public async Task <int> GetNumOfPagesWithProductsForCategory(string categoryName, int numProductsOnPage) { var categoryId = (await _dataContext.Categories.FirstOrDefaultAsync(x => x.Name == categoryName)).CategoryID; var productsCount = _dataContext.Products.Where(x => x.CategoryId == categoryId)?.Count(); var result = (numProductsOnPage <= 0) ? productsCount ?? 0 : (int)MathF.Ceiling((float)productsCount / (float)numProductsOnPage); return(result); }
public override void ReceiveSignal(Signal signal, Connection connection) { if (connection.Name != "signal_in") { return; } if (!float.TryParse(signal.value, NumberStyles.Float, CultureInfo.InvariantCulture, out float value)) { return; } switch (Function) { case FunctionType.Round: value = MathF.Round(value); break; case FunctionType.Ceil: value = MathF.Ceiling(value); break; case FunctionType.Floor: value = MathF.Floor(value); break; case FunctionType.Factorial: int intVal = (int)Math.Min(value, 20); ulong factorial = 1; for (int i = intVal; i > 0; i--) { factorial *= (ulong)i; } value = factorial; break; case FunctionType.AbsoluteValue: value = MathF.Abs(value); break; case FunctionType.SquareRoot: if (value < 0) { return; } value = MathF.Sqrt(value); break; default: throw new NotImplementedException($"Function {Function} has not been implemented."); } signal.value = value.ToString("G", CultureInfo.InvariantCulture); item.SendSignal(signal, "signal_out"); }
private static Rectangle GetBoundingRectangle(Vector2 tl, Vector2 tr, Vector2 bl, Vector2 br) { // Find the minimum and maximum "corners" based on the given vectors float minX = MathF.Min(tl.X, MathF.Min(tr.X, MathF.Min(bl.X, br.X))); float maxX = MathF.Max(tl.X, MathF.Max(tr.X, MathF.Max(bl.X, br.X))); float minY = MathF.Min(tl.Y, MathF.Min(tr.Y, MathF.Min(bl.Y, br.Y))); float maxY = MathF.Max(tl.Y, MathF.Max(tr.Y, MathF.Max(bl.Y, br.Y))); float sizeX = maxX - minX + .5F; float sizeY = maxY - minY + .5F; return(new Rectangle((int)(MathF.Ceiling(minX) - .5F), (int)(MathF.Ceiling(minY) - .5F), (int)MathF.Floor(sizeX), (int)MathF.Floor(sizeY))); }
static void CalcRevenue(string employee, int money) { //부모노드가 없거나 money가 0이면 계산 할 것이 없음. if (employee.Equals("-") || money < 1) { return; } int temp = (int)MathF.Ceiling(money / 10); //소수 첫째자리 올림 m_empTotalRev[employee] += (money - temp); //판매한 칫솔 가격의 10%를 떼고 더해줌 CalcRevenue(m_empRef[employee], temp); }
public BlockLinearSwizzle(int Width, int Bpp, int BlockHeight = 16) { BhMask = (BlockHeight * 8) - 1; BhShift = CountLsbZeros(BlockHeight * 8); BppShift = CountLsbZeros(Bpp); int WidthInGobs = (int)MathF.Ceiling(Width * Bpp / 64f); GobStride = 512 * BlockHeight * WidthInGobs; XShift = CountLsbZeros(512 * BlockHeight); }
public static T[][] Split <T>(this T[] source, int maxLength) { var numParts = (int)MathF.Ceiling(source.Length / (float)maxLength); var result = new T[numParts][]; for (var itP = 0; itP < numParts - 1; itP++) { var part = new T[maxLength]; Array.Copy(source, itP * maxLength, part, 0, maxLength); result[itP] = part; } result[^ 1] = new T[source.Length - (numParts - 1) * maxLength];
private bool CheckHorizontal(int _IdButton, int _idFillPlayer) { int row = (int)(MathF.Ceiling((_IdButton + 1) / 3)); Console.WriteLine("\nCH Row: " + row); if ((board[((row - 1) * 3 + 1) - 1] == _idFillPlayer) && (board[((row - 1) * 3 + 2) - 1] == _idFillPlayer) && (board[((row - 1) * 3 + 3) - 1] == _idFillPlayer)) { return(true); } return(false); }
private bool CheckVertical(int _IdButton, int _idFillPlayer) { int col = (int)MathF.Ceiling((_IdButton + 1) % 3); Console.WriteLine("\nCH col: " + col); if ((board[col + 1 - 2]) == _idFillPlayer && (board[col + 4 - 2]) == _idFillPlayer && (board[col + 7 - 2]) == _idFillPlayer) { return(true); } return(false); }
private void Explode(EntityUid uid, BatteryComponent?battery = null) { _adminLogger.Add(LogType.Explosion, LogImpact.High, $"Sabotaged power cell {ToPrettyString(uid)} is exploding"); if (!Resolve(uid, ref battery)) { return; } var radius = MathF.Min(5, MathF.Ceiling(MathF.Sqrt(battery.CurrentCharge) / 30)); _explosionSystem.TriggerExplosive(uid, radius: radius); QueueDel(uid); }
void DrawFrame(Settings settings) { //Device.DefaultQueue.WriteBuffer() var blockDim = TileDim - (settings.FilterSize - 1); if (_LastSettings.FilterSize == settings.FilterSize && _LastSettings.Iterations == settings.Iterations) { } else { Device.DefaultQueue.WriteBuffer(BlurParamsBuffer, 0, CreateBufferFromArray(new UInt32[] { settings.FilterSize, blockDim })); _LastSettings = settings; } var commandEncoder = Device.CreateCommandEncoder(); var computePass = commandEncoder.BeginComputePass(); computePass.SetPipeline(BlurPipeline); computePass.SetBindGroup(0, ComputeConstants); computePass.SetBindGroup(1, ComputeBindGroup0); computePass.Dispatch((uint)MathF.Ceiling(SrcWidth / ((float)blockDim)), (uint)MathF.Ceiling(SrcHeight / ((float)Batch[1])), 1); computePass.Dispatch(2, (uint)MathF.Ceiling(SrcHeight / ((float)Batch[1])), 1); computePass.SetBindGroup(1, ComputeBindGroup1); computePass.Dispatch((uint)MathF.Ceiling(SrcHeight / ((float)blockDim)), (uint)MathF.Ceiling(SrcWidth / ((float)Batch[1])), 1); for (int i = 0; i < settings.Iterations - 1; ++i) { computePass.SetBindGroup(1, ComputeBindGroup2); computePass.Dispatch((uint)MathF.Ceiling(SrcWidth / ((float)blockDim)), (uint)MathF.Ceiling(SrcHeight / ((float)Batch[1])), 1); computePass.SetBindGroup(1, ComputeBindGroup1); computePass.Dispatch((uint)MathF.Ceiling(SrcHeight / ((float)blockDim)), (uint)MathF.Ceiling(SrcWidth / ((float)Batch[1])), 1); } computePass.EndPass(); var passEncoder = commandEncoder.BeginRenderPass(new GpuRenderPassDescriptor(new GpuRenderPassColorAttachment[] { new GpuRenderPassColorAttachment(SwapChain.GetCurrentTexture().CreateView(), new GpuColorDict() { R = 0, G = 0, B = 0, A = 1 }) })); passEncoder.SetPipeline(Pipeline); passEncoder.SetVertexBuffer(0, VerticesBuffer, 0, VerticesBuffer.Size); passEncoder.SetBindGroup(0, UniformBindGroup); passEncoder.Draw(6, 1, 0, 0); passEncoder.EndPass(); Device.DefaultQueue.Sumit(new GpuCommandBuffer[] { commandEncoder.Finish() }); }
public bool ValidateDeliveryVolume(DeliveryModel delivery) { var deliveries = _orderService.GetAllDeliveriesInStorage(delivery.StorageId).ToList(); var overlappingReservations = _orderService.GetReservationsOverlappingDateRange(delivery.DeliveryDate, delivery.DeliveryDate.AddYears(5), delivery.StorageId); List <OrderValidationModel> orderValidationModels = new List <OrderValidationModel>(); if (deliveries.FirstOrDefault(x => x.Id == delivery.Id) == default) { deliveries.Add(delivery); } else { deliveries.Remove(deliveries.First(x => x.Id == delivery.Id)); deliveries.Add(delivery); } foreach (var d in deliveries) { OrderValidationModel order = new OrderValidationModel(); order.StartDate = d.DeliveryDate; order.EndDate = d.DeliveryDate.AddYears(5); order.Volume = (int)MathF.Ceiling(d.Volume * _itemService.GetOne(d.ItemId).Size); orderValidationModels.Add(order); } foreach (var reservation in overlappingReservations) { OrderValidationModel order = new OrderValidationModel(); order.StartDate = reservation.StartDate; order.EndDate = reservation.EndDate; if (reservation.ItemId != default) { order.Volume = (int)MathF.Ceiling(reservation.Volume * _itemService.GetOne(reservation.ItemId).Size); } else { order.Volume = reservation.Volume; } orderValidationModels.Add(order); } orderValidationModels.Sort((x, y) => x.StartDate.CompareTo(y.StartDate)); CheckStorageOverflow(orderValidationModels, _storageService.GetOne(delivery.StorageId).Capacity); return(!CheckStorageOverflow(orderValidationModels, _storageService.GetOne(delivery.StorageId).Capacity)); }
public unsafe void Fill(int pixelOffset, Span <byte> destination) { int startPixelOffset = dataOffset / Components; int requestedPixelCount = (int)MathF.Ceiling(destination.Length / (float)Components); int column = startPixelOffset % Width; int row = startPixelOffset / Width; var converter32 = new PixelConverter32(); int pixelSize = _pixels.PixelType.ElementSize; // each iteration is supposed to read pixels from a single row at the time int destinationOffset = 0; int pixelsLeft = requestedPixelCount; while (pixelsLeft > 0) { int lastByteOffset = destinationOffset; int count = Math.Min(pixelsLeft, _pixels.Size.Width - column); _pixels.GetPixelByteRow(column, row, _rowBuffer); if (_transform32.Invoke( _rowBuffer, Components, count, destination, ref destinationOffset, ref converter32)) { goto ReadEnd; } // copy over the remaining bytes, // as the Fill() caller may request less bytes than sizeof(TPixel) int bytesRead = destinationOffset - lastByteOffset; int leftoverBytes = Math.Min(Components, count * Components - bytesRead); for (int j = 0; j < leftoverBytes; j++) { destination[j + destinationOffset] = converter32.Raw[j]; } destinationOffset += leftoverBytes; // a case for code that copies bytes directly, // not needing to copy leftovers ReadEnd: pixelsLeft -= count; column = 0; // read from row beginning on next loop row++; // and jump to the next row } }
public static float RoundF(float Value, int Fpcr) { switch ((ARoundMode)((Fpcr >> 22) & 3)) { case ARoundMode.ToNearest: return(MathF.Round(Value)); case ARoundMode.TowardsPlusInfinity: return(MathF.Ceiling(Value)); case ARoundMode.TowardsMinusInfinity: return(MathF.Floor(Value)); case ARoundMode.TowardsZero: return(MathF.Truncate(Value)); } throw new InvalidOperationException(); }
public static float RoundF(float value, CpuThreadState state) { switch (state.FPRoundingMode()) { case RoundMode.ToNearest: return(MathF.Round(value)); case RoundMode.TowardsPlusInfinity: return(MathF.Ceiling(value)); case RoundMode.TowardsMinusInfinity: return(MathF.Floor(value)); case RoundMode.TowardsZero: return(MathF.Truncate(value)); } throw new InvalidOperationException(); }