LoginSignup
7

More than 3 years have passed since last update.

posted at

updated at

「プログラムでシダを描画する」をEmscriptenで描画する

空前のシダ描画ブーム到来!?(^^;)
あなたも得意なプログラミング言語でシダを描画してみよう!

「プログラムでシダを描画する」のこれまでと今後の一覧

久しぶりにC言語使った気がする

ということで、他にやることあんだろーと周囲から白い目で見られることも気にせず、Emscripten版やってみました。

やっぱり、C言語なだけあって、WebRuby版の比ではない速度でした(違

コード

cedar_sdl.cpp
#include <stdio.h>
#include <stdlib.h>
#include <SDL/SDL.h>

#define N 20
#define WIDTH 500
#define HEIGHT 500

SDL_Surface *gScreen = NULL;

double w1x(double x,double y) {
  return 0.836 * x + 0.044 * y;
}

double w1y(double x,double y) {
  return -0.044 * x + 0.836 * y + 0.169;
}

double w2x(double x,double y) {
  return -0.141 * x + 0.302 * y;
}

double w2y(double x,double y) {
  return 0.302 * x + 0.141 * y + 0.127;
}

double w3x(double x,double y) {
  return 0.141 * x - 0.302 * y;
}

double w3y(double x,double y) {
  return 0.302 * x + 0.141 * y + 0.169;
}

double w4x(double x,double y) {
  return 0.0;
}

double w4y(double x,double y) {
  return 0.175337 * y;
}

double getRand() {
  return (double)rand()/RAND_MAX;
}
void cedar(int k, double x, double y) {
if(0<k) {

  //printf("%f\n",getRand());
  cedar(k-1,w1x(x, y), w1y(x, y));
  if(getRand()<0.3) {
    cedar(k - 1, w2x(x, y), w2y(x, y));
  }
  if(getRand()<0.3) {
    cedar(k - 1, w3x(x, y), w3y(x, y));
  }
  if(getRand()<0.3) {
    cedar(k - 1, w4x(x, y), w4y(x, y));
  }

} else {
  // plot
  int xx;
  int yy;

  xx = (int)(x*(WIDTH*0.9)+WIDTH/2);
  yy = (int)(HEIGHT-y*(HEIGHT*0.9));

  *((Uint32*)gScreen->pixels + yy * WIDTH + xx) = SDL_MapRGBA(gScreen->format, 0, 255, 0, 255);
}
}

extern "C" int main(int argc, char** argv) {

  SDL_Init(SDL_INIT_VIDEO);
  gScreen = SDL_SetVideoMode(WIDTH, HEIGHT, 32, SDL_SWSURFACE);

  if (SDL_MUSTLOCK(gScreen)) SDL_LockSurface(gScreen);

  cedar(N,0,0);

  if (SDL_MUSTLOCK(gScreen)) SDL_UnlockSurface(gScreen);
  SDL_Flip(gScreen);

  SDL_Quit();

  return 0;
}

ビルド

emcc cedar_sdl.cpp -o cedar.html
open cedar.html

ネイティブ版

ソースを見れば分かる通り、一瞬で終了するけど。

clang cedar_sdl.cpp `sdl-config --cflags --libs`
./a.out

デモ

関連記事

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
7