/*
 長方形（多角形）を回転させる
*/

#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 の値を加えておく
}

/*
 多角形は fillpoly() を使っている。fillpoly() 関数については別途マニュアル
 参照のこと。
 */

int main()
{
  int win;
  int i;
  double posx[4], posy[4]; // 四角形の頂点位置座標配列
  double newx[4], newy[4]; // 回転させた後の座標位置配列

  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); 
  
  // 適当な長方形の各頂点座標位置を決めて配列に格納
  posx[0]=150.0;    posy[0]=100.0;
  posx[1]=320.0;    posy[1]=100.0;
  posx[2]=320.0;    posy[2]=140.0;
  posx[3]=150.0;    posy[3]=140.0;  

  newpen(win, 2);  // 赤色に設定
  fillpoly(win, posx, posy, 4, 0); // 長方形を描く

  /* (200,200) を中心に、全頂点について回転させた位置を計算して別の配列に格納 */
  for(i=0; i<4; i++) {
    newx[i] = rotateX(200.0, 200.0, posx[i], posy[i], M_PI / 6.0); // まず 1/6π回転
    newy[i] = rotateY(200.0, 200.0, posx[i], posy[i], M_PI / 6.0);
  }
  newpen(win, 3);  // 緑色に設定
  fillpoly(win, newx, newy, 4, 0); // 回転後の長方形を描く

  for(i=0; i<4; i++) {
    newx[i] = rotateX(200.0, 200.0, posx[i], posy[i], M_PI / 3.0); // 次に 1/3π回転
    newy[i] = rotateY(200.0, 200.0, posx[i], posy[i], M_PI / 3.0);
  }
  newpen(win, 4);  // 青色に設定
  fillpoly(win, newx, newy, 4, 0); // 回転後の長方形を描く

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