class Cylinder
{
float topRadius;
float bottomRadius;
float tall;
int sides = 16;
PVector position;
PVector rotation;
Cylinder(float _topRadius, float _bottomRadius, float _tall)
{
topRadius = _topRadius;
bottomRadius = _bottomRadius;
tall = _tall;
}
void render()
{
float angle = 0;
float angleIncrement = TWO_PI / sides;
pushMatrix();
rotateX(PI);
translate(0, -tall, 0);
noStroke();
beginShape(QUAD_STRIP);
for (int i = 0; i < sides + 1; ++i) {
vertex(topRadius*cos(angle), 0, topRadius*sin(angle));
vertex(bottomRadius*cos(angle), tall, bottomRadius*sin(angle));
angle += angleIncrement;
}
endShape();
popMatrix();
}
}
float rotationX, rotationY, velocityX, velocityY = 0;
ArrayList trees = new ArrayList();
void setup()
{
size(800, 600, P3D);
for (int i = 0; i < 1; i++)
{
trees.add( new Tree(random(130, 190), int( random(3,7)), new PVector()) );
}
}
void draw()
{
background(242);
lights();
rotationX += velocityX;
rotationY += velocityY;
velocityX *= 0.95;
velocityY *= 0.95;
//smooth();
pushMatrix();
translate(width/2, 500, -260);
rotateX(radians(-TWO_PI-rotationX));
rotateY(radians(-rotationY));
for (int i = 0; i < trees.size(); i++) {
Tree tree = (Tree) trees.get(i);
tree.drawTree();
}
popMatrix();
if(mousePressed){
velocityX += (mouseY-pmouseY) * 0.05;
velocityY -= (mouseX-pmouseX) * 0.05;
}
}
void keyPressed()
{
switch(key) {
// case 's':
// saveFrame();
// break;
case 'r':
trees.clear();
trees.add( new Tree(random(130, 190), int( random(3,7)), new PVector()) );
break;
}
}
class Tree
{
float treeSize;
float maxLevel;
float rotationX, rotationZ;
PVector initPos;
Cylinder c;
ArrayList rotX = new ArrayList();
ArrayList rotZ = new ArrayList();
Tree(float _treeSize, float _maxLevel, PVector _initPos)
{
treeSize = _treeSize;
maxLevel = _maxLevel;
initPos = _initPos;
for (int i = 0; i < maxLevel; i++){
float rX = random(-50, 50);
float rZ = random(-50, 50);
rotX.add(rX);
rotZ.add(rZ);
}
}
void drawTree()
{
pushMatrix();
translate(initPos.x, initPos.y, initPos.z);
drawBranch(1);
popMatrix();
}
void drawBranch(int level)
{
if (level > maxLevel) return;
fill(lerpColor(#8b4513,#009C22,level/maxLevel));
float branchSize = -treeSize * pow(0.80, level);
c = new Cylinder(treeSize/4.10 * pow(0.4, level), treeSize/1.60 * pow(0.4, level), branchSize);
c.render();
translate(0,branchSize,0);
for(int i = 0; i < maxLevel; i++){
rotationX = (Float) rotX.get(i);
rotationZ = (Float) rotZ.get(i);
pushMatrix();
rotateX(radians(rotationX));
rotateZ(radians(rotationZ));
drawBranch(level + 1);
popMatrix();
}
}
}