OpenGL 레포트였던 밤하늘에 떠있는 달과 별을 그려보았다.
별의 좌표는 랜덤으로 주어지고, 달은 원의 좌표를 계산하여 그렸다.
지형은 일직선을 재귀적으로 쪼개서 각도를 변경하여 그렸다.
void setup(){
size(300, 240, P2D);
background(0);
noLoop();
noStroke();
}
void draw(){
drawSky();
drawStars(50);
drawEclipse();
drawMountain(height / 1.5);
}
void drawSky(){
// gradient
color night = color(0, 0, 125);
color glow = color(255, 102, 0);
for(int i = 0; i < height; i++){
float rate = map(i, 0, height, 0, 1);
color c = lerpColor(night, glow, rate);
stroke(c);
line(0, i, width, i);
}
}
void drawStars(int num){
stroke(255);
for(int i = 0; i < num; i++){
int x = random(width);
int y = random(height / 2);
point(x, y);
}
}
void drawEclipse(){
noStroke();
color yellow = color(255, 255, 0);
fill(yellow);
int cx = width / 2;
int cy = width / 4;
int r = 30;
beginShape();
for(int i = -45; i < 135; i++){
int x = cx + r * cos(radians(i));
int y = cy + r * sin(radians(i));
vertex(x, y);
}
for(int i = 135; i > -45; i--){
int x = cx - 10 + r * cos(radians(i));
int y = cy - 10 + r * sin(radians(i));
vertex(x, y);
}
endShape(CLOSE);
}
void drawMountain(int tall){
beginShape();
vertex(0, height);
vertex(0, tall);
breakLine(0, tall, width, tall);
vertex(width, tall);
vertex(width, height);
endShape(CLOSE);
}
void breakLine(int x0, int y0, int x1, int y1){
float dist = sqrt(pow(x1 - x0, 2) + pow(y1 - y0, 2));
if(dist < 30){
return;
}
// mid point
int cx = x0 + (x1 - x0) / 2;
int cy = y0 + (y1 - y0) / 2;
int x2 = cx + (dist / 8) * cos(QUARTER_PI * random(8));
int y2 = cy + (dist / 8) * sin(QUARTER_PI * random(8));
breakLine(x0, y0, x2, y2);
vertex(x2, y2);
breakLine(x2, y2, x1, y1);
}