Coding trees


I started fiddling around with drawing trees with code. I have something very basic but it looks like a good start.
I start out by placing a point on screen and giving it a base angle to grow towards using a random offset from a given angle. I then set a random growth amount (radius) and come up with my second point, to which i stretch a line. I then recursively move to the next point using the current angle as the new base - and repeat the process.
This alone gives you a nice stalk, but not yet a tree. A tree needs branches. From the second point onwards i randomly pick a number between one and two and call the same recursive function in order to create my branches. Each branch is simply a new point, sprouted from its "parent's" position and angle, with a random offset.
To prevent my tree from growing forever I determine a global growth value from which i subtract with the creation of each new branch. When the growth values reaches 0, the recursive function stops and no new branches are created.
By this point I've ended up with a "tree" made of a scribbly black line. This is not good enough, since we need to differentiate the trunk from the tip branches via girth.
To do this we need to be able to determine that the tip branches are indeed slim, and work backwards to determine the required girth of the trunk.
Each created point in space holds a reference to its parent, allowing us to count backwards from each tip of the tree back to the original trunk node. If we mark each tip as size zero and assign an incrementing value to each parent point, we'll figure out how far it is from the farthest tip to the trunk and therefore - how "big" it is. For instance, if there are 20 points from the farthest tip back to the trunk, then we can now determine the scale of each point on the route, 20 (the trunk )being 1 and 0 (the tip) being 0.
Using this new data we move on to draw the actual tree. First we draw a circle around each point, giving it a radius multiplied by our newly found scale for each node.
We then stretch lines from set points on the circle's circumference to the corresponding points on the next node. We repeat this process for all nodes and voilà - a tree.
Drawing With code can be a very interesting experience. The randomness of the values provides very different looking trees. You can of course play with the number of branches, size and angle spread getting completely wacky results.

תגובות

פוסטים פופולריים מהבלוג הזה

Thoughts on HTML5, a Flash Developers hopeless rant

Pseudo 3d Isometric view

Veroni Noise