/***
This script demonstrates how to switch to a cartesian coordinate system and draw some curves using.
The code is using functions for better structure and readability.
***/

// set the pen
var colors = new Object();
colors.penColor = new Object();
colors.penColor.index = 1;
colors.fillColor = new Object();
colors.fillColor.index = 4;
colors.fillShade = -1;

var pen = new Object();
pen.width = 1;
pen.lineStyle = "solid";
pen.colors = colors;
winfig.setPen(pen);

// the base dpi is 1200dpi. So 1 cm translates to 1200/2.54 = 472.44 dots
// That's the finest precision a fig file can have. For higher precisions the
// base has to be changed from 1200dpi to something bigger
winfig.setUnit("metric");

// in computer graphics the origin is upper left and the y direction is downwards
// but in this example we need a cartesian coordinate system
// so we translate the orgin and swap the vertical direction

// set center to (11cm, 11cm) from the upper left corner
winfig.setCenter(11, 11);

winfig.setDirection("cartesian");

drawCartesianCoordinates();

colors.penColor.index = 4;
winfig.setColors(colors);

// draw a simple parabola with a polyline connecting the points
drawParabola();

// draw another one, but this time only with dots
colors.penColor.index = 12;
winfig.setColors(colors);

pen.width = 2;
winfig.setPen(pen);

drawDottedParabola();

// this is the actual end of the script. Following are the function definitions.

function drawCartesianCoordinates()
{
	var arrow = new Object();
	arrow.type = 2;

	// draw a coordinate system
	var abscissa = new Object();
	abscissa.points = new Array();

	abscissa.points[0] = new Object();
	abscissa.points[0].x = -10;
	abscissa.points[0].y = 0;

	abscissa.points[1] = new Object();
	abscissa.points[1].x = 10;
	abscissa.points[1].y = 0;
	abscissa.forwardArrow = arrow;

	winfig.drawPolyline(abscissa);

	var ordinate = new Object();
	ordinate.points = new Array();

	ordinate.points[0] = new Object();
	ordinate.points[0].x = 0;
	ordinate.points[0].y = -10;

	ordinate.points[1] = new Object();
	ordinate.points[1].x = 0;
	ordinate.points[1].y = 10;
	ordinate.forwardArrow = arrow;

	winfig.drawPolyline(ordinate);
}

function drawDottedParabola()
{
	for (var x=-3; x <= 3.001; x=x+0.1)
	{
		var dot = new Object();
		dot.points = new Array();
		dot.points[0] = new Object();
		dot.points[0].x = x;
		dot.points[0].y = x*x;
		winfig.drawPolyline(dot);
	}
}

function drawParabola()
{
	var curve = new Object();
	curve.points = new Array();

	var i=0;

	// I'm using 4.001 instead of 4 due to numerical imprecision, because 4 is internally represented as 3.999997,
	// which would stop the loop one iteration too early
	for (var x=-4.0; x <= 4.001; x=x+0.1, i++)
	{
		curve.points[i] = new Object();
		curve.points[i].x = x;
		curve.points[i].y = 0.5*x*x;
	}
	winfig.drawPolyline(curve);
}
