public static Boolean TexturesCollide(Color[,] texture1, Matrix matrix1, Color[,] texture2, Matrix matrix2)
        {
            Matrix mat1to2 = matrix1 * Matrix.Invert(matrix2);
            Int32 width1 = texture1.GetLength(0);
            Int32 height1 = texture1.GetLength(1);
            Int32 width2 = texture2.GetLength(0);
            Int32 height2 = texture2.GetLength(1);

            for (Int32 x1 = 0; x1 < width1; x1++) {
                for (Int32 y1 = 0; y1 < height1; y1++) {
                    Vector2 pos1 = new Vector2(x1, y1);
                    Vector2 pos2 = Vector2.Transform(pos1, mat1to2);

                    Int32 x2 = (Int32)pos2.X;
                    Int32 y2 = (Int32)pos2.Y;
                    if ((x2 >= 0) && (x2 < width2)) {
                        if ((y2 >= 0) && (y2 < height2)) {
                            if (texture1[x1, y1].A > 0) {
                                if (texture2[x2, y2].A > 0) {
                                    return true;
                                }
                            }
                        }
                    }
                }
            }

            return false;
        }
        public Color interpolation(Color[,] original_Buffer, PointF p)
        {
            int x1 = (int)Math.Floor(p.X),
                y1 = (int)Math.Floor(p.Y),
                x2 = x1 + 1,
                y2 = y1 + 1;

            x1 = OutBoundery(x1, original_Buffer.GetLength(0));
            x2 = OutBoundery(x2, original_Buffer.GetLength(0));
            y1 = OutBoundery(y1, original_Buffer.GetLength(1));
            y2 = OutBoundery(y2, original_Buffer.GetLength(1));

            Color p1 = original_Buffer[x1, y1];
            Color p2 = original_Buffer[x2, y1];
            Color p3 = original_Buffer[x1, y2];
            Color p4 = original_Buffer[x2, y2];

            double Xfraction = p.X - x1;
            double Yfraction = p.Y - y1;

            //interpolate in X_Direction
            Data dataX1, dataX2, dataFinal;
            dataX1 = interpolate(p1, p2, Xfraction);
            dataX2 = interpolate(p3, p4, Xfraction);
            //interpolate in Y_Direction
            Color newX1 = Color.FromArgb((int)dataX1.R_Val, (int)dataX1.G_Val, (int)dataX1.B_Val);
            Color newX2 = Color.FromArgb((int)dataX2.R_Val, (int)dataX2.G_Val, (int)dataX2.B_Val);
            dataFinal = interpolate(newX1, newX2, Yfraction);

            return Color.FromArgb((int)(dataFinal.R_Val), (int)(dataFinal.G_Val), (int)(dataFinal.B_Val));
        }
Exemple #3
0
        public static Color[,] InterpolateHeight(Color[,] img, int height)
        {
            if (height == img.GetLength(1))
            {
                return(img);
            }

            Color[,] nMatrix = new Color[img.GetLength(0), height];

            for (int i = 0; i < img.GetLength(0); i++)
            {
                Point lastIndex = new Point(0, 0);
                for (int j = 0; j < img.GetLength(1); j++)
                {
                    double percentY = (double)j / (double)img.GetLength(1);

                    int nY = (int)Math.Round(((double)nMatrix.GetLength(1) * (double)percentY));
                    if (nY >= nMatrix.GetLength(1))
                    {
                        nY = nMatrix.GetLength(1) - 1;
                    }
                    nMatrix[i, nY] = img[i, j];

                    for (int tY = lastIndex.Y + 1; tY < nY; tY++)
                    {
                        float time = (float)tY / (float)nY;
                        nMatrix[i, tY] = PixelTransform.InterpolateColor(nMatrix[lastIndex.X, lastIndex.Y], nMatrix[i, nY], time);
                    }
                    lastIndex = new Point(i, nY);
                }
            }

            return(nMatrix);
        }
        public Bitmap Create(Color[,] data)
        {
            int width = data.GetLength(0);
            int height = data.GetLength(1);

            Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format24bppRgb);
            BitmapData bmData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);

            int stride = bmData.Stride;

            byte[] array = new byte[stride * height];

            int index = 0;

            for (int y = height - 1; y >= 0; y--)
            {
                for (int x = 0; x < width; x++)
                {
                    array[index++] = data[x, y].B;
                    array[index++] = data[x, y].G;
                    array[index++] = data[x, y].R;
                }
            }

            IntPtr scan0 = bmData.Scan0;
            Marshal.Copy(array, 0, scan0, stride * bitmap.Height);
            bitmap.UnlockBits(bmData);

            return bitmap;
        }
Exemple #5
0
        public Color[,] RenderEffect(Color[,] buffer, Color[] palette, int eventToRender)
        {
            var colorCount = palette.Length;
            var spiralCount = colorCount * tbPaletteRepeat.Value;
            var bufferHeight = buffer.GetLength(Utils.IndexRowsOrHeight);
            var bufferWidth = buffer.GetLength(Utils.IndexColsOrWidth);
            var deltaStrands = bufferWidth / spiralCount;
            var spiralThickness = (deltaStrands * tbThickness.Value / 100) + 1;
            long spiralState = eventToRender * tbDirection.Value;

            for (var spiral = 0; spiral < spiralCount; spiral++) {
                var strandBase = spiral * deltaStrands;
                var color = palette[spiral % colorCount];
                for (var thickness = 0; thickness < spiralThickness; thickness++) {
                    var strand = (strandBase + thickness) % bufferWidth;
                    for (var row = 0; row < bufferHeight; row++) {
                        var column = (strand + ((int)spiralState / 10) + (row * tbRotations.Value / bufferHeight)) % bufferWidth;
                        if (column < 0) {
                            column += bufferWidth;
                        }
                        if (chkBoxBlend.Checked) {
                            color = palette.GetMultiColorBlend((bufferHeight - row - 1) / (double)bufferHeight, false);
                        }
                        if (chkBox3D.Checked) {
                            var hsv = color.ToHSV();
                            hsv.Value = (float)((double)(tbRotations.Value < 0 ? thickness + 1 : spiralThickness - thickness) / spiralThickness);
                            color = hsv.ToColor();
                        }
                        buffer[row, column] = color;
                    }
                }
            }
            return buffer;
        }
        public static Bitmap CreateIntensityMask(Bitmap bSurface, List <HeatPoint> aHeatPoints, float guc, float yumusat)
        {
            // Create new graphics surface from memory bitmap
            Graphics DrawSurface = Graphics.FromImage(bSurface);

            // Set background color to white so that pixels can be correctly colorized
            DrawSurface.Clear(Color.White);
            // Traverse heat point data and draw masks for each heat point
            //foreach (HeatPoint DataPoint in aHeatPoints)
            //{
            //    // Render current heat point on draw surface
            //    DrawHeatPoint(DrawSurface, DataPoint, 15);
            //}
            Color[,] vals = new Color[bSurface.Size.Width, bSurface.Size.Height];
            System.Threading.Tasks.Parallel.For(0, vals.GetLength(0), x =>
            {
                System.Threading.Tasks.Parallel.For(0, vals.GetLength(1), y =>
                {
                    vals[x, y] = pointValue(new Point(x, y), guc, yumusat, aHeatPoints);
                });
            });

            for (int x = 0; x < bSurface.Size.Width; x++)
            {
                for (int y = 0; y < bSurface.Size.Height; y++)
                {
                    DrawSurface.DrawPolygon(new Pen(vals[x, y]), new Point[] { new Point(x, y), new Point(x + 1, y), new Point(x + 1, y + 1), new Point(x, y + 1) });
                }
            }

            return(bSurface);
        }
Exemple #7
0
        public Color[,] RenderEffect(Color[,] buffer, Color[] palette, int eventToRender)
        {
            _palette = palette;
            _bufferHeight = buffer.GetLength(0);
            _bufferWidth = buffer.GetLength(1);

            if (eventToRender == 0 || _tempBuf == null) {
                InitializeSnowflakes();
            }

            // move snowflakes
            for (var x = 0; x < _bufferWidth; x++) {
                var newX = (x + eventToRender / 20) % _bufferWidth; // CW
                var newX2 = (x - eventToRender / 20) % _bufferWidth; // CCW
                if (newX2 < 0) {
                    newX2 += _bufferWidth;
                }
                for (var y = 0; y < _bufferHeight; y++) {
                    var newY = (y + eventToRender / 10) % _bufferHeight;
                    var newY2 = (newY + _bufferHeight / 2) % _bufferHeight;
                    var color1 = GetTempPixel(newX, newY);
                    if (color1 == Color.Transparent) {
                        color1 = GetTempPixel(newX2, newY2);
                    }
                    buffer[y,x] = color1;
                }
            }
            return buffer;
        }
Exemple #8
0
        public Color[,] RenderEffect(Color[,] buffer, Color[] palette, int eventToRender)
        {
            var bufferHeight = buffer.GetLength(Utils.IndexRowsOrHeight);
            var bufferWidth = buffer.GetLength(Utils.IndexColsOrWidth);
            var random = new Random(chkBoxStrobe.Checked ? DateTime.Now.Millisecond : 2271965);
            var steps = tbSteps.Value;
            var stepsHalf = steps / 2.0f;
            var lights = Convert.ToInt32((bufferHeight * bufferWidth) * (tbLightCount.Value / 100.0));
            var step = Math.Max(1, (bufferHeight * bufferWidth) / lights);

            for (var y = 0; y < bufferHeight; y++) {
                for (var x = 0; x < bufferWidth; x++) {
                    if ((y * bufferHeight + x + 1) % step != 1 && step != 1) {
                        continue;
                    }

                    var hsv = palette[random.Next() % palette.Length].ToHSV();

                    var randomStep = (eventToRender + random.Next()) % steps;

                    hsv.Value = chkBoxStrobe.Checked ? ((randomStep == (int)(stepsHalf + 0.5f)) ? 1.0f : 0.0f) :
                        Math.Max(0.0f, ((randomStep <= stepsHalf ? randomStep : steps - randomStep) / stepsHalf));

                    buffer[y, x] = hsv.ToColor();
                }
            }
            return buffer;
        }
Exemple #9
0
	public override Texture2D CreateSprite (Texture2D texture)
	{
		Color[] pixels = texture.GetPixels ();
		Color[,] pixels2D = new Color[texture.width, texture.height];
		for (int i = 0; i < pixels.Length; i++) {
			
			int x = i % texture.width;
			int y = i / texture.height;

			pixels2D [x, y] = pixels [i];
		}

		int amountOfEyes = (int)(sightAngle / 45);
		for (int i = 0; i < amountOfEyes; i++) {
			
			int radius = (texture.width - eyeSize) / 2;
			float xPos = Mathf.Sin (Mathf.Deg2Rad * (i * 45));
			float yPos = Mathf.Cos (Mathf.Deg2Rad * (i * 45));
			Vector2 pos = new Vector2 (xPos, yPos) * radius + new Vector2 (texture.width - eyeSize, texture.height - eyeSize) / 2;

			ApplyKernel (ref pixels2D, texture.width, texture.height, pos);
		}

		for (int x = 0; x < pixels2D.GetLength (0); x++) {
			for (int y = 0; y < pixels2D.GetLength (1); y++) {
				
				pixels [x + y * texture.width] = pixels2D [x, y];
			}
		}

		texture.SetPixels (pixels);
		texture.Apply ();

		return texture;
	}
Exemple #10
0
        /// <summary>
        /// loading the data of a sprite sheet that has a gridline like specified in index
        /// </summary>
        private void loadSheet()
        {
            List <SpriteRow> r  = new List <SpriteRow>();
            SpriteRow        CR = new SpriteRow();

            Color[,] color = new Color[spriteSheet.Width, spriteSheet.Height];

            // puuting all the wanted points inside a list which ill go over later on
            color = Tools.getColorMap(spriteSheet);
            List <Point> pnt  = new List <Point>();
            Color        refC = color[0, 0];

            for (int h = 1; h < color.GetLength(1); h++)
            {
                for (int w = 0; w < color.GetLength(0); w++)
                {
                    if (color[w, h] == refC)
                    {
                        pnt.Add(new Point(w, h));
                    }
                }
            }

            int firstHight = pnt[0].Y; //height of evet rectangke
            int lastHeight = pnt[0].Y; // current row height
            int startHight = 0;        //height of lasr row


            for (int i = 1; i < pnt.Count - 1; i += 2)
            {
                if (lastHeight != pnt[i].Y)
                {
                    r.Add(CR);
                    i++;
                    CR         = new SpriteRow();
                    startHight = lastHeight;
                    lastHeight = pnt[i].Y;
                }
                //origin.X = pnt[i].X - pnt[i - 1].X
                //origin.Y =  lastHeight-startHight
                CR.org.Add(new Vector2(pnt[i].X - pnt[i - 1].X, lastHeight - startHight));
                //rectangle width = pnt[i + 1].X - pnt[i - 1].X
                CR.rec.Add(new Rectangle(pnt[i - 1].X, startHight, pnt[i + 1].X - pnt[i - 1].X, firstHight));
                if (CR.rec.Count == (pnt.Count - 1) / 2)
                {
                    r.Add(CR);
                }
            }


            for (int i = 0; i < r.Count(); i++)
            {
                CR = r[i];
                for (int t = 0; t < CR.rec.Count(); t++)
                {
                    this.org.Add(CR.org[t]);
                    this.rec.Add(CR.rec[t]);
                }
            }
        }
Exemple #11
0
        public Color[,] RenderEffect(Color[,] buffer, Color[] palette, int eventToRender)
        {
            var bufferHeight = buffer.GetLength(Utils.IndexRowsOrHeight);
            var bufferWidth = buffer.GetLength(Utils.IndexColsOrWidth);
            var colorcnt = palette.Length;

            var halfWidth = Math.Max(1, bufferWidth / 2);
            var halfHeight = Math.Max(1, bufferHeight / 2);
            var outterR = (float) (halfWidth * (tbOuterR.Value / 100.0));
            var innerR = (float) (halfWidth * (tbInnerR.Value / 100.0));
            if (innerR > outterR) innerR = outterR;
            var distance = (float) (halfWidth * (tbDistance.Value / 100.0));

            var mod1440 = eventToRender % 1440;
            var originalDistance = distance;
            for (var i = 1; i <= 360; i++) {
                if (chkBoxAnimate.Checked) distance = (int) (originalDistance + eventToRender / 2.0) % 100;
                var t = (float) ((i + mod1440) * Math.PI / 180);
                var x = Convert.ToInt32((outterR - innerR) * Math.Cos(t) + distance * Math.Cos(((outterR - innerR) / innerR) * t) + halfWidth);
                var y = Convert.ToInt32((outterR - innerR) * Math.Sin(t) + distance * Math.Sin(((outterR - innerR) / innerR) * t) + halfHeight);
                var x2 = Math.Pow((x - halfWidth), 2);
                var y2 = Math.Pow((y - halfHeight), 2);
                var hyp = (Math.Sqrt(x2 + y2) / bufferWidth) * 100.0;

                if (x >= 0 && x < bufferWidth && y >= 0 && y < bufferHeight) {
                    buffer[y, x] = palette[(int)(hyp / (colorcnt > 0 ? bufferWidth / colorcnt : 1)) % colorcnt];
                }
            }
            return buffer;
        }
Exemple #12
0
        private void label3_Click(object sender, EventArgs e)
        {
            int    count = 50;
            Image  T1    = Bitmap.FromFile("D:\\1.png");
            Bitmap TT    = new Bitmap(T1);
            Random Ran   = new Random();

            Color[,] Test  = new Color[iSize, iSize];
            Color[,] TestO = new Color[Test.GetLength(0), Test.GetLength(1)];
            for (int i = 0; i < Test.GetLength(0); i++)
            {
                for (int ii = 0; ii < Test.GetLength(1); ii++)
                {
                    //TestO[i, ii] = Color.FromArgb(Ran.Next(1, 254), Ran.Next(1, 254), Ran.Next(1, 254));
                    Test[i, ii] = TT.GetPixel(i, ii);
                    //Test[i, ii] = Color.FromArgb(count+= +Ran.Next(1, 50), count+ Ran.Next(1, 50), count + Ran.Next(1, 50));
                    if (count >= 154)
                    {
                        count = 1;
                    }
                }
            }


            DateTime DTS = DateTime.Now;

            DTS   = DateTime.Now;
            TestO = myGaussBlur(Test, 5);
            //label3.Text += "   算法耗时:"+ (DateTime.Now-DTS).ToString();
            label3.Refresh();
            ImgDrawBefore(Test);
            ImgDrawAfter(TestO);
            label2.Text = "渲染完成";
            label2.Refresh();
        }
Exemple #13
0
        public override Color[,] apply(Color[,] imageToProcess, MainViewModel reportProgressTo)
        {
            imageToProcess = base.apply(imageToProcess, reportProgressTo);

            for (int i = 0; i < imageToProcess.GetLength(0); i++)
            {
                int firstPixelY = -1;
                for (int j = 0; j < imageToProcess.GetLength(1); j++)
                {
                    if (imageToProcess[i, j].ToArgb() == Color.Black.ToArgb())
                        if (firstPixelY <= 0 || firstPixelY + 1 == j)
                            firstPixelY = j;
                        else
                        {
                            for (int k = firstPixelY + 1; k < j; k++)
                                imageToProcess[i, k] = Color.Black;

                            firstPixelY = -1;
                        }

                    reportProgressTo.Progress++;
                }
            }

            return imageToProcess;
        }
 public static bool TexturesCollide(Color[,] tex1, Matrix mat1, Color[,] tex2, Matrix mat2)
 {
     int width1 = tex1.GetLength(0);
     int height1 = tex1.GetLength(1);
     int width2 = tex2.GetLength(0);
     int height2 = tex2.GetLength(1);
     Matrix mat1to2 = mat1 * Matrix.Invert(mat2);
     for (int x1 = 0; x1 < width1; x1++)
     {
         for (int y1 = 0; y1 < height1; y1++)
         {
             Vector2 pos1 = new Vector2(x1, y1);
             Vector2 pos2 = Vector2.Transform(pos1, mat1to2);
             int x2 = (int)pos2.X;
             int y2 = (int)pos2.Y;
             if ((x2 < 0) || (x2 >= width2)) continue;
             if ((y2 < 0) || (y2 >= height2)) continue;
             if (tex1[x1, y1].A <= 0)
             {
                 var tmp = 1 + 1;
                 var other = tmp + 1;
                 continue;
             }
             if (tex2[x2, y2].A <= 0) continue;
     //                    Vector2 screenPos = Vector2.Transform(pos1, mat1);
     //                    return screenPos;
             return true;
         }
     }
     //            return new Vector2(-1, -1);
     return false;
 }
Exemple #15
0
        /// <summary>
        /// Encodes the specified image data to png.
        /// </summary>
        /// <param name="pixels">
        /// The pixel data (bottom line first).
        /// </param>
        /// <param name="dpi">
        /// The image resolution in dots per inch.
        /// </param>
        /// <returns>
        /// The png image data.
        /// </returns>
        public static byte[] Encode(Color[,] pixels, int dpi = 96)
        {
            int height = pixels.GetLength(0);
            int width = pixels.GetLength(1);
            var bytes = new byte[(width * height * 4) + height];

            int k = 0;
            for (int i = height - 1; i >= 0; i--)
            {
                bytes[k++] = 0; // Filter
                for (int j = 0; j < width; j++)
                {
                    bytes[k++] = pixels[i, j].R;
                    bytes[k++] = pixels[i, j].G;
                    bytes[k++] = pixels[i, j].B;
                    bytes[k++] = pixels[i, j].A;
                }
            }

            var w = new MemoryWriter();
            w.Write((byte)0x89);
            w.Write("PNG\r\n\x1a\n".ToCharArray());
            WriteChunk(w, "IHDR", CreateHeaderData(width, height));
            WriteChunk(w, "pHYs", CreatePhysicalDimensionsData(dpi, dpi));
            WriteChunk(w, "IDAT", CreateUncompressedBlocks(bytes));
            WriteChunk(w, "IEND", new byte[0]);
            return w.ToArray();
        }
Exemple #16
0
    /// <summary>
    /// Erode an image using a k by k box kernel
    /// </summary>
    /// <param name="i">input image</param>
    /// <param name="k">kernel thickness</param>
    /// <returns>modified image</returns>
    public Color[,] Erosion(Color[,] i, int k)
    {
        //set source image to grayscale
        i = PointProcessing.Instance.Treshold(i, 0.5f);

        Color[,] result = new Color[i.GetLength(0), i.GetLength(1)];

        for (int w = 0 + k; w < i.GetLength(0) - k; w++)
        {
            for (int h = 0 + k; h < i.GetLength(1) - k; h++)
            {
                float sum = 0f;
                for (int j = -k / 2; j <= +k / 2; j++)
                {
                    for (int l = -k / 2; l <= +k / 2; l++)
                    {
                        sum += i[w + j, h + l].r;
                    }
                }

                float res = sum < k*k ? 0f : 1f;
                result[w, h].r = res;
                result[w, h].g = res;
                result[w, h].b = res;
            }
        }
        return result;
    }
Exemple #17
0
        public static Color[,] recolor(int[,] geo)
        {
            Color[,] geolocal = new Color[geo.GetLength(0), geo.GetLength(1)];
            Random rn = new Random();

            for (int t1 = 0; t1 < geolocal.GetLength(0) / 20; t1++)
            {
                for (int t2 = 0; t2 < geolocal.GetLength(1) / 20; t2++)
                {
                    // int currTheme = (rn.Next(3) * 11) + (rn.Next(2) * 38);
                    // if (currTheme == 2 * 11 || currTheme == 11 + 38)
                    //   break;
                    double hue = rn.Next(60) - 15;
                    hue = (Math.Abs(hue * 360) + hue) % 360;
                    for (int i = 0; i < 20; i++)
                    {
                        for (int j = 0; j < 20; j++)
                        {
                            if (geo[i + (t1 * 20), j + (t2 * 20)] == gr)
                            {
                                geolocal[i + (t1 * 20), j + (t2 * 20)] = Chroma.RandomBlend(Color.White, Color.FromHsv(hue, rn.NextDouble() / 2.5 + 0.2, 0.8), 0.05, 0.2);
                            }
                            else if (geo[i + (t1 * 20), j + (t2 * 20)] != da)    // && geo[i + (t1 * 20), j + (t2 * 20)] != 1187)
                            {
                                geolocal[i + (t1 * 20), j + (t2 * 20)] = Chroma.RandomBlend(Color.White, Color.FromHsv(hue, rn.NextDouble() / 2.5 + 0.2, 0.8), 0.15, 0.3);
                            }
                        }
                    }
                }
            }
            return(geolocal);
        }
Exemple #18
0
        public static Color[,] InterpolateWidth(Color[,] img, int width)
        {
            if (width == img.GetLength(0))
            {
                return(img);
            }

            Color[,] nMatrix = new Color[width, img.GetLength(1)];

            for (int j = 0; j < img.GetLength(1); j++)
            {
                Point lastIndex = new Point(0, 0);
                for (int i = 0; i < img.GetLength(0); i++)
                {
                    double percentX = (double)i / (double)img.GetLength(0);

                    int nX = (int)Math.Round(((double)nMatrix.GetLength(0) * (double)percentX));
                    if (nX >= nMatrix.GetLength(0))
                    {
                        nX = nMatrix.GetLength(0) - 1;
                    }

                    nMatrix[nX, j] = img[i, j];

                    for (int tX = lastIndex.X + 1; tX < nX; tX++)
                    {
                        float time = (float)tX / (float)nX;
                        nMatrix[tX, j] = PixelTransform.InterpolateColor(nMatrix[lastIndex.X, lastIndex.Y], nMatrix[nX, j], time);
                    }
                    lastIndex = new Point(nX, j);
                }
            }
            return(nMatrix);
        }
Exemple #19
0
 static void DisplayArray(Color[,] array)
 {
     //Visit each item
     for (int row = 0; row < array.GetLength(0); row++)
         for (int col = 0; col < array.GetLength(1); col++)
             canvas.SetBBScaledPixel(col, row, array[row, col]);
 }
Exemple #20
0
        public Color[,] RenderEffect(Color[,] buffer, Color[] palette, int eventToRender)
        {
            const int speedFactor = 200;
            var bufferHeight = buffer.GetLength(Utils.IndexRowsOrHeight);
            var bufferWidth = buffer.GetLength(Utils.IndexColsOrWidth);

            Color color;
            var hsv2 = new HSV();
            var colorcnt = palette.Length;
            var cycleLen = colorcnt * speedFactor;
            var count = tbCount.Value;
            if (eventToRender > (colorcnt - 1) * speedFactor * count && count < 10) {
                color = palette.GetMultiColorBlend(count % 2, false);
            } else {
                color = palette.GetMultiColorBlend(eventToRender % cycleLen / (double)cycleLen, true);
            }
            var hsv = color.ToHSV();
            var halfHeight = (bufferHeight - 1) / 2.0;
            var halfWidth = (bufferWidth - 1) / 2.0;
            for (var col = 0; col < bufferWidth; col++) {
                for (var row = 0; row < bufferHeight; row++) {
                    hsv2.SetToHSV(hsv);
                    if (chkBoxHFade.Checked) hsv2.Value *= (float)(1.0 - Math.Abs(halfWidth - col) / halfWidth);
                    if (chkBoxVFade.Checked) hsv2.Value *= (float)(1.0 - Math.Abs(halfHeight - row) / halfHeight);
                    buffer[row, col] = hsv2.ToColor();
                }
            }
            return buffer;
        }
 public static int[,] ConvertToGreyscale(Color[,] colors, decimal redWeight, decimal greenWeight, decimal blueWeight)
 {
     int[,] grey = new int[colors.GetLength(0), colors.GetLength(1)];
     for (int x = 0; x < colors.GetLength(0); x++)
         for (int y = 0; y < colors.GetLength(1); y++)
             grey[x, y] = (int)(redWeight * colors[x, y].R + greenWeight * colors[x, y].G + blueWeight * colors[x, y].B);
     return grey;
 }
Exemple #22
0
        public Color[,] RenderEffect(Color[,] buffer, Color[] palette, int eventToRender)
        {
            var h = 0.0;
            var bufferHeight = buffer.GetLength(Utils.IndexRowsOrHeight);
            var bufferWidth = buffer.GetLength(Utils.IndexColsOrWidth);
            var hsv = new HSV();
            var maxframe = bufferHeight*2;
            var frame = (int) ((bufferHeight*(double) eventToRender/200.0)%maxframe);
            var offset = eventToRender/100.0;
            for (var col = 0; col < bufferWidth; col++) {
                for (var row = 0; row < bufferHeight; row++) {
                    double x1;
                    double y1;
                    double f;
                    switch (tbStyle.Value) {
                        case 1:
                            var n =
                                Math.Abs((col*col - row*row)*
                                         Math.Sin(offset + ((col + row)*Pi2/(bufferHeight + bufferWidth))));
                            var d = col*col + row*row + 1;
                            h = n/d;
                            break;
                        case 2:
                            f = (frame < maxframe/2) ? frame + 1 : maxframe - frame;
                            x1 = (col - bufferWidth/2.0)/f;
                            y1 = (row - bufferHeight/2.0)/f;
                            h = Math.Sqrt(x1*x1 + y1*y1);
                            break;
                        case 3:
                            f = (frame < maxframe/2) ? frame + 1 : maxframe - frame;
                            f = f*0.1 + bufferHeight/60.0;
                            x1 = (col - bufferWidth/2.0)/f;
                            y1 = (row - bufferHeight/2.0)/f;
                            h = Math.Sin(x1)*Math.Cos(y1);
                            break;

                    }
                    hsv.Saturation = 1.0f;
                    hsv.Value = 1.0f;
                    var chunks = tbChunks.Value;
                    var skip = tbSkip.Value;
                    if (chunks > 1 && ((int) (h*chunks))%skip == 0) {
                        continue;
                    }
                    Color color;
                    if (cbColors.SelectedIndex == 0) {
                        hsv.Hue = (float) h;
                        color = hsv.ToColor();
                    }
                    else {
                        color = palette.GetMultiColorBlend(h, false);
                    }

                    buffer[row, col] = color;
                }
            }
            return buffer;
        }
Exemple #23
0
        public override void ReadImage(uint packetID, uint packetSize, BinaryReader br)
        {
            base.ReadImage(packetID, packetSize, br);
            var  sw      = Stopwatch.StartNew();
            bool Is32x32 = false; // true;

            switch (packetID)
            {
            case 27:     //1b
            case 28:     //1c
            case 29:     //1d (boom beach: in-game_tex.sc & defences_tex.sc)
                Is32x32 = true;
                break;
            }

            Console.WriteLine(@"packetID: " + packetID);
            Console.WriteLine(@"packetSize: " + packetSize);
            Console.WriteLine(@"texPixelFormat: " + _imageType);
            Console.WriteLine(@"texWidth: " + _width);
            Console.WriteLine(@"texHeight: " + _height);
            Console.WriteLine(@"Is32x32: " + Is32x32);


            _bitmap = new Bitmap(_width, _height, PixelFormat.Format32bppArgb);


            Color[,] pixelArray = new Color[_height, _width];
            for (int row = 0; row < pixelArray.GetLength(0); row++)
            {
                for (int col = 0; col < pixelArray.GetLength(1); col++)
                {
                    ushort color = br.ReadUInt16();
                    int    red   = Utils.ConvertMap[(color >> 11) & 0x1F];
                    int    green = Utils.ConvertMap[(color >> 6) & 0x1F];
                    int    blue  = Utils.ConvertMap[(color >> 1) & 0x1F];
                    int    alpha = (int)(color & 0x0001) == 1 ? 0xFF : 0x00;
                    pixelArray[row, col] = Color.FromArgb(alpha, red, green, blue);;
                }
            }
            if (Is32x32)
            {
                pixelArray = Utils.Solve32X32Blocks(_width, _height, pixelArray);
            }

            for (int row = 0; row < pixelArray.GetLength(0); row++)
            {
                for (int col = 0; col < pixelArray.GetLength(1); col++)
                {
                    //Color pxColor = Color.Red;
                    Color pxColor = pixelArray[row, col];
                    _bitmap.SetPixel(col, row, pxColor);
                }
            }

            sw.Stop();
            Console.WriteLine("ImageRgba5551.ReadImage finished in {0}ms", sw.Elapsed.TotalMilliseconds);
        }
Exemple #24
0
        public static Color[] ToColorsA(RayTraceChunkManager rtc, int bits)
        {
            int dcx = rtc.getChunkSize().x;
            int dcy = rtc.getChunkSize().y;
            int dcz = rtc.getChunkSize().z;
            int dgx = rtc.getSizeX();
            int dgy = rtc.getSizeY();
            int dgz = rtc.getSizeZ();

            Color[,,] colors = new Color[dgx, (dgy / bits), dgz];
            for (int cx = 0; cx < dcx; cx++)
            {
                for (int cy = 0; cy < dcy; cy++)
                {
                    for (int cz = 0; cz < dcz; cz++)
                    {
                        RayTraceChunk chunk = rtc.getChunk(cx, cy, cz);
                        for (int bx = 0; bx < Const.ChunkSize; bx++)
                        {
                            for (int by = 0; by < Const.ChunkSize / bits; by++)
                            {
                                for (int bz = 0; bz < Const.ChunkSize; bz++)
                                {
                                    int iv = 0;
                                    for (int n = 0; n < bits; n++)
                                    {
                                        iv |= chunk.testBlock(bx, by * bits + n, bz) ? (1 << n) : 0;
                                    }
                                    float a  = iv / (float)((1 << bits) - 1);
                                    int   gx = cx * Const.ChunkSize + bx;
                                    int   gy = cy * Const.ChunkSize / bits + by;
                                    int   gz = cz * Const.ChunkSize + bz;
                                    colors[gx, gy, gz] = new Color(0, 0, 0, a);
                                }
                            }
                        }
                    }
                }
            }

            int sizeX = colors.GetLength(0);
            int sizeY = colors.GetLength(1);
            int sizeZ = colors.GetLength(2);

            Color[] rlt = new Color[sizeX * sizeY * sizeZ];
            for (int x = 0; x < sizeX; x++)
            {
                for (int y = 0; y < sizeY; y++)
                {
                    for (int z = 0; z < sizeZ; z++)
                    {
                        rlt[z * sizeY * sizeX + y * sizeX + x] = colors[x, y, z];
                    }
                }
            }
            return(rlt);
        }
Exemple #25
0
        public static Color[,] applyFilter(Color[,] screen)
        {
            // search the screen for the sample
            int screen_rows = screen.GetLength(0);
            int screen_colums = screen.GetLength(1);

            int k = 0;
            int l = 0;

            Color[,] subImage = new Color[screen_rows, screen_colums];

            // Vi itererer over vores sample
            while (k < (screen_rows))
            {
                while (l < (screen_colums))
                {
                    // COPY!
                    /*int filter = int.Parse("" + screen[i, j].R + screen[i, j].G + screen[i, j].B);
                    if (filter <= 000)
                    {*/
                    Color c = screen[k, l];
                    if ((int)c.R > 200 || (int)c.G > 200 || (int)c.B > 200)
                    {
                    }
                    else
                    {
                        int grayScale = (int)((screen[k, l].R * .3) + (screen[k, l].G * .59) + (screen[k, l].B * .11));
                        Color newColor = Color.FromArgb(grayScale, grayScale, grayScale);
                        subImage[k, l] = newColor;
                        //subImage[k, l] = screen[i, j];
                    }
                    /*}*/

                    if (k == screen_rows - 1 && l == screen_colums - 1)
                    {
                        k = screen_rows + 1; // Grimt grimt hack, men vi sparer en goto
                        break;
                    }
                    else if (l == screen_colums - 1)
                    {
                        // Hvis vi er for "enden" så reset, og hop til næste row
                        k++;
                        l = 0;

                        // Row jump på screenen også
                    }
                    else
                    {
                        // Hop en enkelt column både på screen og på sample
                        l++;
                    }
                }
            }

            return subImage;
        }
        public static Bitmap CreateImage(Color[,] values)
        {
            Bitmap result = new Bitmap(values.GetLength(0), values.GetLength(1));

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

            return result;
        }
Exemple #27
0
        public override Color[,] Apply(Color[,] image, int minThreshold = 1)
        {
            int width = image.GetLength(0);
            int height = image.GetLength(1);

            int kernelX = this.Size;
            int kernelY = this.Size;
            int kernelOffsetX = (kernelX - 1) / 2;
            int kernelOffsetY = (kernelY - 1) / 2;

            Color[,] result = new Color[width, height];

            // loop over image coordinates
            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    int localMaximum = 0;
                    if (image[x, y].R < minThreshold) continue;

                    // loop over neighbourhood pixels
                    for (int kx = -kernelOffsetX; kx <= kernelOffsetX; kx++)
                    {
                        int offsetX = x + kx;
                        for (int ky = -kernelOffsetY; ky <= kernelOffsetY; ky++)
                        {
                            int offsetY = y + ky;
                            // if not out of bounds
                            if (!(
                                offsetX < 0
                                || offsetX >= width
                                || offsetY < 0
                                || offsetY >= height
                                ))
                            {
                                //find maximum value
                                int val = image[offsetX, offsetY].R;
                                if (val > localMaximum) localMaximum = val;
                            }
                        }
                    }
                    //if the pixel is the highest in the neighbourhood, keep it on.
                    if (image[x, y].R == localMaximum)
                    {
                        result[x, y] = Color.FromArgb(localMaximum, localMaximum, localMaximum);
                    }
                    // otherwise turn the pixel off
                    else
                    {
                        result[x, y] = Color.Black;
                    }
                }
            }
            return result;
        }
Exemple #28
0
        public Color <byte>[,] Median3x3Single(Color <byte>[,] imageUnfiltred)
        {
            string name     = "Median3x3Single";
            int    progress = 2;

            int height = imageUnfiltred.GetLength(0);
            int width  = imageUnfiltred.GetLength(1);

            Color <byte>[,] imageFiltred = new Color <byte> [height, width];

            for (int i = 1; i < height - 1; i++)
            {
                Console.WriteLine($"{name}: thread #{Thread.CurrentThread.ManagedThreadId.ToString()} on height {i.ToString()} -> applicating");

                for (int j = 1; j < width - 1; j++)
                {
                    Color <int[]> newColors = new Color <int[]>
                    {
                        Red   = new int[9],
                        Green = new int[9],
                        Blue  = new int[9]
                    };

                    newColors = Convolution(imageUnfiltred, i, j, newColors);

                    Array.Sort(newColors.Red);
                    Array.Sort(newColors.Green);
                    Array.Sort(newColors.Blue);

                    imageFiltred[i, j].Red   = (byte)(newColors.Red[4]);
                    imageFiltred[i, j].Green = (byte)(newColors.Green[4]);
                    imageFiltred[i, j].Blue  = (byte)(newColors.Blue[4]);
                }

                progress++;

                if (!ProgressCallback(progress, height))
                {
                    Console.WriteLine($"{name}: thread #{Thread.CurrentThread.ManagedThreadId.ToString()} on height {i.ToString()} -> " +
                                      "canceling");
                    Console.WriteLine($"{name} application has been canceled");

                    imageUnfiltred = null;
                    imageFiltred   = null;

                    return(imageFiltred);
                }
            }

            imageUnfiltred = null;

            Console.WriteLine($"{name} is succesfully applicated");

            return(imageFiltred);
        }
Exemple #29
0
        public void InitializeComponent()
        {
            Color[,] colors = new Color[, ] {
                { Color.Black, Color.Gray, Color.Brown, Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.LightBlue, Color.Blue, Color.Violet },
                { Color.White, Color.LightGray, Color.LightCoral, Color.Pink, Color.DarkOrange, Color.LightYellow, Color.GreenYellow, Color.SkyBlue, Color.CadetBlue, Color.Tomato }
            };
            int magion          = DrawingBoardDemo.ColorButtonMagion;
            int x               = magion + 2;
            int y               = magion + 2;
            int colorButtonSize = DrawingBoardDemo.ColorButtonSize;

            foreColorButton          = new ColorButton();
            foreColorButton.Selected = true;
            foreColorButton.Name     = "foreColorButton";
            foreColorButton.Text     = "Fore color";
            foreColorButton.Bounds   = new Rectangle(x, y, colorButtonSize * 2, colorButtonSize * 2);
            foreColorButton.Click   += button_Click;
            this.Controls.Add(foreColorButton);
            x = foreColorButton.Right + magion;

            backColorButton        = new ColorButton();
            backColorButton.Name   = "backColorButton";
            backColorButton.Text   = "Back color";
            backColorButton.Bounds = new Rectangle(x, y, colorButtonSize * 2, colorButtonSize * 2);
            backColorButton.Click += button_Click;
            this.Controls.Add(backColorButton);
            x = backColorButton.Right + magion;

            int startX = x;

            for (int i = 0; i < colors.GetLength(0); i++)
            {
                x = startX;
                for (int j = 0; j < colors.GetLength(1); j++)
                {
                    Button button = new Button();
                    button.Click    += button_Click;
                    button.Bounds    = new Rectangle(x, y, colorButtonSize, colorButtonSize);
                    button.BackColor = colors[i, j];
                    x = button.Right + magion;
                    this.Controls.Add(button);
                }
                y = y + colorButtonSize + magion;
            }
            y  = magion + 3;
            x += 2;
            editColorButton                   = new Button();
            editColorButton.Name              = "editColorButton";
            editColorButton.Text              = "Edit colors";
            editColorButton.Bounds            = new Rectangle(x, y, colorButtonSize * 2, colorButtonSize * 2);
            editColorButton.Click            += button_Click;
            editColorButton.Image             = Properties.Resources.ChooseColor;
            editColorButton.TextImageRelation = TextImageRelation.ImageAboveText;
            this.Controls.Add(editColorButton);
        }
Exemple #30
0
        public Color[,] ApplyMedian(Color[,] image)
        {
            int width = image.GetLength(0);
            int height = image.GetLength(1);
            Color[,] result = new Color[width, height];

            int kernelX = this.matrix.GetLength(0);
            int kernelY = this.matrix.GetLength(1);
            int kernelOffsetX = (kernelX - 1) / 2;
            int kernelOffsetY = (kernelY - 1) / 2;

            int offsetX, offsetY;
            int neighbourhoodSize = kernelX*kernelY;
            int[] neighbourhoodValues = new int[neighbourhoodSize];

            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    for (int kx = -kernelOffsetX; kx <= kernelOffsetX; kx++)
                    {
                        offsetX = x + kx;
                        for (int ky = -kernelOffsetY; ky <= kernelOffsetY; ky++)
                        {
                            offsetY = y + ky;

                            int row = ky + kernelOffsetY;
                            int column = kx + kernelOffsetX;
                            if (
                                offsetX < 0
                                || offsetX >= width
                                || offsetY < 0
                                || offsetY >= height
                                )
                            {

                                neighbourhoodValues[kernelX * row + column] = this.padding;
                            }
                            else
                            {
                                neighbourhoodValues[kernelX * row + column] = image[offsetX, offsetY].R;
                            }
                        }
                    }
                    Array.Sort(neighbourhoodValues);
                    int median = neighbourhoodValues[(neighbourhoodSize + 1)/2];
                    result[x, y] = Color.FromArgb(
                        median, median, median
                    );
                }
            }

            return result;
        }
	public Color[,] Render() {
		Color[,] c = new Color[BlockEditor.textureSize, BlockEditor.textureSize];

		for (int x = 0; x < c.GetLength(0); x++) {
			for (int y = 0; y < c.GetLength(1); y++) {
				c[x, y] = new Color(heightMap[x, y], heightMap[x, y], heightMap[x, y]);
			}
		}

		return c;
	}
Exemple #32
0
 private void initializeImageColorTable()
 {
     currentImageColorTable = new Color[screenPB.Width, screenPB.Height];
     for (int i = 0; i < currentImageColorTable.GetLength(0); i++)
     {
         for (int j = 0; j < currentImageColorTable.GetLength(1); j++)
         {
             currentImageColorTable[i, j] = textureImageColorTable[i, j];
         }
     }
 }
        public Texture2D Array2DToTexture(Color[,] array2D)
        {
            Color[] colors1D = new Color[array2D.GetLength(0) * array2D.GetLength(1)];
            for (int x = 0; x < array2D.GetLength(0); x++)
                for (int y = 0; y < array2D.GetLength(1); y++)
                    colors1D[x + y * array2D.GetLength(0)] = array2D[x, y];

            Texture2D texture = new Texture2D(graphics.GraphicsDevice, array2D.GetLength(0), array2D.GetLength(1));
            texture.SetData<Color>(colors1D);
            return texture;
        }
		/// <summary>
		/// Constructor.
		/// </summary>
		/// <param name="symbol">The unicode character.</param>
		/// <param name="pixels">The pixels array. Must not be larger than 8x8 pixels.</param>
		/// <param name="transparencyColor">The color that represents transparency.</param>
		public MultiColorCharacter(char symbol, Color[,] pixels, Color? transparencyColor = null)
			: base(symbol, pixels.GetLength(0))
		{
			if (pixels.GetLength(1) > 8)
			{
				throw new ArgumentException("The pixels array must not be taller than 8 pixels!");
			}

			Pixels = pixels;
			TransparencyColor = transparencyColor;
		}
		public SpriteMap(Color[,] pixels)
		{
			if (((pixels.GetLength(0) % 8) != 0) || ((pixels.GetLength(1) % 8) != 0))
			{
				throw new ArgumentException("Expecting an image with sides of mutiple of 8 pixels");
			}

			Pixels = pixels;

			SpriteCountHorizontal = Pixels.GetLength(0) / 8;
			SpriteCountVertical = Pixels.GetLength(1) / 8;
		}
        public Color[,] LinearFilter(Color[,] input, double[,] Mask, int originX, int originY, string Postprocessing)
        {
            int width = input.GetLength(0);
            int height = input.GetLength(1);
            int mask_width = Mask.GetLength(0);
            int mask_height = Mask.GetLength(1);

            Color[,] temp = Padding(input, Mask, originX, originY);
            Color[,] result = new Color[width, height];
            Data[,] data = new Data[width, height];
            for (int i = 0; i < width; i++)
            {
                for (int j = 0; j < height; j++)
                {
                    Data sum;
                    sum.R_Val = sum.G_Val = sum.B_Val = 0;
                    for (int k = 0; k < mask_height; k++)
                    {
                        for (int m = 0; m < mask_width; m++)
                        {
                            sum.R_Val += Mask[m, k] * temp[i + m, j + k].R;
                            sum.G_Val += Mask[m, k] * temp[i + m, j + k].G;
                            sum.B_Val += Mask[m, k] * temp[i + m, j + k].B;
                        }
                    }
                    if (Postprocessing == "Cutoff")
                    {
                        sum.R_Val = pixel.cutOff(sum.R_Val);
                        sum.G_Val = pixel.cutOff(sum.G_Val);
                        sum.B_Val = pixel.cutOff(sum.B_Val);
                        result[i, j] = Color.FromArgb((int)sum.R_Val, (int)sum.G_Val, (int)sum.B_Val);

                    }
                    else if (Postprocessing == "Absolute")
                    {

                        sum.R_Val = Math.Abs(sum.R_Val);
                        sum.G_Val = Math.Abs(sum.G_Val);
                        sum.B_Val = Math.Abs(sum.B_Val);
                        data[i, j] = sum;
                    }
                    else if (Postprocessing == "None")
                    {
                        result[i, j] = Color.FromArgb((int)sum.R_Val, (int)sum.G_Val, (int)sum.B_Val);
                    }
                }
            }
            if (Postprocessing == "Absolute")
            {
                result = pixel.Contrast(0, 255, data);
            }
            return result;
        }
Exemple #37
0
 // Use canvas properties to initialize _aBlockColors, and set each element to the primary color.
 // (only used once, so no locks are necessary.)
 private void GetNewColorArray()
 {
     _aBlockColors = new Color[_canvas.ScaledWidth, _canvas.ScaledHeight];
     for (int x = 0; x < _aBlockColors.GetLength(0); x++)
     {
         for (int y = 0; y < _aBlockColors.GetLength(1); y++)
         {
             _aBlockColors[x, y] = Block._cPrimary;
         }
     }
     ResetState(); // set all blocks with no highlighting initially.
 }
	Lab[,] RgbArrayToLabArray(Color[,] RgbArray)
	{
		Lab[,] rawLabArray= new Lab[RgbArray.GetLength(0), RgbArray.GetLength(1)];
		for (int i = 0; i < RgbArray.GetLength (0); i++) 
		{
			for (int j = 0; j < RgbArray.GetLength (1); j++) 
			{
				rawLabArray[i,j] = ColorUtil.ConvertRGBtoLAB (RgbArray[i,j]);
			}
		}
		return rawLabArray;
	}
Exemple #39
0
 private Color[,] GetClusters(double[,] map, int clusterCount, double min = 0, double max = 1)
 {
     Color[,] cMap = new Color[map.GetLength(0), map.GetLength(1)];
     for (int x = 0; x < cMap.GetLength(0); x++)
     {
         for (int y = 0; y < cMap.GetLength(1); y++)
         {
             cMap[x, y] = GetClusteredColor(map[x, y], clustersCount, min, max);
         }
     }
     return(cMap);
 }
Exemple #40
0
 private Color[,] createEmptyBoard()
 {
     Color[,] array = new Color[10, 20];
     for (int i = 0; i < array.GetLength(0); i++)
     {
         for (int j = 0; j < array.GetLength(1); j++)
         {
             array[i, j] = new Color(20, 20, 20);
         }
     }
     return(array);
 }
Exemple #41
0
 private Color[,] GetRangeBlueToRed(double[,] map, double min = 0, double max = 1)
 {
     Color[,] cMap = new Color[map.GetLength(0), map.GetLength(1)];
     for (int x = 0; x < cMap.GetLength(0); x++)
     {
         for (int y = 0; y < cMap.GetLength(1); y++)
         {
             cMap[x, y] = GetColor(map[x, y], min, max);
         }
     }
     return(cMap);
 }
 private static Bitmap CreateBitmapFromColors(Color[,] image)
 {
   Bitmap bitmap = new Bitmap(image.GetLength(0), image.GetLength(1));
   for (int i = 0; i < image.GetLength(0); i++)
   {
     for (int j = 0; j < image.GetLength(1); j++)
     {
       bitmap.SetPixel(i, j, image[i, j]);
     }
   }
   return bitmap;
 }
Exemple #43
0
 /**
  * Konstruktor
  */
 public BoardEventArgs(Color[,] boardData)
 {
     Color[,] newBoardData = new Color[boardData.GetLength(0), boardData.GetLength(1)];
     for (int i = 0; i < boardData.GetLength(1); i++)
     {
         for (int j = 0; j < boardData.GetLength(0); j++)
         {
             newBoardData[j, i] = boardData[j, i];
         }
     }
     removedLines = new List<int>();
     this.boardData = newBoardData;
 }
Exemple #44
0
        /// <summary>
        /// Event occurs when the pixel grid needs to be re-painted.
        /// </summary>
        private void pixelGrid_Paint(object sender, PaintEventArgs e)
        {
            // Initialize required objects
            SyntheticCamera   c      = new SyntheticCamera(_e, _g, _p, 15, 150, 45.0, 1.0, pixelGrid.Grid.Width, pixelGrid.Grid.Height);
            DrawingController drawer = new DrawingController(e.Graphics);
            RayTracer         ray    = new RayTracer(c, 1);

            int superWidth  = pixelGrid.Grid.Width * ray.ResolutionMultiplier;
            int superHeight = pixelGrid.Grid.Height * ray.ResolutionMultiplier;

            // Buffer holds the super width and super height colors to eventually avg and render.
            Color[,] buffer = new Color[superHeight, superWidth];

            // Loop through each pixel and trace a ray through it to find an intersection with the object
            Parallel.For(0, superHeight, (y) =>
            {
                Parallel.For(0, superWidth, (x) =>
                {
                    PointLight pointLight = new PointLight(Color.FromScRgb(1, 1, 1, 1), new Point3D(1000, 1000, 1000));
                    DirectionalLight sun  = new DirectionalLight(Color.FromScRgb(1, 1, 1, 1), new Vector3D(0, 0, -1));
                    buffer[y, x]          = ray.RayTrace(_objects, x, y, pointLight, sun);
                });
            });

            // Calculates the avg's of the super resolution buffer and displys to screen.
            for (int i = 0; i < buffer.GetLength(0); i += ray.ResolutionMultiplier)
            {
                for (int j = 0; j < buffer.GetLength(1); j += ray.ResolutionMultiplier)
                {
                    // Add all the rbg values for each super resolution block of points.
                    float r = 0, g = 0, b = 0;
                    for (int m = 0; m < ray.ResolutionMultiplier; ++m)
                    {
                        for (int n = 0; n < ray.ResolutionMultiplier; ++n)
                        {
                            r += buffer[i + m, j + n].ScR;
                            g += buffer[i + m, j + n].ScG;
                            b += buffer[i + m, j + n].ScB;
                        }
                    }

                    // Avg the block of points to 1 pixel
                    float avgR = (float)(r / Math.Pow(ray.ResolutionMultiplier, 2));
                    float avgG = (float)(g / Math.Pow(ray.ResolutionMultiplier, 2));
                    float avgB = (float)(b / Math.Pow(ray.ResolutionMultiplier, 2));

                    drawer.Color = Color.FromScRgb(1, avgR, avgG, avgB).ToDColor();
                    drawer.DrawPoint(new System.Drawing.Point(j / ray.ResolutionMultiplier, i / ray.ResolutionMultiplier));
                }
            }
        }
Exemple #45
0
    /// <summary>
    /// Draws the grid.
    /// </summary>
    /// <param name="lines">Lines. how many lines you want in the grid</param>
    /// <param name="columns">Columns. how many columns you want in the grid</param>
    /// <param name="gridLocal">Grid local. The grid being changed.</param>
    /// <param name="borderColor">Border color. Im using Unity Color class, basic RGBA style.</param>
    public void DrawGrid(int lines,int columns,Color[,] gridLocal, Color borderColor)
    {
        //I`m going to draw the grid with 4 fors, skipping the grid space to save processing.
        //This method can only be used if the background is clear. otherwize it will keep garbage.
        //Another way of doing it could be to use 2 fors and if statements inside. It really depends on what we want to do.
        //in this drawing method I am cleaning the background each time it changes.
        //grid.gridArray = new Color[grid.GridWidth+1, grid.GridHeight+1];
        for (int x = 0; x < gridLocal.GetLength(0); x++) {
            for (int y = 0; y < gridLocal.GetLength(1); y++) {
                gridLocal[x,y] = grid.backgroundColor;
                //Debug.Log(gridLocal[x,y]);
            }
        }

        //Getting all first pixels positions of all cells
        grid.gridPositions = new Vector2[grid.GridColumns, grid.GridLines];
        float rectWidth = (gridLocal.GetLength(0)/columns);
        float rectHeigh = (gridLocal.GetLength (1) / lines);
        for (int x=0; x < grid.GridColumns; x++) {
            for(int y=0; y < grid.GridLines;y++){
                grid.gridPositions[x,y] = new Vector2(x*rectWidth,y*rectHeigh);
            }
        }

        //then I paint the lines, pixel by pixel.
        for (int x = 0; x < gridLocal.GetLength(0) ; x+=(gridLocal.GetLength(0)/(columns))) {
            for (int y = 0; y < gridLocal.GetLength(1) ; y++) {
                gridLocal[x,y] = borderColor;
                gridLocal[gridLocal.GetLength(0)-1,y] = borderColor;
            }
        }
        for (int x = 0; x < gridLocal.GetLength(0); x++) {
            for (int y = 0; y < gridLocal.GetLength(1); y+=(gridLocal.GetLength(1)/lines)) {
                gridLocal [x, y] = borderColor;
                gridLocal[x,gridLocal.GetLength(1)-1] = borderColor;
            }
        }

        //then I paint the user selected points
        Vector2 linePoint = new Vector2 (8, 15);
        Vector2 endLinePoint = new Vector2 (60, 104);
        for (float t=0; t<1; t+=(0.001f)) {
            linePoint = CalculatePointOfLine(t,pointA,pointB);
            gridLocal[(int)linePoint.x, (int)linePoint.y] = Color.blue;
        }

        //then I paint the line between selected points
        //I am using a Bresenham algorithm to calculate the cells
        gridGeneratedPointsText = ""; //setting up string to be filled with grid positions
        int sizeW = (int)((gridLocal.GetLength(0)/(columns)));
        int sizeH = (int)((gridLocal.GetLength(1)/(lines)));
        for (int i=1; i<= grid.thickness; i++) {
            Vector2 tempThickA = new Vector2(pointA.x + (i*sizeW),pointA.y+(i*sizeH));
            Vector2 tempThickB = new Vector2(pointB.x + (i*sizeW),pointB.y+(i*sizeH));
            gridLocal = lineBresenham (tempThickA, tempThickB, gridLocal);
        }

        //sends information to renderer
        gridRenderer.SetGridTexture(grid.gridArray);
    }
Exemple #46
0
    private void DumpDebugHeightmap()
    {
        // Re-normalize the terrain
        float minHeight = float.MaxValue;
        float maxHeight = -float.MaxValue;

        Color[,] heightmap = new Color[m_root.heightmapData.GetLength(0), m_root.heightmapData.GetLength(1)];

        System.Array.Copy(m_root.heightmapData, heightmap, m_root.heightmapData.GetLength(0) * m_root.heightmapData.GetLength(1));

        for (int x = 0; x < heightmap.GetLength(0); ++x)
        {
            for (int y = 0; y < heightmap.GetLength(1); ++y)
            {
                if (heightmap[x, y].r < minHeight)
                {
                    minHeight = heightmap[x, y].r;
                }
                if (heightmap[x, y].r > maxHeight)
                {
                    maxHeight = heightmap[x, y].r;
                }
            }
        }

        for (int x = 0; x < heightmap.GetLength(0); ++x)
        {
            for (int y = 0; y < heightmap.GetLength(1); ++y)
            {
                heightmap[x, y].r = (heightmap[x, y].r - minHeight) / (maxHeight - minHeight);
            }
        }

        Color[] texFormatData = new Color[Resolution * Resolution];

        for (int y = 0; y < Resolution; ++y)
        {
            for (int x = 0; x < Resolution; ++x)
            {
                texFormatData[y * Resolution + x]   = heightmap[x, y];
                texFormatData[y * Resolution + x].a = 1.0f;
            }
        }

        Texture2D testTexture = new Texture2D(Resolution, Resolution);

        testTexture.SetPixels(texFormatData);

        System.IO.File.WriteAllBytes(@"D:\heightmap.png", testTexture.EncodeToPNG());
    }
Exemple #47
0
        public static Texture2D DrawAsPointsToTexture(GraphicsDevice GD)
        {
            Color[,] Col2D = new Color[(int)GameValues.ScreenSize.X, (int)GameValues.ScreenSize.Y];

            for (int x = 0; x < Col2D.GetLength(0); x++)
                for (int y = 0; y < Col2D.GetLength(1); y++)
                    Col2D[x, y] = Color.Black;

            List<Particle> P = GetAllParticles();
            for (int i = 0; i < P.Count; i++)
            {
                if (P[i].Pos.X > 0 && P[i].Pos.X < GameValues.ScreenSize.X && P[i].Pos.Y > 0 && P[i].Pos.Y < GameValues.ScreenSize.Y)
                    Col2D[(int)P[i].Pos.X, (int)P[i].Pos.Y] = P[i].C;
            }

            Color[] Col1D = new Color[Col2D.GetLength(0) * Col2D.GetLength(1)];
            for (int x = 0; x < Col2D.GetLength(0); x++)
                for (int y = 0; y < Col2D.GetLength(1); y++)
                    Col1D[x * y] = Col2D[x, y];

            Texture2D Output = new Texture2D(GD, Col2D.GetLength(0), Col2D.GetLength(1));
            Output.SetData(Col1D);

            return Output;
        }
Exemple #48
0
    /// <summary>
    /// Sets the grid texture.
    /// </summary>
    /// <returns><c>true</c>, if grid texture was set, <c>false</c> otherwise.</returns>
    /// <param name="grid">X and Y array of colors</param>
    public bool SetGridTexture(Color[,] grid)
    {
        //first we make simple tests, to make sure our caller gets the correct feedback from this method
        if (grid == null) return false;
        if (grid.GetLength(0) == 0) return false;
        if (grid.GetLength(1) == 0) return false;
        if (texture == null) return false;

        //we have to make sure the grid is compatible with the texture.
        //if they are not compatible, I can just create a new texture with matching sizes.
        if ((grid.GetLength(0) != texture.width) || (grid.GetLength(1) != texture.height)) {
            texture = new Texture2D(grid.GetLength(0),grid.GetLength(1));
            Debug.Log("New texture generated'" + grid.GetLength(0) + "," + grid.GetLength(1));
            //This is required, since a new instance of Texture2D has been created on it.
            guiTexture.texture = texture;
        }

        for (int x = 0; x < texture.width; x++) {
            for (int y = 0; y < texture.height; y++) {
                texture.SetPixel(x, y, grid[x,y]);
            }
        }
        //Screen.SetResolution(texture.width, texture.height, false);
        texture.Apply ();
        return true;
    }
Exemple #49
0
        /// <summary>
        /// Sets entire wall to a single color
        /// </summary>
        /// <param name="c"></param>
        private void setWallSolidColor(Color c)
        {
            Color[,] grid = new Color[StripCount, LedsPerStrip];
            for (int i = 0; i < grid.GetLength(0); i++)
            {
                for (int j = 0; j < grid.GetLength(1); j++)
                {
                    grid[i, j] = c;
                }
            }
            _ledWall.SetWall(grid);

            //TODO: use "set entire wall" message instead of entire grid
            //_ledWall.SetWall(c);
        }
Exemple #50
0
        public override string ToString()
        {
            Color[,] colors = new Color[3, 3];
            foreach (Color color in coordinates.Keys)
            {
                foreach (Coordinate coordinate in coordinates[color])
                {
                    colors[coordinate.GetRow(), coordinate.GetColumn()] = GetColor(coordinate);
                }
            }
            string result = "";

            for (int i = 0; i < colors.Length; i++)
            {
                for (int j = 0; j < colors.GetLength(i); j++)
                {
                    char color = '.';
                    if (colors[i, j] != null)
                    {
                        color = colors[i, j].ToString()[0];
                    }
                    result += color + " ";
                }
                result += " \n";
            }
            return(result);
        }
Exemple #51
0
        public void CreateTexture(Game1 game)
        {
            Texture2D newTexture = new Texture2D(game.GraphicsDevice, spriteWidth, spriteHeight);

            Color[] headPixels  = new Color[headSource.Width * headSource.Height];
            Color[] bodyPixels  = new Color[bodySource.Width * bodySource.Height];
            Color[] finalPixels = new Color[bodySource.Width * bodySource.Height];

            head.GetData <Color>(0, headSource, headPixels, 0, headSource.Width * headSource.Height);
            body.GetData <Color>(0, bodySource, bodyPixels, 0, bodySource.Width * bodySource.Height);

            for (int i = 0; i < headPixels.GetLength(0); i++)
            {
                int j = i + (HeadYOffset() * spriteWidth) + HeadXOffset();
                if (j >= 0 && j < finalPixels.GetLength(0) && j % spriteWidth >= i % spriteWidth)
                {
                    finalPixels[j] = headPixels[i];
                }
            }
            for (int i = 0; i < bodyPixels.GetLength(0); i++)
            {
                if (finalPixels[i].A == 0)
                {
                    finalPixels[i] = bodyPixels[i];
                }
            }

            newTexture.SetData <Color>(0, new Rectangle(0, 0, bodySource.Width, bodySource.Height), finalPixels, 0, bodySource.Width * bodySource.Height);
            this.texture = newTexture;
        }
Exemple #52
0
        public static string WhoIsWinner(List <string> piecesPositionList)
        {
            char[] letters = "ABCDEFG".ToCharArray();
            Color[,] board = new Color[8, 7];
            string result = string.Empty;

            foreach (var str in piecesPositionList)
            {
                var split = str.Split("_");
                int x     = Array.IndexOf(letters, char.Parse(split[0]));
                int y     = 0;

                for (int i = 0; i < board.GetLength(1); i++)
                {
                    if (board[x, i] == Color.Null)
                    {
                        y = i;
                        break;
                    }
                }

                board[x, y] = (Color)Enum.Parse(typeof(Color), split[1], true);

                result = CheckWin(board);

                if (result != "Draw")
                {
                    break;
                }
            }

            return(result);
        }
Exemple #53
0
        /// <summary>
        /// Описание метода для проверки принадлежности изображения к маркеру
        /// </summary>
        protected virtual void CheckOnMark()
        {
            // Проверка на соответсвию маркеру
            if (drawing.Format == "a3")
            {
                // Проверка на ориентацию страницы,
                // Если вертикальная, то ее нужно повернуть
                if (drawing.Orientation == OrientationType.Vertical)
                {
                    bitmap.RotateFlip(RotateFlipType.Rotate90FlipNone);
                }

                // Проверка на центральную точну, если ее нет то это не маркер и далее код не делать
                Marker marker = info.Markers.FirstOrDefault(m => m.Position == MarkerPosition.Center);

                if (marker == null)
                {
                    return;
                }

                Color[,] colors = new Color[10, 10];

                int x = (int)Math.Floor(marker.X * bitmap.HorizontalResolution / inch) - (colors.GetLength(0) / 2);
                int y = (int)Math.Floor(marker.Y * bitmap.VerticalResolution / inch) - (colors.GetLength(1) / 2);

                for (int i = 0; i < colors.GetLength(0); i++)
                {
                    for (int j = 0; j < colors.GetLength(1); j++)
                    {
                        colors[i, j] = bitmap.GetPixel(x + j, y + i);
                    }
                }

                int count = 0;

                foreach (Color color in colors)
                {
                    if (color.Name == "ff000000")
                    {
                        count++;
                    }
                }

                drawing.IsMarker = count > colors.Length * 0.8;
            }
        }
Exemple #54
0
        private void button1_Click(object sender, EventArgs e)
        {
            Color[,] color  = processor.GetImageMatrix((Bitmap)processor.image);
            Color[,] resize = new Color[color.GetLength(0) + 200, color.GetLength(1) + 200];
            int x_ratio = resize.GetLength(0) / color.GetLength(0);
            int y_ratio = resize.GetLength(1) / color.GetLength(1);
            int px, py;

            for (int i = 0, orx = 0; i < resize.GetLength(0) && orx < color.GetLength(0); i += x_ratio, orx++)
            {
                for (int j = 0, ory = 0; j < resize.GetLength(1) && ory < color.GetLength(1); j += y_ratio, ory++)
                {
                    resize[i, j] = color[orx, ory];
                }
            }
            drawMatrix(resize);
        }
Exemple #55
0
        private void HandleKeyboardCustomEffect(byte[] message)
        {
            var keyboardEffect = new uint[6, 22];

            MultiDemFromBytes(keyboardEffect, message);

            var colors = new Color[6, 22];

            for (var x = 0; x < colors.GetLength(0); x++)
            {
                for (var y = 0; y < colors.GetLength(1); y++)
                {
                    colors[x, y] = ColorFromUint(keyboardEffect[x, y]);
                }
            }
            OnKeyboardColorUpdate?.Invoke(colors);
            CheckForChampionUpdate(colors);
        }
Exemple #56
0
        private void UpdateTextureSize()
        {
            var currentTexture = (Color[, ])Stencil.Clone();
            var newTexture     = new Color[TextureWidth, TextureHeight];

            for (int x = 0; x < TextureWidth; x++)
            {
                for (int y = 0; y < TextureHeight; y++)
                {
                    newTexture[x, y] = Color.Transparent;
                }
            }

            var largerX = currentTexture.GetLength(0) > newTexture.GetLength(0) ? currentTexture.GetLength(0) : newTexture.GetLength(0);
            var largerY = currentTexture.GetLength(1) > newTexture.GetLength(1) ? currentTexture.GetLength(1) : newTexture.GetLength(1);

            for (int i = 0; i < largerX; i++)
            {
                for (int j = 0; j < largerY; j++)
                {
                    if (currentTexture.GetLength(0) <= i)
                    {
                        continue;
                    }
                    if (currentTexture.GetLength(1) <= j)
                    {
                        continue;
                    }
                    if (newTexture.GetLength(0) <= i)
                    {
                        continue;
                    }
                    if (newTexture.GetLength(1) <= j)
                    {
                        continue;
                    }
                    newTexture[i, j] = currentTexture[i, j];
                }
            }

            Stencil = newTexture;

            UpdateStencil();
        }
Exemple #57
0
        public Color[] GenerateWalkableTexture()
        {
            Color[,] rawTexture = new Color[(_desiredScreenWidth / DrawScale), (_desiredScreenheight / DrawScale)];

            for (int y = 0; y < _tilemap.Grid.GetLength(1); y++)
            {
                for (int x = 0; x < _tilemap.Grid.GetLength(0); x++)
                {
                    Color drawColor;
                    if (_tilemap.Grid[x, y])
                    {
                        drawColor = Color.White * 0;
                    }
                    else
                    {
                        drawColor = Color.Lime * 0.5f;
                    }

                    for (int pixelX = 0; pixelX < 16; pixelX++)
                    {
                        for (int pixelY = 0; pixelY < 16; pixelY++)
                        {
                            rawTexture[(x * 16) + pixelX, (y * 16) + pixelY] = drawColor;
                        }
                    }
                }
            }

            Color[] output = new Color[(_desiredScreenWidth / DrawScale) * (_desiredScreenheight / DrawScale)];

            int i = 0;

            for (int y = 0; y < rawTexture.GetLength(1); y++)
            {
                for (int x = 0; x < rawTexture.GetLength(0); x++)
                {
                    output[i] = rawTexture[x, y];
                    i++;
                }
            }

            return(output);
        }
Exemple #58
0
        private Color[,] ShearX(Color[,] colors, float angle)
        {
            //return colors;
            float alpha = -(float)Math.Tan(angle / 2f);
            int   yl    = colors.GetLength(1);
            int   xd    = (int)(((float)colors.GetLength(1) - 1f) * alpha);
            int   xl    = Math.Abs(xd) + colors.GetLength(0);

            Color[,] newColors = new Color[xl, yl];

            for (int i = 0; i < newColors.GetLength(0); i++)
            {
                for (int j = 0; j < newColors.GetLength(1); j++)
                {
                    newColors[i, j] = Color.Transparent;
                }
            }

            for (int i = 0; i < colors.GetLength(0); i++)
            {
                for (int j = 0; j < colors.GetLength(1); j++)
                {
                    if (colors[i, j] == Color.Transparent)
                    {
                        continue;
                    }
                    if (i != 0)
                    {
                        float f = frac(alpha * (float)j);
                        newColors[i + (int)(j * alpha), j] = Color.FromArgb(
                            (int)((1 - f) * colors[i, j].R + f * colors[i - 1, j].R),
                            (int)((1 - f) * colors[i, j].G + f * colors[i - 1, j].G),
                            (int)((1 - f) * colors[i, j].B + f * colors[i - 1, j].B)
                            );
                    }
                    else
                    {
                        newColors[i + (int)(j * alpha), j] = colors[i, j];
                    }
                }
            }
            return(newColors);
        }
Exemple #59
0
        public static Color[] ToColorsA(RayCastManager rtc, int bits)
        {
            int dgx = rtc.getSizeX();
            int dgy = rtc.getSizeY();
            int dgz = rtc.getSizeZ();

            Color[,,] colors = new Color[dgx, (dgy / bits), dgz];
            for (int gx = 0; gx < dgx; gx++)
            {
                for (int gy = 0; gy < dgy / bits; gy++)
                {
                    for (int gz = 0; gz < dgz; gz++)
                    {
                        int iv = 0;
                        for (int n = 0; n < bits; n++)
                        {
                            iv |= rtc.testBlock(gx, gy * bits + n, gz, RayCastBlockType.Opacity) ? (1 << n) : 0;
                        }
                        float a = iv / (float)((1 << bits) - 1);
                        colors[gx, gy, gz] = new Color(0, 0, 0, a);
                    }
                }
            }


            int sizeX = colors.GetLength(0);
            int sizeY = colors.GetLength(1);
            int sizeZ = colors.GetLength(2);

            Color[] rlt = new Color[sizeX * sizeY * sizeZ];
            for (int x = 0; x < sizeX; x++)
            {
                for (int y = 0; y < sizeY; y++)
                {
                    for (int z = 0; z < sizeZ; z++)
                    {
                        rlt[z * sizeY * sizeX + y * sizeX + x] = colors[x, y, z];
                    }
                }
            }
            return(rlt);
        }
Exemple #60
0
        private Color[,] ShearY(Color[,] colors, float angle)
        {
            float beta = (float)Math.Sin(angle);
            int   xl   = colors.GetLength(0);
            int   yd   = Math.Abs((int)(((float)colors.GetLength(0) - 1f) * beta));
            int   yl   = yd + colors.GetLength(1);

            Color[,] newColors = new Color[xl, yl];

            for (int i = 0; i < newColors.GetLength(0); i++)
            {
                for (int j = 0; j < newColors.GetLength(1); j++)
                {
                    newColors[i, j] = Color.Transparent;
                }
            }

            for (int i = 0; i < colors.GetLength(0); i++)
            {
                float f = Math.Abs(frac(beta * (float)i));
                for (int j = 0; j < colors.GetLength(1); j++)
                {
                    if (colors[i, j] == Color.Transparent)
                    {
                        continue;
                    }
                    if (j != 0)
                    {
                        newColors[i, j + (int)(i * beta) + yd] = Color.FromArgb(
                            (int)((1 - f) * colors[i, j].R + f * colors[i, j - 1].R),
                            (int)((1 - f) * colors[i, j].G + f * colors[i, j - 1].G),
                            (int)((1 - f) * colors[i, j].B + f * colors[i, j - 1].B)
                            );
                    }
                    else
                    {
                        newColors[i, j + (int)(i * beta) + yd] = colors[i, j];
                    }
                }
            }
            return(newColors);
        }