Simple diffusion limited aggregation image PHP

Diffusion-Limited Aggregation creates great looking fractals, I made a fast(but not the fastest) Diffusion-Limited Aggregation simulator. You define how many molecules will be released and the size of the board. A more accurate Brownian motion system will make the image look better, but it is going to be a lot slower.
Don't assign numbers larger than 700 for step, it is going to consume a huge amount of time to generate. A size 100 step 700 image cost around 60 seconds.
A faster version can be implemented by change the random movement of molecules into linear movement.
Diffusion-Limited Aggregation Simulation result

	set_time_limit(0);
	//Very fast Diffusion-Limited Aggregation
 
 
$s = 100;
$step = 700;
$area = 2;//smaller = faster, larger = more accurate(random)
 
$image = imagecreate($s,$s);
imagecolorallocate($image,255,255,255);
$color = imagecolorallocate($image,0,0,0);
$s2 = $s/2;
$grid[$s2][$s2] = 1;
imagesetpixel($image,$s2,$s2,$color);
 
while($i<$step){
	//calculate releasing area
	$n = max($max_x - $min_x, $max_y - $min_y) + $area;
	$s2mn = $s2-$n;
	$s2an = $s2+$n;
	//release a molecule
	do{
		$x = rand($s2mn,$s2an);
		$y = rand($s2mn,$s2an);
	}while($grid[$x][$y]);
	//move the molecule randomly
while(!($grid[$x-1][$y-1]+$grid[$x-1][$y]+$grid[$x-1][$y+1]+
$grid[$x][$y-1]+$grid[$x][$y+1]+$grid[$x+1][$y-1]+
$grid[$x+1][$y]+$grid[$x+1][$y+1])){
		$x += rand(-1,1);
		$y += rand(-1,1);
		if($x<$s2mn||$x>$s2an||$y<$s2mn||$y>$s2an){
			continue 2;
		}
	}
	$grid[$x][$y] = 1;
	if($max_x<$x){
		$max_x = $x;
	}elseif($min_x>$x){
		$min_x = $x;
	}
	if($max_y<$y){
		$max_y = $y;
	}elseif($min_y>$y){
		$min_y = $y;
	}
	imagesetpixel($image,$x,$y,$color);
 
++$i;
}
 
	header("Content-type: image/png");
	imagepng($image);

Post new comment

The content of this field is kept private and will not be shown publicly.
If you have a Gravatar account, used to display your avatar.
  • Allowed HTML tags: <img> <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <span> <fn>
  • Lines and paragraphs break automatically.
  • Textual smileys will be replaced with graphical ones.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. Beside the tag style "<foo>" it is also possible to use "[foo]".
  • Use [fn]...[/fn] (or <fn>...</fn>) to insert automatically numbered footnotes.

More information about formatting options

What is 60 + 18?
To combat spam, please solve the math question above.
Honey Pot that kill bots