Skip to content

Instantly share code, notes, and snippets.

@jacob-g
Created May 14, 2015 20:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jacob-g/2ba376f1329b73379d4b to your computer and use it in GitHub Desktop.
Save jacob-g/2ba376f1329b73379d4b to your computer and use it in GitHub Desktop.
<?php
//sherpinski triangle fractal generator for PHP
//Copyright (C)2015 FutureSight Technologies - all rights reserved, do not copy
$iterations = input('Iterations?');;
$squaresize = input('Size?');
function input($prompt) {
echo $prompt . ' ';
$line = fgets(STDIN);
return (int)strtok($line, "\n");
}
function drawtriangle($vertex1, $vertex2, $vertex3) {
global $image, $black;
imageline($image, $vertex1[0], $vertex1[1], $vertex2[0], $vertex2[1], $black);
imageline($image, $vertex2[0], $vertex2[1], $vertex3[0], $vertex3[1], $black);
imageline($image, $vertex3[0], $vertex3[1], $vertex1[0], $vertex1[1], $black);
}
$image = imagecreate($squaresize, $squaresize * sqrt(3) / 2);
imagecolorallocate($image, 255, 255, 255); //change to adjust background color
$black = imagecolorallocate($image, 0, 0, 0); //change to adjust line color
//draw original triangle
drawtriangle(array(0, $squaresize * sqrt(3) / 2), array($squaresize, $squaresize * sqrt(3) / 2), array($squaresize / 2, 0));
$triangles = array(
0 => array(
array(
array(0, $squaresize * sqrt(3) / 2), array($squaresize, $squaresize * sqrt(3) / 2), array($squaresize / 2, 0)
)
)
);
//draw triangle at midpoints
for ($i = 0; $i < $iterations; $i++) {
$newrow = array();
$triangleset = $triangles[$i];
$iterationstart = microtime();
echo 'Starting iteration ' . ($i + 1);
foreach ($triangleset as $triangle) {
//for each triangle, draw 3 more
$a = $triangle[0];
$c = $triangle[1];
$e = $triangle[2];
$b = array(($triangle[0][0] + $triangle[1][0]) / 2, ($triangle[0][1] + $triangle[1][1]) / 2);
$d = array(($triangle[1][0] + $triangle[2][0]) / 2, ($triangle[1][1] + $triangle[2][1]) / 2);
$f = array(($triangle[2][0] + $triangle[0][0]) / 2, ($triangle[2][1] + $triangle[0][1]) / 2);
drawtriangle($b, $d, $f);
$newrow[] = array($a, $b, $f);
$newrow[] = array($b, $c, $d);
$newrow[] = array($d, $e, $f);
}
$triangles[] = $newrow;
unset($triangles[$i]);
echo ' ... completed (' . ((microtime() - $iterationstart) * 1000) . ' milliseconds)' . "\n";
}
echo 'Saving image (this may take a while)...' . "\n";
imagepng($image, 'out.png');
system('out.png');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment