/* * ----------------------------------------------------- * CS2S03/SE2S03, October 2011 * Assignment 4, Question 2 * File: PE0615.cpp * ----------------------------------------------------- * This program draws a stylized representation * of a tree by using recursive decomposition. * ----------------------------------------------------- */ #include #include #include "simpio.h" #include "graphics.h" #include "genlib.h" #include "random.h" using namespace std; /* Constants Declaration*/ const double PI = 3.1415926535; const double RATIO = 0.8; const double ANGLE = 45; // angle between two neighboring branches const int MAX_LEVEL = 15; // max level of recursion const int MIN_LEVEL = 3; // min level of recursion /* Private function prototype */ void DrawTree(double x, double y, double theta, double len, int order); /* Main program */ int main() { Randomize(); InitGraphics(); cout << "Program to draw a tree" << endl; // root position double x0 = GetWindowWidth() / 2; double y0 = 0.2; // trunk length double trunkLen = GetWindowHeight() * (1 - RATIO); DrawTree(x0, y0, 90, trunkLen, 0); return 0; } /* * Function: DrawTree * Usage: DrawTree(x, y, theta, len, order); * --------------------------------------------------------------------------------- * * The function draws a tree at root position (x, y) with trunk length *len* at the * angle *theta* (degrees) with the horizontal line. * * The decision to branch is made randomly at each step of the process, so the tree is * asymmetric, like trees in the nature. It branches at least MIN_LEVEL times and at * most MAX_LEVEL times. * --------------------------------------------------------------------------------- */ void DrawTree(double x, double y, double theta, double len, int order) { // draw the trunk MovePen(x, y); double radian = (theta / 180) * PI; double dx = len * cos(radian); double dy = len * sin(radian); DrawLine(dx, dy); if (order > RandomInteger(MIN_LEVEL, MAX_LEVEL)) return; // trunk length for subtrees double subLen = len * RATIO; // draw two subtrees at the top the trunk DrawTree(x + dx, y + dy, theta + ANGLE / 2.0, subLen, order + 1); DrawTree(x + dx, y + dy, theta - ANGLE / 2.0, subLen, order + 1); }