/*
 回転させた座標位置を得る
*/

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <eggx.h>

/*
 rotateX , rotateY
 座標 (posX, posY) を、(orgX, orgY) を中心に angle 度だけ回転させた
 座標位置の X, Y 成分を得る
*/
double rotateX(double orgX, double orgY, double posX, double posY, double angle)
{
  double x, y; // (orgX, orgY) を原点とした場合の (posX, posY) 座標位置 
  double rotX; // (x, y) を angle 度回転させた座標位置（の X 成分）
  x = posX - orgX;
  y = posY - orgY;
  rotX = x * cos(angle) - y * sin(angle);
  return rotX + orgX; // 戻り値には orgX の値を加えておく
}

double rotateY(double orgX, double orgY, double posX, double posY, double angle)
{
  double x, y; // (orgX, orgY) を原点とした場合の (posX, posY) 座標位置 
  double rotY; // (x, y) を angle 度回転させた座標位置（の Y 成分）
  x = posX - orgX;
  y = posY - orgY;
  rotY = x * sin(angle) + y * cos(angle);
  return rotY + orgY; // 戻り値には orgX の値を加えておく
}

/*
 傾いた楕円を描く
*/
int main()
{
  int win;
  double th; // 角度
  double x, y, newX, newY; // 最初の座標位置と、回転させた後の座標位置

  win=gopen(400,400);  
  winname(win, "rotation");

  // 座標軸を描く
  newpen(win, 1); 
  drawline(win, 0.0, 200.0, 400.0, 200.0); 
  drawline(win, 200.0, 0.0, 200.0, 400.0); 
  
  // 適当な精度（0.2 radian ごと）に打点して平たい楕円を描く
  for(th=0.0; th<2.0*M_PI; th+=0.02) { 
    x = 250.0 + cos(th)*100.0; 
    y = 150.0 + sin(th)*50.0;
    newpen(win, 2);  // 赤色に設定
    pset(win, x, y); // 正常位置に打点

    /* (200,200) を中心に、(x,y) を回転させた打点位置を計算*/
    newX = rotateX(200.0, 200.0, x, y, M_PI / 6.0); // まず 1/6π回転
    newY = rotateY(200.0, 200.0, x, y, M_PI / 6.0);
    newpen(win, 3);  // 緑色に設定
    pset(win, newX, newY); // 回転後の位置に打点

    newX = rotateX(200.0, 200.0, x, y, M_PI / 3.0); // 次に 1/3π回転
    newY = rotateY(200.0, 200.0, x, y, M_PI / 3.0);
    newpen(win, 4);  // 青色に設定
    pset(win, newX, newY); // 回転後の位置に打点
  }

  ggetch();
  gclose(win); 
  return 0;
}