#include <math.h>
#include <stdio.h>
#include "svg.h"

double startX, startY, width, height;
int cols, rows;

//== 極方程式を描画

// x = r cos(θ) + cx
// y = r sin(θ) + cy
// r/t = 1 + sc sin(stc θ) + cc cos(ctc θ)

// 中心座標 cx cy
// 何倍で表示するか t
// sinの係数 sc
// cosの係数 cc
// sinのθの係数 stc
// cosのθの係数 ctc

// 荒さ (255の約数であることを推奨) d
void polar(double cx, double cy, double t, double sc, double cc, int stc, int ctc, int d) {
int i;
int unit = (0xFF / d) + 1;
int len = 6*unit;
// 点座標
double lx = cx + (1.0 + cc)*t;
double ly = cy;
// 色
int cr = 0xFF;
int cg = 0x00;
int cb = 0x00;

for (i = 1; i <= len; i++) {
  // 極方程式
  double a = i * 2*PI / len;
  double tr = 1.0 + sc*sin(a*stc) + cc*cos(a*ctc);
  double nx = cx + tr*cos(a)*t;
  double ny = cy - tr*sin(a)*t;
  // 色 (RGB)
  stroke(rgb255(cr, cg, cb));
  // 描画
  line(lx, ly, nx, ny);
  // 座標更新
  lx = nx;
  ly = ny;
  // 色更新
  if (i % unit == 0) continue;
  switch (i / unit) {
    case 0: cg += d; break;
    case 1: cr -= d; break;
    case 2: cb += d; break;
    case 3: cg -= d; break;
    case 4: cr += d; break;
    case 5: cb -= d; break;
    }
  }
}

void CardSpec(double sx, double sy, double dx, double dy, int c, int r) {
  startX = sx; startY = sy; width = dx; height = dy;
  cols = c; rows = r;
}

void f10a4_1(void) { CardSpec(14, 11, 91, 55, 2, 5); }
void f10a4_2(void) { CardSpec(18.6, 21.2, 86.4, 50.8, 2, 5); }
void f8a4_5(void)  { CardSpec(8, 10.5, 97, 69, 2, 4); }

void init(void) {
}

void drawFrame(void) {
  strokeWeight(0.1);
  stroke(bw1(0));
  noFill();
  rect(0, 0, width, height);
}

void drawCard(int n, int i, int j, double ratio) {
  int t;
  double d = 0.25;

  double sc = 0.1*n;
  double cc = 0.1 * (rows * cols - n);
  double stc = 5;
  double ctc = 10;
  char buf[150];

  drawFrame();  // for debug, comment out
  noStroke();
  fill(hsb360(ratio*360, 100, 100));
  textFont("MS-Mincho", 8);
  text("讃岐 太郎", 10, 35);

  textFont("Times New Roman", 4);
  fill(hsb360(ratio*360+90, 100, 100));
  sprintf(buf, "r ＝ 1 ＋ %.2f sin(%.2f θ) ＋ %.2f cos(%.2f θ)", sc, stc, cc, ctc);
  text(buf, 5, 60);
  noFill();
  pushMatrix();

  strokeWeight(1);
  polar(width*3/4.0, height/2, 12, sc, cc, stc, ctc, 1);
  strokeWeight(0.1);

  popMatrix();
}

int main(void) {
	int i, j, n=0;
	double x;
	a4Portrait();
	start();
	init();
	f8a4_5();
  x = startX;
	for (i=0; i<cols; i++) {
		double y = startY;
		for (j=0; j<rows; j++, n++) {
			pushMatrix();
			translate(x, y);
			drawCard(n, i, j, (double)n/(cols*rows));
			popMatrix();
			y += height;
		}
		x += width;
	}
	finish();
  return 0;
}

