Image_Turtle

Description

Simple fractalSimple fractal

This implements the Lindenmayer system in PHP. This is a system to draw images based on simple grammars. Most used for fractals or to simulate natural growth of plants.

You perhaps wonder because of the name of this class, but the cursor which draws the objects is often called "turtle".

A simple usage example for this tree:

Simple tree with Lindenmayer systemSimple tree with Lindenmayer system
<?php require_once 'Image/Turtle/Memory.php'; $turtle = new Image_Turtle_Memory(array(310, 590), -90); // Configure turtle $turtle->step = 130; // Width of step forward $turtle->a = 25; // Angle $turtle->s = .25; // Buckling // Create and execute the "programm" $turtle->addRule('w', 'FFF[+F+F+F][-F+F+F+F+F]'); $turtle->addRule('F', 'FFF[+F+F+F][-F+F+F+F+F]'); $turtle->setStartRule('w'); $turtle->process(3); // Render output $turtle->render(400, 600, 'tree.png');

First you initialise and configure your turtle. In this case we use Image_Turtle_Memory, because we want to use a language, in which we can use [ and ] to push and pop the current state of our turtle to a stack.

Then we define some simple production rules, in which the alpha characters are variables (nonterminal symbols), and the other symbols are terminal symbols. Their common meanings:

+ turn left (You can define the angle, as you can see above) - turn right | turn back [ push state to stack ] pop state from stack

As you might know from grammars, you can use as much variables as you want in your grammar. Currently they are limited to single characters. If you use an uppercase letter the turtle will step forward and draw a line, on a lowercase letter it will only do a step forward.

As always, you need to define the rule you want to start with, and in case of Lindenmayer systems you define a recursion depth. The last thing is to call the renderer and you are done. I added four examples to the package, have fun playing around with them.

You perhaps want to extend the language, you can use within your grammar. Just extend the existing classes and add symbols with you own functions. Possible extensions could be changing the color of your turtle or let it run in threedimensional space.

Releases

Files