/*
* The Bezier curve / La courbe de Bezier
*/

import java.lang.*;
import java.awt.*;

class Bezier extends Canvas
{

// Global variables to the class
Point point[];
int i;
int ptSelected = -1;
int cWidth = 14;
Image im = null;

public Bezier()
{

// Creation of control points
point = new Point[4];
for (i=0;i<4;i++)

point[i] = new Point();


// Initialization of control points
point[0].x = 20;
point[0].y = 250;
point[1].x = 20;
point[1].y = 20;
point[2].x = 410;
point[2].y = 20;
point[3].x = 410;
point[3].y = 250;

// Creation and addition of listeners
MouseMotion aMouseMotion = new MouseMotion();
this.addMouseMotionListener(aMouseMotion);
Mouse aMouse = new Mouse();
this.addMouseListener(aMouse);

}

public void paint(Graphics g)
{

// Creation of a buffered image
if (im == null)

im = createImage((this.getSize()).width,(this.getSize()).height);

Graphics img = im.getGraphics();

int c = cWidth/2;

img.setColor(Color.white);
img.fillRect(0,0,(this.getSize()).width,(this.getSize()).height);
img.setColor(Color.black);
img.fillOval(point[0].x-c ,point[0].y-c ,cWidth,cWidth);
img.drawOval(point[0].x-c ,point[0].y-c ,cWidth,cWidth);
img.fillOval(point[1].x-c ,point[1].y-c ,cWidth,cWidth);
img.drawOval(point[1].x-c ,point[1].y-c ,cWidth,cWidth);
img.fillOval(point[2].x-c ,point[2].y-c ,cWidth,cWidth);
img.drawOval(point[2].x-c ,point[2].y-c ,cWidth,cWidth);
img.fillOval(point[3].x-c ,point[3].y-c ,cWidth,cWidth);
img.drawOval(point[3].x-c ,point[3].y-c ,cWidth,cWidth);
img.drawLine(point[0].x ,point[0].y ,point[1].x ,point[1].y);
img.drawLine(point[2].x ,point[2].y ,point[3].x ,point[3].y);

bezier(point,img);

g.drawImage(im,0,0,null);

}

class Mouse extends java.awt.event.MouseAdapter
{

public void mousePressed(java.awt.event.MouseEvent event)
{

ptSelected = -1;
for (i=0;i<4;i++)

{

Rectangle r = new Rectangle(cWidth,cWidth);
r.setLocation(point[i].x-(cWidth/2) ,point[i].y-(cWidth/2));
if (r.contains(event.getX(),event.getY()))

ptSelected = i;

}

}

}

class MouseMotion extends java.awt.event.MouseMotionAdapter
{

public void mouseDragged(java.awt.event.MouseEvent event)
{

if (ptSelected > -1)
{

point[ptSelected].x = event.getX();
point[ptSelected].y = event.getY();

paint(getGraphics());

}

}

}

// The bezier algorithym
public void bezier(Point p[],Graphics g)
{

int x,y,oldx,oldy;
float i;
float t;

// t is between 0 and 1
// so t represent 32 lines in the curve
t = (float)0.032;
i = (float)0.0;

g.setColor(Color.red);

// Set the first point
oldx = p[0].x;
oldy = p[0].y;

do
{

x = (int)((((1-i)*(1-i)*(1-i))*p[0].x)+(3*i*((1-i)*(1-i))*p[1].x)+

(3*(i*i)*(1-i)*p[2].x)+((i*i*i)*p[3].x));

y = (int)((((1-i)*(1-i)*(1-i))*p[0].y)+(3*i*((1-i)*(1-i))*p[1].y)+

(3*(i*i)*(1-i)*p[2].y)+((i*i*i)*p[3].y));

g.drawLine(oldx,oldy,x,y);
oldx = x;
oldy = y;
i = i + t;

}
while (i <= 1.0);

}

}