Sign in to follow this  
JustusAa

OpenGL Glut change Xcord and Y cord

Recommended Posts

Hey I would love some help, been stuck with this for a while. I spent 16h myself to solve the problem so dont think I havnt put heart into it. My grafics engine will get cords x and y (its 2d) and draw objekt there. Problem is I cant change the cords I set, I am sure I made some kind of error but cant find what. Hoping for you guys.. Code , some is in other modules but I will try to explain so I wont waste your time.
<<<<<<<<<<<<<<<<<<<<<
// These variables set the dimensions of the rectanglar region we wish to view.
const double Xmin = 0.0, Xmax = 1066.0;
const double Ymin = 0.0, Ymax = 600.0;
GLint littleMen_display_list;
float oldPosX=0, oldPosY=0, posX=0, posY=0;
int startGraficsEngine(int argc, char** argv) 
{
    	glutInit(&argc, argv);
        // The image is not animated so single buffering is OK. 
	glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH );
        // Window position (from top corner), and size (width and hieght)
	glutInitWindowPosition(200,200);
	glutInitWindowSize(1066,600);
	glutCreateWindow("EH");
        // Initialize OpenGL as we like it..
        initRendering();  
        startKeyboard(); //works as intended
        glutReshapeFunc( resizeWindow );
        glutDisplayFunc(renderScene);

        // here is the setting of the idle function
	glutIdleFunc(renderScene);
        
        /* set clear color */
	glClearColor (1.0, 1.0, 1.0, 1.0);
	/* set fill  color */
	glColor3f(1.0, 1.0, 0.0);
	glutMainLoop();
  
    return (EXIT_SUCCESS);
}
void glutExit()
{
    exit(1);
}
void initRendering()
{
        glEnable ( GL_DEPTH_TEST );
       littleMen_display_list = createDL();
        
	// Uncomment out the first block of code below, and then the second block,
	//		to see how they affect line and point drawing.

	// The following commands should cause points and line to be drawn larger
	//	than a single pixel width.
	glPointSize(1);
	glLineWidth(1);


	// The following commands should induce OpenGL to create round points and 
	//	antialias points and lines.  (This is implementation dependent unfortunately).
	glEnable(GL_POINT_SMOOTH);
	glEnable(GL_LINE_SMOOTH);
	glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);	// Make round points, not square points
	glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);		// Antialias the lines
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
void renderScene(void) 
{
   sleepTime.tv_sec = 0;              //set to 0
   sleepTime.tv_nsec = 33000000;      //set how much time that is minimum for loop to take
   clock_gettime(CLOCK_THREAD_CPUTIME_ID  , &startTime); 
   ///SET RENDER CODE BETWEEN HERE

   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
   
   glPushMatrix();
   glTranslatef(returnPos(1), returnPos(2), 0.0);
   drawLittleMan();
   glPopMatrix();   

    glPushMatrix();
    glTranslatef(returnPos(1)+20, returnPos(2), 0.0);
    glCallList(littleMen_display_list);
    glPopMatrix();

   
    glPushMatrix();
    glTranslatef(555, 555, 0.0);
    glCallList(littleMen_display_list);
    glPopMatrix();
   
  ///AND HERE
  glutSwapBuffers();
   

  clock_gettime(CLOCK_THREAD_CPUTIME_ID , &endTime);
  someTime.tv_sec = endTime.tv_sec - startTime.tv_sec;
  someTime.tv_nsec = endTime.tv_nsec - startTime.tv_nsec;
  sleepTime.tv_sec -= someTime.tv_sec;
  sleepTime.tv_nsec -= someTime.tv_nsec;
  nanosleep(&sleepTime, NULL);

}
void resizeWindow(int w, int h)
{
	double scale, center;
	double windowXmin, windowXmax, windowYmin, windowYmax;

	// Define the portion of the window used for OpenGL rendering.
	glViewport( 0, 0, w, h );	// View port uses whole window

	// Set up the projection view matrix: orthographic projection
	// Determine the min and max values for x and y that should appear in the window.
	// The complication is that the aspect ratio of the window may not match the
	//		aspect ratio of the scene we want to view.
	w = (w==0) ? 1 : w;
	h = (h==0) ? 1 : h;
	if ( (Xmax-Xmin)/w < (Ymax-Ymin)/h ) {
		scale = ((Ymax-Ymin)/h)/((Xmax-Xmin)/w);
		center = (Xmax+Xmin)/2;
		windowXmin = center - (center-Xmin)*scale;
		windowXmax = center + (Xmax-center)*scale;
		windowYmin = Ymin;
		windowYmax = Ymax;
	}
	else {
		scale = ((Xmax-Xmin)/w)/((Ymax-Ymin)/h);
		center = (Ymax+Ymin)/2;
		windowYmin = center - (center-Ymin)*scale;
		windowYmax = center + (Ymax-center)*scale;
		windowXmin = Xmin;
		windowXmax = Xmax;
	}
	
	// Now that we know the max & min values for x & y that should be visible in the window,
	//		we set up the orthographic projection.
	glMatrixMode( GL_PROJECTION );
	glLoadIdentity();
	glOrtho( windowXmin, windowXmax, windowYmin, windowYmax, -1, 1 );

}
GLuint createDL()
{
	GLuint littleManDL;
	// Create the id for the list
	littleManDL = glGenLists(1);
	// start list
	glNewList(littleManDL,GL_COMPILE);
	// call the function that contains 
	// the rendering commands
	drawLittleMan();
	// endList
	glEndList();
	return(littleManDL);
}
void changePos(float f_posx, float f_posy)//funktion keybord presses uses
{
    posX =f_posx;
    posY = f_posx;
    printf("changePos\n");
 //   posX = oldPosX - f_posx;
 //   posY = oldPosY - f_posy;
 //   oldPosX = posX;
 //   oldPosY = posY;
    return ;
}
int returnPos(int val)// use it to change pos to draw men at.. works but no differnce..
{
    int x=0, y=0;
    x = posX - x ;
    y = posY - y;
    if(val==1)
    {printf("X\n");
     return x;}
    if(val==2){printf("Y\n");
        return y;}
    else
    return 0;
}
void drawLittleMan() { //my patetented man withouth his head ^^
    
    //Sets startingpoint of little man
    float posX=0.0, posY=0.0;

    //Set leglenght of little man
    float leftLeg=8.0, rightLeg=8.0;
    //Set Bodylenght of little man
    float bodyLeangth=8.0;
    float neckLeanght=4.0;
    float headSize=4.0;
    //Set armlenght of little man
    float armLeft=8.0, armRight=8.0;

        // Set drawing color 
        glColor3f(1.0f, 0.0f, 1.0f);
        
         //Draws little man
        glBegin(  GL_LINES );
        glVertex2f( posX             ,    posY );
        glVertex2f( posX-leftLeg     ,    posY-leftLeg );

        glVertex2f( posX             ,    posY );
        glVertex2f( posX+rightLeg    ,    posY-rightLeg );

        glVertex2f( posX             ,    posY);
        glVertex2f( posX             ,    posY+bodyLeangth );

        glVertex2f( posX             ,    posY+bodyLeangth );
        glVertex2f( posX-armLeft     ,    posY+bodyLeangth );

        glVertex2f( posX             ,    posY+bodyLeangth );
        glVertex2f( posX+armRight    ,    posY+bodyLeangth );

        glVertex2f( posX             ,    posY+bodyLeangth );
        glVertex2f( posX             ,    posY+bodyLeangth+neckLeanght );

        glVertex2f( posX             ,    posY+bodyLeangth+neckLeanght );
        glVertex2f( posX-headSize    ,    posY+bodyLeangth+neckLeanght );


        glEnd();
        return ;
}

<<<<<<<<<<<<<<<<<<<<<


Thanx first edit source tags, second want to tell you I think its a problem with double buffert or idlefunk thats a part of glut. I dont know though. I dont have any compilation problems and work in linux. [Edited by - JustusAa on April 23, 2008 7:04:46 AM]

Share this post


Link to post
Share on other sites
The code is a bit hard to read - TIP: use the
 tag.

Anyway two areas that might the cause of your issue:
This routine:


int returnPos(int val)// use it to change pos to draw men at.. works but no differnce..
{
int x=0, y=0;
x = posX - x ; // ARE YOU SURE MEAN THIS - ITS WAYS GOING TO SUBTRACT 0
y = posY - y;
if(val==1)
{printf("X\n");
return x;}
if(val==2){printf("Y\n");
return y;}
else
return 0;
}



Will always do nothing of any use. Local variables x and y are always going to be posX and posY.

More worrying is this line in the render loop

//Sets startingpoint of little man
float posX=0.0, posY=0.0;

Here you hiding your globals vars with local vars. I suggest you don't do this.
remove the float declaration from the above line and see if this helps.


Share this post


Link to post
Share on other sites
I am sorry i just edited the text with code snippets so it looks nicer.
Forgot to say that void drawLittleMan() is in a completely different module called drawThings with .c and .h.
The posX and posY starts at 0,0 but I call changePos() when an button is pressed and sends new positions 300,300 for ex. the happenings is in another module for keyboardpresses that I didnt add but looks like this:


void keyboardFunc( unsigned char key, int x, int y )
{
switch ( key ) {
case 'w':
posy=400.0;
posx=400.0;
changePos(posx, posy);
break;


left out end of it as I can test it and it works..

That changes posX and posY, then I return it, the kode snippet you complain abouth is more of testing in progress.

In short I can set the littleman anywhere on screen to start but not move him once I did. I can change posX and posY how much I want then with no change of the little men on screen. Two of them are supposed to move ^^

[Edited by - JustusAa on April 23, 2008 7:12:11 AM]

Share this post


Link to post
Share on other sites
In your startup code instead of:

glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH );

use

glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL);

Since, I bet every new project you will use the lines you have here. Anyway this wont solve the issue.

What happens if you try and simple put a specific set of transalate commands in before you call drawLittleGreenMen in the renderloop. Just want to check that you get expected values for that specific debug case.

Once your satisfied with the result when revert back to the use of your global vars. In your render loop - you still declare local vars by the same name. This is bad practice - remove or rename.

Share this post


Link to post
Share on other sites
Added GLUT_STENCIL (gonna read what it does now.. ;) )
Doesnt solve issue, abouth alfa channel I may add that later.

"What happens if you try and simple put a specific set of transalate commands in before you call drawLittleGreenMen in the renderloop."

I am atm drawing three little men at different positions, two very close to eatch other. This are the ones that should be possible to move by pressing keys.

Added
glTranslatef(0.01, 0.01, 0.0);




before the first push matrix and the three men started to move slowly to the right and up aswell. I must press I dont care much if the move around every update, I want to set the objects at specific cords every update, information that I get from a server.

"Once your satisfied with the result when revert back to the use of your global vars. In your render loop - you still declare local vars by the same name. This is bad practice - remove or rename."
I presume u talking abouth drawLittleMan() thats is a member of drawItems.h so they dont share global variables. Sure can change the names for variables. Other code is graficsengineglut.c and .h to explain.

forget abouth
void changePos(float f_posx, float f_posy)
int returnPos(int val)
I will design another system to change posX and Y. If it works I will hit myself with a book.

[Edited by - JustusAa on April 23, 2008 8:55:51 AM]

Share this post


Link to post
Share on other sites
SOLVED

I am sorry for taking up your time. Problem was this:
My keyboard reader was supposed to send a value:

case 'w':
posy=400.0;
posx=400.0;
printf("hej\n");
changePos(posx, posy);

for ex. 400 to my module that draw the objects. By the help of BionicBytes I got in the right direction with my debugging.

void changePos(float f_posx, float f_posy)
{
printf("%f %f\n", f_posx, f_posx);


printed 0.000 0.0000 all the time. So I found my error somewhere I didnt expect, guess it is sometimes like this when you are new to an api. Its strange though that changePos was run from the keyboard reader and no values was sent. Although thats a feature i dont need.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Announcements

  • Forum Statistics

    • Total Topics
      628388
    • Total Posts
      2982403
  • Similar Content

    • By test opty
      Hi all,
       
      I'm starting OpenGL using a tut on the Web. But at this point I would like to know the primitives needed for creating a window using OpenGL. So on Windows and using MS VS 2017, what is the simplest code required to render a window with the title of "First Rectangle", please?
       
       
    • By DejayHextrix
      Hi, New here. 
      I need some help. My fiance and I like to play this mobile game online that goes by real time. Her and I are always working but when we have free time we like to play this game. We don't always got time throughout the day to Queue Buildings, troops, Upgrades....etc.... 
      I was told to look into DLL Injection and OpenGL/DirectX Hooking. Is this true? Is this what I need to learn? 
      How do I read the Android files, or modify the files, or get the in-game tags/variables for the game I want? 
      Any assistance on this would be most appreciated. I been everywhere and seems no one knows or is to lazy to help me out. It would be nice to have assistance for once. I don't know what I need to learn. 
      So links of topics I need to learn within the comment section would be SOOOOO.....Helpful. Anything to just get me started. 
      Thanks, 
      Dejay Hextrix 
    • By mellinoe
      Hi all,
      First time poster here, although I've been reading posts here for quite a while. This place has been invaluable for learning graphics programming -- thanks for a great resource!
      Right now, I'm working on a graphics abstraction layer for .NET which supports D3D11, Vulkan, and OpenGL at the moment. I have implemented most of my planned features already, and things are working well. Some remaining features that I am planning are Compute Shaders, and some flavor of read-write shader resources. At the moment, my shaders can just get simple read-only access to a uniform (or constant) buffer, a texture, or a sampler. Unfortunately, I'm having a tough time grasping the distinctions between all of the different kinds of read-write resources that are available. In D3D alone, there seem to be 5 or 6 different kinds of resources with similar but different characteristics. On top of that, I get the impression that some of them are more or less "obsoleted" by the newer kinds, and don't have much of a place in modern code. There seem to be a few pivots:
      The data source/destination (buffer or texture) Read-write or read-only Structured or unstructured (?) Ordered vs unordered (?) These are just my observations based on a lot of MSDN and OpenGL doc reading. For my library, I'm not interested in exposing every possibility to the user -- just trying to find a good "middle-ground" that can be represented cleanly across API's which is good enough for common scenarios.
      Can anyone give a sort of "overview" of the different options, and perhaps compare/contrast the concepts between Direct3D, OpenGL, and Vulkan? I'd also be very interested in hearing how other folks have abstracted these concepts in their libraries.
    • By aejt
      I recently started getting into graphics programming (2nd try, first try was many years ago) and I'm working on a 3d rendering engine which I hope to be able to make a 3D game with sooner or later. I have plenty of C++ experience, but not a lot when it comes to graphics, and while it's definitely going much better this time, I'm having trouble figuring out how assets are usually handled by engines.
      I'm not having trouble with handling the GPU resources, but more so with how the resources should be defined and used in the system (materials, models, etc).
      This is my plan now, I've implemented most of it except for the XML parts and factories and those are the ones I'm not sure of at all:
      I have these classes:
      For GPU resources:
      Geometry: holds and manages everything needed to render a geometry: VAO, VBO, EBO. Texture: holds and manages a texture which is loaded into the GPU. Shader: holds and manages a shader which is loaded into the GPU. For assets relying on GPU resources:
      Material: holds a shader resource, multiple texture resources, as well as uniform settings. Mesh: holds a geometry and a material. Model: holds multiple meshes, possibly in a tree structure to more easily support skinning later on? For handling GPU resources:
      ResourceCache<T>: T can be any resource loaded into the GPU. It owns these resources and only hands out handles to them on request (currently string identifiers are used when requesting handles, but all resources are stored in a vector and each handle only contains resource's index in that vector) Resource<T>: The handles given out from ResourceCache. The handles are reference counted and to get the underlying resource you simply deference like with pointers (*handle).  
      And my plan is to define everything into these XML documents to abstract away files:
      Resources.xml for ref-counted GPU resources (geometry, shaders, textures) Resources are assigned names/ids and resource files, and possibly some attributes (what vertex attributes does this geometry have? what vertex attributes does this shader expect? what uniforms does this shader use? and so on) Are reference counted using ResourceCache<T> Assets.xml for assets using the GPU resources (materials, meshes, models) Assets are not reference counted, but they hold handles to ref-counted resources. References the resources defined in Resources.xml by names/ids. The XMLs are loaded into some structure in memory which is then used for loading the resources/assets using factory classes:
      Factory classes for resources:
      For example, a texture factory could contain the texture definitions from the XML containing data about textures in the game, as well as a cache containing all loaded textures. This means it has mappings from each name/id to a file and when asked to load a texture with a name/id, it can look up its path and use a "BinaryLoader" to either load the file and create the resource directly, or asynchronously load the file's data into a queue which then can be read from later to create the resources synchronously in the GL context. These factories only return handles.
      Factory classes for assets:
      Much like for resources, these classes contain the definitions for the assets they can load. For example, with the definition the MaterialFactory will know which shader, textures and possibly uniform a certain material has, and with the help of TextureFactory and ShaderFactory, it can retrieve handles to the resources it needs (Shader + Textures), setup itself from XML data (uniform values), and return a created instance of requested material. These factories return actual instances, not handles (but the instances contain handles).
       
       
      Is this a good or commonly used approach? Is this going to bite me in the ass later on? Are there other more preferable approaches? Is this outside of the scope of a 3d renderer and should be on the engine side? I'd love to receive and kind of advice or suggestions!
      Thanks!
    • By nedondev
      I 'm learning how to create game by using opengl with c/c++ coding, so here is my fist game. In video description also have game contain in Dropbox. May be I will make it better in future.
      Thanks.
  • Popular Now