/*
 *  Copyright (c) 1994, Riley Rainey,  riley@netcon.com
 *
 *  Permission to use, copy, modify and distribute (without charge) this
 *  software, documentation, images, etc. is granted, provided that this 
 *  comment and the author's name is retained.
 *
 *  This software is provided by the author as is, and without any expressed
 *  or implied warranties, including, but not limited to, the implied
 *  warranties of merchantability and fitness for a particular purpose.  In no
 *  event shall the author be liable for any direct, indirect, incidental, or
 *  consequential damages arising in any way out of the use of this software.
 */

#include <math.h>

#include "shared.h"
#include "edit.h"
#include "gutil.h"
#include "gutil1.h"

#define circle_IMPORT
#include "circle.h"

#define NUM_POINTS 12


static point_t drag;

void
ScaleCircle(view_info_t *p, polygon_t *poly, double scale)
{
	double a = 0.0, a_incr = M_PI * 2.0 / NUM_POINTS;
	double other = 0.0, ocos, osin;
	int i;

	for (i=0; i<NUM_POINTS; ++i) {

		osin = sin (a);
		ocos = cos (a);
		poly->point[i] = drag;
		switch (p->layout) {
		case VL_NYX:
		case VL_NXNY:
			poly->point[i].point.x += osin * scale;
			poly->point[i].point.y += ocos * scale;
			poly->point[i].point.z += other;
			break;
		case VL_NYZ:
			poly->point[i].point.x += other;
			poly->point[i].point.y += ocos * scale;
			poly->point[i].point.z += osin * scale;
			break;
		case VL_NXZ:
			poly->point[i].point.x += osin * scale;
			poly->point[i].point.y += other;
			poly->point[i].point.z += ocos * scale;         
			break;
		default:
			poly->point[i].point.x += osin * scale;
			poly->point[i].point.y += ocos * scale;
			poly->point[i].point.z += other;
			break;  
		}
		a += a_incr;    
		PointToXYZ (p, &poly->point[i]);
	}
	
	if (scale > 0.0) {
		ComputePlaneEquation (poly);
	}
}

void
BeginCirclePoint (Widget w, view_info_t *p, int x, int y)
{
	polygon_t *poly;
	
	poly = BeginPolygon();
	poly->num_points = NUM_POINTS;
	drag_origin.x = x;
	drag_origin.y = y;
	PointXY (w, p, x, y, &drag);
	ScaleCircle (p, poly, 0.0);
}

void
DragCirclePoint(Widget w, view_info_t *p, int x, int y)
{
	double dx = x - drag_origin.x, dy = y - drag_origin.y;
	double scale = sqrt (dx * dx + dy * dy) * pixel_scale;
	Display *dpy = XtDisplay(w);

	XSetFunction (dpy, p->gc, GXxor);
	XSetFunction (dpy, p->other_view->gc, GXxor);
	
	DrawPolygon (w, cur_polygon, True);
	DrawPolygon (p->other_widget, cur_polygon, True);

	ScaleCircle (p, cur_polygon, scale);
	DrawPolygon (w, cur_polygon, True);
	DrawPolygon (p->other_widget, cur_polygon, True);

	XSetFunction (dpy, p->gc, GXcopy);
	XSetFunction (dpy, p->other_view->gc, GXcopy);
}

void
CompleteCirclePoint(Widget w, view_info_t *p, int x, int y)
{
	CompletePolygon (w, cur_polygon);
}
