Beispiel #1
0
        protected override void LoadContent()
        {
            _spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
            DefaultFont = Content.Load <SpriteFont>("Default");

            Cursor    = Content.Load <Texture2D>("Cursor");
            FullBoard = Content.Load <Texture2D>("FullBoard");

            Color[] colors = new Color[FullBoard.Width * FullBoard.Height];
            FullBoard.GetData(colors);
            IEnumerable <int> blah = colors
                                     .Select((c, i) => (i, c.R, c.A))
                                     .Where(x => x.R == 0 && x.A == 255)
                                     .Select(x => x.i);

            Vector2 boardCorner = new Vector2(
                (GraphicsDevice.Viewport.Width / 2) - (FullBoard.Width / 2f),
                (GraphicsDevice.Viewport.Height / 2) - (FullBoard.Height / 2f)
                );

            Points = blah
                     .Select(t => new Vector2(t % FullBoard.Width, t / FullBoard.Width))
                     .Select(p => p + boardCorner);

            FullBoard.SetData(
                colors
                .Select(c => new Color(c.A == 0 ? 0 : 255, c.G, c.B, c.A))
                .ToArray()
                );

            CursorPosition = Points.First();
        }
        public IColor[] GetPixels(int x, int y, int width, int height)
        {
            var data = new Color[width * height];

            texture.GetData(0, new Rectangle(x, y, width, height), data, 0, data.Length);
            return(data.Select(c => new ColorAdapter(c) as IColor).ToArray());
        }
Beispiel #3
0
 /// <summary>
 /// Com
 /// </summary>
 protected void computeMask()
 {
     Color[] T = new Color[image.Width * image.Height];
     image.GetData(T);
     // Mask = new BitArray(T.Select(c => c != new Color(0,0,0,0)).ToArray());
     Mask = new BitArray(T.Select(c => c.A != 0).ToArray());
 }
Beispiel #4
0
        ImmutablePalette IProvidesCursorPaletteInfo.ReadPalette(IReadOnlyFileSystem fileSystem)
        {
            using (var s = fileSystem.Open(Filename))
            {
                s.Seek(56, SeekOrigin.Begin);
                var cpal = s.ReadASCII(4);
                if (cpal != "data")
                {
                    throw new InvalidDataException();
                }

                var something = s.ReadUInt32();

                var framePalettes = new List <uint>();
                var colors        = 256;
                var paletteData   = new Color[colors];
                for (var c = 0; c < colors; c++)
                {
                    var red   = s.ReadByte();
                    var green = s.ReadByte();
                    var blue  = s.ReadByte();
                    paletteData[c] = Color.FromArgb(red, green, blue);
                    var reserved = s.ReadByte();

                    // var un = s.ReadUInt32();
                    // framePalettes[c] = un;
                }

                return(new ImmutablePalette(paletteData.Select(d => (uint)d.ToArgb()).ToArray()));
            }
        }
Beispiel #5
0
        /// <summary>
        /// Draws text with a border.
        /// </summary>
        /// <param name="gfx">The source graphics object</param>
        /// <param name="text">The text to render</param>
        /// <param name="font">The font to render</param>
        /// <param name="brush">The brush to use for the rendered text</param>
        /// <param name="x">The x location to render the text at</param>
        /// <param name="y">The y location to render the text at</param>
        /// <param name="border">The width of the border to render in pixels</param>
        /// <param name="borderColors">A collection of colors to border should cycle through</param>
        /// <param name="colorOffsets">An index-matching collection of offsets to render the border colors at</param>
        public static void DrawString(this Graphics gfx, string text, Font font, Brush brush, int x, int y, int border, Color[] borderColors, float[] colorOffsets)
        {
            if (string.IsNullOrWhiteSpace(text))
                return;
            if (gfx == null)
                throw new ArgumentNullException("gfx");
            if (font == null)
                throw new ArgumentNullException("font");
            if (brush == null)
                throw new ArgumentNullException("brush");
            if (border <= 0)
                throw new ArgumentException("Border must be greater than 0", "border");
            if (borderColors.Length == 0)
                throw new ArgumentException("Border requires at least 1 color", "borderColors");
            if (borderColors.Length > 1 && borderColors.Length != colorOffsets.Length)
                throw new ArgumentException("A border with more than 1 color requires a matching number of offsets", "colorOffsets");
            if (colorOffsets == null || colorOffsets.Length == 0)
                colorOffsets = new[] {(float)0};

            // Organize color fades from inner to outer
            var colors = borderColors
                .Select((c, i) => new KeyValuePair<float, Color>(colorOffsets[i], c))
                .OrderBy(c => c.Key)
                .ToArray();
            // Get bordered boundaries
            var offset = gfx.MeasureStringBoundaries(text, font).Location;
            var measure = gfx.MeasureStringBoundaries(text, font, border);

            using (var workImage = new Bitmap((int)measure.Width, (int)measure.Height))
            using (var gfxWork = Graphics.FromImage(workImage))
            {
                gfxWork.PageUnit = GraphicsUnit.Point;
                gfxWork.SmoothingMode = gfx.SmoothingMode;
                var path = new GraphicsPath();
                path.AddString(text, font.FontFamily, (int) font.Style, font.Size, new PointF((border-offset.X)*(float).75, (border-offset.Y)*(float).75), StringFormat.GenericDefault);

                // Fade the border from outer to inner.
                for (var b = border; b > 0; b--)
                {
                    var colorIndex = (float) 1/border*b;
                    var colorStart = colors.Length > 1 ? colors.Last(c => c.Key <= colorIndex) : colors.First();
                    var colorEnd = colors.Length > 1 ? colors.First(c => c.Key >= colorIndex) : colors.First();
                    var colorOffset = 1/Math.Max((float).0000001, colorEnd.Key - colorStart.Key)*(colorIndex - colorStart.Key);
                    var color = colorStart.Value.FadeTo(colorEnd.Value, colorOffset);

                    const float lineWidthOffset = (float) .65; // This is approximate
                    using (var pen = new Pen(color, b/lineWidthOffset) { LineJoin = LineJoin.Round })
                        gfxWork.DrawPath(pen, path);
                }

                // Draw the text
                gfxWork.FillPath(brush, path);
                var bounds = workImage.DetectPadding();
                var offsetX = ((measure.Width - bounds.Right) - bounds.X)/2;

                // Apply the generated image
                gfx.DrawImage(workImage, x + offsetX, y);
            }
        }
Beispiel #6
0
        public void TestImageStatsSimplePasses()
        {
            System.Func <Color, string>   fcolor = c => string.Format("({0:f3},{1:f3},{2:f3})", c.r, c.g, c.b);
            System.Func <Vector3, string> fvec3  = v => string.Format("({0:f3},{1:f3},{2:f3})", v.x, v.y, v.z);


            var colors = new Color[] { Color.red };

            DebugOut(colors, "In RGB : {0}", fcolor);

            DebugOut(colors.Select(c => c.ColorToRGB().RGBToLMS()), "In LMS : {0}", fvec3);

            DebugOut(colors.Select(c => c.ColorToRGB().RGBToLMS().LMSToLogLMS()),
                     "In Log LMS : {0}", fvec3);

            DebugOut(colors.Select(c => c.ColorToRGB().RGBToLMS().LMSToLogLMS().LogLMSToLAB()),
                     "In LAB : {0}", fvec3);
        }
        public IColor[] GetPixels()
        {
            var data = new Color[texture.Width * texture.Height];

            texture.GetData(data);
            return(data
                   .Select(c => new ColorAdapter(c) as IColor)
                   .ToArray());
        }
 private static byte[] GetTextureData(Texture2D Texture)
 {
     if (!cachedTextureData.ContainsKey(Texture))
     {
         Color[] colorData = new Color[Texture.Width * Texture.Height];
         Texture.GetData(colorData);
         cachedTextureData[Texture] = colorData.Select(c => c.A).ToArray();
     }
     return(cachedTextureData[Texture]);
 }
Beispiel #9
0
        ImmutablePalette IProvidesCursorPaletteInfo.ReadPalette(IReadOnlyFileSystem fileSystem)
        {
            using (var s = fileSystem.Open(Filename))
            {
                var cpal = s.ReadASCII(4);
                if (cpal != "CPAL")
                {
                    throw new InvalidDataException();
                }

                var framePalettes = new List <uint[]>();
                var paletteCount  = s.ReadUInt32();
                for (var p = 0; p < paletteCount; p++)
                {
                    var ppal = s.ReadASCII(4);
                    if (ppal != "PPAL")
                    {
                        throw new InvalidDataException();
                    }

                    var offset = s.ReadUInt32();

                    var head = s.ReadASCII(4);
                    if (head != "head")
                    {
                        throw new InvalidDataException();
                    }

                    var bytesPerEntry = s.ReadUInt32();
                    var unknown       = s.ReadUInt32();

                    var data = s.ReadASCII(4);
                    if (data != "data")
                    {
                        throw new InvalidDataException();
                    }

                    var paletteSize = s.ReadUInt32();
                    var colors      = paletteSize / bytesPerEntry;
                    var paletteData = new Color[colors];
                    for (var c = 0; c < colors; c++)
                    {
                        var red   = s.ReadByte();
                        var green = s.ReadByte();
                        var blue  = s.ReadByte();
                        paletteData[c] = Color.FromArgb(red, green, blue);
                        var reserved = s.ReadByte();
                    }

                    framePalettes.Add(paletteData.Select(d => (uint)d.ToArgb()).ToArray());
                }

                return(new ImmutablePalette(Enumerable.Range(0, Palette.Size).Select(i => (i == TransparentIndex) ? 0 : framePalettes[Number][i])));
            }
        }
        public Bitmap Process(Bitmap image)
        {
            var result = new Bitmap(image.Width - 1, image.Height);

            int newX = 0;
            int newY = 0;

            var pixels = new Color[image.Height][];

            for (int y = 0; y < image.Height; y++)
            {
                pixels[y] = new Color[image.Width];
                for (int x = 0; x < image.Width; x++)
                {
                    pixels[y][x] = image.GetPixel(x, y);
                }
            }

            var colors = pixels
                         .Select((arr, y) =>
                                 arr.Where((c, x) =>
                                           !PointsOfShortestPath.Contains(new Point(x, y)))
                                 .ToArray())
                         .ToArray();

            for (int y = 0; y < result.Height; y++)
            {
                for (int x = 0; x < result.Width; x++)
                {
                    result.SetPixel(x, y, colors[y][x]);
                }
            }

            //for (int y = 0; y < image.Height; y++)
            //{
            //    for (int x = 0; x < image.Width; x++)
            //    {
            //        if (PointsOfShortestPath.Contains(new Point(x, y)))
            //        {
            //            continue;
            //        }

            //        result.SetPixel(newX, newY, image.GetPixel(x, y));

            //        newX++;
            //        newY++;
            //    }

            //    newX = 0;
            //    newY = 0;
            //}

            return(result);
        }
Beispiel #11
0
        List <uint[]> LoadPalettes(Stream s)
        {
            var cpal = s.ReadASCII(4);

            if (cpal != "CPAL")
            {
                throw new InvalidDataException();
            }

            var palettes     = new List <uint[]>();
            var paletteCount = s.ReadUInt32();

            for (var p = 0; p < paletteCount; p++)
            {
                var ppal = s.ReadASCII(4);
                if (ppal != "PPAL")
                {
                    throw new InvalidDataException();
                }

                var offset = s.ReadUInt32();

                var head = s.ReadASCII(4);
                if (head != "head")
                {
                    throw new InvalidDataException();
                }

                var bytesPerEntry = s.ReadUInt32();
                var unknown       = s.ReadUInt32();

                var data = s.ReadASCII(4);
                if (data != "data")
                {
                    throw new InvalidDataException();
                }

                var paletteSize = s.ReadUInt32();
                var colors      = paletteSize / bytesPerEntry;
                var paletteData = new Color[colors];
                for (var c = 0; c < colors; c++)
                {
                    var blue  = s.ReadByte();
                    var green = s.ReadByte();
                    var red   = s.ReadByte();
                    paletteData[c] = Color.FromArgb(red, green, blue);
                    var reserved = s.ReadByte();
                }

                palettes.Add(paletteData.Select(d => (uint)d.ToArgb()).ToArray());
            }

            return(palettes);
        }
Beispiel #12
0
        private byte[] TexToData(Texture2D tex, bool compressed)
        {
            var data = new Color[tex.Width * tex.Height];

            tex.GetData(data);
            if (compressed)
            {
                //let's assume the width and height didn't change. the default settings should always result in textures divisible by 4.
                return(TextureUtils.DXT5Compress(data, tex.Width, tex.Height).Item1);
            }
            return(ToByteArray(data.Select(x => x.PackedValue).ToArray()));
        }
Beispiel #13
0
        private void InitColorValues()
        {
            Color[]  colors       = new Color[] { Color.White, Color.Black, Color.Blue, Color.Orange, Color.Green };
            String[] colorStrings = colors.Select(c => c.ToString().Substring(7).Replace("]", "")).ToArray();

            circleColorSelect.Items.AddRange(colorStrings);
            borderColorSelect.Items.AddRange(colorStrings);
            textColorSelect.Items.AddRange(colorStrings);

            circleColorSelect.SelectedItem = colorStrings[0];
            borderColorSelect.SelectedItem = colorStrings[0];
            textColorSelect.SelectedItem   = colorStrings[0];
        }
Beispiel #14
0
        public static void Load(ContentManager content, GraphicsDevice device)
        {
            point = new Texture2D(device, 1, 1);
            point.SetData <Color>(new Color[] { Color.White });

            circle = content.Load <Texture2D>(@"./Graphics/circle");
            Color[] colors = new Color[circle.Width * circle.Height];
            circle.GetData(colors);
            circle.SetData(colors.Select(c => { if (c.A > 0)
                                                {
                                                    return(new Color(255, 255, 255));
                                                }
                                                return(c); }).ToArray());
        }
Beispiel #15
0
            /// <summary>
            /// Create a new Texture2D from a Color
            /// </summary>
            public static Texture2D CreateColorTexture(GraphicsDevice graphicsDevice, Color color, int Width = 1, int Height = 1)
            {
                Texture2D texture2D = new Texture2D(graphicsDevice, Width, Height, false, SurfaceFormat.Color);

                Color[] colors = new Color[Width * Height];

                // Set each pixel to color
                colors = colors
                         .Select(x => x = color)
                         .ToArray();

                texture2D.SetData(colors);

                return(texture2D);
            }
Beispiel #16
0
        private async void Awake()
        {
            Player.Texture = new Texture2D(32, 32);
            Color[] colors = new Color[Player.Texture.width * Player.Texture.height];
            colors.Select(color => Color.clear);
            Player.Texture.SetPixels(colors);
            Player.Texture.Apply();
            Player.Texture.wrapMode   = TextureWrapMode.Clamp;
            Player.Texture.filterMode = FilterMode.Point;
            drawingRawImage.texture   = Player.Texture;

            doneDrawingButton.onClick.AddListener(OnDoneDrawing);
            characterController0D.InputEvent += OnInput;

            await WriteToConsole(nothingName, "Hey... wait... what was your name again?");
        }
Beispiel #17
0
        void Initialize()
        {
            bgColor = Color.Rgb(0, 0x99, 0xcc);
            var colors = new Color[] {
                Color.Rgb(0xaa, 0x66, 0xcc),
                Color.Rgb(0x99, 0xcc, 0x00),
                Color.Rgb(0xff, 0xbb, 0x33),
                Color.Rgb(0xff, 0x44, 0x44)
            };

            circlePaints = colors.Select(c => new Paint()
            {
                AntiAlias = true, Color = c
            }).ToArray();
            pointers = new PointF?[circlePaints.Length];

            player = new AsyncPlayer(generator);
        }
Beispiel #18
0
        public EditorPageColorSelectorControlViewModule()
        {
            var colors = new Color[] { Colors.Black, Colors.Red, Colors.Yellow, Colors.Blue, Colors.Green, Colors.Gray, Colors.Aqua, Colors.Gold, Colors.White };

            ColorButtons = colors.Select(c => {
                var b = new Button {
                    Padding = new Thickness(0),
                    Content = new Rectangle {
                        Height = 24, Width = 24, Fill = new SolidColorBrush(c)
                    }
                };
                b.Click += (sender, args) => {
                    BackgroundColorBrush = ((Rectangle)((Button)sender).Content).Fill;
                };
                return(b);
            }).ToList();

            BackgroundColorBrush = new SolidColorBrush(Colors.Black);
        }
Beispiel #19
0
        private void Form1_Load(object sender, EventArgs e)
        {
            for (int i = 0; i < Wid; i++)
            {
                buff[Siz + i] = 220;
                buff[Siz - i] = 220;
            }


            colors = new Color[256];
            int j = 0;

            for (int i = 0; i < 64; i++)
            {
                colors[j++] = Color.FromArgb(i << 2, 0, 0);
            }
            for (int i = 0; i < 64; i++)
            {
                colors[j++] = Color.FromArgb(255, i << 2, 0);
            }
            for (int i = 0; i < 64; i++)
            {
                colors[j++] = Color.FromArgb(255, 255, i << 2);
            }
            for (int i = 0; i < 64; i++)
            {
                colors[j++] = Color.FromArgb(255 - i, 255 - i, 255);
            }

            brushes = colors.Select(x => new SolidBrush(x)).ToArray();

            //bmp = new Bitmap(Wid, Hei);
            bmp = new Bitmap(Wid << ScalePow, Hei << ScalePow);
            gfx = System.Drawing.Graphics.FromImage(bmp);

            KeepRunning = true;
            //not threadsafe, but it should look ok anyway?
            threads = Enumerable.Range(0, NumThreads).Select(x => new Thread(() => RunBurn())).ToArray();
            foreach (var t in threads)
            {
                t.Start();
            }
        }
Beispiel #20
0
        public static Texture2D InvertColors(this Texture2D texture, Color?excludeColor = null)
        {
            if (texture is null)
            {
                throw new ArgumentNullException(nameof(texture));
            }

            Texture2D result = new Texture2D(texture.GraphicsDevice, texture.Width, texture.Height);

            Color[] pixelData = new Color[texture.Width * texture.Height];

            texture.GetData(pixelData);

            Color[] invertedPixelData = pixelData.Select(p => excludeColor.HasValue && p == excludeColor ? p : new Color(255 - p.R, 255 - p.G, 255 - p.B, p.A)).ToArray();

            result.SetData(invertedPixelData);

            return(result);
        }
Beispiel #21
0
        private int GetTopPixel()
        {
            var data             = _enfFileProvider.ENFFile[NPC.ID];
            var frameTexture     = _npcSpriteSheet.GetNPCTexture(data.Graphic, NPCFrame.Standing, EODirection.Down);
            var frameTextureData = new Color[frameTexture.Width * frameTexture.Height];

            frameTexture.GetData(frameTextureData);

            if (frameTextureData.All(x => x.A == 0))
            {
                return(0);
            }

            var firstVisiblePixelIndex = frameTextureData.Select((color, index) => new { color, index })
                                         .Where(x => x.color.A != 0)
                                         .Select(x => x.index)
                                         .First();

            return(firstVisiblePixelIndex / frameTexture.Height);
        }
        private void InitializeTopPixel()
        {
            int tries;

            for (tries = 0; tries < 3; ++tries)
            {
                try
                {
                    //get the first non-transparent pixel to determine offsets for name labels and damage counters
                    var frameTexture     = _npcSheet.GetNPCTexture(NPC.Data.Graphic, NPCFrame.Standing, NPC.Direction);
                    var frameTextureData = new Color[frameTexture.Width * frameTexture.Height];
                    frameTexture.GetData(frameTextureData);

                    if (frameTextureData.All(x => x.A == 0))
                    {
                        TopPixel = 0;
                    }
                    else
                    {
                        var firstVisiblePixelIndex = frameTextureData.Select((color, index) => new { color, index })
                                                     .Where(x => x.color.R != 0)
                                                     .Select(x => x.index)
                                                     .First();
                        TopPixel = firstVisiblePixelIndex / frameTexture.Height;
                    }
                } //this block throws errors sometimes..no idea why. It usually doesn't fail 3 times.
                catch (InvalidOperationException) { continue; }

                break;
            }

            if (tries >= 3)
            {
                throw new InvalidOperationException("Something weird happened initializing this NPC.");
            }
        }
 void DisplayResultForColors(Color[][] colors)
 {
     colors
         .Select((c, i) => new { color = c, i })
         .Do(_ => Console.WriteLine(_.i))
         .SelectMany(_ => _.color)
         .Execute(c => Console.WriteLine(c.Name));
 }
Beispiel #24
0
        private void DrawRainbowBand(SpriteBatch batch, Vector2 origin, float angle, float scaleFactor, float extraIntensity)
        {
            DrawRainbowBand(batch, origin, angle, scaleFactor, RainbowBandTexture);

            if (extraIntensity > 0)
            {
                //Draw a white texture of the same size and shape on top of the rainbow we just drew

                var RainbowBandWhiteTexels = new Color[RainbowBandTexture.Height];
                RainbowBandTexture.GetData(RainbowBandWhiteTexels);

                RainbowBandWhiteTexels = RainbowBandWhiteTexels.Select(c => new Color(new Vector4(new Vector3(c.ToVector3().Length() > 0 ? extraIntensity : 0), 0))).ToArray();
                var RainbowBandWhiteTexture = new Texture2D(device, 1, RainbowBandWhiteTexels.Length);
                RainbowBandWhiteTexture.SetData(RainbowBandWhiteTexels);

                DrawRainbowBand(batch, origin, angle, scaleFactor, RainbowBandWhiteTexture);
            }
        }
Beispiel #25
0
        private void GraphStaffBusiness()
        {
            GetData getData = new GetData(DBMethods.GraphingRequests.GetBusinessOfStaff);

            Color[] colours = new Color[]
            {
                Color.FromRgb(183, 28, 28),                // Red
                Color.FromRgb(2, 119, 189),                // Blue
                Color.FromRgb(190, 96, 0),                 // Dark orange? Not quite brown
                Color.FromRgb(46, 125, 50),                // Green
                Color.FromRgb(49, 27, 146)                 // Deep Purple
            };
            GenerateBarGraph(getData, grdStaffBusiness, "No. Of Appointments Per Staff Member", "", "", colours.Select(c => new SolidColorBrush(c)).ToArray());
        }
Beispiel #26
0
 private void startButton_Click(object sender, EventArgs e)
 {
     int numberOfPlayers = 0;
     int.TryParse(nrPlayers.Text, out numberOfPlayers);
     if (numberOfPlayers == 0)
     {
         MessageBox.Show("Alegeti numarul de jucatori!");
         return;
     }
     string[] names = new string[numberOfPlayers];
     Color[] colors = new Color[numberOfPlayers];
     for (int i = 0; i < int.Parse(nrPlayers.Text); i++)
     {
         names[i] = textBox[i].Text;
         if (names[i].Trim() == string.Empty)
         {
             MessageBox.Show("Completati numele jucatorilor!");
             return;
         }
         colors[i] = playerColor[i].BackColor;
     }
     //numarul de culori diferite trebuie sa fie egal cu numarul de jucatori
     var colorNo = colors.Select(p => p.Name).Distinct().Count();
     if (names.Count() != colorNo)
     {
         MessageBox.Show("Culorile nu pot fi la fel");
         return;
     }
     MainForm form = new MainForm(this, names, colors);
     form.Show();
     this.Visible = false;
 }
Beispiel #27
0
		static public Color ProcessPixel(string mode, Color[] values)
		{
			int n = values.Length;
			Color ret;
			Color mean;
			Color stddev;
			float temp;
			switch (mode)
			{
				case "mean":
					ret = new Color();
					ret.R = values.GetRChannel().Average();
					ret.G = values.GetGChannel().Average();
					ret.B = values.GetBChannel().Average();
					return ret;
				case "stddev":
					mean = ProcessPixel("mean", values);
					ret = new Color();
					ret.R = values.GetRChannel().Select(i => (float)Math.Pow(i - mean.R, 2)).Average();
					ret.R = (float)Math.Sqrt(ret.R);
					if (ret.R < .000001) ret.R = .000001f;
					ret.G = values.GetGChannel().Select(i => (float)Math.Pow(i - mean.G, 2)).Average();
					ret.G = (float)Math.Sqrt(ret.G);
					if (ret.G < .000001) ret.G = .000001f;
					ret.B = values.GetBChannel().Select(i => (float)Math.Pow(i - mean.B, 2)).Average();
					ret.B = (float)Math.Sqrt(ret.B);
					if (ret.B < .000001) ret.B = .000001f;
					return ret;
				case "xi":
				{
					mean = ProcessPixel("mean", values);
					stddev = ProcessPixel("stddev", values);
					ret = new Color();
					temp = xi(values[0], mean, stddev);
					ret.R = ret.G = ret.B = temp;
					return ret;
				}
				case "CDi":
				{
					mean = ProcessPixel("mean", values);
					stddev = ProcessPixel("stddev", values);
					float Xi = ProcessPixel("xi", values).R;
					Func<Color, Color, Color, float, float> func =
						(I, U, Sig, xi) =>
						{
							return (float)Math.Sqrt(
								(float)Math.Pow((I.R - xi * U.R) / Sig.R, 2)
								+ (float)Math.Pow((I.G - xi * U.G) / Sig.G, 2)
								+ (float)Math.Pow((I.B - xi * U.B) / Sig.B, 2));
						};
					ret = new Color();
					temp = func(values[0], mean, stddev, Xi) / 10;
					ret.R = ret.G = ret.B = temp;
					return ret;
				}
				case "bi":
				{
					mean = ProcessPixel("mean", values);
					stddev = ProcessPixel("stddev", values);
					Func<Color, Color, Color, float, float> func =
						(I, U, Sig, xi) =>
						{
							return (float)Math.Sqrt(
								(float)Math.Pow((I.R - xi * U.R) / Sig.R, 2)
								+ (float)Math.Pow((I.G - xi * U.G) / Sig.G, 2)
								+ (float)Math.Pow((I.B - xi * U.B) / Sig.B, 2));
						};
					ret = new Color();
					temp = values
						.Select(i => new Tuple<Color, Color, Color, float>(i, mean, stddev, xi(i, mean, stddev)))
						.Select(i => func(i.Item1, i.Item2, i.Item3, i.Item4))
						.Sum(i => (float)Math.Pow(i, 2));
					temp = (float)Math.Sqrt(temp / n) / 10;
					ret.R = ret.G = ret.B = temp;
					return ret;
				}
				case "ai":
				{
					mean = ProcessPixel("mean", values);
					stddev = ProcessPixel("stddev", values);
					ret = new Color();
					temp = values
						.Select(i => new Tuple<Color, Color, Color>(i, mean, stddev))
						.Select(i => xi(i.Item1, i.Item2, i.Item3))
						.Sum(i => (float)Math.Pow(i - 1f, 2));
					temp = (float)Math.Sqrt(temp / n);
					//temp = temp / n;
					ret.R = ret.G = ret.B = temp;
					return ret;
				}
				default:
					throw new System.Exception("The passed mode was not valid!!");
			}
		}
Beispiel #28
0
		private void InitializeTopPixel()
		{
			int tries;
			for (tries = 0; tries < 3; ++tries)
			{
				try
				{
					//get the first non-transparent pixel to determine offsets for name labels and damage counters
					Frame = NPCFrame.Standing;

					var frameTexture = _npcSheet.GetNPCTexture();
					var frameTextureData = new Color[frameTexture.Width * frameTexture.Height];
					frameTexture.GetData(frameTextureData);

					if (frameTextureData.All(x => x.A == 0))
						TopPixel = 0;
					else
					{
						var firstVisiblePixelIndex = frameTextureData.Select((color, index) => new { color, index })
																	 .Where(x => x.color.R != 0)
																	 .Select(x => x.index)
																	 .First();
						TopPixel = firstVisiblePixelIndex/frameTexture.Height;
					}
				} //this block throws errors sometimes..no idea why. It usually doesn't fail 3 times.
				catch (InvalidOperationException) { continue; }

				break;
			}

			if (tries >= 3)
				throw new InvalidOperationException("Something weird happened initializing this NPC.");
		}
        public IImage CreateImage(Color[] colors, int pixelWidth, double scale = 1)
        {
            var pixelHeight = colors.Length / pixelWidth;
            var palette = new BitmapPalette(colors.Select(c => c.GetColor()).ToList());
            var pixelFormat = PixelFormats.Indexed1;
            var dpi = DPI * scale;
            var stride = pixelWidth / pixelFormat.BitsPerPixel;
            var pixels = new byte[pixelHeight * stride];

            var bitmap = BitmapSource.Create(pixelWidth, pixelHeight, dpi, dpi, pixelFormat, palette, pixels, stride);
            return new ImageSourceImage(bitmap);
        }