#ifndef XSW_H
#define XSW_H

#include <stdio.h>
#include <sys/types.h>

#include "../include/objects.h"
#include "../include/imgrefs.h"
#include "../include/osw-x.h"
#include "../include/widget.h"

#include "gctl.h"
#include "sndrefs.h"
#include "msglist.h"
#include "cdlg.h"
#include "page.h"
#include "bridgewin.h"
#include "vsmenu.h"
#include "msgwin.h"
#include "unvlist.h"
#include "ignoredobj.h"
#include "unvlistwin.h"
#include "unvpropdlg.h"
#include "ecowin.h"
#include "starchartwin.h"
#include "optwin.h"
#include "keymapwin.h"
#ifdef JS_SUPPORT
# include "jsmaps.h"
# include "jsmapwin.h"
#endif
#include "vsmenuwin.h"


/*
 *	Program name and version:
 */
#define PROG_NAME_FULL			"XShipWars"
#define PROG_NAME			"XSW"
#define PROG_VERSION			"2.5.5"

#define PROG_VERSION_MAJOR		2
#define PROG_VERSION_MINOR		5
#define PROG_VERSION_RELEASE		5

#define PROG_URL		"\
http://wolfpack.twu.net/ShipWars/XShipWars"


/*
 *	Client Type Code:
 *
 *	To identify this client to the universe server, sent in
 *	a CS_CODE_LOGIN.
 */
#define XSW_CLIENT_TYPE_CODE		6


/*
 *	Usage information:
 */
#define PROG_USAGE_MESSAGE "\
Usage: xsw [url] [options] [GUI_options]\n\
\n\
    [url] is the URL to the universe that you want to connect to.\n\
    the format is:\n\
\n\
        sw://[name]:[password]@<address>:[port]\n\
\n\
    [options] can be any of the following:\n\
\n\
	--cfgfile <file>        Open configuration from <file>.\n\
	--rcfile                Same as --cfgfile.\n\
	-f                      Same as --cfgfile.\n\
	--control <type>        Specify which controller to use:\n\
				   keyboard\n\
				   joystick\n\
	-c                      Same as --control.\n\
	--help                  Prints (this) help screen and exits.\n\
	--version               Prints version information and exits.\n\
\n\
    Most customizations can be performed in the options menu.\n\
\n\
    Command line options override any options in the configuration file.\n\
\n\
    [GUI_options] can be any of the following:\n\
\n\
	--display <address>     Specifies the address to the X server.\n\
	--visual <id>           Specifies a particular Visual to use.\n\
	--depth <bits>          Specifies the bit depth.\n\
	--geometry <WxH+X+Y>    Specifies the window position and/or\n\
				size.\n\
	--no_shm                Do not use XShm (MIT-SHM).\n\
\n"

   
/*
 *	Copyright information:
 */
#define PROG_COPYRIGHT "\
Copyright (C) 1997-2006 WolfPack Entertainment.\n\
This program is protected by international copyright laws and treaties,\n\
distribution and/or modification of this software in violation of the\n\
GNU Public License is strictly prohibited. Violators will be prosecuted\n\
to the fullest extent of the law."


/*
 *	Default connect/disconnect timeout (in seconds):
 */
#define XSW_DEF_NET_TIMEOUT		45

/*
 *	Default Network Bandwidth (in bytes per second):
 */
#define XSW_DEF_NET_BANDWIDTH		3600	/* 28.8 kbps */


/*
 *	Prompt Limits (in bytes):
 */
#define XSW_DEF_PROMPT_BUF_LEN		256	/* In bytes */
#define XSW_DEF_PROMPT_HIST_BUFS	30


/*
 *   Default program directories:
 */
#ifdef __WIN32__
#define XSW_DEF_LOCAL_DATA_DIR		CWD_STR
#define XSW_DEF_GLOBAL_DATA_DIR		CWD_STR
#define XSW_DEF_GLOBAL_IMAGES_DIR	CWD_STR "images"
#define XSW_DEF_GLOBAL_SOUNDS_DIR	CWD_STR "sounds"
#define XSW_DEF_GLOBAL_ETC_DIR		CWD_STR
#define XSW_DEF_SW_SERVER_DIR		CWD_STR
#else
#define XSW_DEF_LOCAL_DATA_DIR		".shipwars"
#define XSW_DEF_GLOBAL_DATA_DIR		PREFIX "/share/games/xshipwars"
#define XSW_DEF_GLOBAL_IMAGES_DIR	PREFIX "/share/games/xshipwars/images"
#define XSW_DEF_GLOBAL_SOUNDS_DIR	PREFIX "/share/games/xshipwars/sounds"
#define XSW_DEF_GLOBAL_ETC_DIR		PREFIX "/share/games/xshipwars/etc"
#define XSW_DEF_SW_SERVER_DIR		"/home/swserv"
#endif


/*
 *	File Name Extensions & Masks:
 */
#define XSW_UNIVERSES_LIST_EXT		".ini"
#define XSW_UNIVERSES_LIST_EXT_MASK	"*.ini"

#define XSW_IMGREFS_EXT			".isr"
#define XSW_IMGREFS_EXT_MASK		"*.isr"

#define XSW_OCSN_EXT			".ocsn"
#define XSW_OCSN_EXT_MASK		"*.ocsn"

#define XSW_SNDREFS_EXT			".ss"
#define XSW_SNDREFS_EXT_MASK		"*.ss"

#define XSW_STARCHART_EXT		".cht"
#define XSW_STARCHART_EXT_MASK		"*.cht"

#define XSW_TGA_EXT			".tga"
#define XSW_TGA_EXT_MASK		"*.tga"


/*
 *	Default configuration files:
 *
 *	These files are searched for in the XSW_DEF_LOCAL_DATA_DIR
 *	directory by default or from the command line or other
 *	configuration file specified location.
 *
 *	If these files cannot be found, a global one will be
 *	coppied to its default location.
 */
#define XSW_DEF_CFG_FILE		"xsw.ini"
#define XSW_DEF_UNIVERSES_FILE		"universes.ini"

/*
 *	Default Page Files:
 */
#define XSW_DEF_MAIN_PAGE_FILE		"main.page"
#define XSW_DEF_DESTROYED_PAGE_FILE	"destroyed.page"

/*
 *	Default log file location:
 *
 *	Default parent is user's home directory.
 */
#define XSW_DEF_LOG_FILE		"xsw.log"

/*
 *	Default OCSNs file location:
 *
 *	Default parent is /usr/games/xshipwars/etc/.
 */
#define XSW_DEF_OCSN_FILE		"default.ocsn"

/*
 *	Default ImgRefs file location:
 *
 *	Default parent is /usr/games/xshipwars/images/.
 */
#define XSW_DEF_IMGREFS_FILE		"default.isr"

/*
 *	Default SndRefs file location:
 *
 *	Default parent is /usr/games/xshipwars/sounds/.
 */
#define XSW_DEF_SNDREFS_FILE		"default.ss"


/*
 *	Default Server Address * Port Number:
 */
#define XSW_DEF_SWSERV_ADDRESS		"localhost"
#define XSW_DEF_SWSERV_PORT		1701
#define XSW_DEF_SWSERV_URL		"swserv://Guest:guest@localhost:1701"

/*
 *	Default Guest Login Name & Password:
 */
#define XSW_DEF_GUEST_LOGIN_NAME	"Guest"
#define XSW_DEF_GUEST_LOGIN_PASSWORD	"guest"


/*
 *	XSW Images Codes:
 *
 *	IMPORTANT: These codes are NOT Image Set Referance numbers!
 *
 *	These are base images codes used soly by the client for
 *	its various internal images.
 */
/* Desktop Icons */
#define XSW_IMG_ICON_XSW		1
#define XSW_IMG_ICON_ECONOMY		2
#define XSW_IMG_ICON_UNIVERSE		3
#define XSW_IMG_ICON_OPTIONS		4
#define XSW_IMG_ICON_STARCHART		5

/* Dialog Icons */
#define XSW_IMG_DIALOG_ICON_INFO	6
#define XSW_IMG_DIALOG_ICON_WARNING	7
#define XSW_IMG_DIALOG_ICON_ERROR	8
#define XSW_IMG_DIALOG_ICON_QUESTION	9

/* Viewscreen Markings */
#define XSW_IMG_VIEWSCREEN_MARK_OBJECT	10
#define XSW_IMG_VIEWSCREEN_MARK_VESSEL	11
#define XSW_IMG_VIEWSCREEN_MARK_INCOMING_FIRE	12

#define XSW_IMG_VIEWSCREEN_WEAPON_PROJECTILE	13
#define XSW_IMG_VIEWSCREEN_WEAPON_PULSE		14
#define XSW_IMG_VIEWSCREEN_WEAPON_STREAM	15

#define XSW_IMG_VIEWSCREEN_ENERGY_SAVER_MODE	16

#define XSW_IMG_VIEWSCREEN_LENSFLARE01	17
#define XSW_IMG_VIEWSCREEN_LENSFLARE02	18
#define XSW_IMG_VIEWSCREEN_STROBEGLOW01	19

/* Scanner Markings */
#define XSW_IMG_SCANNER_MARK_UNKNOWN	20
#define XSW_IMG_SCANNER_MARK_LOCKED	21
#define XSW_IMG_SCANNER_MARK_WEAPON	22
#define XSW_IMG_SCANNER_MARK_HOME	23
#define XSW_IMG_SCANNER_MARK_AREA	24

/* Universe List Icons */
#define XSW_IMG_ICON_UNIVERSE_SMALL	25
#define XSW_IMG_ICON_UNIVERSE_LOGIN_SMALL	26
#define XSW_IMG_ICON_UNIVERSE_OUTDATED_SMALL	27
#define XSW_IMG_ICON_UNIVERSE_UNKNOWN_SMALL	28

/* Startup splash background */
#define XSW_IMG_SPLASH_BG		29
#define XSW_IMG_SPLASH_PBAR_LEFT	30
#define XSW_IMG_SPLASH_PBAR_RIGHT	31
#define XSW_IMG_SPLASH_PBAR_TICK	32

/* Consoles */
#define IMG_CODE_STATS_CON1		33	/* Bridge consoles */
#define IMG_CODE_STATS_CON2		34
#define IMG_CODE_STATS_CON3		35
#define IMG_CODE_STATS_CON4		36
#define IMG_CODE_SCANNER		37	/* Scanner background */
#define IMG_CODE_SRO_CON1		38
#define IMG_CODE_SRO_CON2		39
#define IMG_CODE_SRO_CON3		40
#define IMG_CODE_MESG_CON		41

/* Console decorations */
#define IMG_CODE_BPANEL_OL_HULL		42
#define IMG_CODE_BPANEL_OL_POWER	43
#define IMG_CODE_BPANEL_OL_VIS		44
#define IMG_CODE_BPANEL_OL_SHIELDS	45
#define IMG_CODE_BPANEL_OL_DMGCTL	46

#define IMG_CODE_BPANEL_OL_ANTIMATTER	47
#define IMG_CODE_BPANEL_OL_LTHROTTLE	48
#define IMG_CODE_BPANEL_OL_RTHROTTLE 	49

#define IMG_CODE_BPANEL_OL_THRUSTVECTOR	50

/* StarChart */
#define XSW_IMG_STARCHART_ZOOM_IN	51
#define XSW_IMG_STARCHART_ZOOM_OUT	52
#define XSW_IMG_STARCHART_JUMP_TO_PLAYER 53

/* Message Window */
#define XSW_IMG_MESGWIN_BG		54


/*
 *	Update Object To Server Intervals (in ms):
 *
 *      In milliseconds. These are the minimum and maximum object updates
 *      intervals that we can request of the server to send us object
 *	updates.   The server code's minimum and maximum update intervals
 *	settings will override these minimum and maximum settings.
 *
 *	These settings should match SWServ's settings
 */
#define XSW_SWSERV_MIN_UPDATE_INT	25
#define XSW_SWSERV_MAX_UPDATE_INT	5000
#define XSW_SWSERV_DEF_UPDATE_INT	1000


/*
 *	Objects Allocate Ahead:
 *
 *	Objects are allocated ahead in this many chunks.
 */
#define XSW_OBJECT_ALLOCATE_AHEAD	10


/*
 *	Object Outdated Timeout:
 *
 *	Objects that have not been updated by network data from the
 *	server for this many milliseconds are assumed outdated and
 *	will not be drawn.
 *
 *	However the object will not be recycled.
 */
#define XSW_DEF_OBJECT_OUTDATED_TIME	6000


/*
 *	Maximum object create script name entries:
 *
 *	Do not confuse this with object create scripts on the server.
 *
 *	See the ocsn_struct further below.
 */
#define XSW_OCSN_MAX			100000


/*
 *	Extended XSW Object Flags:
 */
#define XSW_OBJ_FLAG_ON_FIRE		(1 << 8)
#define XSW_OBJ_FLAG_SMOKE_TRAIL	(1 << 9)


/*
 *	Timming Intervals (in ms):
 */
#define XSW_MEMORY_CLEAN_INTERVAL	150000		/* 2.5 minutes */
#define XSW_CONSOLES_UPDATE_INTERVAL	5000
#define XSW_SPAWN_PARTICLES_INTERVAL	100
#define XSW_PARTICLE_LIFE_SPAN		2000


/*
 *	Client Command Maximum Length:
 */
#define XSW_CLIENT_CMD_MAX		256


/*
 *	Prompt Codes:
 *
 *	These are codes to indicate which prompt mode XSW is in.
 *	0 means no prompt mode and that keys should be handled
 *	normally.
 *	THe global variable prompt_mode holds one of these codes
 *	to indicate to the various functions which prompt mode
 *	we are in.
 */
#define XSW_PROMPT_NONE			0
#define XSW_PROMPT_CONNECT		1
#define XSW_PROMPT_CLIENT_CMD		2
#define XSW_PROMPT_SERVER_CMD		3
#define XSW_PROMPT_MESSAGE		4
#define XSW_PROMPT_WEAPONS_FREQ		5
#define XSW_PROMPT_SHIELD_FREQ		6
#define XSW_PROMPT_INTERCEPT		7
#define XSW_PROMPT_COM_CHANNEL		8


/*
 *	Universe entry maximums:
 */
#define UNIV_MAX_ALIAS_LEN		128
#define UNIV_MAX_URL_LEN		MAX_URL_LEN
#define UNIV_MAX_COMMENT_LEN		256


/*
 *	Scanner Orientations:
 */
#define XSW_SCANNER_ORIENT_GC		0	/* Galactic Core */
#define XSW_SCANNER_ORIENT_PLAYER	1	/* Player */


/*
 *	Throttle Modes:
 */
#define XSW_THROTTLE_MODE_NORMAL	0
#define XSW_THROTTLE_MODE_BIDIRECTIONAL	1
#define XSW_THROTTLE_MODE_INCREMENTAL	2


/*
 *	HP & Power Level Coefficients:
 *
 *	These coefficients are used to determine when levels of hp
 *	and power are considered at "warning" or "danger" levels in
 *	order to determine the color of the display and when to
 *	announce it to the player.
 */
#define XSW_HP_WARNING_COEFF		0.58
#define XSW_HP_DANGER_COEFF		0.30
#define XSW_POWER_WARNING_COEFF		XSW_HP_WARNING_COEFF
#define XSW_POWER_DANGER_COEFF		XSW_HP_DANGER_COEFF




/*
 *	Runlevel:
 *
 *	Used to keep track of XSWMain() levels.
 */
extern "C" int		runlevel;


/*
 *	Current time in milliseconds since midnight:
 */
extern "C" time_t	cur_millitime;

/*
 *	Current time in seconds since EPOCH:
 */
extern "C" time_t	cur_systime;


/*
 *	Lapsed MilliTime:
 *
 *	In milliseconds, the time it took the previous loop to execute.
 *	This is compared to CYCLIC_MILLITIME_LAPSE (#defined in reality.h)
 *	to adjust for time lost in the last loop.
 */
extern "C" time_t	lapsed_millitime;


/*
 *	Time Compensation:
 *
 *	This value is always in the range of 1.0 to <big number>.
 *	It is used as the coefficent to various momentum and movement
 *	calculations to compensate for lost time in the previous
 *	loop.
 */
extern "C" float	time_compensation;


/*
 *	Prompt Mode:
 *
 *	Indicates which prompt mode we are in so key events are handled
 *	correctly.   0 means we are not in any prompt mode.
 */
extern "C" int		prompt_mode;


/*
 *	Global debug values:
 *
 *	Used for run time debugging.
 */
#define DEBUG_LEVEL_NONE			0
#define DEBUG_LEVEL_ALL				1
#define DEBUG_LEVEL_MEMORY			2
#define DEBUG_LEVEL_NETWORK			3

typedef struct {

	int		level;		/* One of DEBUG_LEVEL_* */
	float		val;

} xsw_debug_struct;
extern "C" xsw_debug_struct debug;


/*
 *	Options:
 */
typedef struct _xsw_option_struct	xsw_option_struct;

/*
 *	CPU Priorities:
 */
#define XSW_CPU_PRIORITY_HIGHEST	0	/* usleep(0) */
#define XSW_CPU_PRIORITY_HIGH		1	/* usleep(1000) */
#define XSW_CPU_PRIORITY_MEDIUM		2	/* usleep(8000) (default) */
#define XSW_CPU_PRIORITY_LOWEST		3	/* usleep(16000) */

/*
 *	Show Formal Object Labels:
 */
#define XSW_SHOW_FORMAL_LABEL_NEVER	0
#define XSW_SHOW_FORMAL_LABEL_AS_NEEDED	1
#define XSW_SHOW_FORMAL_LABEL_ALWAYS	2

/*
 *	Viewscreen Show Flags:
 */
#define XSW_SHOW_VIEWSCREEN_SELECTED_WEAPON	(1 << 0)
#define XSW_SHOW_VIEWSCREEN_MARKINGS		(1 << 1)
#define XSW_SHOW_VIEWSCREEN_OBJECT_LABELS	(1 << 2)
#define XSW_SHOW_VIEWSCREEN_NETSTATS		(1 << 3)

/*
 *	Sound Levels:
 */
#define XSW_SOUNDS_NONE			0
#define XSW_SOUNDS_EVENTS		1
#define XSW_SOUNDS_ENGINE		2
#define XSW_SOUNDS_ALL			3

/*
 *	Units:
 */
#define XSW_UNITS_XSW			0	/* XSW Internal units */
#define XSW_UNITS_METRIC		1	/* Meters, Kilometers,
						 * Astronomical units */
#define XSW_UNITS_PARSECS		2	/* MilliParsecs, Parsecs */
#define XSW_UNITS_ENGLISH		3	/* Feet, Miles, Astronomical
						 * units */

struct _xsw_option_struct {

	/* Configuration file version */
	int		cfg_version_major,
			cfg_version_minor,
			cfg_version_release;

	/* CPU Priority (one of XSW_CPU_PRIORITY_*) */
	int		cpu_priority;

	/* Units, one of XSW_UNITS_* */
	int		units;

	/* Async (passive) image loading? */
	bool_t		async_image_loading;

	/* Maximum pixels to load per iteration (if
	 * async_image_loading is True)
	 */
	int		async_image_pixels;

	/* Logging, any value that is set True specifies that logging
	 * is on
	 */
	bool_t		log_client,
			log_net,
			log_errors;

	/* Redraw viewscreen, scanner, etc, asyncronusly? */
	bool_t		async_redraws;


	/* Scanner orientation at startup (one of
	 * XSW_SCANNER_ORIENT_*) */
	int		def_scanner_orient;


	/* Show object labels in formal format (one of
	 * XSW_SHOW_FORMAL_LABEL_*)
	 */
	int		show_formal_label;

	/* Show viewscreen details (any of XSW_SHOW_VIEWSCREEN_* */
	unsigned int	show_viewscreen_flags;

	/* Viewscreen effects graphics */
	bool_t		show_lens_flares,
			show_strobe_glow,
			show_nebula_glow,
			show_fires,		/* Objects on fire */
			show_smoke_trails;

	int		max_particles;

	/* Bandwidth in bytes per second */
	unsigned long	net_bandwidth;

	/* Connect/disconnect timeout in seconds
	 *
	 * Specfies how long to wait for connect() and close() of
	 * connection sockets
	 */
	time_t		net_timeout;

	/* Do not show objects that have not been updated for this
	 * many ms
	 */
	time_t		net_object_outdated_time;


	/* Show network warnings and non-fatal errors? */
	bool_t		show_net_errors;

	/* Show server error messages in dialogs? */
	bool_t		show_server_errors;


	/* Update objects locally by predicting movement patterns from
	 * object velocity values (produces smoother movement),
	 * otherwise uses positions alone
	 */
	bool_t		local_updates;


	/* Automatic viewscreen zoom */
	bool_t		auto_zoom;


	/* Sounds level and music */
	int		sounds;		/* One of XSW_SOUNDS_* */
	bool_t		music;		/* True for on */

	/* Controller (one of XSW_CONTROLLER_*) */
	int		controller;
	bool_t		cmd_line_set_controller;

	/* Throttle mode (one of XSW_THROTTLE_MODE_*) */
	int		throttle_mode;

#ifdef JS_SUPPORT
	/* Close joystick when bridge is out of focus? */
	bool_t		focus_out_js_close;
#endif	/* JS_SUPPORT */


	/* Reduces CPU usage, good for idling */
	bool_t		energy_saver_mode;


	/* Scanner range affected by enviroment? (set true, no cheating!) */
	bool_t		scanner_limiting;

	/* Notify when objects come into or leave scanner range? */
	bool_t		notify_scanner_contacts;


	/* Automatically map eco window as needed */
	bool_t		auto_map_eco_win;

	/* Automatically map universe list window at startup */
	bool_t		auto_map_univ_list_win;

	/* Clear star chart on connect */
	bool_t		clear_chart_on_connect;

	/* Save configuration on exit */
	bool_t		save_on_exit;


	/* Last window positions */
	int		bridge_x, bridge_y;
	unsigned int	bridge_width, bridge_height;

	int		msgw_x, msgw_y;
	unsigned int	msgw_width, msgw_height;

	int		ulw_x, ulw_y;
	unsigned int	ulw_width, ulw_height;

	int		ecow_x, ecow_y;
	unsigned int	ecow_width, ecow_height;

	int		scht_x, scht_y;
	unsigned int	scht_width, scht_height;


};

extern "C" xsw_option_struct option;


/*
 *	Directories:
 *
 *	All values must be absolute paths.
 */
typedef struct {

	char		startup[PATH_MAX],
			home[PATH_MAX],
			ltoplevel[PATH_MAX],	/* Local XSW toplevel */
			toplevel[PATH_MAX],	/* Global XSW toplevel */
			etc[PATH_MAX],		/* Configuration */
			images[PATH_MAX],
			sounds[PATH_MAX],
			scripts[PATH_MAX],
			downloads[PATH_MAX],	/* Screen shots */
			starchart[PATH_MAX];

} xsw_dname_struct;
extern "C" xsw_dname_struct dname;


/*
 *	File Names:
 */
typedef struct {

	char		cfg[NAME_MAX + PATH_MAX],
			universes[NAME_MAX + PATH_MAX],

#ifdef JS_SUPPORT
			js_calib[NAME_MAX + PATH_MAX],
#endif

			main_page[NAME_MAX + PATH_MAX],
			destroyed_page[NAME_MAX + PATH_MAX],

			ocsn[NAME_MAX + PATH_MAX],
			imgrefs[NAME_MAX + PATH_MAX],
			sndrefs[NAME_MAX + PATH_MAX],

			log[NAME_MAX + PATH_MAX];

} xsw_fname_struct;
extern "C" xsw_fname_struct fname;


/*
 *	Next Instances:
 *
 *	All units are in milliseconds.
 */
typedef struct _xsw_next_struct		xsw_next_struct;

struct _xsw_next_struct {

	time_t		update_check,
			viewscreen,	/* Redraw viewscreen */
			consoles,	/* Redraw some bridge panel consoles */
			memory_clean,	/* Reclaim memory */
			player_pos_send,/* Next send player position */
			spawn_particles,
			wormhole_enter;

};

extern "C" xsw_next_struct next;


/*
 *	FPS Counter:
 *
 *	Record for keeping track of the frames drawn per second on
 *	the viewscreen.
 */
typedef struct {

	int		fcount,		/* Frames drawn counter */
			lfcount;	/* Frames drawn last time */

	time_t		interval,	/* Always 1000 milliseconds */
			next;		/* In milliseconds */

} xsw_fps_counter_struct;
extern "C" xsw_fps_counter_struct fps_counter;


/*
 *	Animation Timmer:
 *
 *	Timming and frame records for various animation timmers.
 *	Each timmer has a code #defined above.
 */
typedef struct _xsw_anim_timmer_struct	xsw_anim_timmer_struct;

#define XSW_ANIM_TIMMER_DEFAULT		0
#define XSW_ANIM_TIMMER_GLOW_SHORT	1
#define XSW_ANIM_TIMMER_GLOW_MEDIUM	2	/* Cursors, arrows */
#define XSW_ANIM_TIMMER_GLOW_LONG	3
#define XSW_ANIM_TIMMER_BLINK_SHORT	4
#define XSW_ANIM_TIMMER_BLINK_LONG	5

#define XSW_MAX_ANIM_TIMMERS		6	/* Total animation timmers */

struct _xsw_anim_timmer_struct {

	int		count,
			count_max;

	time_t		interval,	/* In ms */
			next;		/* In ms */

};

#define XSW_ANIM_TIMMER(p)	((xsw_genanim_timmer_struct *)(p))

extern "C" xsw_anim_timmer_struct xsw_anim_timmer[XSW_MAX_ANIM_TIMMERS];


/*
 *	Fonts:
 */
typedef struct {

	font_t		*std,			/* Standard */
			*std_bold;		/* Standard bold */

	/* Bridge and message window console panel fonts */
	font_t		*con_heading,		/* Bold */
			*con_standard,		/* Standard */
			*con_message;		/* Msgbox fixed width font */

	/* Viewscreen fonts */
	font_t		*vs_heading,		/* Bold and big */
			*vs_standard;

} xsw_font_struct;
extern "C" xsw_font_struct xsw_font;


/*
 *	Colors:
 *
 *	Allocated GUI color pixels and their values.
 *
 *	RGB values are stored in WColorStruct structures, they
 *	are members denoted with _cv postpended to their name.
 */
typedef struct {

	/* Standard text colors */
	pixel_t		standard_text,
			bold_text,
			withdrawn_text;

	WColorStruct	standard_text_cv,
			bold_text_cv,
			withdrawn_text_cv;


	/* Bridge console panel readout colors */
	pixel_t		bp_standard_text,
			bp_bold_text,
			bp_withdrawn_text,	/* Disabled */

			bp_light_outline,
			bp_normal_outline,
			bp_dark_outline;

	WColorStruct    bp_standard_text_cv,
			bp_bold_text_cv,
			bp_withdrawn_text_cv,

			bp_light_outline_cv,
			bp_normal_outline_cv,
			bp_dark_outline_cv;

	/* Warning, danger, and critical colors */
	pixel_t		bp_warning,
			bp_danger,
			bp_critical;

	WColorStruct	bp_warning_cv,
			bp_danger_cv,
			bp_critical_cv;

	/* Friendly, unknown, and hostile IFF colors */
	pixel_t		bp_friendly,
			bp_unknown,
			bp_hostile;

	WColorStruct	bp_friendly_cv,
			bp_unknown_cv,
			bp_hostile_cv;

	/* Bridge console panel readout outline colors */
	pixel_t		bpol_hull,
			bpol_power,
			bpol_vis,
			bpol_shields,
			bpol_dmgctl,
			bpol_throttle,
			bpol_throttle_rev;

	WColorStruct	bpol_hull_cv,
			bpol_power_cv,
			bpol_vis_cv,
			bpol_shields_cv,
			bpol_dmgctl_cv,
			bpol_throttle_cv,
			bpol_throttle_rev_cv;

	/* Viewscreen labels (no corresponding pixel value) */
	WColorStruct	vs_label_bg_cv,
			vs_label_text_bg_cv,	/* Shadow of vs_label_fg_cv */
			vs_label_fg_cv;


	/* Scanner mark colors */
	pixel_t		scmark_unknown,		/* Most objects */
			scmark_locked,
			scmark_weapon,
			scmark_home,
			scmark_area;

	WColorStruct	scmark_unknown_cv,
			scmark_locked_cv,
			scmark_weapon_cv,
			scmark_home_cv,
			scmark_area_cv;

	/* Keymap edit window */
	pixel_t		keymap_query_bg,
			keymap_query_fg;

	WColorStruct	keymap_query_bg_cv,
			keymap_query_fg_cv;


	/* Viewscreen graphics colors (no corresponding pixel value) */
	WColorStruct	heading_arrow,
			lock_arrow,
			lock_cursor,
			stream_green,
			stream_yellow,   
			stream_purple,
			stream_orange,
			shield_blue,
			visibility_marker,
			star_glow;

	/* Starchart */
	pixel_t		chart_bg,
			chart_grid,
			chart_sector_grid,
			chart_cross_hairs;

	WColorStruct    chart_bg_cv,
			chart_grid_cv,
			chart_sector_grid_cv,
			chart_cross_hairs_cv;

} xsw_color_struct;
extern "C" xsw_color_struct xsw_color;


/*
 *    XSW Cursors:
 *
 *	Allocated GUI cursors.
 */
typedef struct {

	WCursor	*scanner_lock,
		*text,
		*wait,

		*translate,
		*zoom;

} xsw_cursor_struct;
extern "C" xsw_cursor_struct xsw_cursor;



/*
 *	XSW Images:
 *
 *	Images used internally by the program.
 *
 *	IMPORTANT: These are not Image Set Referance numbers.
 */
typedef struct _xsw_image_struct	xsw_image_struct;
struct _xsw_image_struct {

	int		load_state;	/* 0 = not loaded, 1 = loaded */
	char		*filename;
	image_t		*image;
	pixmap_t	pixmap;		/* May be None */
	bitmap_t	mask;		/* May be None */

};
extern "C" xsw_image_struct **xsw_image;
extern "C" int total_images;


/*
 *	Messages List:
 */
extern "C" xsw_mesg_struct	*mesg_list;
extern "C" int			total_messages;


/*
 *	Universes List:
 */
extern "C" unvitem_struct	**univ_item;
extern "C" int			total_univ_items;


/*
 *	Ignored Objects List:
 */
extern "C" ignored_obj_struct	**ignored_obj_list;
extern "C" int			total_ignored_objs;


/* Bridge Window */
extern "C" xsw_bridge_win_struct	*xsw_bridge_win;

/* VSMenu */
extern "C" xsw_vsmenu_struct	*xsw_vsmenu;

/* Message Window */
extern "C" xsw_msg_win_struct	*xsw_msg_win;

/* Universe List Window */
extern "C" xsw_unvlist_win_struct	*xsw_unvlist_win;

/* Universe Properties Dialog */
extern "C" xsw_unvprop_dlg_struct	*xsw_unvprop_dlg;

/* Economy */
extern "C" xsw_eco_win_struct	*xsw_ecow;

/* StarChart */
extern "C" starchart_win_struct	*xsw_scht;


/* Options Window */
extern "C" xsw_options_win_struct	*xsw_optwin;

/* Keymap Window */
extern "C" xsw_keymap_win_struct	*xsw_keymap_win;

#ifdef JS_SUPPORT
/* Joystick Map Window */
extern "C" xsw_jsmap_win_struct		*xsw_jsmap_win;
#endif

/* Configure VSMenu Window */
extern "C" xsw_vsmenu_win_struct	*xsw_vsmenu_win;


/* Dialog */
extern "C" dialog_struct	*xsw_dlg;

/* Confirmation Dialog */
extern "C" cdlg_struct	*xsw_cdlg;

/* File Selector */
extern "C" fb_struct	*xsw_file_selector;


/*
 *    Program memory stat structure:
 */
typedef struct {

	/* Memory used */
	long		total,
			gui,
			sound,
			images,		/* Not counting imgref images */
			univ_entries,
			objects,
			imgrefs,
			ocsns,
			vs_labels,	/* Viewscreen labels */
			scanner_contacts;

} xsw_mem_stat_struct;


/*
 *	ImgRefs:
 */
extern "C" imgref_struct	**xsw_imgref;
extern "C" int		total_imgrefs;


/*
 *	SndRefs:
 */
extern "C" sndref_struct	**xsw_sndref;
extern "C" int		total_sndrefs;


/*
 *	Objects Database:
 */
extern "C" xsw_object_struct	**xsw_object;
extern "C" int			total_objects;

/*
 *	In Range Objects:
 *
 *	Contains a list of pointers to objects that are in scanner
 *	range.
 */
extern "C" xsw_object_struct	**inrange_xsw_object;
extern "C" int			total_inrange_objects;


/*
 *	Object Labels:
 *
 *	These label images are displayed next to objects on the
 *	viewscreen.
 */
typedef struct _xsw_vs_object_label_struct	vs_object_label_struct;

struct _xsw_vs_object_label_struct {

	image_t		*image;		/* Label's image */

	int		obj_num;
	xsw_object_struct	*obj;

};

extern "C" vs_object_label_struct	**vs_object_label;
extern "C" int				total_vs_object_labels;


#ifdef JS_SUPPORT

extern "C" xsw_jsmap_struct	**xsw_jsmap;
extern "C" int			total_jsmaps;

#endif	/* JS_SUPPORT */



/*
 *	Game Controller:
 */
extern "C" xsw_gctl_struct	*xsw_gctl;


/*
 *	Player Values:
 *
 *	Additional values for the player object not stored on the
 *	object structure. This is needed to conserve the
 *	xsw_object_struct structure size since only the player object
 *	needs these values.
 *
 *	Do not confuse this with the gctl_struct.
 */
typedef struct {

	/* Toggles weapons online/offline (safety lock) */
	char		weapons_online;

	/* Frequency and yield of weapon */
	float		weapon_freq,
			weapon_yield;	/* 0.0 to 1.0 */

	/* Direction to fire weapon (relative to vessel, in radians) */
	float		weapon_fire_heading,
			weapon_fire_pitch;

	time_t		auto_destruct_start_int,	/* Interval in seconds */
			auto_destruct_last_sec_left;	/* In systime seconds */

	/* Warning Indicators */
	char		warning_weapons_lock,	/* Someone locked on player */
			warning_incoming_fire;	/* Weapons fired at player */

} xsw_player_values_struct;
extern "C" xsw_player_values_struct	player_values;


/*
 *	Universe Legend:
 */
extern "C" sw_legend_struct	sw_legend;


/*
 *	Scanner Contact:
 *
 *	For keeping track of objects that are in scanner contact.
 */
typedef struct _scanner_contact_struct	scanner_contact_struct;
#define SCANNER_CONTACT(p)		((scanner_contact_struct *)(p))

struct _scanner_contact_struct {

	int		obj_num;

};

extern "C" scanner_contact_struct	**scanner_contact_list;
extern "C" int				total_scanner_contacts;


/*
 *	Automatic Network Interval Tuning:
 *
 *	Relies on information in loadstat.
 */
typedef struct _xsw_auto_interval_tune_struct	xsw_auto_interval_tune_struct;

#define AINT_DEF_TUNE_INT	1000

struct _xsw_auto_interval_tune_struct {

	bool_t		state;		/* True = automatic tuning is on */

	time_t		interval,	/* Retune interval in ms */
			next;		/* Next time to tune in ms */

};
extern "C" xsw_auto_interval_tune_struct	auto_interval_tune;


/*
 *	Server script upload structure:
 */
typedef struct {

	char		*filename;
	FILE		*fp;

	off_t		filepos;
	off_t		filesize;

	/* Arguments to substitute */
	char		**argv;
	int		argc;

} serv_script_struct;
extern "C" serv_script_struct **serv_script;
extern "C" int total_serv_scripts;


/* ******************************************************************* */


/* autointerval.cpp */
extern "C" void AutoIntervalTune(void);


/* cmd*.cpp */
extern "C" int CmdHandleInput(const char *cmd);

extern "C" int CmdAutoInterval(const char *arg);
extern "C" int CmdConnect(const char *arg);
extern "C" int CmdDebug(const char *arg);
extern "C" int CmdDisconnect(const char *arg);
extern "C" int CmdHelp(const char *arg);
extern "C" int CmdLog(const char *arg);
extern "C" int CmdLoginName(const char *arg);
extern "C" int CmdLoginPassword(const char *arg);
extern "C" int CmdMemory(const char *arg);
extern "C" int CmdNetInterval(const char *arg);
extern "C" int CmdRefresh(const char *arg);
extern "C" int CmdServScript(const char *arg);
extern "C" int CmdSet(const char *arg);
extern "C" int CmdSynctime(const char *arg);
extern "C" int CmdTest(const char *arg);
extern "C" int CmdVersion(const char *arg);


/* db.cpp */
extern "C" int DBIsObjectGarbage(int obj_num);

extern "C" int DBCreateObject(
	int imageset,
	int type,
	int owner,
	long sect_x, long sect_y, long sect_z,
	float x, float y, float z,
	float heading, float pitch, float bank
);
extern "C" int DBCreateExplicitObject(
	int obj_num,
	int imageset,
	int type,
	int owner,
	long sect_x, long sect_y, long sect_z,
	float x, float y, float z,
	float heading, float pitch, float bank
);
extern "C" void DBDeleteAllObjects(void);
extern "C" void DBRecycleObject(const int obj_num);

extern "C" void DBReclaim(
	const time_t cur_ms, const time_t cur_sec, const float tc
);


/* dbinrange.cpp */
extern "C" void DBInRangeUpdate(
	const int obj_num,
	const time_t cur_ms, const time_t cur_sec, const float tc
);
extern "C" int DBInRangeAdd(
	int ref_obj_num, int tar_obj_num, char check_range
);
extern "C" void DBInRangeDelete(xsw_object_struct *obj);
extern "C" void DBInRangeClear(void);


/* dbutil.cpp */
extern "C" int DBGetPlayerOwner(const int obj_num);
extern "C" int DBGetTopObjectNumber(void);

extern "C" int DBCreateObjectEconomyProduct(
	int obj_num,
	const char *product_name,
	int ocs_code,
	sw_credits_t sell_price,
	sw_credits_t buy_price,
	float product_amount,
	float product_max
);

extern "C" void DBObjectTractor(int obj_num, int tar_obj_num);
extern "C" void DBObjectUntractor(int obj_num, int tar_obj_num);

extern "C" int DBValidateObjectName(const char *name);
extern "C" int DBValidateObjectPassword(const char *password);

extern "C" float DBGetObjectVisibility(int obj_num);
extern "C" float DBGetObjectVisibilityPtr(xsw_object_struct *obj);

extern "C" float DBGetObjectEffectiveScannerRange(int obj_num);
extern "C" float DBGetObjectEffectiveScannerRangePtr(xsw_object_struct *obj);

extern "C" char DBIsObjectInEffectiveScannerRange(
	int obj_num, int tar_obj_num,
	float scanner_range
);
extern "C" char DBIsObjectInEffectiveScannerRangePtr(
	xsw_object_struct *obj, xsw_object_struct *tar_obj,
	float scanner_range
);

extern "C" int DBGetObjectNumByPtr(xsw_object_struct *obj);
extern "C" const char *DBGetFormalNameStr(const int obj_num);
extern "C" const char *DBGetObjectVectorName(const float theta);
extern "C" float DBGetObjectVisibility(const int obj_num);
extern "C" float DBGetObjectVisibilityPtr(xsw_object_struct *obj);

extern "C" void DBSetPlayerObject(const int obj_num);


/* In images.cpp */
extern "C" int ImgIsAllocated(int img_num);
extern "C" int ImgIsLoaded(int img_num);

extern "C" void ImgResize(
	int img_num, unsigned int width, unsigned int height
);
extern "C" int ImgCreate(int img_num);
extern "C" int ImgOpenFile(
	int img_num, const char *filename, bool_t load_pixmap
);
extern "C" int ImgOpenData(
	int img_num, const u_int8_t *data, bool_t load_pixmap
);
extern "C" void ImgUnload(int img_num);

extern "C" int ImgLoadAll(void *sw_ptr);
extern "C" void ImgUnloadAll(void);


/* imglabels.cpp */
extern "C" int ImgLabelIsAllocated(xsw_imglabel_struct *label);
extern "C" int ImgLabelIsLoaded(xsw_imglabel_struct *label);

extern "C" xsw_imglabel_struct *ImgLabelNew(void);
extern "C" void ImgLabelReset(xsw_imglabel_struct *label);
extern "C" void ImgLabelDelete(xsw_imglabel_struct *label);


/* log.cpp */
extern "C" void XSWLogFile(const char *path, const char *s);
extern "C" void XSWLog(const char *s);


/* main.cpp */
extern "C" win_t XSWGetWindowToplevel(void *win);

extern "C" mode_t XSWCurrentFileMode(void);
extern "C" const char *XSWCurrentDirectory(void);

extern "C" void XSWStartServer(const char *cmd);

extern "C" void XSWOpenOCSNs(const char *path);
extern "C" void XSWOpenImgRefs(const char *path);
extern "C" void XSWOpenSndRefs(const char *path);

extern "C" void XSWGetMemUsage(xsw_mem_stat_struct *buf);
extern "C" void XSWReclaimMem(
	bool_t verbose,
	const time_t cur_ms, const time_t cur_sec, const float tc
);

extern "C" int XSWManageGUI(
	void *data,
	const time_t cur_ms, const time_t cur_sec, const float tc
);
extern "C" int XSWManageSound(void *data);
extern "C" int XSWManageNet(void *data);
extern "C" void XSWResetTimmers(
	const time_t cur_ms, const time_t cur_sec, const float tc
);

extern "C" int XSWInit(int argc, char *argv[]);
extern "C" void XSWMainIteration(void *data);
extern "C" void XSWMain(void *data);
extern "C" void XSWMainPop(void *data);
extern "C" void XSWMainPopAll(void *data);
extern "C" void XSWShutdown(void);


/* rengine.cpp */
extern "C" int REngInit(void);
extern "C" void REngManage(
	xsw_object_struct *player_obj,
	const time_t cur_ms, const time_t cur_sec, const float tc
);
extern "C" void REngShutdown(void);


/* In scannercontacts.cpp */
extern "C" scanner_contact_struct *ScNew(void);
extern "C" void ScDelete(scanner_contact_struct *sc);

extern "C" int ScListFindByObject(
        scanner_contact_struct **list, const int total,
        xsw_object_struct *obj
);
extern "C" int ScListAddObject(
        scanner_contact_struct ***list, int *total,
        xsw_object_struct *obj
);
extern "C" void ScListDeleteByObject(
        scanner_contact_struct ***list, int *total,
        xsw_object_struct *obj
);
extern "C" void ScListClear(
	scanner_contact_struct **list, const int total
);
extern "C" void ScListReclaim(
	scanner_contact_struct ***list, int *total
);

extern "C" int ScHandleContacts(
	scanner_contact_struct ***list, int *total,
	const int obj_num
);


/* In serverscript.cpp */
extern "C" int ServScriptIsAllocated(int n);

extern "C" int ServScriptStart(
	const char *filename,
	int argc, char **argv
);
extern "C" void ServScriptDelete(int n);
extern "C" void ServScriptDeleteAll(void);
extern "C" void ServScriptReclaim(void);

extern "C" void ServScriptDoSend(serv_script_struct *ss);
extern "C" void ServScriptManage(void);

extern "C" void ServScriptMapPrompt(const char *path);


/* timming.cpp */
extern "C" time_t MilliTime(void);


/* vsdraw.cpp */
extern "C" void ScannerDraw(
	xsw_bridge_win_struct *bw,
	const int cam_obj_num,
	win_t w, shared_image_t *image,
	const int win_x, const int win_y,
	const float scanner_scale,
	const time_t cur_ms, const time_t cur_sec, const float tc
);
extern "C" void ScannerUpdateLabels(
	xsw_bridge_win_struct *bw, int obj_num
);

extern "C" void VSDrawViewScreen(xsw_bridge_win_struct *bw);

extern "C" void VSDrawUpdateWeaponLabel(
	image_t **image, pixmap_t pixmap
);
extern "C" void VSDrawUpdateNetstatsLabel(
	image_t **image, pixmap_t pixmap
);


/* vsevent.cpp */
extern "C" int ScannerButtonMatch(
	xsw_bridge_win_struct *bw,
	int x, int y,			/* In window coordinates */
	int start_obj_num
);

extern "C" void VSChangePage(
	xsw_bridge_win_struct *bw, page_struct *new_page
);
extern "C" int VSButtonMatch(
	xsw_bridge_win_struct *bw, event_t *event
);
extern "C" int VSManage(
	xsw_bridge_win_struct *bw, event_t *event
);
extern "C" void VSMap(xsw_bridge_win_struct *bw);
extern "C" void VSUnmap(xsw_bridge_win_struct *bw);
extern "C" void VSDestroy(xsw_bridge_win_struct *bw);


/* vslabels.cpp */
extern "C" int VSLabelIsAllocated(int n);
extern "C" int VSLabelIsLoaded(int n);
extern "C" int VSLabelGetByPointer(xsw_object_struct *obj);
extern "C" int VSLabelGetHighest(void);
extern "C" int VSLabelAdd(
	const char *text,
	const WColorStruct *c_fg,
	const WColorStruct *c_empire,
	font_t *font,
	int obj_num, xsw_object_struct *obj
);
extern "C" void VSLabelDelete(int n);
extern "C" void VSLabelDeleteByObjectPtr(xsw_object_struct *obj);
extern "C" void VSLabelDeleteAll(void);
extern "C" void VSLabelReclaimMemory(void);


/* xswops.cpp */
extern "C" int XSWConnect(const char *url);
extern "C" int XSWConnectLast(void);
extern "C" void XSWSendDisconnect(void);
extern "C" void XSWDisconnect(void);
extern "C" void XSWRefresh(
	const time_t cur_ms, const time_t cur_sec, const float tc
);
extern "C" void XSWObjectSectorChangedNotify(
	const int obj_num,
	const time_t cur_ms, const time_t cur_sec, const float tc
);
extern "C" void XSWDamageNotify(
        const int obj_num,
        const float prev_hp, const float hp,
        const float prev_power, const float power,
        const int shield_state
);
extern "C" void XSWHitNotify(
	const int src_obj_num,		/* Object that hit tar_obj_num */
	const int tar_obj_num,		/* Object that got hit */
	const int owner_obj_num,	/* Owner of src_obj_num */
	const float dmg_structure,
	const float dmg_shield,
	const float bearing		/* Target to source, in radians */
);
extern "C" void XSWDestroyNotify(
	const int src_obj_num,		/* Object that caused destruction */
	const int tar_obj_num,		/* Object that was destroyed */
	const int owner_obj_num,	/* Owner of src_obj_num */
	const int reason		/* One of SW_DESTROY_REASON_* */
);

extern "C" void XSWUpdateLoopSounds(void);
extern "C" void XSWUpdateBackgroundMusic(void);


/* xswprint.cpp */
extern "C" void XSWDialog(
	const char *title, int icon_img_code, const char *msg,
	win_t toplevel
);
extern "C" int XSWGetResponse(
	const char *title, int icon_img_code, const char *msg,
	unsigned int btn_flags, win_t toplevel
);
extern "C" void XSWPrint(const char *msg);
extern "C" void XSWPrintWarning(const char *msg);
extern "C" void XSWPrintError(const char *msg);
extern "C" void XSWPrintBold(const char *msg);
extern "C" void XSWPrintDebugStderr(int error_level);
extern "C" void XSWPrintHelpStdout(void);
extern "C" void XSWPrintVersionStdout(void);
extern "C" void XSWPrintHelp(void);

extern "C" dialog_struct *XSWDialogNew(void);
extern "C" void XSWDialogDelete(dialog_struct *d);

extern "C" cdlg_struct *XSWConfirmationDialogNew(void);
extern "C" void XSWConfirmationDialogDelete(cdlg_struct *d);


/* xswselectfile.cpp */
extern "C" bool_t XSWSelectFile(
	const char *title,
	const char *ok_label, const char *cancel_label,
	const char *path, char ***paths_rtn, int *npaths_rtn,
	win_t toplevel
);

extern "C" fb_struct *XSWFileSelectorNew(void);
extern "C" void XSWFileSelectorDelete(fb_struct *file_sel);


#endif	/* XSW_H */