示例#1
0
        public float LinearInterpolate(Vector2 position, OverworldField fieldType)
        {
            float x  = position.X;
            float y  = position.Y;
            float x1 = (int)MathFunctions.Clamp((float)Math.Ceiling(x), 0, Map.GetLength(0) - 2);
            float y1 = (int)MathFunctions.Clamp((float)Math.Ceiling(y), 0, Map.GetLength(1) - 2);
            float x2 = (int)MathFunctions.Clamp((float)Math.Floor(x), 0, Map.GetLength(0) - 2);
            float y2 = (int)MathFunctions.Clamp((float)Math.Floor(y), 0, Map.GetLength(1) - 2);

            if (Math.Abs(x1 - x2) < 0.5f)
            {
                x1 = x1 + 1;
            }

            if (Math.Abs(y1 - y2) < 0.5f)
            {
                y1 = y1 + 1;
            }

            float q11 = Map[(int)x1, (int)y1].GetValue(fieldType);
            float q12 = Map[(int)x1, (int)y2].GetValue(fieldType);
            float q21 = Map[(int)x2, (int)y1].GetValue(fieldType);
            float q22 = Map[(int)x2, (int)y2].GetValue(fieldType);

            return(MathFunctions.LinearCombination(x, y, x1, y1, x2, y2, q11, q12, q21, q22));
        }
        protected async void ChangeBackgroundImage()
        {
            var element = Element as CalendarButton;

            if (element?.BackgroundImage == null)
            {
                return;
            }

            var d     = new List <Drawable>();
            var image = await GetBitmap(element.BackgroundImage);

            d.Add(new BitmapDrawable(image));
            var drawable = new GradientDrawable();

            drawable.SetShape(ShapeType.Rectangle);
            var borderWidth = (int)Math.Ceiling(element.BorderWidth);

            drawable.SetStroke(borderWidth > 0 ? borderWidth + 1 : borderWidth, element.TintBorderColor.ToAndroid());
            drawable.SetColor(Color.Transparent);
            d.Add(drawable);
            var layer = new LayerDrawable(d.ToArray());

            layer.SetLayerInset(d.Count - 1, 0, 0, 0, 0);
            Control.SetBackground(layer);
        }
示例#3
0
        private static int Math_Modf(ILuaState lua)
        {
            double d = lua.L_CheckNumber(1);
            double c = Math.Ceiling(d);

            lua.PushNumber(c);
            lua.PushNumber(d - c);
            return(2);
        }
        public int Dp(float value, Context context)
        {
            if (Density == 1.0F)
            {
                CheckDisplaySize(context);
            }

            return(value == 0.0F ? 0 : (int)Math.Ceiling((double)(Density * value)));
        }
示例#5
0
        public static void AfterWorldLoad()
        {
            var worldChunks = GetWorldChunks();

            _numberOfCycles = (int)Math.Ceiling((double)worldChunks.Count / CHUNKS_PER_CYCLE);
            _previousSesion = _seasons.Count - 1;
            ChunkUpdating.PlayerLoadedMaxRange = ChunkUpdating.PlayerLoadedMaxRange * 3;
            ChunkUpdating.PlayerLoadedMinRange = ChunkUpdating.PlayerLoadedMaxRange;
        }
        public SimpleLRUCache_OrgPort(int cacheSize)
            : base(null)
        {
            this.cacheSize = cacheSize;
            int capacity = (int)Math.Ceiling(cacheSize / LOADFACTOR) + 1;

            base.map = new System.Collections.Hashtable(capacity, LOADFACTOR);

            lru = new LinkedList();
        }
示例#7
0
        /// <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);
        }
        protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);
            if (!(Element is CalendarButton element))
            {
                return;
            }

            if (e.PropertyName == nameof(element.TextWithoutMeasure) || e.PropertyName == "Renderer")
            {
                Control.Text = element.TextWithoutMeasure;
            }

            if (e.PropertyName == nameof(element.TextColor) || e.PropertyName == "Renderer")
            {
                Control.SetTextColor(element.TextColor.ToAndroid());
            }

            if (e.PropertyName == nameof(element.BorderWidth) || e.PropertyName == nameof(element.TintBorderColor) ||
                e.PropertyName == nameof(element.TintColor) || e.PropertyName == "Renderer")
            {
                if (element.BackgroundPattern == null)
                {
                    if (element.BackgroundImage == null)
                    {
                        var drawable = new GradientDrawable();
                        drawable.SetShape(ShapeType.Rectangle);
                        var borderWidth = (int)Math.Ceiling(element.BorderWidth);
                        drawable.SetStroke(borderWidth > 0 ? borderWidth + 1 : borderWidth, element.TintBorderColor.ToAndroid());
                        drawable.SetColor(element.TintColor.ToAndroid());
                        Control.SetBackground(drawable);
                    }
                    else
                    {
                        ChangeBackgroundImage();
                    }
                }
                else
                {
                    ChangeBackgroundPattern();
                }
            }

            if (e.PropertyName == nameof(element.BackgroundPattern))
            {
                ChangeBackgroundPattern();
            }

            if (e.PropertyName == nameof(element.BackgroundImage))
            {
                ChangeBackgroundImage();
            }
        }
示例#9
0
        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)));
        }
示例#10
0
        public static float GetLineHeight(this CTFont font)
        {
            // https://stackoverflow.com/questions/5511830/how-does-line-spacing-work-in-core-text-and-why-is-it-different-from-nslayoutm
            //var ascent = (double)font.AscentMetric;
            //var descent = (double)font.DescentMetric;
            //var leading = (double)font.LeadingMetric;
            //leading = leading < 0 ? 0.0 : Math.Floor(leading + 0.5);
            //var lineHeight = Math.Floor(ascent + 0.5) + Math.Floor(descent + 0.5) + leading;
            //var ascenderDelta = leading > 0 ? 0.0 : Math.Floor(0.2 * lineHeight + 0.5);
            //return (float)(lineHeight + ascenderDelta);

            return((float)NMath.Ceiling(font.AscentMetric + font.DescentMetric + font.LeadingMetric + 1));
        }
示例#11
0
        private void add(double d) {
            long value = 0;

            if (d > 0)
                value = (long)SM.Floor(d);
            else
                value = (long)SM.Ceiling(d);
            accumulated += (d - value);

            if (accumulated >= 1) {
                ++value;
                --accumulated;
            } else if (accumulated <= -1) {
                --value;
                ++accumulated;
            }
            Total += value;
        }
示例#12
0
        public LevelTileTypes TickCollisions()
        {
            var levelGrid = LevelConstants.LEVEL_GRID;
            var blockSize = levelGrid.Size;

            var(centerLevelC, centerLevelR) =
                ((int)CMath.Floor(this.PlayerRigidbody.CenterX / blockSize),
                 (int)CMath.Floor(this.PlayerRigidbody.CenterY / blockSize));

            var windowWidth =
                (int)(1 +
                      CMath.Ceiling(PlayerConstants.HSIZE / blockSize) +
                      1);
            var windowHeight =
                (int)(1 +
                      CMath.Ceiling(PlayerConstants.VSIZE / blockSize) +
                      1);

            var relativeWindowHStart = (int)-CMath.Floor(windowWidth / 2d);
            var relativeWindowVStart = (int)-CMath.Floor(windowHeight / 2d);

            var collidedTypes = LevelTileTypes.EMPTY;

            for (var r = 0; r < windowHeight; ++r)
            {
                for (var c = 0; c < windowWidth; ++c)
                {
                    var(relativeCacheC, relativeCacheR) =
                        (relativeWindowHStart + c, relativeWindowVStart + r);
                    var(absoluteLevelC, absoluteLevelR) = (centerLevelC + relativeCacheC,
                                                           centerLevelR +
                                                           relativeCacheR);
                    var tile = levelGrid.GetAtIndex(absoluteLevelC, absoluteLevelR);
                    if (tile != LevelTileTypes.EMPTY)
                    {
                        var blockPosition = (absoluteLevelC * blockSize,
                                             absoluteLevelR *blockSize);
                        collidedTypes |= this.CheckCollisions_(tile, blockPosition);
                    }
                }
            }

            return(collidedTypes);
        }
        protected void ChangeBackgroundPattern()
        {
            var element = Element as CalendarButton;

            if (element?.BackgroundPattern == null || Control.Width == 0)
            {
                return;
            }

            var d = new List <Drawable>();

            for (var i = 0; i < element.BackgroundPattern.Pattern.Count; i++)
            {
                var bp = element.BackgroundPattern.Pattern[i];
                d.Add(!string.IsNullOrEmpty(bp.Text)
                    ? new TextDrawable(bp.Color.ToAndroid())
                {
                    Pattern = bp
                }
                    : new ColorDrawable(bp.Color.ToAndroid()));
            }
            var drawable = new GradientDrawable();

            drawable.SetShape(ShapeType.Rectangle);
            var borderWidth = (int)Math.Ceiling(element.BorderWidth);

            drawable.SetStroke(borderWidth > 0 ? borderWidth + 1 : borderWidth, element.TintBorderColor.ToAndroid());
            drawable.SetColor(Color.Transparent);
            d.Add(drawable);
            var layer = new LayerDrawable(d.ToArray());

            for (var i = 0; i < element.BackgroundPattern.Pattern.Count; i++)
            {
                var l = (int)Math.Ceiling(Control.Width * element.BackgroundPattern.GetLeft(i));
                var t = (int)Math.Ceiling(Control.Height * element.BackgroundPattern.GetTop(i));
                var r = (int)Math.Ceiling(Control.Width * (1 - element.BackgroundPattern.Pattern[i].WidthPercent)) - l;
                var b = (int)Math.Ceiling(Control.Height * (1 - element.BackgroundPattern.Pattern[i].HightPercent)) - t;
                layer.SetLayerInset(i, l, t, r, b);
            }
            layer.SetLayerInset(d.Count - 1, 0, 0, 0, 0);
            Control.SetBackground(layer);
        }
示例#14
0
        /// <summary>
        /// Classify With KNN
        /// </summary>
        /// <param name="predictor"></param>
        /// <param name="neighbors"></param>
        /// <param name="min"></param>
        /// <param name="max"></param>
        /// <returns></returns>
        public Predictor <int> Classify(Predictor <int> predictor, IEnumerable <Neighbor <int> > neighbors, int min, int max)
        {
            var totalClasses = (int)Mathematics.Ceiling(Mathematics.Sqrt(neighbors.GroupBy(x => x.Classifier).Count()));

            var results = new List <Result <int> >();

            int k = totalClasses % 2 == 0 ? totalClasses + 1 : totalClasses; //k should always be odd

            //normalize data
            var data = neighbors.Select(x => new Neighbor <int>()
            {
                ExternalId = x.ExternalId,
                Classifier = x.Classifier,
                Features   = x.Features.Normalize(max, min)
            });

            predictor.Features = predictor.Features.Normalize(max, min);

            //calculate euclidean distance
            foreach (var item in data)
            {
                results.Add(
                    new Result <int>()
                {
                    Value    = Distance.CalculateEuclidean(predictor.Features.ToArray(), item.Features.ToArray()),
                    Neighbor = item
                }
                    );
            }

            //get nearest neighbors
            var topResults = results.OrderByDescending(x => x.Value).Take(k);

            //get majority vote by neighbors
            var classes = topResults.GroupBy(x => x.Neighbor.Classifier).OrderByDescending(x => x.Count());

            //set classifier prediction
            predictor.Prediction = classes.SingleOrDefault().SingleOrDefault().Neighbor.Classifier;

            return(predictor);
        }
示例#15
0
            // Main draw method of a group that is called from outside
            public void Draw(float yOffset, Vector2 scrollPos, ref int rowsInUse)
            {
                NeedsRepaint = false;

                // We need to always draw the header as it uses controlIDs (and we cannot cull gui elements using controlID)
                bool isRepaint = Event.current.type == EventType.Repaint || Event.current.type == EventType.Layout;

                if (!isRepaint)
                {
                    DrawHeader(yOffset, m_Collapsable); // logic here, draw on top below
                }
                if (!IsInView(yOffset, scrollPos, m_Owner.m_VisibleRect.height))
                {
                    return;
                }

                int invisibleRows  = FirstVisibleRow(yOffset, scrollPos);
                int beginItem      = invisibleRows * m_Grid.columns;
                int totalItemCount = ItemCount;

                if (beginItem >= 0 && beginItem < totalItemCount)
                {
                    int itemIdx = beginItem;
                    // Limit by items avail and max items to show
                    // (plus an extra row to allow half a row in top and bottom at the same time)
                    int endItem = Math.Min(totalItemCount, m_Grid.rows * m_Grid.columns);

                    // Also limit to what can possible be in view in order to limit draws
                    float itemHeight        = m_Grid.itemSize.y + m_Grid.verticalSpacing;
                    int   rowsInVisibleRect = (int)Math.Ceiling(m_Owner.m_VisibleRect.height / itemHeight);

                    //When a row is hidden behind the header, it is still counted as visible, therefore to avoid
                    //weird popping in and out for the icons, we make sure that a new row will be rendered even if one
                    //is considered visible, even though it cannot be seen in the window
                    rowsInVisibleRect += 1;

                    int rowsNotInUse = rowsInVisibleRect - rowsInUse;
                    if (rowsNotInUse < 0)
                    {
                        rowsNotInUse = 0;
                    }

                    rowsInUse = Math.Min(rowsInVisibleRect, Mathf.CeilToInt((endItem - beginItem) / (float)m_Grid.columns));

                    endItem = rowsNotInUse * m_Grid.columns + beginItem;
                    if (endItem > totalItemCount)
                    {
                        endItem = totalItemCount;
                    }

                    DrawInternal(itemIdx, endItem, yOffset);
                }

                if (isRepaint)
                {
                    DrawHeader(yOffset, m_Collapsable);
                }

                // Always handle drag events in the case where we have no items we still want to be able to drag into the group.
                HandleUnusedDragEvents(yOffset);
            }
示例#16
0
        protected override void Draw(GameTime gameTime)
        {
            //Clear our background
            GraphicsDevice.Clear(new Color(75, 75, 75));

            //Begin sprite batch : We need to clamp as point and blend with alpha
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp);

            //Draw chunks based on current camera's position clamped to chunk grid
            int xGrid = (int)Math.Ceiling((PlayerPositionWorld().X / (float)WorldMetrics.ChunkSizeX) / (float)WorldMetrics.SpriteSize);
            int yGrid = (int)Math.Ceiling((PlayerPositionWorld().Y / (float)WorldMetrics.ChunkSizeY) / (float)WorldMetrics.SpriteSize);


            int drawingCount   = 0;
            int chunkCount     = 0;
            int fullBlockCount = 0;

            //Loop through all nearest chunks
            for (int xChunk = xGrid - toDrawChunksThreshold; xChunk <= xGrid + toDrawChunksThreshold; xChunk++)
            {
                for (int yChunk = yGrid - toDrawChunksThreshold; yChunk <= yGrid + toDrawChunksThreshold; yChunk++)
                {
                    //Check for chunk availability
                    if (xChunk < 0 || yChunk < 0 || xChunk >= WorldMetrics.ChunkCountX || yChunk >= WorldMetrics.ChunkCountY)
                    {
                        continue;
                    }
                    chunkCount++;
                    //Loop through chunk's blocks
                    for (int x = 0; x < WorldMetrics.ChunkSizeX; x++)
                    {
                        for (int y = 0; y < WorldMetrics.ChunkSizeY; y++)
                        {
                            //Calculate block's position
                            int     blockX    = xChunk * WorldMetrics.ChunkSizeX + x;
                            int     blockY    = yChunk * WorldMetrics.ChunkSizeY + y;
                            Vector2 screenPos = new Vector2(blockX, blockY) * WorldMetrics.SpriteSize;
                            fullBlockCount++;
                            if (Vector2.DistanceSquared(screenPos, PlayerPositionWorld()) <= ScreenWidthSquared)
                            {
                                ////Calculate block's color
                                //float PlayerToBlockDistance = Vector2.DistanceSquared(PlayerPositionGrid(), new Vector2(blockX, blockY));
                                //float ColorValue = (300f - PlayerToBlockDistance) / 300f;
                                Color color = Color.White;
                                //if (ColorValue > 0f)
                                //{
                                //    color = new Color(ColorValue, ColorValue, ColorValue);
                                //}
                                //else
                                //{
                                //    color = Color.Black;
                                //}

                                //Draw background
                                //spriteBatch.Draw(BackgroundTexture, new Vector2(blockX * WorldMetrics.SpriteSize, blockY * WorldMetrics.SpriteSize) - CameraPosition, null, color, 0f, Vector2.Zero, WorldMetrics.SpriteSize / 16f, SpriteEffects.None, 1f);

                                //If block is solid (Not air)
                                if (GetBlock(blockX, blockY) != 0)
                                {
                                    //Draw it
                                    int       State           = Chunks[xChunk, yChunk].GetBlockType(x, y);
                                    Rectangle SourceRectangle = new Rectangle((State * 16) % 64, ((State * 16) / 64) * 16, 16, 16);

                                    Color colorToAttach = Data[Chunks[xChunk, yChunk].GetBlock(x, y) - 1].GetColor();
                                    //spriteBatch.Draw(GroundTexture, new Vector2(blockX * WorldMetrics.SpriteSize, blockY * WorldMetrics.SpriteSize) - CameraPosition, null, new Color(0.5f, 0.5f, 0.5f), 0f, Vector2.Zero, WorldMetrics.SpriteSize / 16f, SpriteEffects.None, 0.5f);
                                    spriteBatch.Draw(GroundTexture, new Vector2(blockX * WorldMetrics.SpriteSize, blockY * WorldMetrics.SpriteSize) - CameraPosition, SourceRectangle, colorToAttach, 0f, Vector2.Zero, WorldMetrics.SpriteSize / 16f, SpriteEffects.None, 0.5f);
                                    //Get health
                                    int health = Chunks[xChunk, yChunk].GetBlockHealth(x, y);

                                    //If block is damaged : display damage
                                    if (health < 5)
                                    {
                                        spriteBatch.Draw(BreakTextures[health], new Vector2(blockX * WorldMetrics.SpriteSize, blockY * WorldMetrics.SpriteSize) - CameraPosition, null, color, 0f, Vector2.Zero, WorldMetrics.SpriteSize / 16f, SpriteEffects.None, 0f);
                                    }
                                    drawingCount++;
                                }
                            }
                        }
                    }
                }
            }

            int MouseGridX = (int)Math.Floor(mouseCameraPosition.X / WorldMetrics.SpriteSize);
            int MouseGridY = (int)Math.Floor(mouseCameraPosition.Y / WorldMetrics.SpriteSize);

            int BlockID = 0;

            if (MouseGridX > 0 && MouseGridY > 0 && MouseGridX <= WorldMetrics.ChunkSizeX * WorldMetrics.ChunkCountX &&
                MouseGridY <= WorldMetrics.ChunkSizeY * WorldMetrics.ChunkCountY)
            {
                BlockID = Chunks[MouseGridX / WorldMetrics.ChunkSizeX, MouseGridY / WorldMetrics.ChunkSizeY].
                          GetBlock(MouseGridX % WorldMetrics.ChunkSizeX, MouseGridY % WorldMetrics.ChunkSizeY);
            }

            if (BlockID != 0)
            {
                var name = Data[BlockID - 1].Name;
                spriteBatch.DrawString(defaultFont, name, mousePosition, Color.Black);
            }
            //Draw cursor
            spriteBatch.Draw(Cursor, new Vector2(mousePosition.X - 16, mousePosition.Y - 16), Color.White);

            //Draw player
            spriteBatch.Draw(Player, player.Position - new Vector2(16, 16), Color.Pink);

            //Format our fps and draw it
            var fps = string.Format("FPS : {0}, Full tiles drawn : {3},Tiles drawn : {1}, Chunk drawn : {2}", FPSCounter.AverageFramesPerSecond, drawingCount, chunkCount, fullBlockCount);

            spriteBatch.DrawString(defaultFont, fps, new Vector2(0, 0), Color.White);

            var pos = string.Format("Player : {0}", currentPlayerState);

            spriteBatch.DrawString(defaultFont, pos, new Vector2(0, 40), Color.White);
            //Close sprite batch
            spriteBatch.End();
            base.Draw(gameTime);
        }
示例#17
0
 private static int Math_Ceil(ILuaState lua)
 {
     lua.PushNumber(Math.Ceiling(lua.L_CheckNumber(1)));
     return(1);
 }
示例#18
0
        public void Execute(IRocketPlayer caller, string[] command)
        {
            if (command.Length == 0)
            {
                UnturnedChat.Say(caller, PlayerInfoLib.Instance.Translate("investigate_help"));
            }
            else if (command.Length > 2)
            {
                UnturnedChat.Say(caller, PlayerInfoLib.Instance.Translate("too_many_parameters"));
                return;
            }
            var  totalRecods = 1u;
            uint?page        = 1;
            var  perPage     = caller is ConsolePlayer ? 10u : 4u;
            var  pInfo       = new List <PlayerData>();
            uint start;

            if (command.Length == 2)
            {
                page = command.GetUInt32Parameter(1);
                if (page == null || page == 0)
                {
                    UnturnedChat.Say(caller, PlayerInfoLib.Instance.Translate("invalid_page"));
                    return;
                }
            }
            // Is what is entered in the command a SteamID64 number?
            if (command[0].IsCSteamID(out var cSteamID))
            {
                var pData = PlayerInfoLib.Database.QueryById(cSteamID);
                if (pData.IsValid())
                {
                    pInfo.Add(pData);
                }
            }
            else
            {
                pInfo = PlayerInfoLib.Database.QueryByName(command[0], Parser.checkIP(command[0]) ? QueryType.IP : QueryType.Both, out totalRecods, true, (uint)page, perPage);
            }
            if (pInfo.Count == 0)
            {
                UnturnedChat.Say(caller, "No players found by that name.");
                return;
            }
            start = ((uint)page - 1) * perPage;
            UnturnedChat.Say(caller, PlayerInfoLib.Instance.Translate("number_of_records_found", totalRecods, command[0], page, Math.Ceiling(totalRecods / (float)perPage)), Color.red);
            foreach (var pData in pInfo)
            {
                start++;
                if (pData.IsLocal())
                {
                    UnturnedChat.Say(caller, string.Format("{0}: {1} [{2}] ({3}), IP: {4}, Local: {5}, IsVip: {6}", start, caller is ConsolePlayer ? pData.CharacterName : pData.CharacterName.Truncate(12), caller is ConsolePlayer ? pData.SteamName : pData.SteamName.Truncate(12), pData.SteamID, pData.IP, pData.IsLocal(), pData.IsVip()), Color.yellow);
                    UnturnedChat.Say(caller, string.Format("Seen: {0}, TT: {1}, Cleaned:{2}:{3}", pData.LastLoginLocal, pData.TotalPlayTime.FormatTotalTime(), pData.CleanedBuildables, pData.CleanedPlayerData), Color.yellow);
                }
                else
                {
                    UnturnedChat.Say(caller, string.Format("{0}: {1} [{2}] ({3}), IP: {4}, Local: {5}", start, caller is ConsolePlayer ? pData.CharacterName : pData.CharacterName.Truncate(12), caller is ConsolePlayer ? pData.SteamName : pData.SteamName.Truncate(12), pData.SteamID, pData.IP, pData.IsLocal()), Color.yellow);
                    UnturnedChat.Say(caller, string.Format("Seen: {0}, TT: {1}, on: {2}:{3}", pData.LastLoginLocal, pData.TotalPlayTime.FormatTotalTime(), pData.LastServerID, pData.LastServerName), Color.yellow);
                }
            }
        }
示例#19
0
        public static Bitmap DrawAutomat(IAutomat A, uint?highlightState = null)
        {
            var alreadyDrawn = new IncDictionary <int>();

            int lastCurveHeigth = 3 * CURVE_BONUS;

            float relFactor = 1;

            var vls = A.VisualizationLines();

            if (vls.Length > A.StatesCount * 3)
            {
                relFactor *= vls.Length / (A.StatesCount * 3);
                Utils.DebugMessage($"corrected bmpRelFactor to {relFactor} by transform count", A, Uni.Utils.eDebugLogLevel.Verbose);
            }
            else if (A.Alphabet.Length > A.StatesCount * 4)
            {
                relFactor *= A.Alphabet.Length / (A.StatesCount * 4);
                Utils.DebugMessage($"corrected bmpRelFactor to {relFactor} by alphabet count", A, Uni.Utils.eDebugLogLevel.Verbose);
            }

            int bmpwidth = Math.Max(500, (int)(IMAGE_SPACE + (A.StatesCount) * (STATE_DIAMETER + IMAGE_SPACE) * relFactor));
            var bmp      = new Bitmap(bmpwidth, (int)(bmpwidth / 1.5));

            Graphics g        = Graphics.FromImage(bmp);
            Font     headFont = new Font(SystemFonts.DefaultFont.FontFamily, Math.Max(14, bmpwidth / 60));

            int vCenter = (int)(bmp.Height / 2.6);

            g.FillRectangle(Brushes.White, 0, 0, bmp.Width, bmp.Height);

            g.DrawString(A.Name, headFont, Brushes.Black, 20, 20);

            //Draw full declaration to bottom
            string FullDesc = A.ToString();

            try {
                FullDesc = FullDesc.Replace(A.Name, "").Trim();
            } catch { }

            const int MARGIN = 10;

            var FullDescSize = g.MeasureString(FullDesc, CourierNewFont);

            if (FullDescSize.Width < bmpwidth - MARGIN * 2)
            {
                g.DrawString(FullDesc, CourierNewFont, Brushes.Black, 15f, bmp.Height - FullDescSize.Height * 1.5f);
            }
            else
            {
                int DescPartCount       = (int)Math.Ceiling(FullDescSize.Width / (bmpwidth - MARGIN * 2));
                int toStringSplitFactor = (int)Math.Ceiling((float)FullDesc.Length / DescPartCount);
                for (int i = 0; i < DescPartCount; i++)
                {
                    string rowString = FullDesc.Substring(i * toStringSplitFactor, Math.Min(toStringSplitFactor, FullDesc.Length - i * toStringSplitFactor));
                    g.DrawString(rowString, CourierNewFont, Brushes.Black, 15,
                                 bmp.Height - (DescPartCount - i + 1) * (FullDescSize.Height));
                }
            }


            // draw States
            for (uint iq = 0; iq < A.StatesCount; iq++)
            {
                var strSize = g.MeasureString(A.States[iq], CourierNewFont);
                g.DrawString(A.States[iq], CourierNewFont, Brushes.Black, qPos(iq) + STATE_DIAMETER / 2 - strSize.Width / 2, vCenter - strSize.Height / 2);

                var ellipsePen = PEN;
                if (A.IsAcceptedState(iq))
                {
                    ellipsePen = PEN_DOUBLE;
                }
                if (iq == highlightState)
                {
                    ellipsePen = Pens.Red;
                }

                g.DrawEllipse(ellipsePen, qPos(iq), vCenter - STATE_DIAMETER / 2, STATE_DIAMETER, STATE_DIAMETER);
            }

            // draw Start Arrow
            {
                int lineX  = qPos(A.StartState) - IMAGE_SPACE / 2;
                int lineX2 = qPos(A.StartState);
                g.DrawLine(PEN_START_ARROW, lineX, vCenter, lineX2, vCenter);
            }

            // draw Transform Lines, depends which automat, because of inconsistent transform inheritance and nondeterministic transform
            foreach (var vtl in vls)
            {
                DrawTransformLine(ref g, vtl.Item1, vtl.Item2, vtl.Item3, vCenter, ref lastCurveHeigth, ref alreadyDrawn);
            }

            return(bmp);
        }
示例#20
0
 public static int Ceiling(double a)
 {
     return((int)MathCore.Ceiling(a));
 }
 public static int dp(float value)
 {
     return((int)Math.Ceiling(density * value));
 }