/*
 *  acm : an aerial combat simulator for X
 *  Copyright (C) 1991,1992  Riley Rainey
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; version 2 dated June, 1991.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program;  if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave., Cambridge, MA 02139, USA.
 */

#include <math.h>
#include "pm.h"
#include "events.h"
#include "joystick.h"

#define mouse_IMPORT
#include "mouse.h"


void
mouse_getPosition(craft * c, viewer * u)
{

	_BOOL     gotValues;
	int       x, y;
	double    pitchComm, rollComm, steerComm;

	gotValues = FALSE;

/*
 *  Sample joystick, if present
 */

/*
	if (joystick_processInput() >= 0) {
		double    dummy, throttle;
		int       sw;

		XSync(u->dpy, False);
		joystick_getPosition(&rollComm, &pitchComm, &dummy, &throttle, &sw);
		steerComm = rollComm;
		events_joystick(c, u, throttle, sw);
		gotValues = TRUE;
	}
*/

/*
 *  No joystick, sample mouse
 */

	//else
	{
		int width, height;
		
		gui_getPointerPosition(u->gui, &x, &y);

		width = gui_getWidth(u->gui);
		height = gui_getHeight(u->gui);

		if (x >= 0 && y >= 0 && x < width && y < height) {
			int r;

			/*
				x/y mouse movements should give a response in pitch/roll
				command independent from the format of the window:
			*/

			if( width < height )
				r = width / 2;
			else
				r = height / 2;

			x = x - (width / 2);
			y = y - (height / 2);

			rollComm = - (double) x / (double) r;
			if( rollComm < -1.0 )
				rollComm = -1.0;
			else if( rollComm > 1.0 )
				rollComm = 1.0;

			steerComm = rollComm;

			pitchComm = - (double) y / (double) r;
			if( pitchComm < -1.0 )
				pitchComm = -1.0;
			else if( pitchComm > 1.0 )
				pitchComm = 1.0;

			if( mouse_stick_mode == mouse_NORMAL ){

				/* quadratic response */
				if (rollComm < 0.0)
					rollComm = -rollComm * rollComm;
				else
					rollComm = rollComm * rollComm;

				if (pitchComm < 0.0)
					pitchComm = -pitchComm * pitchComm;
				else
					pitchComm = pitchComm * pitchComm;
			
			} else if( mouse_stick_mode == mouse_PRECISE ){

				/* cubic response */
				rollComm = rollComm * rollComm * rollComm;
				pitchComm = pitchComm * pitchComm * pitchComm;

			} else {
				/* linear response */
			}

			gotValues = TRUE;

		}
	}

	if ( gotValues && u->hasFocus && u->hasComm && c->type != CT_DRONE ) {
		c->pitchComm = pitchComm;
		c->rollComm = rollComm;
		c->steerComm = steerComm;
	}
}
