/* Copyright (C) 2002 Damir Zucic */

/*=============================================================================

				half_stick.c

Purpose:
	Draw half of a stick.

Input:
	(1) Pointer to Aux2S structure, which contains required data.
	(2) Bond index.

Output:
	(1) Half of a stick drawn.
	(2) Return value.

Return value:
	(1) Positive on success.
	(2) Negative on failure.

Notes:
	(1) The stick is drawn circle by circle.  Only  one half  of each
	    circle is drawn,  because it is assumed  that another side of
	    the circle is invisible to the observer. The rear side of the
	    stick is not drawn!

	(2) Indentation is exceptionally 4 spaces.

=============================================================================*/

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xos.h>
#include <X11/Xatom.h>

#include "defines.h"
#include "typedefs.h"

/*======function prototypes:=================================================*/

double		AbsoluteValue_ (VectorS *);
double		ScalarProduct_ (VectorS *, VectorS *);
void		VectorProduct_ (VectorS *, VectorS *, VectorS *);
unsigned long	SpacefillColor_ (AtomS *, GUIS *, double);
unsigned long	Sp2Color_ (AtomS *, GUIS *, double);
unsigned long	WeightColors_ (unsigned long, unsigned long, double, GUIS *);

/*======draw half of a stick:================================================*/

int HalfStick_ (Aux2S *aux2SP, int bondI)
{
static int		imageI;
static int		image_center_screen_x, image_center_screen_y;
static int		left_edge, right_edge, bottom_edge;
static double		screen_atomic_z;
static double		nominator_x, nominator_y;
static RawAtomS		*raw_atom1SP, *raw_atom2SP;
static double		user_screen_atomic_distance;
static double		atomic_to_screen_scale;
static double		user_atomic_position;
static VectorS		*light_vectorSP;
static int		atom1_styleI, atom2_styleI;
double			r1, r2;
static AtomS		*far_atomSP;
static double		far_radius, far_z;
static double		denominator, reciprocal_denominator;
static double		pixel_atomic_size;
double			d0, u0, u0min, u0max, stick_radius;
double			delta_x, delta_y, delta_z;
VectorS			start_vectorS, end_vectorS;
static VectorS		unit_vector0S, unit_vector1S, unit_vector2S;
static VectorS		aux_vector0S, aux_vector1S;
static double		abs_value, reciprocal_abs_value;
static double		linear_increment, double_linear_increment;
static double		angular_increment;
static double		reciprocal_delta_u0;
static double		scale_factor;
static double		circle_x0, circle_y0, circle_z0;
static double		projection_factor_x, projection_factor_y;
static double		rationalized_x, rationalized_y;
static int		circle_screen_x0, circle_screen_y0;
double			angle, cos_angle, sin_angle;
static double		surface_offset_1, surface_offset_2;
static double		surface_offset_x, surface_offset_y, surface_offset_z;
static double		surface_x, surface_y, surface_z;
static int		surface_screen_x, surface_screen_y;
static size_t		pixelI;
static NearestAtomS	*curr_pixelSP;
static int		drawF;
static double		shifted_z;
static VectorS		normal_vectorS;
static double		normal_abs_value;
static double		scalar_product;
static double		cos_light_angle;
static unsigned long	colorID;
static int		localI;
static int		pixel_screen_x, pixel_screen_y;
static int		pixel_shift_xA[4] = { 0,  1,  0,  1};
static int		pixel_shift_yA[4] = { 0,  0,  1,  1};

/*---------------------------------------------------------------------------*/

/* Copy some data and prepare some parameters. */

/* Image index: */
imageI = aux2SP->imageI;

/* Image center, in screen units: */
image_center_screen_x = aux2SP->configSP->center_screen_x[imageI];
image_center_screen_y = aux2SP->configSP->center_screen_y;

/* Bounding rectangle: */
left_edge   = aux2SP->configSP->image_screen_x0[imageI];
right_edge  = aux2SP->configSP->image_screen_x1[imageI];
bottom_edge = (int) aux2SP->guiSP->main_win_free_area_height;

/* Screen position, in atomic units: */
screen_atomic_z = aux2SP->configSP->screen_atomic_z;

/* Prepare two factors which are required for scaling: */
nominator_x = aux2SP->configSP->user_screen_atomic_distance *
	      aux2SP->configSP->atomic_to_screen_scale_x;
nominator_y = aux2SP->configSP->user_screen_atomic_distance *
	      aux2SP->configSP->atomic_to_screen_scale_y;

/* Pointers to raw atomic data: */
raw_atom1SP = &aux2SP->atom1SP->raw_atomS;
raw_atom2SP = &aux2SP->atom2SP->raw_atomS;

/* Both atoms should be on the opposite side of */
/* the screen,  with  respect to  the observer: */
if (raw_atom1SP->z[imageI] < screen_atomic_z) return -1;
if (raw_atom2SP->z[imageI] < screen_atomic_z) return -2;

/* Distance between user and screen, in atomic units: */
user_screen_atomic_distance = aux2SP->configSP->user_screen_atomic_distance;

/* The scale factor  required for conversion from atomic to */
/* screen units. There are originally two such factors. Use */
/* the  larger one  here  because  it goes  to denominator. */
if (aux2SP->configSP->atomic_to_screen_scale_x >
    aux2SP->configSP->atomic_to_screen_scale_y)
    {
    atomic_to_screen_scale = aux2SP->configSP->atomic_to_screen_scale_x;
    }
else atomic_to_screen_scale = aux2SP->configSP->atomic_to_screen_scale_y;

/* User position in atomic units: */
user_atomic_position = aux2SP->configSP->user_atomic_position;

/* Pointer to the light source vector: */
light_vectorSP = &aux2SP->configSP->light_vectorS;

/* Copy the drawing style of the first atom: */
atom1_styleI = raw_atom1SP->atom_styleI;

/* Copy the drawing style of the second atom: */
atom2_styleI = raw_atom2SP->atom_styleI;

/* Copy and check the bond length: */
d0 = aux2SP->curr_bondSP->bond_length;
if (d0 <= 0.001) return -9;

/* The range of the variable u0, which scans half of the bond: */
u0min = 0.0;
u0max = 0.5 * d0;

/* Stick radius: */
stick_radius = aux2SP->stick_radius;

/*---------------------------------------------------------------------------*/

/* Copy and check the atomic radii. Two atoms forming the bond */
/* should be drawn using some sort of spacefill drawing style. */

/* Radius of the first atom (the current bond belongs to this atom): */
if ((atom1_styleI == SPACEFILL) || (atom1_styleI == SPACEFILL2))
    {
    r1 = raw_atom1SP->radius;
    }
else if ((atom1_styleI == COVALENT) || (atom1_styleI == COVALENT2))
    {
    r1 = raw_atom1SP->covalent_radius;
    }
else if ((atom1_styleI == SMALL_ATOM) || (atom1_styleI == SMALL_ATOM2))
    {
    r1 = raw_atom1SP->small_radius;
    }
else if ((atom1_styleI == BIG_SPHERE) || (atom1_styleI == BIG_SPHERE2))
    {
    r1 = raw_atom1SP->van_der_Waals_radius;
    }
else if ((atom1_styleI == BALL) || (atom1_styleI == BALL2))
    {
    r1 = raw_atom1SP->ball_radius;
    }
else return -3;

/* Radius of the second atom (the bond partner of the first atom): */
if ((atom2_styleI == SPACEFILL) || (atom2_styleI == SPACEFILL2))
    {
    r2 = raw_atom2SP->radius;
    }
else if ((atom2_styleI == COVALENT) || (atom2_styleI == COVALENT2))
    {
    r2 = raw_atom2SP->covalent_radius;
    }
else if ((atom2_styleI == SMALL_ATOM) || (atom2_styleI == SMALL_ATOM2))
    {
    r2 = raw_atom2SP->small_radius;
    }
else if ((atom2_styleI == BIG_SPHERE) || (atom2_styleI == BIG_SPHERE2))
    {
    r2 = raw_atom2SP->van_der_Waals_radius;
    }
else if ((atom2_styleI == BALL) || (atom2_styleI == BALL2))
    {
    r2 = raw_atom2SP->ball_radius;
    }
else return -4;

/*---------------------------------------------------------------------------*/

/* Now estimate the size  (in atomic units) of the pixel which */
/* represents the  most distant point.  This point  belongs to */
/* the atom  (i.e. sphere) which is farther from the observer. */
/* The atom with higher z value is treated as the farther one. */

/* Find which atom has higher z value (in most cases, but */
/* not always,  this atom is farther  from the observer): */
if (raw_atom2SP->z[imageI] > raw_atom1SP->z[imageI])
    {
    far_atomSP = aux2SP->atom2SP;
    far_radius = r2;
    }
else
    {
    far_atomSP = aux2SP->atom1SP;
    far_radius = r1;
    }

/* Find the z coordinate of the most distant point: */
far_z = far_atomSP->raw_atomS.z[imageI] + far_radius;

/* Check is this point on  the opposite side of */
/* the screen,  with  respect to  the observer. */
/* If it is, the entire bond will be invisible. */
if (far_z < screen_atomic_z) return -6;

/* Prepare denominator  required to calculate */
/* the atomic size of the most distant pixel: */
denominator = user_screen_atomic_distance * atomic_to_screen_scale;
if (denominator <= 0.001) return -7;

/* The size of the most distant pixel in atomic units: */
pixel_atomic_size = 1.0 * (far_z - user_atomic_position) / denominator;

/*---------------------------------------------------------------------------*/

/* Find the start point and the end point, which define the bond axis. */

/* Distance between two atoms which form the bond (three components): */
delta_x = raw_atom2SP->x[imageI] - raw_atom1SP->x[imageI];
delta_y = raw_atom2SP->y         - raw_atom1SP->y;
delta_z = raw_atom2SP->z[imageI] - raw_atom1SP->z[imageI];

/* Prepare the start point: */
start_vectorS.x = raw_atom1SP->x[imageI];
start_vectorS.y = raw_atom1SP->y;
start_vectorS.z = raw_atom1SP->z[imageI];

/* Prepare the end point: */
end_vectorS.x = 0.5 * (raw_atom1SP->x[imageI] + raw_atom2SP->x[imageI]);
end_vectorS.y = 0.5 * (raw_atom1SP->y         + raw_atom2SP->y);
end_vectorS.z = 0.5 * (raw_atom1SP->z[imageI] + raw_atom2SP->z[imageI]);

/* Both points  should be on  the opposite side */
/* of the screen, with respect to the observer: */
if (start_vectorS.z < screen_atomic_z) return -13;
if (  end_vectorS.z < screen_atomic_z) return -14;

/*---------------------------------------------------------------------------*/

/* Prepare  three unit vectors,  required for angular scan.  These */
/* three vectors define the plane, required to define the  circle. */

/* Prepare the unit vector pointing from the start point to the end point: */
unit_vector0S.x = end_vectorS.x - start_vectorS.x;
unit_vector0S.y = end_vectorS.y - start_vectorS.y;
unit_vector0S.z = end_vectorS.z - start_vectorS.z;
abs_value = AbsoluteValue_ (&unit_vector0S);
if (abs_value <= 0.001) return -15;
reciprocal_abs_value = 1.0 / abs_value;
unit_vector0S.x *= reciprocal_abs_value;
unit_vector0S.y *= reciprocal_abs_value;
unit_vector0S.z *= reciprocal_abs_value;

/* Prepare the unit vector parallel to z axis: */
aux_vector0S.x = 0.0;
aux_vector0S.y = 0.0;
aux_vector0S.z = 1.0;

/* Check the absolute value of  the vector product between  unit_vector0S */
/* and aux_vector0S; if the absolute value is too small, use aux_vector0S */
/* perpendicular to z axis  (the vector parallel to x axis will be good): */
VectorProduct_ (&aux_vector1S, &unit_vector0S, &aux_vector0S);
abs_value = AbsoluteValue_ (&aux_vector1S);
if (abs_value < 0.001)
    {
    aux_vector0S.x = 1.0;
    aux_vector0S.y = 0.0;
    aux_vector0S.z = 0.0;
    }

/* Prepare the unit vector perpendicular to unit_vector0S */
/* and to z axis.  This is  the first vector  required to */
/* define the plane,  which is used to define the circle. */
VectorProduct_ (&unit_vector1S, &unit_vector0S, &aux_vector0S);
abs_value = AbsoluteValue_ (&unit_vector1S);
reciprocal_abs_value = 1.0 / abs_value;
unit_vector1S.x *= reciprocal_abs_value;
unit_vector1S.y *= reciprocal_abs_value;
unit_vector1S.z *= reciprocal_abs_value;

/* Prepare the second unit vector required to define the plane: */
VectorProduct_ (&unit_vector2S, &unit_vector0S, &unit_vector1S);

/*---------------------------------------------------------------------------*/

/* Prepare  the linear increment.  This variable  should be used as */
/* the maximal translational step, to prevent holes in the surface. */

/* The linear increment should be smaller than pixel size: */
linear_increment = 0.70 * pixel_atomic_size;
double_linear_increment = 2.0 * linear_increment;

/* Check the distance between the start point and end point. */
/* The curved surface will be drawn only if this distance is */
/* at least  three times larger  than  the linear increment. */
if (u0max - u0min < 3.0 * linear_increment) return -16;

/*---------------------------------------------------------------------------*/

/* Prepare the angular increment. This variable should be used as */
/* the maximal  angular step,  to prevent holes  in  the surface. */

/* Calculate the angular increment, in radians: */
if (stick_radius <= 0.001) return -17;
angular_increment = 0.70 * linear_increment / stick_radius;

/* Be sure that the angular increment is not larger than PI/4: */
if (angular_increment > 0.78539816) angular_increment = 0.78539816;

/*---------------------------------------------------------------------------*/

/* Draw half of the bond. */

/* Prepare some factors which are used to */
/* reduce the number  of multiplications: */
delta_x = end_vectorS.x - start_vectorS.x;
delta_y = end_vectorS.y - start_vectorS.y;
delta_z = end_vectorS.z - start_vectorS.z;
reciprocal_delta_u0 = 1.0 / (u0max - u0min);

/* Loop which scans the variable u0 (see nice_bonds.c for definition): */
for (u0 = u0min; u0 <= u0max; u0 += linear_increment)
    {

    /* Calculate the position of the point on the axis, */
    /* defined by u0.  This point is the circle center. */
    scale_factor = (u0 - u0min) * reciprocal_delta_u0;
    circle_x0 = start_vectorS.x + delta_x * scale_factor;
    circle_y0 = start_vectorS.y + delta_y * scale_factor;
    circle_z0 = start_vectorS.z + delta_z * scale_factor;

    /* Prepare  the reciprocal denominator,  used to */
    /* reduce the number of mathematical operations: */
    denominator = circle_z0 - user_atomic_position;
    if (denominator <= 0.001) continue;
    reciprocal_denominator = 1.0 / denominator;

    /* Prepare two factors required for projection: */
    projection_factor_x = nominator_x * reciprocal_denominator;
    projection_factor_y = nominator_y * reciprocal_denominator;

    /* Project the position of the circle center. Note that */
    /* two different  projection  factors  are  used  here! */
    rationalized_x = circle_x0 * projection_factor_x;
    rationalized_y = circle_y0 * projection_factor_y;
    circle_screen_x0 = (int) rationalized_x + image_center_screen_x;
    circle_screen_y0 = (int) rationalized_y + image_center_screen_y;

    /* The angular loop, required to create the rotational surface: */
    for (angle = 0.0; angle <= 6.2831853; angle += angular_increment)
	{
	/* Cosine and sine of the angle: */
	cos_angle = cos (angle);
	sin_angle = sin (angle);

	/* Relative  position  of  the  point  at the */
	/* surface with respect to the circle center: */
	surface_offset_1 = stick_radius * cos_angle;
	surface_offset_2 = stick_radius * sin_angle;
	surface_offset_x = surface_offset_1 * unit_vector1S.x +
			   surface_offset_2 * unit_vector2S.x;
	surface_offset_y = surface_offset_1 * unit_vector1S.y +
			   surface_offset_2 * unit_vector2S.y;
	surface_offset_z = surface_offset_1 * unit_vector1S.z +
			   surface_offset_2 * unit_vector2S.z;

	/* Calculate the coordinates of the point at bond surface: */
	surface_x = circle_x0 + surface_offset_x;
	surface_y = circle_y0 + surface_offset_y;
	surface_z = circle_z0 + surface_offset_z;

	/* The vector from the point at the surface */
	/* to  the center of  the spherical  probe: */
	normal_vectorS.x = surface_offset_x;
	normal_vectorS.y = surface_offset_y;
	normal_vectorS.z = surface_offset_z;

	/* If this vector has a positive  z component, */
	/* do not draw this point because it is not on */
	/* the side which is visible for the observer: */
	if (normal_vectorS.z >= 0.0) continue;

	/* Calculate the absolute value of this vector: */
	normal_abs_value = AbsoluteValue_ (&normal_vectorS);

	/* Project the relative position of surface point. Note */
	/* that  projection_factor_x is used in both equations! */
	rationalized_x = surface_offset_x * projection_factor_x;
	rationalized_y = surface_offset_y * projection_factor_x;

	/* Combine the projection of  the circle */
	/* center and projection of the relative */
	/* position of the point at the surface: */
	surface_screen_x = (int) rationalized_x + circle_screen_x0;
	surface_screen_y = (int) rationalized_y + circle_screen_y0;

	/* Prepare the color. */

	/* The scalar product between the normal */
	/* vector and  the light source  vector: */
	scalar_product = ScalarProduct_ (&normal_vectorS, light_vectorSP);

	/* Cosine of  the angle between  the normal */
	/* vector and the light source unit vector: */
	if (normal_abs_value <= 0.001) cos_light_angle = 0.0;
	else cos_light_angle = scalar_product / normal_abs_value;

	/* Prepare color: */
	switch (atom1_styleI)
	    {
	    case SPACEFILL:
	    case COVALENT:
	    case SMALL_ATOM:
	    case BIG_SPHERE:
	    case BALL:
		colorID = SpacefillColor_ (aux2SP->atom1SP, aux2SP->guiSP,
					   cos_light_angle);
		break;

	    case SPACEFILL2:
	    case COVALENT2:
	    case SMALL_ATOM2:
	    case BIG_SPHERE2:
	    case BALL2:
		colorID = Sp2Color_ (aux2SP->atom1SP, aux2SP->guiSP,
				     cos_light_angle);
		break;

	    default:
		colorID = aux2SP->guiSP->white_colorID;
	    }

	/* Set color to GC: */
	XSetForeground (aux2SP->guiSP->displaySP,
			aux2SP->guiSP->theGCA[0],
			colorID);

	/* Draw four pixels: */
	for (localI = 0; localI < 4; localI++)
	    {
	    /* Prepare and check the pixel position: */
	    pixel_screen_x = surface_screen_x + pixel_shift_xA[localI];
	    pixel_screen_y = surface_screen_y + pixel_shift_yA[localI];
	    if (pixel_screen_x < 0)            continue;
	    if (pixel_screen_x < left_edge)    continue;
	    if (pixel_screen_x >= right_edge)  continue;
	    if (pixel_screen_y < 0)            continue;
	    if (pixel_screen_y >= bottom_edge) continue;

	    /* Prepare and check the index for the */
	    /* array of  NearestAtomS  structures: */
	    pixelI = aux2SP->guiSP->main_win_free_area_width *
		     pixel_screen_y + pixel_screen_x;
	    if (pixelI >= aux2SP->pixelsN) continue;

	    /* Pointer to NearestAtomS struct. */
	    /* assigned to  the current pixel: */
	    curr_pixelSP = aux2SP->nearest_atomSP + pixelI;

	    /*------------------------------------------------------------*/
	    /* There are three cases when this pixel should be drawn:     */
	    /* (1) Nothing was drawn to this pixel in this drawing step.  */
	    /* (2) Drawing was done  but the point at the bond surface is */
	    /*     closer to  the observer  than  the point drawn before. */
	    /* (3) Drawing was done  and the point at the bond surface is */
	    /*     more distant than the point drawn before. However, the */
	    /*     pixel belongs  to the atom  to which this bond belongs */
	    /*     and the  z coordinate of the point at the bond surface */
	    /*     is just slightly larger than the stored z value.       */
	    /*------------------------------------------------------------*/

	    /* Assume initially that drawing is not necessary: */
	    drawF = 0;

	    /* Check for the cases when drawing is necessary: */
	    do
		{
		/* Case (1) - no drawing was done before: */
		if (aux2SP->refreshI != curr_pixelSP->last_refreshI)
		    {
		    drawF = 1;
		    break;
		    }

		/* If this point is reached, drawing was done before. */

		/* Case (2): drawing was done before, but the point at the */
		/* bond surface  is closer  than  the point  drawn before. */
		if (surface_z < curr_pixelSP->z)
		    {
		    drawF = 1;
		    break;
		    }

		/* Now check the conditions for the case (3): */

		/* The pixel should belong to the surface of the atom: */
		if (curr_pixelSP->bondI != -1) break;

		/* The pixel  should belong  to the */
		/* same atom and macromol. complex: */
		if (curr_pixelSP->mol_complexI != aux2SP->mol_complexI) break;
		if (curr_pixelSP->atomI != aux2SP->atomI) break;

		/* If z is too large, no drawing will be done: */
		shifted_z = curr_pixelSP->z + 2.0 * pixel_atomic_size;
		if (surface_z > shifted_z) break;

		/* Case (3): all conditions were satisfied. */
		drawF = 1;

		/* End of inner single pass loop: */
		} while (0);

	    /* Check is drawing necessary at all: */
	    if (drawF == 0) continue;

	    /* Draw the current pixel: */
	    XDrawPoint (aux2SP->guiSP->displaySP,
			aux2SP->guiSP->main_hidden_pixmapID,
			aux2SP->guiSP->theGCA[0],
			pixel_screen_x, pixel_screen_y);

	    /* Refresh the NearestAtomS structure */
	    /* associated with the current pixel: */
	    curr_pixelSP->styleI = atom1_styleI;
	    curr_pixelSP->last_refreshI = aux2SP->refreshI;
	    curr_pixelSP->mol_complexI = aux2SP->mol_complexI;
	    curr_pixelSP->atomI = aux2SP->atomI;
	    curr_pixelSP->bondI = bondI;
	    curr_pixelSP->z = surface_z;
	    curr_pixelSP->colorID = colorID;
	    }
	}
    }

/*---------------------------------------------------------------------------*/

/* If this point is reached, the entire bond was drawn: */
return 1;
}

/*===========================================================================*/


