Showing posts with label Fractal. Show all posts
Showing posts with label Fractal. Show all posts

Saturday, August 4, 2012

C# Tree fractal

NOTE: I UPDATED ALL DOWNLOAD LINK 

Hello again!
Remember i did a javascript version of the Tree Fractal(with the help of rosettacode)
So iv'e built another version in C# 








So here is the code: 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TreeFractal
{
    public partial class Form1 : Form
    {
        static public Pen p = new Pen(Color.Black, 1);
        static public Graphics g;
        static public double deg_2_rad = Math.PI / 180.0; 
        static public float globalH;
        static public float globalW;
        static readonly object _locky = new object();

        public Form1()
        {
            InitializeComponent();
        }


        private void drawTree(float x1, float y1, double angle, int depth,  double angle1)
        {
            try
            {
                if (depth != 0)
                {

                    float x2 = (float)(x1 + (Math.Cos(angle * deg_2_rad) * depth * 10.0));
                    float y2 = (float)(y1 + (Math.Sin(angle * deg_2_rad) * depth * 10.0));
                    lock (_locky)
                    {
                        this.Update();
                        p.Color = Color.FromArgb((depth * 255) % 16 * 14, (depth * 255) % 16 * 14, (depth * 255) % 128 * 2);
                        g.DrawLine(p, x1, y1, x2, y2);
                    }
                   
                    drawTree(x2, y2, angle - angle1, depth - 1, angle1);
                    drawTree(x2, y2, angle + angle1, depth - 1, angle1);
                    
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        
        private void TreeCanvasLimits(float x1,float y1, double angle,int depth,double angle1)
        {
             if (depth != 0){
              float x2 = (float)(x1 - (Math.Cos(angle * deg_2_rad) * depth * 10.0));
              float y2 = (float)(y1 - (Math.Sin(angle * deg_2_rad) * depth * 10.0));
              if (globalW > x2)
              {
                  globalW = x2;
              }
              if(globalH < y2)
              {
                  globalH = y2;
              }
              TreeCanvasLimits(x2, y2, angle - angle1, depth - 1,angle1);
              TreeCanvasLimits(x2, y2, angle + angle1, depth - 1,angle1);
             }
        }
        private void btnCreate_Click(object sender, EventArgs e)
        {
            g = this.CreateGraphics();
            
            try
            {
                //globalH = 0;
                //globalW = 0;
                //TreeCanvasLimits(0, 0, -90.0, int.Parse(txtDep.Text), double.Parse(txtAngle.Text));
                //this.Size = new Size((int)((globalW * (-2)) + 40), (int)((globalH + 60)));
                g.Clear(Color.White);
                drawTree((this.Width ) / 2, (this.Height - 150), -90.0, int.Parse(txtDep.Text), double.Parse(txtAngle.Text));
            }
            catch(Exception exx)
            {
                MessageBox.Show(exx.ToString());
            }
        }

        private void btnLoop_Click(object sender, EventArgs e)
        {
            try
            {
                g = this.CreateGraphics();
                g.Clear(Color.White);
                for (int i = 0; i < 361; i++)
                {
                    //g.Clear(Color.White);
                    //p.Color = Color.FromArgb((int)(i/4),(int)(i/3), (int)(i/2));
                    //MessageBox.Show("before " + i.ToString());
                    this.SuspendLayout();
                    drawTree((this.Width) / 2, (this.Height - 150), -90.0, 10, (double)i);
                    //System.Threading.Thread.Sleep(100);
                    this.ResumeLayout();
                    Application.DoEvents();
                    //MessageBox.Show("after " + i.ToString());
                    this.Update();
                }
                MessageBox.Show("Done");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
            this.Update();
        }
    }
}


and here is a download link
Download The Project (rar file)

Saturday, July 28, 2012

JavaScript Mandelbrot set Fractal

Hello Everyone!
To expand my "Build Fractals" Corner I've Taken from RosettaCode the code for the Mandelbrot set fractal.

I know it seems like I'm just copying others code, but I'll Post my original code soon.
So here is the link http://rosettacode.org/wiki/Mandelbrot_set

Iv'e taken the code from there, and i claim no rights on this code or whatsoever.
(To zoom change min and max!)



Mandelbrot set
    
  
 
  
    

Mandelbrot set

xmin = xmax =
ymin = ymax =
iterations =
This page needs a browser with canvas support.
Mandelbrot set

Mandelbrot set

xmin = xmax =
ymin = ymax =
iterations =
This page needs a browser with canvas support.

Thursday, July 19, 2012

JavaScript Tree Fractal

Hello Everyone! Today we are going to discuss one of the most simple and beautiful fractals there is, the Tree Fractal!
Algorithm (very simple one):
1. Draw a line
2. From the end of that line draw another two lines, that are split by an angle
3. Repeat with shorter lines, but with the same angle
 Now, I've taken a code from http://rosettacode.org/wiki/Fractal_tree , and made some changes in it so you can have the opportunity to create your own tree fractal right here in the site,
So Here Is The JavaScript Code:


Just enter the parameters(angle and depth) and it will create you the tree(credit for rosettacode):
BEWARE - to much depth will get your browser stuck!
Angle: Depth:            
 

Thursday, March 22, 2012

C# Mandelbrot set Fractal

Welcome back!

Today I'm going to show you how to build a program that does this:


















(image from Wikipedia)

But What is this?
This is a fractal based on the Mandelbrot Set. I don't really know anything on the Mandelbrot Set except what i read from Wikipedia, so here is a link on the Mandelbrot Set - Look at the "for programmers" section, this is what i looked at.

So How we Program This?
Ok, From what I understood from Wikipedia the fractal we are trying to represent is based on the following formula:





when c is a complex number.
(info from Wikipedia)

Which means we need to programmatically consider the real and imaginary values of x and y.
As far as i understood, we are checking if the x and y values that we put in the formula above is not going above infinity, if they do they are not in the set.

So the whole program I built is based on the pseudocode on Wiki.
I added an extra thing that i found on the web, to make it more interesting I'm taking the number of times the loop went for every pixel and if it's not the max value(not in the set) i'm using the following code to paint it:

You can play with the colors if you change this code.

Code Explanation:
Ok, so what I'm doing in my code is as follows:
1. I define a bitmap that is representing the real axis and imaginary axis, which means that the middle of the bitmap is actually the (0,0) point of the grid, and as written in Wiki "for programmers" section i define the left edge as -2, the right edge as 2, the upper edge as 2 and the down edge as -2.
now we defined a grid.

2. I'm running on every pixel on the bitmap, calculating it's x and y value and then starting the loop that checks if it's in the Mandelbrot Set.

3.Calculating and printing the color of the pixel and then starting again with the next pixel.

The Program Output's this:


Now I added a zooming function, to zoom in you just click on the bitmap.
How Does It Work?
I just define new borders to the bitmap, something less than two.
So If you zoom in you can get quite astonishing pictures, as so:



Now you have to remember that this program isn't accurate!
Why?
The program relies on "double" type numbers, that has limited accuracy, so the more zoomed in you get The more it is not accurate (at first it's accurate but after zooming in it won't be).

I added another couple of things:
Save Button - saves the current bitmap image to desktop.
Reset Button - to start from the beginning.

So here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace Fractals
{
    public partial class Form1 : Form
    {
        static double currentmaxr = 0;
        static double currentminr = 0;
        static double currentmaxi = 0;
        static double currentmini = 0;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            Bitmap img = MandelbrotSet(pictureBox1, 2, -2, 2, -2);
            pictureBox1.Image = img;
        }
        static Bitmap MandelbrotSet(PictureBox pictureBox1, double maxr, double minr, double maxi, double mini)
        {
            currentmaxr = maxr;
            currentmaxi = maxi;
            currentminr = minr;
            currentmini = mini;
            Bitmap img = new Bitmap(pictureBox1.Width, pictureBox1.Height);
            double zx = 0;
            double zy = 0;
            double cx = 0;
            double cy = 0;
            double xjump = ((maxr - minr) / Convert.ToDouble(img.Width));
            double yjump = ((maxi - mini) / Convert.ToDouble(img.Height));
            double tempzx = 0;
            int loopmax = 1000;
            int loopgo = 0;
            for (int x = 0; x < img.Width; x++)
            {
                cx = (xjump * x) - Math.Abs(minr);
                for (int y = 0; y < img.Height; y++)
                {
                    zx = 0;
                    zy = 0;
                    cy = (yjump * y) - Math.Abs(mini);
                    loopgo = 0;
                    while (zx * zx + zy * zy <= 4 && loopgo < loopmax)
                    {
                        loopgo++;
                        tempzx = zx;
                        zx = (zx * zx) - (zy * zy) + cx;
                        zy = (2 * tempzx * zy) + cy;
                    }
                    if (loopgo != loopmax)
                        img.SetPixel(x, y, Color.FromArgb(loopgo % 128 * 2, loopgo % 32 * 7, loopgo % 16 * 14));
                    else
                        img.SetPixel(x, y, Color.Black);

                }
            }
            return img;

        }


        private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
        {
            int ex = e.X;
            int ey = e.Y;
            double currentxjump = ((currentmaxr - currentminr) / Convert.ToDouble(pictureBox1.Width));
            double currentyjump = ((currentmaxi  - currentmini) / Convert.ToDouble(pictureBox1.Height));

            int zoomx = pictureBox1.Width/5 ;
            int zoomy = pictureBox1.Height/5;
            Bitmap img = MandelbrotSet(pictureBox1,((ex +zoomx) * currentxjump) -Math.Abs(currentminr) , ((ex-zoomx) * currentxjump) -Math.Abs(currentminr) , ((ey+zoomy ) * currentyjump) - Math.Abs(currentmini) , ((ey- zoomy) * currentyjump) - Math.Abs(currentmini));
            pictureBox1.Image.Dispose();
            pictureBox1.Image = img;
        }

        private void button1_Click(object sender, EventArgs e)
        {
           Bitmap img = MandelbrotSet(pictureBox1, 2, -2, 2, -2);
            pictureBox1.Image.Dispose();
            pictureBox1.Image = img;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            
            string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            //string folderf = @"\Fractals";
            string filename = @"\Fractals";
            string filetype = @".jpeg";
            int mone=0;
            
            while (File.Exists(path + filename + mone.ToString() + filetype))
            {
                mone++;
            }
           
            pictureBox1.Image.Save(path + filename + mone.ToString() + filetype);
            MessageBox.Show("Saved To Desktop");

            
        }
    }

}





And here is the downloading link:
Download This Project (rar file)

Run without compiling: Go to the project folder -> bin -> debug -> Fractals.exe
Have Fun!
And Remember
Questions = Comments!

C# Sierpinski Triangle

Hello again lads!
Today we are going to program Sierpinski Triangle,

But What is Sierpinski Triangle? 
Sierpinski Triangle is a very nice triangle fractal, the fractal shows a triangle that has 3 triangles inside of it, and inside everyone of these triangles there is another 3 triangles and so on.

Here is a picture of it: 
















(This image is taken from Wikipedia)

Some of you may recognize this shape - it is a very common fractal.
Ok, so if you want to read more about this fractal here is a Wikipedia link

And Now to the Programming:
Ok, I  found an algorithm that represents this fractal, and it goes as follows:

1. Write three dots that represent the vertexes of the biggest triangle (the first triangle).
2. Start with a random point that is in the triangle borders.
3. Now choose a random point of the three vertexes you defined earlier, and calculate the distance between the current point and the vertex you choose, and print a point at the half of this distance.
Now use the point you printed and Do step 3 again and again, until you get the requested result.

I added another thing that makes it a bit more interesting. I painted the first vertexes with 3 different colors, red green and blue, and every time I'm printing a point I'm printing it with the color of the vertex that is chosen randomly.

This Program outputs this:


Now you need to remember that this algorithm is not 100% accurate!

Ok so here is the Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SerpinskiTri
{
    class Program
    {
        static void DotPrint(int x, int y, ConsoleColor col)
        {
            Console.ForegroundColor = col;
            Console.CursorLeft = x;
            Console.CursorTop = y;
            Console.Write(".");
        }
        static void Main(string[] args)
        {
            Console.CursorVisible = false;
            Console.SetWindowSize(80,40);
            int times = 0;
            Random rnd = new Random();
            Console.WriteLine();
            Console.Write("Enter Number of Times:");
            times = int.Parse(Console.ReadLine());
            int ChangeX = 35;
            int ChangeY = 20;
            int random = 0;
            for (int i = 0; i < times; i++)
            {
                random = rnd.Next(0,3);
                switch (random)
                {
                    case 0: //red dot
                        ChangeX = (ChangeX + 35) / 2; // the 35 is the x value of the red dot
                        ChangeY = (ChangeY + 1) / 2;
                        DotPrint(ChangeX, ChangeY, ConsoleColor.Red);
                        break;
                    case 1: // blue dot
                        ChangeX = (ChangeX + 1) / 2;
                        ChangeY = (ChangeY + 35) / 2;
                        DotPrint(ChangeX, ChangeY, ConsoleColor.Blue);
                        break;
                    case 2: // green dot
                        ChangeX = (ChangeX + 70) / 2;
                        ChangeY = (ChangeY + 35) / 2;
                        DotPrint(ChangeX, ChangeY, ConsoleColor.Green);
                        break;
                }
            }
            Console.ReadKey();
        }
    }
}


You can also download this project:
Download This Project (rar file)

Run Without Compiling: go to the project folder ->bin -> debug -> SerpinskiTri.exe

Questions = Comments!
I'll try to answer Asap.