Arc Ball code

I need a hand with my modified arc ball code. It just does’nt work as it should. I get seg error when running on Linux. Its not all the time, I cant put my finger on it:

I have included three files.

Any ideas?

</font><blockquote><font size=“1” face=“Verdana, Arial”>code:</font><hr /><pre style=“font-size:x-small; font-family: monospace;”>/** KempoApi: The Turloc Toolkit ***************************/
/
* * /
/
** ** Filename: ArcBall.cpp /
/
** Version: Common /
/
** /
/
/
/
Arcball class for mouse manipulation. /
/
/
/
/
/
/
/
/
/
© 1999-2003 Tatewake.com /
/
History: /
/
08/17/2003 - (TJG) - Creation /
/
09/23/2003 - (TJG) - Bug fix and optimization /
/
09/25/2003 - (TJG) - Version for NeHe Basecode users /
/
**/
/*************************************************************/

#include <GL/gl.h> // Header File For The OpenGL32 Library
#include <GL/glu.h> // Header File For The GLu32 Library
#include <stdio.h>

#include “math.h” // Needed for sqrtf

#include “ArcBall.h” // ArcBall header

//Arcball sphere constants:
//Diameter is 2.0f
//Radius is 1.0f
//Radius squared is 1.0f

void ArcBall_t::_mapToSphere(const Point2fT* NewPt, Vector3fT* NewVec) const
{
Point2fT TempPt;
GLfloat length;

//Copy paramter into temp point
TempPt = *NewPt;

//Adjust point coords and scale down to range of [-1 ... 1]
TempPt.s.X  =        (TempPt.s.X * this-&gt;AdjustWidth)  - 1.0f;
TempPt.s.Y  = 1.0f - (TempPt.s.Y * this-&gt;AdjustHeight);

//Compute the square of the length of the vector to the point from the center
length      = (TempPt.s.X * TempPt.s.X) + (TempPt.s.Y * TempPt.s.Y);

//If the point is mapped outside of the sphere... (length &gt; radius squared)
if (length &gt; 1.0f)
{
    GLfloat norm;

    //Compute a normalizing factor (radius / sqrt(length))
    norm    = 1.0f / FuncSqrt(length);

    //Return the "normalized" vector, a point on the sphere
    NewVec-&gt;s.X = TempPt.s.X * norm;
    NewVec-&gt;s.Y = TempPt.s.Y * norm;
    NewVec-&gt;s.Z = 0.0f;
}
else    //Else it's on the inside
{
    //Return a vector to a point mapped inside the sphere sqrt(radius squared - length)
    NewVec-&gt;s.X = TempPt.s.X;
    NewVec-&gt;s.Y = TempPt.s.Y;
    NewVec-&gt;s.Z = FuncSqrt(1.0f - length);
}

}

//Create/Destroy
ArcBall_t::ArcBall_t(GLfloat NewWidth, GLfloat NewHeight)
{
//Clear initial values
this->StVec.s.X =
this->StVec.s.Y =
this->StVec.s.Z =

this-&gt;EnVec.s.X     =
this-&gt;EnVec.s.Y     = 
this-&gt;EnVec.s.Z     = 0.0f;

//Set initial bounds
this-&gt;setBounds(NewWidth, NewHeight);

}

//Mouse down
void ArcBall_t::click(const Point2fT* NewPt)
{
//Map the point to the sphere
this->_mapToSphere(NewPt, &this->StVec);
}

//Mouse drag, calculate rotation
void ArcBall_t::drag(const Point2fT* NewPt, Quat4fT* NewRot)
{
//Map the point to the sphere
this->_mapToSphere(NewPt, &this->EnVec);

//Return the quaternion equivalent to the rotation
if (NewRot)
{
    Vector3fT  Perp;

    //Compute the vector perpendicular to the begin and end vectors
    Vector3fCross(&Perp, &this-&gt;StVec, &this-&gt;EnVec);

    //Compute the length of the perpendicular vector
    if (Vector3fLength(&Perp) &gt; Epsilon)    //if its non-zero
    {
        //We're ok, so return the perpendicular vector as the transform after all
        NewRot-&gt;s.X = Perp.s.X;
        NewRot-&gt;s.Y = Perp.s.Y;
        NewRot-&gt;s.Z = Perp.s.Z;
        //In the quaternion values, w is cosine (theta / 2), where theta is rotation angle
        NewRot-&gt;s.W= Vector3fDot(&this-&gt;StVec, &this-&gt;EnVec);
    }
    else                                    //if its zero
    {
        //The begin and end vectors coincide, so return an identity transform
        NewRot-&gt;s.X = 
        NewRot-&gt;s.Y = 
        NewRot-&gt;s.Z = 
        NewRot-&gt;s.W = 0.0f;
    }
}

}

#include <GL/gl.h> // Header File For The OpenGL32 Library
#include <GL/glu.h> // Header File For The GLu32 Library
#include <GL/glx.h>
#include <X11/extensions/xf86vmode.h>
#include <X11/keysym.h>

#include “NeHeGL.h” // Header File For NeHeGL

#include “ReadFile.h”
#include “math.h” // NEW: Needed For Sqrtf
#include “ArcBall.h”
#include “gd.h” // NEW: ArcBall Header

#define LipidTotal 1000

#ifndef CDS_FULLSCREEN // CDS_FULLSCREEN Is Not Defined By Some
#define CDS_FULLSCREEN 4 // Compilers. By Defining It This Way,
#endif // We Can Avoid Errors

double arr_lipids[LipidTotal][3][3];
double scalefactor = 3.0;
double sigma = 1.0;
int MCFrame = 1000;

//double *scalefactor;
//double *sigma;
//int *MCFrame;
double Xbox;
double Ybox;
double Zbox;

GL_Window* g_window;
Keys* g_keys;

// User Defined Variables
GLUquadricObj *quadratic; // Used For Our Quadric

const float PI2 = 2.0*3.1415926535f; // PI Squared

Matrix4fT Transform = { 1.0f, 0.0f, 0.0f, 0.0f, // NEW: Final Transform
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f };

Matrix3fT LastRot = { 1.0f, 0.0f, 0.0f, // NEW: Last Rotation
0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 1.0f };

Matrix3fT ThisRot = { 1.0f, 0.0f, 0.0f, // NEW: This Rotation
0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 1.0f };

ArcBallT ArcBall(640.0f, 480.0f); // NEW: ArcBall Instance
Point2fT MousePt; // NEW: Current Mouse Point
bool isClicked = false; // NEW: Clicking The Mouse?
bool isRClicked = false; // NEW: Clicking The Right Mouse Button?
bool isDragging = false; // NEW: Dragging The Mouse?

// Local Variables

// End Local Variables

void saveimage(int width, int height, const char filename)
{
unsigned char buffer = new unsigned char[widthheight
3];
glReadPixels(0,0,width,height,GL_RGB,GL_UNSIGNED_BYTE,buffer);

gdImagePtr mypixels;
mypixels = gdImageCreateTrueColor(width, height);
for (int yctr=0; yctr &lt; height; yctr++)
for (int xctr=0; xctr &lt; width; xctr++)
{
    int color = gdTrueColor(buffer[yctr*width*3+xctr*3], buffer[yctr*width*3+xctr*3+1], buffer[yctr*width*3+xctr*3+2]);
    gdImageSetPixel(mypixels, xctr, yctr, color);
}

FILE *pngout;
pngout = fopen(filename, "wb");
gdImagePng(mypixels, pngout);
fclose(pngout);
gdImageDestroy(mypixels);
delete[] buffer;

}

void SaveAnImage(void)
{

int color;
int yctr;
int xctr;
FILE *pngout;
gdImagePtr mypixels;
unsigned char *buffer = new unsigned char[256*256*3];
mypixels = gdImageCreateTrueColor(1024, 768);
//mypixels = gdImageCreate(1024, 768);
//mypixels = gdImageCreateTrueColor(1024, 768);

glReadPixels(0,0,1024,768,GL_RGB,GL_UNSIGNED_BYTE,buffer);
//printf("read pixels

");

for (yctr=0;yctr&lt;768;yctr++)
{
	for (xctr=0;xctr&lt;1024;xctr++)
	{
		color = gdTrueColor(buffer[yctr*1024*3+xctr*3], buffer[yctr*1024*3+xctr*3+1], buffer[yctr*1024*3+xctr*3+2]);
		gdImageSetPixel(mypixels, xctr, yctr, color);
	
	
	}
	
}

printf("creating file

");
pngout = fopen(“123.png”, “wb”);
printf("opened file
");

gdImagePng(mypixels, pngout);
fclose(pngout);	
delete pngout;
printf("closed file

");

gdImageDestroy(mypixels);
delete[] buffer;
//delete[] mypixels;

}

bool Initialize (GL_Window* window, Keys* keys) // Any GL Init Code & User Initialiazation Goes Here
{

GetArray(arr_lipids,LipidTotal,MCFrame,Xbox,Ybox,Zbox);
Normalise(arr_lipids,LipidTotal,Xbox,Ybox,Zbox,scalefactor);
printf("Normalised is done

");
g_window = window;
g_keys = keys;

// Start Of User Initialization
isClicked   = false;								            // NEW: Clicking The Mouse?
isDragging  = false;							                // NEW: Dragging The Mouse?

glClearColor (0.0f, 0.0f, 0.0f, 0.5f);							// Black Background
glClearDepth (1.0f);											// Depth Buffer Setup
glDepthFunc (GL_LEQUAL);										// The Type Of Depth Testing (Less Or Equal)
glEnable (GL_DEPTH_TEST);										// Enable Depth Testing
glShadeModel (GL_FLAT);											// Select Flat Shading (Nice Definition Of Objects)
glHint (GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);				// Set Perspective Calculations To Most Accurate

quadratic=gluNewQuadric();										// Create A Pointer To The Quadric Object
gluQuadricNormals(quadratic, GLU_SMOOTH);						// Create Smooth Normals
gluQuadricTexture(quadratic, GL_TRUE);							// Create Texture Coords

glEnable(GL_LIGHT0);											// Enable Default Light
glEnable(GL_LIGHTING);											// Enable Lighting

glEnable(GL_COLOR_MATERIAL);									// Enable Color Material

printf("End of Init

");
return true; // Return true (Initialization Successful)
}

void Deinitialize (void) // Any User DeInitialization Goes Here
{

gluDeleteQuadric(quadratic);

}

void Update (long milliseconds) // Perform Motion Updates Here
{
if (isRClicked) // If Right Mouse Clicked, Reset All Rotations
{
Matrix3fSetIdentity(&LastRot); // Reset Rotation
Matrix3fSetIdentity(&ThisRot); // Reset Rotation
Matrix4fSetRotationFromMatrix3f(&Transform, &ThisRot); // Reset Rotation
}

if (!isDragging)												// Not Dragging
{
    if (isClicked)												// First Click
    {
		isDragging = true;										// Prepare For Dragging
		LastRot = ThisRot;										// Set Last Static Rotation To Last Dynamic One
		ArcBall.click(&MousePt);								// Update Start Vector And Prepare For Dragging
    }
}
else
{
    if (isClicked)												// Still Clicked, So Still Dragging
    {
        Quat4fT     ThisQuat;

        ArcBall.drag(&MousePt, &ThisQuat);						// Update End Vector And Get Rotation As Quaternion
        Matrix3fSetRotationFromQuat4f(&ThisRot, &ThisQuat);		// Convert Quaternion Into Matrix3fT
        Matrix3fMulMatrix3f(&ThisRot, &LastRot);				// Accumulate Last Rotation Into This One
        Matrix4fSetRotationFromMatrix3f(&Transform, &ThisRot);	// Set Our Final Transform's Rotation From This One
    }
    else														// No Longer Dragging
        isDragging = false;
}

}

void Torus(float MinorRadius, float MajorRadius) // Draw A Torus With Normals
{
int i, j;
glBegin( GL_TRIANGLE_STRIP ); // Start A Triangle Strip
for (i=0; i<20; i++ ) // Stacks
{
for (j=-1; j<20; j++) // Slices
{
float wrapFrac = (j%20)/(float)20;
float phi = PI2*wrapFrac;
float sinphi = float(sin(phi));
float cosphi = float(cos(phi));

			float r = MajorRadius + MinorRadius*cosphi;

			glNormal3f(float(sin(PI2*(i%20+wrapFrac)/(float)20))*cosphi, sinphi, float(cos(PI2*(i%20+wrapFrac)/(float)20))*cosphi);
			glVertex3f(float(sin(PI2*(i%20+wrapFrac)/(float)20))*r,MinorRadius*sinphi,float(cos(PI2*(i%20+wrapFrac)/(float)20))*r);

			glNormal3f(float(sin(PI2*(i+1%20+wrapFrac)/(float)20))*cosphi, sinphi, float(cos(PI2*(i+1%20+wrapFrac)/(float)20))*cosphi);
			glVertex3f(float(sin(PI2*(i+1%20+wrapFrac)/(float)20))*r,MinorRadius*sinphi,float(cos(PI2*(i+1%20+wrapFrac)/(float)20))*r);
		}
	}
glEnd();														// Done Torus

}

void drawsphere(double xpos, double ypos, double zpos, double radiusr)
{
glEnable(GL_LIGHT0);
glTranslatef(xpos,ypos,zpos);
//glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, diffuse0);
//glutSolidSphere(radiusr,100,100);
gluSphere(quadratic,radiusr,100,100);
glDisable(GL_LIGHT0);
}

void drawlipid(double single_lipid[][3], double radiusr)
{
for (int i=0;i<3;i++)
{
glPushMatrix();

	   if (i==0)
	   {
			glColor3f(1.0f,0.0f,10.0f);
			glEnable(GL_LIGHT0);
			glTranslatef(single_lipid[0][0],single_lipid[0][1],single_lipid[0][2]);
			//glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, diffuse0);
			//glutSolidSphere(radiusr,15,15);
			gluSphere(quadratic,radiusr,15,15);
   	   
	   }else
	   {
		glColor3f(1.0f,1.0f,10.0f);
		glEnable(GL_LIGHT0);
		glTranslatef(single_lipid[i][0],single_lipid[i][1],single_lipid[i][2]);
		//glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, diffuse0);
		//glutSolidSphere(radiusr,15,15);
		gluSphere(quadratic,radiusr,15,15);
	   }
   
		glDisable(GL_LIGHT0);
		glPopMatrix();
   }

}

void Display_Lipids(double scalefactor, double arr_lipids[][3][3], int N, double sigma, double Xbox, double Ybox, double Zbox)
{
int i,j,z;
double a_lipid[3][3];

   //Draw_Lipids();
   	for (z=0;z&lt;N;z++)
	{
		for (i=0;i&lt;3;i++)
		{
			for (j=0;j&lt;3;j++)
			{
				a_lipid[i][j] = arr_lipids[z][i][j];
			}
		}
		
		//glCallList(DLid)
		if (Xbox &gt; Zbox)
		{
			drawlipid(a_lipid,scalefactor*(sigma/(2*Xbox)));
		}else
		{
			drawlipid(a_lipid,scalefactor*(sigma/(2*Xbox)));
		}
	}

}

void DisplayBox(double scalefactor)
{

// 0,0,0 vertex

glBegin(GL_LINES);
glVertex3f(0,0,0);
glVertex3f(scalefactor,0,0);
glEnd();
glBegin(GL_LINES);
glVertex3f(0,0,0);
glVertex3f(0,scalefactor,0);
glEnd();
glBegin(GL_LINES);
glVertex3f(0,0,0);
glVertex3f(0,0,scalefactor*Zbox/Xbox);
glEnd();

// 1,1,0 vertex
glBegin(GL_LINES);
glVertex3f(scalefactor,scalefactor,0);
glVertex3f(0,scalefactor,0);
glEnd();
glBegin(GL_LINES);
glVertex3f(scalefactor,scalefactor,0);
glVertex3f(scalefactor,0,0);
glEnd();
glBegin(GL_LINES);
glVertex3f(scalefactor,scalefactor,0);
glVertex3f(scalefactor,scalefactor,scalefactor*Zbox/Xbox);
glEnd();


// 1,1,1 vertex
glBegin(GL_LINES);
glVertex3f(scalefactor,scalefactor,scalefactor*Zbox/Xbox);
glVertex3f(scalefactor,scalefactor,0);
glEnd();
glBegin(GL_LINES);
glVertex3f(scalefactor,scalefactor,scalefactor*Zbox/Xbox);
glVertex3f(scalefactor,0,scalefactor*Zbox/Xbox);
glEnd();
glBegin(GL_LINES);
glVertex3f(scalefactor,scalefactor,scalefactor*Zbox/Xbox);
glVertex3f(0,scalefactor,scalefactor*Zbox/Xbox);
glEnd();

// 0,1,0 vertex
glBegin(GL_LINES);
glVertex3f(0,scalefactor,0);
glVertex3f(0,scalefactor,scalefactor*Zbox/Xbox);
glEnd();
glBegin(GL_LINES);
glVertex3f(0,scalefactor,0);
glVertex3f(0,0,0);
glEnd();
glBegin(GL_LINES);
glVertex3f(0,scalefactor,0);
glVertex3f(scalefactor,scalefactor,0);
glEnd();

// 1,0,1 vertex
glBegin(GL_LINES);
glVertex3f(scalefactor,0,scalefactor*Zbox/Xbox);
glVertex3f(scalefactor,scalefactor,scalefactor*Zbox/Xbox);
glEnd();
glBegin(GL_LINES);
glVertex3f(scalefactor,0,scalefactor*Zbox/Xbox);
glVertex3f(scalefactor,0,0);
glEnd();
glBegin(GL_LINES);
glVertex3f(scalefactor,0,scalefactor*Zbox/Xbox);
glVertex3f(0,0,scalefactor*Zbox/Xbox);
glEnd();



// 0,0,1 vertex
glBegin(GL_LINES);
glVertex3f(0,0,scalefactor*Zbox/Xbox);
glVertex3f(0,scalefactor,scalefactor*Zbox/Xbox);
glEnd();
glBegin(GL_LINES);
glVertex3f(0,0,scalefactor*Zbox/Xbox);
glVertex3f(0,0,0);
glEnd();
glBegin(GL_LINES);
glVertex3f(0,0,scalefactor*Zbox/Xbox);
glVertex3f(scalefactor,0,scalefactor*Zbox/Xbox);
glEnd();


// 0,1,1 vertex
glBegin(GL_LINES);
glVertex3f(0,scalefactor,scalefactor*Zbox/Xbox);
glVertex3f(scalefactor,scalefactor,scalefactor*Zbox/Xbox);
glEnd();
glBegin(GL_LINES);
glVertex3f(0,scalefactor,scalefactor*Zbox/Xbox);
glVertex3f(0,0,scalefactor*Zbox/Xbox);
glEnd();
glBegin(GL_LINES);
glVertex3f(0,scalefactor,scalefactor*Zbox/Xbox);
glVertex3f(0,scalefactor,0);
glEnd();

// 1,0,0 vertex
glBegin(GL_LINES);
glVertex3f(scalefactor,0,0);
glVertex3f(scalefactor,scalefactor,0);
glEnd();
glBegin(GL_LINES);
glVertex3f(scalefactor,0,0);
glVertex3f(0,0,0);
glEnd();
glBegin(GL_LINES);
glVertex3f(scalefactor,0,0);
glVertex3f(scalefactor,0,scalefactor*Zbox/Xbox);
glEnd();



//glTranslatef(0.5*scalefactor,0.5*scalefactor,0.5*scalefactor);
//glutWireCube(scalefactor);

}

void Draw (void)
{
//glFlush ();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer
glMultMatrixf(Transform.M);
glPushMatrix();
glTranslatef(-0.0f,-1.0f,-7.0f);
glLoadIdentity();

												// Reset The Current Modelview Matrix

													// NEW: Prepare Dynamic Transform


// NEW: Apply Dynamic Transform
//glColor3f(1.0f,1.0f,10.0f);

printf("displaying lipids

");
Display_Lipids(scalefactor,arr_lipids,LipidTotal,sigma,Xbox,Ybox,Zbox );
printf("displaying the box
");
DisplayBox(scalefactor);

// Flush The GL Rendering Pipeline
glPopMatrix();								
glFlush ();		
printf("After flush

");

									// Flush The GL Rendering Pipeline

}

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

  •                                          *
    
  • Jeff Molofee’s Revised OpenGL Basecode *
  • Huge Thanks To Maxwell Sayles & Peter Puck *
  •        [http://nehe.gamedev.net](http://nehe.gamedev.net)           *
    
  •                 2001                     *
    
  •                                          *
    

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

#include <stdio.h>
#include <sys/time.h>
#include <time.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glx.h>
#include <X11/Xlib.h>
#include <X11/extensions/xf86vmode.h>
#include <X11/keysym.h>

#include “NeHeGL.h”

#include “math.h”

#include “ArcBall.h”

#define WM_TOGGLEFULLSCREEN (WM_USER+1)

static bool done = false;
static bool g_createFullScreen; // If true, Then Create Fullscreen

extern ArcBallT ArcBall; //NEW ArcBall instance
extern Point2fT MousePt; //NEW Current mouse point
extern bool isClicked; //NEW Clicking the mouse?
extern bool isRClicked; //NEW Clicking the right mouse button?

static int attrListSgl[] = {
GLX_RGBA,
GLX_RED_SIZE, 4,
GLX_GREEN_SIZE, 4,
GLX_BLUE_SIZE, 4,
GLX_DEPTH_SIZE, 16,
None
};

static int attrListDbl[] = {
GLX_RGBA, GLX_DOUBLEBUFFER,
GLX_RED_SIZE, 4,
GLX_GREEN_SIZE, 4,
GLX_BLUE_SIZE, 4,
GLX_DEPTH_SIZE, 16,
None
};

void Normalise(double arr_lipids[][3][3], int N, double Xbox, double Ybox, double Zbox, double scalefactor)
{

int i,j;
for (i=0;i&lt;N;i++)
{
	for (j=0;j&lt;3;j++)
	{
			arr_lipids[i][j][0] = (arr_lipids[i][j][0] / Xbox) * scalefactor;
			arr_lipids[i][j][1] = (arr_lipids[i][j][1] / Ybox) * scalefactor;
			arr_lipids[i][j][2] = (arr_lipids[i][j][2] / Zbox) * scalefactor * Zbox/Xbox;
			printf("i: %d j: %d g: %d pos: %f 

",i,j,0,arr_lipids[i][j][0]);
printf("i: %d j: %d g: %d pos: %f
",i,j,1,arr_lipids[i][j][1]);
printf("i: %d j: %d g: %d pos: %f
",i,j,2,arr_lipids[i][j][2]);

	}
}

}

void ReshapeGL (int width, int height) // Reshape The Window When It’s Moved Or Resized
{
glViewport (0, 0, (GLsizei)(width), (GLsizei)(height)); // Reset The Current Viewport
glMatrixMode (GL_PROJECTION); // Select The Projection Matrix
glLoadIdentity (); // Reset The Projection Matrix
gluPerspective (45.0f, (GLfloat)(width)/(GLfloat)(height), // Calculate The Aspect Ratio Of The Window
1.0f, 100.0f);
glMatrixMode (GL_MODELVIEW); // Select The Modelview Matrix
glLoadIdentity (); // Reset The Modelview Matrix

ArcBall.setBounds((GLfloat)width, (GLfloat)height);                 //*NEW* Update mouse bounds for arcball

}

bool CreateWindowGL (GL_Window* window) {
XVisualInfo *vi;
Colormap cmap;
int dpyWidth, dpyHeight;
int i;
int glxMajorVersion, glxMinorVersion;
int vidModeMajorVersion, vidModeMinorVersion;
XF86VidModeModeInfo **modes;
int modeNum;
int bestMode;
Atom wmDelete;
Window winDummy;
unsigned int borderDummy;
int x, y;

bestMode = 0;

window-&gt;init.dpy = XOpenDisplay( NULL );
window-&gt;init.screen = DefaultScreen( window-&gt;init.dpy );
XF86VidModeQueryVersion( window-&gt;init.dpy, &vidModeMajorVersion,
												 &vidModeMinorVersion );

printf( "XF86VMExt-Version %d.%d

",
vidModeMajorVersion, vidModeMinorVersion );
XF86VidModeGetAllModeLines( window->init.dpy, window->init.screen,
&modeNum, &modes );
window->init.deskMode = *modes[0];

for( i=0;i&lt;modeNum;i++ ) {
	if( (modes[i]-&gt;hdisplay == window-&gt;init.width) &&
			(modes[i]-&gt;vdisplay == window-&gt;init.height) )
		bestMode = i;
}

vi = glXChooseVisual( window-&gt;init.dpy, window-&gt;init.screen, attrListDbl );
if( vi == NULL ) {
	vi = glXChooseVisual( window-&gt;init.dpy, window-&gt;init.screen, attrListSgl );
	window-&gt;init.doubleBuffered = false;
	printf( "Single Buffered visual

" );
} else {
window->init.doubleBuffered = true;
printf( "Double Buffered visual
" );
}

glXQueryVersion( window-&gt;init.dpy, &glxMajorVersion, &glxMinorVersion );
printf( "glx-version %d.%d

", glxMajorVersion, glxMinorVersion );

window-&gt;init.ctx = glXCreateContext( window-&gt;init.dpy, vi, 0, GL_TRUE );

cmap = XCreateColormap( window-&gt;init.dpy,
												RootWindow( window-&gt;init.dpy, vi-&gt;screen ),
												vi-&gt;visual, AllocNone );
window-&gt;init.attr.colormap = cmap;
window-&gt;init.attr.border_pixel = 0;

if( window-&gt;init.isFullScreen ) {
	XF86VidModeSwitchToMode( window-&gt;init.dpy, window-&gt;init.screen,
													 modes[bestMode] );
	XF86VidModeSetViewPort( window-&gt;init.dpy, window-&gt;init.screen, 0, 0 );
	dpyWidth = modes[bestMode]-&gt;hdisplay;
	dpyHeight = modes[bestMode]-&gt;vdisplay;
	XFree( modes );

	window-&gt;init.attr.override_redirect = true;
	window-&gt;init.attr.event_mask =
		ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask |
		ButtonReleaseMask | StructureNotifyMask | PointerMotionMask;
	window-&gt;init.win =
		XCreateWindow( window-&gt;init.dpy,
									 RootWindow( window-&gt;init.dpy, vi-&gt;screen ),
									 0, 0, dpyWidth, dpyHeight, 0, vi-&gt;depth, InputOutput,
									 vi-&gt;visual, CWBorderPixel | CWColormap | CWEventMask |
									 CWOverrideRedirect, &window-&gt;init.attr );
	XWarpPointer( window-&gt;init.dpy, None, window-&gt;init.win, 0, 0, 0, 0, 0, 0 );
	XMapRaised( window-&gt;init.dpy, window-&gt;init.win );
	XGrabKeyboard( window-&gt;init.dpy, window-&gt;init.win, True, GrabModeAsync,
								 GrabModeAsync, CurrentTime );
	XGrabPointer( window-&gt;init.dpy, window-&gt;init.win, True, ButtonPressMask,
								GrabModeAsync, GrabModeAsync, window-&gt;init.win, None,
								CurrentTime );
} else {
	window-&gt;init.attr.event_mask =
		ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask |
		ButtonReleaseMask | StructureNotifyMask | PointerMotionMask;
	window-&gt;init.win =
		XCreateWindow( window-&gt;init.dpy,
									 RootWindow( window-&gt;init.dpy, vi-&gt;screen ),
									 0, 0, window-&gt;init.width, window-&gt;init.height,
									 0, vi-&gt;depth, InputOutput, vi-&gt;visual,
									 CWBorderPixel | CWColormap | CWEventMask,
									 &window-&gt;init.attr );
	wmDelete = XInternAtom( window-&gt;init.dpy, "WM_DELETE_WINDOW", True );
	XSetWMProtocols( window-&gt;init.dpy, window-&gt;init.win, &wmDelete, 1 );
	XSetStandardProperties( window-&gt;init.dpy, window-&gt;init.win,
													window-&gt;init.title, window-&gt;init.title, None, NULL,
													0, NULL );
	XMapRaised( window-&gt;init.dpy, window-&gt;init.win );
}

glXMakeCurrent( window-&gt;init.dpy, window-&gt;init.win, window-&gt;init.ctx );
XGetGeometry( window-&gt;init.dpy, window-&gt;init.win, &winDummy, &x, &y,
							&window-&gt;init.width, &window-&gt;init.height, &borderDummy,
							&window-&gt;init.depth );

if( glXIsDirect( window-&gt;init.dpy, window-&gt;init.ctx ) )
	printf( "Direct rendering

" );
else
printf( "Not Direct rendering
" );

return true;

}

void DestroyWindowGL(GL_Window* window) {
if(window->init.ctx ) {
if( !glXMakeCurrent(window->init.dpy, None, NULL ) ) {
fprintf( stderr, "Error releasing drawing context
" );
}
glXDestroyContext( window->init.dpy, window->init.ctx );
}

if(window-&gt;init.isFullScreen) {
	XF86VidModeSwitchToMode( window-&gt;init.dpy,
													 window-&gt;init.screen, &window-&gt;init.deskMode );
	XF86VidModeSetViewPort( window-&gt;init.dpy, window-&gt;init.screen, 0, 0 );
}
XCloseDisplay( window-&gt;init.dpy );

}

void initGL( GL_Window *window, Keys *keys ) {
Initialize( window, keys );
ReshapeGL( window->init.width, window->init.height );
}

int main( int argc, char *argv[] ) {
XEvent event;
GL_Window window;
Keys keys;
KeySym key;
struct timeval tv, tickCount;

window.keys	= &keys;
window.init.title	= "Membranes";
window.init.width	= 1024;
window.init.height = 768;
window.init.depth = 32;
window.init.isFullScreen = false;

g_createFullScreen = window.init.isFullScreen;
if( CreateWindowGL (&window) == false ) {
//	exit( 1 );
}

initGL(&window, &keys);
printf("Fully initialized

");

while( !done ) {
	while( XPending( window.init.dpy ) &gt; 0 ) {
		XNextEvent( window.init.dpy, &event );
		switch( event.type ) {
			case Expose:
				if( event.xexpose.count != 0 )
					break;
				printf("drawing now

");
Draw();
printf("breaking now
");
break;
case ConfigureNotify:
if( (event.xconfigure.width != window.init.width)

Please don’t post entire programs…
Isolate the problem (or at least make an attempt to) and post relevant code.

We’re not here to debug programs.

A good place to start would be to check your heap allocations, deallocations, and any dereferences.

EDIT: oh, and also…this has nothing to do with OpenGL.

Sorry, it seems I’m damned if I do and damned if I dont. I get people
complain if I have’nt posted enough of the code, so this time thought
that I would post in entirity.

As for the source of the problem, I am having trouble tracking this
one down. Possibly try the draw routine.