void MeshView::paintGL() { qglClearColor( m_backgroundColor ); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); if ( m_resolution.isEmpty() ) return; if ( m_textureDirty ) { generateTexture(); m_textureDirty = false; } double offset = m_colorMapping.offset() + m_animationState.scrolling(); if ( offset > 1.0 ) offset -= 1.0; double scale = m_colorMapping.scale(); glMatrixMode( GL_TEXTURE ); glLoadIdentity(); if ( m_colorMapping.isMirrored() && hasMirroredRepeat() ) { if ( m_colorMapping.isReversed() ) glTranslated( 2.0 * offset + 1.0, 0.0, 0.0 ); else glTranslated( 2.0 * offset, 0.0, 0.0 ); glScaled( scale, 1.0, 1.0 ); glTexParameteri( GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT_ARB ); } else { if ( m_colorMapping.isReversed() ) { glTranslated( -offset, 0.0, 0.0 ); glScaled( -scale, 1.0, 1.0 ); } else { glTranslated( offset, 0.0, 0.0 ); glScaled( scale, 1.0, 1.0 ); } glTexParameteri( GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_REPEAT ); } GLint viewport[ 4 ]; glGetIntegerv( GL_VIEWPORT, viewport ); double vw = viewport[ 2 ]; double vh = viewport[ 3 ]; double fy = tan( 0.5 * m_settings.cameraZoom() * M_PI / 180.0 ) * NearClipping; double fx = fy * vw / vh; glMatrixMode( GL_PROJECTION ); glLoadIdentity(); glFrustum( -fx, fx, -fy, fy, NearClipping, FarClipping ); double rotation = m_rotation - m_animationState.rotation() * 360.0; glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); glTranslated( 0.0, 0.0, -CameraDistance ); glRotated( m_angle, 1.0, 0.0, 0.0 ); glRotated( rotation, 0.0, 0.0, 1.0 ); glScaled( 1.0, 1.0, m_settings.heightScale() ); glTranslated( 0.0, 0.0, m_averageHeight ); double plane[ 4 ] = { 0.0, 0.0, 1.0, m_maximumDepth - 0.001 }; glClipPlane( GL_CLIP_PLANE0, plane ); glEnable( GL_CLIP_PLANE0 ); int width = m_resolution.width(); if ( hasLockArrays( context() ) ) p_glLockArraysEXT( 0, m_resolution.height() * m_resolution.width() ); int* indexArray = new int[ 2 * width ]; for ( int y = 0; y < m_resolution.height() - 1; y++ ) { int offset = y * width; for ( int x = 0; x < width; x++ ) { indexArray[ 2 * x ] = x + offset; indexArray[ 2 * x + 1 ] = x + offset + width; } glDrawElements( GL_TRIANGLE_STRIP, 2 * width - 2, GL_UNSIGNED_INT, indexArray ); } delete[] indexArray; if ( hasLockArrays( context() ) ) p_glUnlockArraysEXT(); }
// Called to draw scene void RenderScene(void) { // Track camera angle glMatrixMode(GL_PROJECTION); glLoadIdentity(); if (windowWidth > windowHeight) { GLdouble ar = (GLdouble)windowWidth / (GLdouble)windowHeight; glFrustum(-ar * cameraZoom, ar * cameraZoom, -cameraZoom, cameraZoom, 1.0, 1000.0); } else { GLdouble ar = (GLdouble)windowHeight / (GLdouble)windowWidth; glFrustum(-cameraZoom, cameraZoom, -ar * cameraZoom, ar * cameraZoom, 1.0, 1000.0); } glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(cameraPos[0], cameraPos[1], cameraPos[2], 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f); glViewport(0, 0, windowWidth, windowHeight); if ((whichShader == FOGCOORD) || (whichShader == FOG)) { // Use a green-gray color for fog glClearColor(fogColor[0], fogColor[1], fogColor[2], fogColor[3]); glFogf(GL_FOG_DENSITY, density); } else { glClearColor(0.0f, 0.0f, 0.0f, 1.0f ); } // Clear the window with current clearing color glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Validate our shader before first use if (needsValidation[whichShader]) { GLint success; glValidateProgram(progObj[whichShader]); glGetProgramiv(progObj[whichShader], GL_VALIDATE_STATUS, &success); if (!success) { GLchar infoLog[MAX_INFO_LOG_SIZE]; glGetProgramInfoLog(progObj[whichShader], MAX_INFO_LOG_SIZE, NULL, infoLog); fprintf(stderr, "Error in program #%d validation!\n", whichShader); fprintf(stderr, "Info log: %s\n", infoLog); Sleep(10000); exit(0); } needsValidation[whichShader] = GL_FALSE; } // Draw objects in the scene DrawModels(); if (glGetError() != GL_NO_ERROR) fprintf(stderr, "GL Error!\n"); // Flush drawing commands glutSwapBuffers(); }
void resizeGL(int width, int height ) { glViewport(0, 0,width,height); glFrustum(-2.0,2.0,-2.0,2.0,-2.0,2.0); }
void OGLPyramid::resizeGL(int nWidth, int nHeight) { glViewport(0, 0, (GLint)nWidth, (GLint)nHeight); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(-1.0, 1.0, -1.0, 1.0, 1.0, 10.0); }
void DemoApplication::updateCamera() { glMatrixMode(GL_PROJECTION); glLoadIdentity(); btScalar rele = m_ele * btScalar(0.01745329251994329547);// rads per deg btScalar razi = m_azi * btScalar(0.01745329251994329547);// rads per deg btQuaternion rot(m_cameraUp,razi); btVector3 eyePos(0,0,0); eyePos[m_forwardAxis] = -m_cameraDistance; btVector3 forward(eyePos[0],eyePos[1],eyePos[2]); if (forward.length2() < SIMD_EPSILON) { forward.setValue(1.f,0.f,0.f); } btVector3 right = m_cameraUp.cross(forward); btQuaternion roll(right,-rele); eyePos = btMatrix3x3(rot) * btMatrix3x3(roll) * eyePos; m_cameraPosition[0] = eyePos.getX(); m_cameraPosition[1] = eyePos.getY(); m_cameraPosition[2] = eyePos.getZ(); m_cameraPosition += m_cameraTargetPosition; if (m_glutScreenWidth == 0 && m_glutScreenHeight == 0) return; btScalar aspect; btVector3 extents; aspect = m_glutScreenWidth / (btScalar)m_glutScreenHeight; extents.setValue(aspect * 1.0f, 1.0f,0); if (m_ortho) { // reset matrix glLoadIdentity(); extents *= m_cameraDistance; btVector3 lower = m_cameraTargetPosition - extents; btVector3 upper = m_cameraTargetPosition + extents; //gluOrtho2D(lower.x, upper.x, lower.y, upper.y); glOrtho(lower.getX(), upper.getX(), lower.getY(), upper.getY(),-1000,1000); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //glTranslatef(100,210,0); } else { // glFrustum (-aspect, aspect, -1.0, 1.0, 1.0, 10000.0); glFrustum (-aspect * m_frustumZNear, aspect * m_frustumZNear, -m_frustumZNear, m_frustumZNear, m_frustumZNear, m_frustumZFar); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(m_cameraPosition[0], m_cameraPosition[1], m_cameraPosition[2], m_cameraTargetPosition[0], m_cameraTargetPosition[1], m_cameraTargetPosition[2], m_cameraUp.getX(),m_cameraUp.getY(),m_cameraUp.getZ()); } }
PIGLIT_GL_TEST_CONFIG_END /** * Draw some simple quads in a bunch of viewports which tile the window. * Note that viewports extend beyond the edges of the window too. */ static void draw_test_image(void) { int vx, vy, vw = 200, vh = 200; glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(-1, 1, -1, 1, 3, 9.5); /* Draw some quads at an odd rotation. * Note that we want near/far frustum clipping. */ glMatrixMode(GL_MODELVIEW); glPushMatrix(); glTranslatef(0, 1, -6.20); glRotatef(-60, 1, 0, 0); glRotatef(30, 0, 0, 1); glScalef(3.5, 3.5, 3.5); /* loop over viewports */ for (vy = -50; vy < piglit_height; vy += vh+10) { for (vx = -30; vx < piglit_width; vx += vw+10) { glViewport(vx, vy, vw, vh); glBegin(GL_QUADS); glColor3f(1, 0, 0); glVertex2f(-1, -1); glVertex2f( 0, -1); glVertex2f( 0, 0); glVertex2f(-1, 0); glColor3f(0, 1, 0); glVertex2f( 0, -1); glVertex2f( 1, -1); glVertex2f( 1, 0); glVertex2f( 0, 0); glColor3f(0, 0, 1); glVertex2f(-1, 0); glVertex2f( 0, 0); glVertex2f( 0, 1); glVertex2f(-1, 1); glColor3f(1, 1, 1); glVertex2f( 0, 0); glVertex2f( 1, 0); glVertex2f( 1, 1); glVertex2f( 0, 1); glEnd(); } } glPopMatrix(); }
void draw(void) { int x,y; if (reshape) { X=rx/MUL; Y=ry/MUL; glViewport (0,0,rx,ry); //u=(double*)realloc(u,sizeof(double)*X*Y*2); //memset(u,0,sizeof(double)*X*Y*2); reshape = 0; printf ("X=%d, Y=%d\n", X, Y); X1 = X*Xmul; Y1 = Y*Ymul; //how do we enlongate that? DT = (T1 - T0) / max(X,Y); DX = (X1 - X0) / (X-1); DY = (Y1 - Y0) / (Y-1); DTDXDX = DT / (DX * DX); DTDYDY = DT / (DY * DY); } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode (GL_PROJECTION); glLoadIdentity (); glFrustum (-X/2, X/2, -Y/2, Y/2, 100, 1000); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt (0,0,-100, 0,0,0, 0,-1,0); glTranslatef (-X/2, -Y/2, 0); glDisable(GL_CULL_FACE); glCullFace(GL_FRONT); if (firsttime) { memset(hist,0,sizeof(int)*INITXY*INITXY); } if (curver == VER_LOOPING) { //printf ("using looping version\n"); rectiter(t, t+max(X,Y)*TIER, 0, X, 0, Y); } else { //printf ("using cache oblivious version\n"); rect(t, t+max(X,Y)*TIER, 0, X, 0, Y); } if (firsttime) { int i,j,tmp; for (i=0;i<INITXY;i++) for (j=i;j<INITXY;j++) { tmp = (i==j) ? hist[i][j] : hist[i][j] + hist[j][i]; if (tmp) printf ("leave of size (%d,%d) or (%d,%d) %d\n", i, j, j, i, tmp); } firsttime = 0; } t+=max(X,Y)*TIER; glClearColor(0.0, 0.0, 0.0, 0.0); for (x=0; x<X; x++) { for (y=0; y<Y; y++) { glColor3d(U(0,x,y), 0.5*U(0,x,y), 1.0-0.8*U(0,x,y)); glBegin(GL_POLYGON); { glVertex3f(x, y, 0); glVertex3f(x, y+1, 0); glVertex3f(x+1, y+1, 0); glVertex3f(x+1, y, 0); } glEnd(); } } { char s[20]; sprintf (s, "frame rate: %f", (1/((float)(clock()-lasttime)/(float)CLOCKS_PER_SEC))); lasttime = clock(); glMatrixMode (GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); RenderString(-1, -1, GLUT_BITMAP_TIMES_ROMAN_24, s, 1,1,0); //sprintf (s, "current version : %s", (curver == VER_CO) ? "cache oblivious" : "looping"); // RenderString(-1, -0.8, GLUT_BITMAP_TIMES_ROMAN_24, s, 1,1,0); } glFlush(); glutSwapBuffers(); }
static void draw(void) { if ( use_ztrick ) { static GLboolean flip = GL_FALSE; static const GLfloat vert[4][3] = { { -1, -1, -0.999 }, { 1, -1, -0.999 }, { 1, 1, -0.999 }, { -1, 1, -0.999 } }; static const GLfloat col[4][3] = { { 1.0, 0.6, 0.0 }, { 1.0, 0.6, 0.0 }, { 0.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0 }, }; if ( flip ) { glDepthRange(0, 0.5); glDepthFunc(GL_LEQUAL); } else { glDepthRange(1.0, 0.4999); glDepthFunc(GL_GEQUAL); } flip = !flip; /* The famous Quake "Z trick" only works when the whole screen is * re-drawn each frame. */ glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-1, 1, -1, 1, -1, 1); glDisable(GL_LIGHTING); glShadeModel(GL_SMOOTH); glEnableClientState( GL_VERTEX_ARRAY ); glEnableClientState( GL_COLOR_ARRAY ); glVertexPointer( 3, GL_FLOAT, 0, vert ); glColorPointer( 3, GL_FLOAT, 0, col ); glDrawArrays( GL_POLYGON, 0, 4 ); glDisableClientState( GL_COLOR_ARRAY ); glDisableClientState( GL_VERTEX_ARRAY ); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(-aspectX, aspectX, -aspectY, aspectY, 5.0, 60.0); glEnable(GL_LIGHTING); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0.0, 0.0, -45.0); } else { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } glPushMatrix(); glRotatef(view_rotx, 1.0, 0.0, 0.0); glRotatef(view_roty, 0.0, 1.0, 0.0); glRotatef(view_rotz, 0.0, 0.0, 1.0); glPushMatrix(); glTranslatef(-3.0, -2.0, 0.0); glRotatef(angle, 0.0, 0.0, 1.0); glCallList(gear1); glPopMatrix(); glPushMatrix(); glTranslatef(3.1, -2.0, 0.0); glRotatef(-2.0 * angle - 9.0, 0.0, 0.0, 1.0); glCallList(gear2); glPopMatrix(); glPushMatrix(); glTranslatef(-3.1, 4.2, 0.0); glRotatef(-2.0 * angle - 25.0, 0.0, 0.0, 1.0); glCallList(gear3); glPopMatrix(); glPopMatrix(); }
void create_frustum(int width, int height) { GLfloat h = (GLfloat) height / (GLfloat) width; glFrustum(-1.0, 1.0, -h, h, 5.0, 500.0); }
void view_draw(Link link){ unsigned long draw_status_save; View self = current_view = link->value.vptr; GLdouble mod_mat[16]; static GLdouble bounds[6]; glMatrixMode (GL_PROJECTION); // Set up projection view glLoadIdentity (); if (draw_status & SELECT){ glTranslatef( (current_viewport[2] - 2 * (pick_x - current_viewport[0])) / SELECTION_SIZE, (current_viewport[3] - 2 * (pick_y - current_viewport[1])) / SELECTION_SIZE, 0); glScalef(current_viewport[2] / SELECTION_SIZE, current_viewport[3] / SELECTION_SIZE, 1.0); } setBounds(self, bounds); // Perspective or Orthographic projection if (self->projection){ // left right bottom top near far glOrtho(bounds[0],bounds[1],bounds[2],bounds[3],bounds[4],bounds[5]); }else{ // left right bottom top near far glFrustum(bounds[0],bounds[1],bounds[2],bounds[3],bounds[4],bounds[5]); } if (self->camera_pos){ glTranslated(self->camera_pos[0],self->camera_pos[1], self->camera_pos[2]); } if (!(draw_status & SELECT)){ // Store the value of the projection matrix while rendering glGetDoublev(GL_PROJECTION_MATRIX, self->proj_mat_render); } glGetDoublev(GL_PROJECTION_MATRIX, self->proj_mat); glMatrixMode (GL_MODELVIEW); glLoadIdentity (); glGetDoublev(GL_MODELVIEW_MATRIX, mod_mat); raster_pos_select[0] = 0.0; raster_pos_select[1] = 0.0; raster_pos_select[2] = 0.0; glRasterPos2f( (bounds[0]+bounds[1])/2.0 ,(bounds[2]+bounds[3])/2.0); glGetDoublev(GL_CURRENT_RASTER_POSITION, raster_pos); if (self->fog_parameters[0]){ glFogi(GL_FOG_MODE, GL_LINEAR); // Fog Mode glFogfv(GL_FOG_COLOR, current_window->clear_color); // Set Fog Color to clear color glFogf(GL_FOG_DENSITY, self->fog_parameters[0]); // How Dense Will The Fog Be glHint(GL_FOG_HINT, GL_NICEST); // Fog Hint Value glFogf(GL_FOG_START, self->fog_parameters[1]); // Fog Start Depth glFogf(GL_FOG_END, self->fog_parameters[2]); // Fog End Depth glEnable(GL_FOG); // Enables GL_FOG }else{ glDisable(GL_FOG); } // Reset light_index to 0 , everytime it encounters a light it increments the light index // So first light it runs into is GL_LIGHT0 int c; for(c=0; c < light_index ; c++) glDisable(trans[c]); light_index = 0; glDisable(GL_LIGHTING); // DRAW // remember some important states draw_status_save = draw_status; glPushAttrib( GL_ALL_ATTRIB_BITS ); im_draw(self->items); // return saved states glPopAttrib(); // make sure material, lighting, and texture don't propagate up draw_status = draw_status_save; }
void updateCamera() { glMatrixMode(GL_PROJECTION); glLoadIdentity(); btScalar rele = 0; btScalar razi = 0; btVector3 m_cameraUp(0,1,0); btScalar m_cameraDistance = 10.f; btVector3 m_cameraPosition; btVector3 m_cameraTargetPosition = (tr[0].getOrigin()+tr[1].getOrigin())*0.5; btQuaternion rot(m_cameraUp,razi); int m_forwardAxis = 2; btVector3 eyePos(0,0,0); eyePos[m_forwardAxis] = -m_cameraDistance; btVector3 forward(eyePos[0],eyePos[1],eyePos[2]); if (forward.length2() < SIMD_EPSILON) { forward.setValue(1.f,0.f,0.f); } btVector3 right = m_cameraUp.cross(forward); btQuaternion roll(right,-rele); eyePos = btMatrix3x3(rot) * btMatrix3x3(roll) * eyePos; m_cameraPosition[0] = eyePos.getX(); m_cameraPosition[1] = eyePos.getY(); m_cameraPosition[2] = eyePos.getZ(); m_cameraPosition += m_cameraTargetPosition; if (m_glutScreenWidth == 0 && m_glutScreenHeight == 0) return; btScalar aspect; btVector3 extents; if (m_glutScreenWidth > m_glutScreenHeight) { aspect = m_glutScreenWidth / (btScalar)m_glutScreenHeight; extents.setValue(aspect * 1.0f, 1.0f,0); } else { aspect = m_glutScreenHeight / (btScalar)m_glutScreenWidth; extents.setValue(1.0f, aspect*1.f,0); } if (m_ortho) { // reset matrix glLoadIdentity(); extents *= m_cameraDistance; btVector3 lower = m_cameraTargetPosition - extents; btVector3 upper = m_cameraTargetPosition + extents; //gluOrtho2D(lower.x, upper.x, lower.y, upper.y); glOrtho(lower.getX(), upper.getX(), lower.getY(), upper.getY(),-1000,1000); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //glTranslatef(100,210,0); } else { if (m_glutScreenWidth > m_glutScreenHeight) { // glFrustum (-aspect, aspect, -1.0, 1.0, 1.0, 10000.0); glFrustum (-aspect * m_frustumZNear, aspect * m_frustumZNear, -m_frustumZNear, m_frustumZNear, m_frustumZNear, m_frustumZFar); } else { // glFrustum (-1.0, 1.0, -aspect, aspect, 1.0, 10000.0); glFrustum (-aspect * m_frustumZNear, aspect * m_frustumZNear, -m_frustumZNear, m_frustumZNear, m_frustumZNear, m_frustumZFar); } glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(m_cameraPosition[0], m_cameraPosition[1], m_cameraPosition[2], m_cameraTargetPosition[0], m_cameraTargetPosition[1], m_cameraTargetPosition[2], m_cameraUp.getX(),m_cameraUp.getY(),m_cameraUp.getZ()); } }
// common run state void RunState() { #if defined(USE_SDL) // last ticks unsigned int ticks = SDL_GetTicks(); #elif defined(USE_SFML) // timer sf::Clock timer; // start timer timer.Reset(); #elif defined(USE_GLFW) double prevtime = glfwGetTime(); #endif // input logging TiXmlDocument inputlog(RECORD_CONFIG.c_str()); TiXmlElement *inputlogroot; TiXmlElement *inputlognext; if (playback) { if (!inputlog.LoadFile()) DebugPrint("error loading recording file \"%s\": %s\n", RECORD_CONFIG.c_str(), inputlog.ErrorDesc()); inputlogroot = inputlog.RootElement(); inputlognext = inputlogroot->FirstChildElement(); } else if (record) { inputlogroot = inputlog.LinkEndChild(new TiXmlElement("journal"))->ToElement(); inputlognext = NULL; } else { inputlogroot = NULL; inputlognext = NULL; } #ifdef GET_PERFORMANCE_DETAILS PerfTimer::Init(); PerfTimer control_timer; PerfTimer simulate_timer; PerfTimer collide_timer; PerfTimer update_timer; PerfTimer render_timer; PerfTimer overlay_timer; PerfTimer display_timer; PerfTimer total_timer; total_timer.Stamp(); #endif #ifdef COLLECT_DEBUG_DRAW // create a new draw list GLuint debugdraw = glGenLists(1); #endif // wait for user exit do { #ifdef GET_PERFORMANCE_DETAILS PerfTimer::Next(); control_timer.Clear(); simulate_timer.Clear(); collide_timer.Clear(); update_timer.Clear(); render_timer.Clear(); overlay_timer.Clear(); display_timer.Clear(); total_timer.Clear(); #endif // INPUT PHASE #if defined(USE_SDL) // event handler SDL_Event event; // process events while( SDL_PollEvent( &event ) ) { /* Give the console first dibs on event processing */ if (OGLCONSOLE_SDLEvent(&event)) continue; switch (event.type) { case SDL_KEYDOWN: input.OnPress( Input::TYPE_KEYBOARD, event.key.which, event.key.keysym.sym ); switch (event.key.keysym.sym) { case SDLK_F4: if (event.key.keysym.mod & KMOD_ALT) setgamestate = STATE_QUIT; break; case SDLK_RETURN: if (event.key.keysym.mod & KMOD_ALT) { CloseWindow(); SCREEN_FULLSCREEN = !SCREEN_FULLSCREEN; OpenWindow(); } break; case SDLK_ESCAPE: if (curgamestate == STATE_PLAY) { if (escape) EscapeMenuExit(); else EscapeMenuEnter(); } break; case SDLK_PAUSE: if (event.key.keysym.mod & KMOD_SHIFT) { paused = true; singlestep = true; } else { paused = !paused; } if (paused) Pause(); else Resume(); break; case SDLK_PRINT: Screenshot(); break; } break; case SDL_KEYUP: input.OnRelease( Input::TYPE_KEYBOARD, event.key.which, event.key.keysym.sym ); break; case SDL_MOUSEMOTION: input.OnAxis( Input::TYPE_MOUSE_AXIS, event.motion.which, 0, float(event.motion.x * 2 - SCREEN_WIDTH) / float(SCREEN_HEIGHT) ); input.OnAxis( Input::TYPE_MOUSE_AXIS, event.motion.which, 1, float(event.motion.y * 2 - SCREEN_HEIGHT) / float(SCREEN_HEIGHT) ); input.OnAxis( Input::TYPE_MOUSE_AXIS, event.motion.which, 2, event.motion.xrel / 32.0f ); input.OnAxis( Input::TYPE_MOUSE_AXIS, event.motion.which, 3, event.motion.yrel / 32.0f ); break; case SDL_MOUSEBUTTONDOWN: input.OnPress( Input::TYPE_MOUSE_BUTTON, event.button.which, event.button.button ); break; case SDL_MOUSEBUTTONUP: input.OnRelease( Input::TYPE_MOUSE_BUTTON, event.button.which, event.button.button ); break; case SDL_JOYAXISMOTION: input.OnAxis( Input::TYPE_JOYSTICK_AXIS, event.jaxis.which, event.jaxis.axis, event.jaxis.value / 32767.0f ); break; case SDL_JOYBUTTONDOWN: input.OnPress( Input::TYPE_JOYSTICK_BUTTON, event.jaxis.which, event.jbutton.button ); break; case SDL_JOYBUTTONUP: input.OnRelease( Input::TYPE_JOYSTICK_BUTTON, event.jbutton.which, event.jbutton.button ); break; case SDL_QUIT: setgamestate = STATE_QUIT; break; } } // get loop time in ticks unsigned int nextticks = SDL_GetTicks(); float delta = (nextticks - ticks) / 1000.0f; ticks = nextticks; #elif defined(USE_SFML) sf::Event event; while (window.GetEvent(event)) { /* Give the console first dibs on event processing */ if (OGLCONSOLE_SFMLEvent(&event)) continue; // Some code for stopping application on close or when escape is pressed... switch (event.Type) { case sf::Event::Resized: glViewport(0, 0, event.Size.Width, event.Size.Height); break; case sf::Event::KeyPressed: input.OnPress( Input::TYPE_KEYBOARD, 0, event.Key.Code ); switch(event.Key.Code) { case sf::Key::F4: if (event.Key.Alt) setgamestate = STATE_QUIT; break; case sf::Key::Return: if (event.Key.Alt) { CloseWindow(); SCREEN_FULLSCREEN = !SCREEN_FULLSCREEN; OpenWindow(); } break; case sf::Key::Escape: if (curgamestate == STATE_PLAY) { if (escape) EscapeMenuExit(); else EscapeMenuEnter(); } break; case sf::Key::Pause: if (event.Key.Shift) { paused = true; singlestep = true; } else { paused = !paused; } if (paused) Pause(); else Resume(); break; } break; case sf::Event::KeyReleased: input.OnRelease( Input::TYPE_KEYBOARD, 0, event.Key.Code ); break; case sf::Event::MouseMoved: input.OnAxis( Input::TYPE_MOUSE_AXIS, 0, 0, float(int(event.MouseMove.X) * 2 - SCREEN_WIDTH) / float(SCREEN_HEIGHT) ); input.OnAxis( Input::TYPE_MOUSE_AXIS, 0, 1, float(int(event.MouseMove.Y) * 2 - SCREEN_HEIGHT) / float(SCREEN_HEIGHT) ); break; case sf::Event::MouseButtonPressed: input.OnPress( Input::TYPE_MOUSE_BUTTON, 0, event.MouseButton.Button ); break; case sf::Event::MouseButtonReleased: input.OnRelease( Input::TYPE_MOUSE_BUTTON, 0, event.MouseButton.Button ); break; case sf::Event::JoyMoved: input.OnAxis( Input::TYPE_JOYSTICK_AXIS, event.JoyMove.JoystickId, event.JoyMove.Axis, event.JoyMove.Position / 100.0f ); break; case sf::Event::JoyButtonPressed: input.OnPress( Input::TYPE_JOYSTICK_BUTTON, event.JoyButton.JoystickId, event.JoyButton.Button ); break; case sf::Event::JoyButtonReleased: input.OnRelease( Input::TYPE_JOYSTICK_BUTTON, event.JoyButton.JoystickId, event.JoyButton.Button ); break; case sf::Event::Closed: setgamestate = STATE_QUIT; break; } } // get loop time in ticks float delta = timer.GetElapsedTime(); timer.Reset(); //ticks += delta; #elif defined(USE_GLFW) if (glfwGetJoystickParam(0, GLFW_PRESENT)) { // get joystick axis positions int axiscount = glfwGetJoystickParam(0, GLFW_AXES); float *axis = static_cast<float *>(_alloca(axiscount * sizeof(float))); axiscount = glfwGetJoystickPos(0, axis, axiscount); for (int i = 0; i < axiscount; ++i) input.OnAxis(Input::TYPE_JOYSTICK_AXIS, 0, i, axis[i]); // get joystick button states int buttoncount = glfwGetJoystickParam(0, GLFW_BUTTONS); unsigned char *button = static_cast<unsigned char *>(_alloca(buttoncount * sizeof(unsigned char))); buttoncount = glfwGetJoystickButtons(0, button, buttoncount); for (int i = 0; i < buttoncount; ++i) input.OnAxis(Input::TYPE_JOYSTICK_BUTTON, 0, i, button[i]); } double nexttime = glfwGetTime(); float delta = float(nexttime - prevtime); prevtime = nexttime; #endif // clamp ticks to something sensible // (while debugging, for example) if (delta > 0.1f) delta = 0.1f; // frame time and turns if (singlestep) { // advance 1/60th of a second frame_time = TIME_SCALE / 60.0f; frame_turns = frame_time * sim_rate; } else if (paused || escape) { // freeze time frame_time = 0.0f; frame_turns = 0.0f; } else if (FIXED_STEP) { // advance one simulation step frame_time = TIME_SCALE * sim_step; frame_turns = TIME_SCALE; } else { // advance by frame time frame_time = delta * TIME_SCALE; frame_turns = frame_time * sim_rate; } // turns per motion-blur step float step_turns = std::min(TIME_SCALE * MOTIONBLUR_TIME * sim_rate, 1.0f) / MOTIONBLUR_STEPS; // advance to beginning of motion blur steps sim_fraction += frame_turns; sim_fraction -= MOTIONBLUR_STEPS * step_turns; // for each motion-blur step for (int blur = 0; blur < MOTIONBLUR_STEPS; ++blur) { // clear the screen glClear( GL_COLOR_BUFFER_BIT #ifdef ENABLE_DEPTH_TEST | GL_DEPTH_BUFFER_BIT #endif ); // set projection glMatrixMode( GL_PROJECTION ); glLoadIdentity(); glFrustum( -0.5*VIEW_SIZE*SCREEN_WIDTH/SCREEN_HEIGHT, 0.5*VIEW_SIZE*SCREEN_WIDTH/SCREEN_HEIGHT, 0.5f*VIEW_SIZE, -0.5f*VIEW_SIZE, 256.0f*1.0f, 256.0f*5.0f ); // set base modelview matrix glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); glTranslatef( 0.0f, 0.0f, -256.0f ); glScalef( -1.0f, -1.0f, -1.0f ); // advance the sim timer sim_fraction += step_turns; if (escape) { input.Update(); input.Step(); } // while simulation turns to run... else while ((singlestep || !paused) && sim_fraction >= 1.0f) { // deduct a turn sim_fraction -= 1.0f; // advance the turn counter ++sim_turn; // save original fraction float save_fraction = sim_fraction; // switch fraction to simulation mode sim_fraction = 0.0f; #ifdef COLLECT_DEBUG_DRAW // collect any debug draw glNewList(debugdraw, GL_COMPILE); #endif // seed the random number generator Random::Seed(0x92D68CA2 ^ sim_turn); (void)Random::Int(); // update database Database::Update(); if (curgamestate == STATE_PLAY) { if (playback) { // quit if out of turns if (!inputlognext) { setgamestate = STATE_SHELL; break; } // get the next turn value int turn = -1; inputlognext->QueryIntAttribute("turn", &turn); // if the turn matches the simulation turn... if ((unsigned int)turn == sim_turn) { // update the control values input.Playback(inputlognext); // go to the next entry inputlognext = inputlognext->NextSiblingElement(); } } else if (record) { // save original input values float prev[Input::NUM_LOGICAL]; memcpy(prev, input.output, sizeof(prev)); // update input values input.Update(); // if any controls have changed... bool changed = false; for (int i = 0; i < Input::NUM_LOGICAL; ++i) { if (input.output[i] != prev[i]) { changed = true; break; } } if (changed) { // create an input turn entry TiXmlElement item( "input" ); item.SetAttribute( "turn", sim_turn ); // add changed control values input.Record(&item, prev); // add the new input entry inputlogroot->InsertEndChild(item); } } else { // update input values input.Update(); } } // do any pending turn actions DoTurn(); // CONTROL PHASE #ifdef GET_PERFORMANCE_DETAILS control_timer.Start(); #endif // control all entities Controller::ControlAll(sim_step); #ifdef GET_PERFORMANCE_DETAILS control_timer.Stop(); simulate_timer.Start(); #endif // SIMULATION PHASE // (generate forces) Simulatable::SimulateAll(sim_step); #ifdef GET_PERFORMANCE_DETAILS simulate_timer.Stop(); collide_timer.Start(); #endif // COLLISION PHASE // (apply forces and update positions) Collidable::CollideAll(sim_step); #ifdef GET_PERFORMANCE_DETAILS collide_timer.Stop(); update_timer.Start(); #endif // UPDATE PHASE // (use updated positions) Updatable::UpdateAll(sim_step); #ifdef GET_PERFORMANCE_DETAILS update_timer.Stop(); #endif // step inputs for next turn input.Step(); #ifdef COLLECT_DEBUG_DRAW // finish the draw list glEndList(); #endif // restore original fraction sim_fraction = save_fraction; } // clear single-step singlestep = false; // seed the random number generator FloatInt floatint; floatint.f = sim_fraction; Random::Seed(0x92D68CA2 ^ sim_turn ^ floatint.u); (void)Random::Int(); #ifdef PRINT_SIMULATION_TIMER DebugPrint("delta=%f ticks=%d sim_t=%f\n", delta, ticks, sim_fraction); #endif #ifdef GET_PERFORMANCE_DETAILS render_timer.Start(); #endif // RENDERING PHASE // push camera transform glPushMatrix(); // get interpolated track position Vector2 viewpos(Lerp(camerapos[0], camerapos[1], sim_fraction)); // set view position glTranslatef( -viewpos.x, -viewpos.y, 0 ); // calculate view area AlignedBox2 view; view.min.x = viewpos.x - VIEW_SIZE * 0.5f * SCREEN_WIDTH / SCREEN_HEIGHT; view.max.x = viewpos.x + VIEW_SIZE * 0.5f * SCREEN_WIDTH / SCREEN_HEIGHT; view.min.y = viewpos.y - VIEW_SIZE * 0.5f; view.max.y = viewpos.y + VIEW_SIZE * 0.5f; // render all entities // (send interpolation ratio and offset from simulation time) Renderable::RenderAll(view); // reset camera transform glPopMatrix(); // if performing motion blur... if (MOTIONBLUR_STEPS > 1) { // accumulate the image glAccum(blur ? GL_ACCUM : GL_LOAD, 1.0f / float(MOTIONBLUR_STEPS)); } #ifdef GET_PERFORMANCE_DETAILS render_timer.Stop(); #endif } #ifdef GET_PERFORMANCE_DETAILS render_timer.Start(); #endif // if performing motion blur... if (MOTIONBLUR_STEPS > 1) { // return the accumulated image glAccum(GL_RETURN, 1); } // switch blend mode glPushAttrib(GL_COLOR_BUFFER_BIT | GL_TEXTURE_BIT); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); #ifdef GET_PERFORMANCE_DETAILS render_timer.Stop(); overlay_timer.Start(); #endif #ifdef COLLECT_DEBUG_DRAW if (DEBUG_DRAW) { // push camera transform glPushMatrix(); // get interpolated track position Vector2 viewpos(Lerp(camerapos[0], camerapos[1], sim_fraction)); // set camera to track position glTranslatef( -viewpos.x, -viewpos.y, 0 ); // debug draw glCallList(debugdraw); // pop camera transform glPopMatrix(); } #endif // push projection transform glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, 640, 480, 0, -1, 1); // use 640x480 screen coordinates glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // render all overlays Overlay::RenderAll(); #ifdef GET_PERFORMANCE_DETAILS overlay_timer.Stop(); if (!OPENGL_SWAPCONTROL) { display_timer.Start(); // wait for rendering to finish glFinish(); display_timer.Stop(); } #ifdef DRAW_PERFORMANCE_DETAILS if (PROFILER_OUTPUTSCREEN) { struct BandInfo { const LONGLONG * time; float r; float g; float b; float a; }; static BandInfo band_info[] = { { control_timer.mHistory, 1.0f, 0.0f, 0.0f, 0.5f }, { simulate_timer.mHistory, 1.0f, 1.0f, 0.0f, 0.5f }, { collide_timer.mHistory, 0.0f, 1.0f, 0.0f, 0.5f }, { update_timer.mHistory, 0.0f, 0.5f, 1.0f, 0.5f }, { render_timer.mHistory, 1.0f, 0.0f, 1.0f, 0.5f }, { overlay_timer.mHistory, 1.0f, 0.5f, 0.0f, 0.5f }, { display_timer.mHistory, 0.5f, 0.5f, 0.5f, 0.5f }, }; // generate y samples float sample_y[SDL_arraysize(band_info)+1][PerfTimer::NUM_SAMPLES]; int index = PerfTimer::mIndex; for (int i = 0; i < PerfTimer::NUM_SAMPLES; ++i) { float y = 480.0f; sample_y[0][i] = y; for (int band = 0; band < SDL_arraysize(band_info); ++band) { y -= 60.0f * 480.0f * band_info[band].time[index] / PerfTimer::mFrequency; sample_y[band+1][i] = y; } if (++index >= PerfTimer::NUM_SAMPLES) index = 0; } glBegin(GL_QUADS); for (int band = 0; band < SDL_arraysize(band_info); ++band) { glColor4fv(&band_info[band].r); float x = 0; float dx = 640.0f / PerfTimer::NUM_SAMPLES; for (int i = 0; i < PerfTimer::NUM_SAMPLES; i++) { glVertex3f(x, sample_y[band][i], 0); glVertex3f(x+dx, sample_y[band][i], 0); glVertex3f(x+dx, sample_y[band+1][i], 0); glVertex3f(x, sample_y[band+1][i], 0); x += dx; } } glEnd(); } #endif #ifdef PRINT_PERFORMANCE_DETAILS if (PROFILER_OUTPUTPRINT) { DebugPrint("C=%d S=%d P=%d U=%d R=%d O=%d D=%d\n", control_timer.Microseconds(), simulate_timer.Microseconds(), collide_timer.Microseconds(), update_timer.Microseconds(), render_timer.Microseconds(), overlay_timer.Microseconds(), display_timer.Microseconds()); } #endif // update frame timer total_timer.Stamp(); #if defined(PRINT_PERFORMANCE_FRAMERATE) || defined(DRAW_PERFORMANCE_FRAMERATE) if (FRAMERATE_OUTPUTSCREEN || FRAMERATE_OUTPUTPRINT) { // compute minimum, maximum, and average frame times over the past second LONGLONG total_min = LLONG_MAX; LONGLONG total_max = LLONG_MIN; LONGLONG total_sum = 0; LONGLONG total_samples = 0; int i = PerfTimer::mIndex; do { total_min = std::min(total_min, total_timer.mHistory[i]); total_max = std::max(total_max, total_timer.mHistory[i]); total_sum += total_timer.mHistory[i]; ++total_samples; i = (i > 0) ? i - 1 : PerfTimer::NUM_SAMPLES - 1; } while (total_sum <= PerfTimer::mFrequency && i != PerfTimer::mIndex && total_samples != PerfTimer::mCount); total_sum /= total_samples; // compute frame rates double rate_max = (double)PerfTimer::mFrequency / total_min; double rate_avg = (double)PerfTimer::mFrequency / total_sum; double rate_min = (double)PerfTimer::mFrequency / total_max; #if defined(DRAW_PERFORMANCE_FRAMERATE) if (FRAMERATE_OUTPUTSCREEN) { // draw frame rate indicator glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, OGLCONSOLE_glFontHandle); glBegin(GL_QUADS); char fps[16]; sprintf(fps, "%.2f max", rate_max); glColor4f(0.5f, 0.5f, 0.5f, 1.0f); OGLCONSOLE_DrawString(fps, 640 - 16 - 8 * strlen(fps), 16, 8, -8, 0); sprintf(fps, "%.2f avg", rate_avg); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); OGLCONSOLE_DrawString(fps, 640 - 16 - 8 * strlen(fps), 24, 8, -8, 0); sprintf(fps, "%.2f min", rate_min); glColor4f(0.5f, 0.5f, 0.5f, 1.0f); OGLCONSOLE_DrawString(fps, 640 - 16 - 8 * strlen(fps), 32, 8, -8, 0); glEnd(); glDisable(GL_TEXTURE_2D); } #endif #if defined(PRINT_PERFORMANCE_FRAMERATE) if (FRAMERATE_OUTPUTPRINT) { DebugPrint("%.2f<%.2f<%.2f\n", rate_min, rate_avg, rate_max); } #endif } #endif #endif // reset camera transform glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); // restore blend mode glPopAttrib(); /* Render our console */ OGLCONSOLE_Draw(); // show the back buffer Platform::Present(); #if 0 #ifdef GET_PERFORMANCE_DETAILS if (OPENGL_SWAPCONTROL) #endif // wait for rendering to finish glFinish(); #endif // clear device reset flag wasreset = false; } while( setgamestate == curgamestate ); if (record) { // save input log inputlog.SaveFile(); } }
void viewport_switch_3d( t_viewport *viewport) { int width; int height; int x; int y; t_context *C = ctx_get(); t_camera *camera = viewport->camera; if( viewport->fullscreen) { width = C->app->window->width; height = C->app->window->height; x = 0; y = 0; } else { width = viewport->width; height = viewport->height; x = viewport->x; y = viewport->y; } if( camera->update_frustum) { op_camera_frustum_init( camera, width, height); C->app->window->change = 0; } glViewport( x, y, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); //if( camera->restrict_matrix) op_camera_restrict( C, camera); glFrustum( camera->left, camera->right, camera->bottom, camera->top, camera->near, camera->far); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt( camera->eye[0], camera->eye[1], camera->eye[2], camera->target[0], camera->target[1], camera->target[2], camera->up[0], camera->up[1], camera->up[2] ); float zenith = camera->zenith; glTranslatef(camera->pos[0],camera->pos[1],camera->pos[2]); // Camera Up rotation glRotatef(zenith,camera->cross[0],camera->cross[1],camera->cross[2]); op_3d_orientation(); }
void initialize(void) { GLfloat light0Pos[4] = { 0.3, 0.3, 0.0, 1.0 }; GLfloat matAmb[4] = { 0.01, 0.01, 0.01, 1.00 }; GLfloat matDiff[4] = { 0.65, 0.65, 0.65, 1.00 }; GLfloat matSpec[4] = { 0.30, 0.30, 0.30, 1.00 }; GLfloat matShine = 10.0; GLfloat eyePlaneS[] = { 1.0, 0.0, 0.0, 0.0 }; GLfloat eyePlaneT[] = { 0.0, 1.0, 0.0, 0.0 }; GLfloat eyePlaneR[] = { 0.0, 0.0, 1.0, 0.0 }; GLfloat eyePlaneQ[] = { 0.0, 0.0, 0.0, 1.0 }; /* ** Setup Misc. */ glClearColor(0.41, 0.41, 0.31, 0.0); glEnable(GL_DEPTH_TEST); glLineWidth(2.0); glCullFace(GL_FRONT); glEnable(GL_CULL_FACE); glMatrixMode(GL_PROJECTION); glFrustum(-0.5, 0.5, -0.5, 0.5, 1, 3); glMatrixMode(GL_MODELVIEW); glTranslatef(0, 0, -2); matrixIdentity((GLfloat *) objectXform); matrixIdentity((GLfloat *) textureXform); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0, 1, 0, 1, -1, 1); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glRasterPos2i(0, 0); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); /* ** Setup Lighting */ glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, matAmb); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, matDiff); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, matSpec); glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, matShine); glEnable(GL_COLOR_MATERIAL); glLightfv(GL_LIGHT0, GL_POSITION, light0Pos); glEnable(GL_LIGHT0); glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE); glEnable(GL_LIGHTING); /* ** Setup Texture */ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); (*loadTexture)(); glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR); glTexGenfv(GL_S, GL_EYE_PLANE, eyePlaneS); glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR); glTexGenfv(GL_T, GL_EYE_PLANE, eyePlaneT); glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR); glTexGenfv(GL_R, GL_EYE_PLANE, eyePlaneR); glTexGeni(GL_Q, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR); glTexGenfv(GL_Q, GL_EYE_PLANE, eyePlaneQ); }
void updateCamera() { float m_ele = 0; float m_azi=0; btVector3 m_cameraPosition(12,20,12); btVector3 m_cameraTargetPosition(0,10,0); btVector3 m_cameraUp(0,1,0); int m_forwardAxis=2; btScalar m_cameraDistance = 130; glMatrixMode(GL_PROJECTION); glLoadIdentity(); float m_frustumZNear=1; float m_frustumZFar=1000; if (m_glutScreenWidth == 0 && m_glutScreenHeight == 0) return; float aspect; btVector3 extents; if (m_glutScreenWidth > m_glutScreenHeight) { aspect = m_glutScreenWidth / (float)m_glutScreenHeight; extents.setValue(aspect * 1.0f, 1.0f,0); } else { aspect = m_glutScreenHeight / (float)m_glutScreenWidth; extents.setValue(1.0f, aspect*1.f,0); } if (m_ortho) { // reset matrix glLoadIdentity(); extents *= m_cameraDistance; btVector3 lower = m_cameraTargetPosition - extents; btVector3 upper = m_cameraTargetPosition + extents; glOrtho(lower.getX(), upper.getX(), lower.getY(), upper.getY(),-1000,1000); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } else { if (m_glutScreenWidth > m_glutScreenHeight) { glFrustum (-aspect * m_frustumZNear, aspect * m_frustumZNear, -m_frustumZNear, m_frustumZNear, m_frustumZNear, m_frustumZFar); } else { glFrustum (-aspect * m_frustumZNear, aspect * m_frustumZNear, -m_frustumZNear, m_frustumZNear, m_frustumZNear, m_frustumZFar); } glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(m_cameraPosition[0], m_cameraPosition[1], m_cameraPosition[2], m_cameraTargetPosition[0], m_cameraTargetPosition[1], m_cameraTargetPosition[2], m_cameraUp.getX(),m_cameraUp.getY(),m_cameraUp.getZ()); } }
int main(int argc, char *argv[]) { SDL_Surface *screen; if ( SDL_Init(SDL_INIT_VIDEO) != 0 ) { printf("Unable to initialize SDL: %s\n", SDL_GetError()); return 1; } SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); screen = SDL_SetVideoMode( 640, 480, 24, SDL_OPENGL ); if ( !screen ) { printf("Unable to set video mode: %s\n", SDL_GetError()); return 1; } glClearColor( 0, 0, 0, 0 ); glClear( GL_COLOR_BUFFER_BIT ); // Create a texture GLuint texture; glGenTextures( 1, &texture ); glBindTexture( GL_TEXTURE_2D, texture ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); GLubyte textureData[16*16*4]; for (int x = 0; x < 16; x++) { for (int y = 0; y < 16; y++) { *((int*)&textureData[(x*16 + y) * 4]) = x*16 + ((y*16) << 8); } } glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, 16, 16, 0, GL_RGBA, GL_UNSIGNED_BYTE, textureData ); // Create a second texture GLuint texture2; glGenTextures( 1, &texture2 ); glBindTexture( GL_TEXTURE_2D, texture2 ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); GLubyte texture2Data[] = { 0xff, 0, 0, 0xff, 0, 0xff, 0, 0xaa, 0, 0, 0xff, 0x55, 0x80, 0x90, 0x70, 0 }; glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, 2, 2, 0, GL_RGBA, GL_UNSIGNED_BYTE, texture2Data ); // BEGIN #if USE_GLEW glewInit(); #endif glMatrixMode(GL_PROJECTION); glLoadIdentity(); // original: glFrustum(-0.6435469817188064, 0.6435469817188064 ,-0.48266022190470925, 0.48266022190470925 ,0.5400000214576721, 2048); glFrustum(-0.6435469817188064, 0.1435469817188064 ,-0.48266022190470925, 0.88266022190470925 ,0.5400000214576721, 2048); glRotatef(-30, 1, 1, 1); //GLfloat pm[] = { 1.372136116027832, 0, 0, 0, 0, 0.7910231351852417, 0, 0, -0.6352481842041016, 0.29297152161598206, -1.0005275011062622, -1, 0, 0, -1.080284833908081, 0 }; //glLoadMatrixf(pm); glMatrixMode(GL_MODELVIEW); GLfloat matrixData[] = { -1, 0, 0, 0, 0, 0,-1, 0, 0, 1, 0, 0, 0, 0, 0, 1 }; glLoadMatrixf(matrixData); //glTranslated(-512,-512,-527); // XXX this should be uncommented, but if it is then nothing is shown glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glClear(GL_DEPTH_BUFFER_BIT); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glActiveTexture(GL_TEXTURE0); glEnableClientState(GL_VERTEX_ARRAY); GLuint arrayBuffer, elementBuffer; glGenBuffers(1, &arrayBuffer); glGenBuffers(1, &elementBuffer); GLubyte arrayData[] = { /* [0, 0, 0, 67] ==> 128 float [0, 0, 128, 67] ==> 256 float [0, 0, 0, 68] ==> 512 float [0, 0, 128, 68] ==> 1024 float [vertex x ] [vertex y ] [vertex z ] [nr] [texture u ] [texture v ] [lm u ] [lm v ] [color r,g,b,a ] */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 68, 11, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, // 0 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 68, 23, 20, 0, 0, 0, 0, 0, 67, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, // 1 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 35, 30, 0, 0, 0, 0, 0, 67, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 2 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 68, 47, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 3 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 68, 51, 50, 0, 0, 0, 0, 0, 67, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, // 4 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 68, 64, 60, 0, 0, 0, 0, 128, 67, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, // 5 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 68, 70, 70, 0, 0, 0, 0, 128, 67, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 6 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 89, 80, 0, 0, 0, 0, 0, 67, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 7 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 68, 94, 90, 0, 0, 0, 0, 0, 0, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 8 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 20, 10, 0, 0, 0, 0, 0, 67, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 9 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 68, 31, 20, 0, 0, 0, 0, 0, 67, 0, 0, 128, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 10 0, 0, 0, 0, 0, 0, 128, 68, 0, 0, 0, 68, 42, 30, 0, 0, 0, 0, 0, 0, 0, 0, 128, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 11 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 53, 40, 0, 0, 0, 0, 0, 67, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 12 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 68, 64, 50, 0, 0, 0, 0, 128, 67, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 13 0, 0, 128, 68, 0, 0, 128, 68, 0, 0, 0, 68, 75, 60, 0, 0, 0, 0, 128, 67, 0, 0, 128, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 14 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 68, 86, 70, 0, 0, 0, 0, 0, 67, 0, 0, 128, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 15 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 128, 68, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128 }; assert(sizeof(arrayData) == 1408); glBindBuffer(GL_ARRAY_BUFFER, arrayBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(arrayData), arrayData, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); GLushort elementData[] = { 1, 2, 0, 2, 3, 0, 5, 6, 4, 6, 7, 4, 9, 10, 8, 10, 11, 8, 13, 14, 12, 14, 15, 12 }; assert(sizeof(elementData) == 48); glBindBuffer(GL_ARRAY_BUFFER, arrayBuffer); // sauer vertex data is apparently 0-12: V3F, 12: N1B, 16-24: T2F, 24-28: T2S, 28-32: C4B glVertexPointer(3, GL_FLOAT, 32, (void*)0); // all these apply to the ARRAY_BUFFER that is bound glTexCoordPointer(2, GL_FLOAT, 32, (void*)16); glClientActiveTexture(GL_TEXTURE1); // XXX seems to be ignored in native build glTexCoordPointer(2, GL_SHORT, 32, (void*)24); glClientActiveTexture(GL_TEXTURE0); // likely not needed, it is a cleanup glNormalPointer(GL_BYTE, 32, (void*)12); glColorPointer(4, GL_UNSIGNED_BYTE, 32, (void*)28); glBindTexture(GL_TEXTURE_2D, texture); // diffuse? glActiveTexture(GL_TEXTURE0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texture2); // lightmap? glActiveTexture(GL_TEXTURE0); GLint ok; const char *vertexShader = "uniform vec4 texgenscroll;\n" "void main(void)\n" "{\n" " gl_Position = ftransform();\n" " gl_TexCoord[0].xy = gl_MultiTexCoord0.xy/10000.0 + (0.001*texgenscroll.xy) + gl_Normal.xy;\n" // added /100 here " gl_TexCoord[1].xy = gl_MultiTexCoord1.xy/100.0 * 3.051851e-05;\n" "}\n"; const char *fragmentShader = "uniform vec4 colorparams;\n" "uniform sampler2D diffusemap, lightmap;\n" "void main(void)\n" "{\n" " vec4 diffuse = texture2D(diffusemap, gl_TexCoord[0].xy);\n" " vec4 lm = texture2D(lightmap, gl_TexCoord[1].xy);\n" " diffuse *= colorparams;\n" " gl_FragColor = diffuse * lm;\n" "}\n"; GLuint vs = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vs, 1, &vertexShader, NULL); glCompileShader(vs); glGetShaderiv(vs, GL_COMPILE_STATUS, &ok); assert(ok); GLuint fs = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fs, 1, &fragmentShader, NULL); glCompileShader(fs); glGetShaderiv(fs, GL_COMPILE_STATUS, &ok); assert(ok); GLuint program = glCreateProgram(); glAttachShader(program, vs); glAttachShader(program, fs); glLinkProgram(program); glGetProgramiv(program, GL_LINK_STATUS, &ok); assert(ok); glUseProgram(program); GLint lightmapLocation = glGetUniformLocation(program, "lightmap"); assert(lightmapLocation >= 0); glUniform1i(lightmapLocation, 1); // sampler2D? Is it the texture unit? GLint diffusemapLocation = glGetUniformLocation(program, "diffusemap"); assert(diffusemapLocation >= 0); glUniform1i(diffusemapLocation, 0); GLint texgenscrollLocation = glGetUniformLocation(program, "texgenscroll"); assert(texgenscrollLocation >= 0); GLint colorparamsLocation = glGetUniformLocation(program, "colorparams"); assert(colorparamsLocation >= 0); GLfloat texgenscrollData[] = { 0, 0, 0, 0 }; glUniform4fv(texgenscrollLocation, 1, texgenscrollData); GLfloat colorparamsData[] = { 2, 2, 2, 1 }; glUniform4fv(colorparamsLocation, 1, colorparamsData); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)&elementData[12/sizeof(GLushort)]); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)&elementData[ 0/sizeof(GLushort)]); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)&elementData[24/sizeof(GLushort)]); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)&elementData[36/sizeof(GLushort)]); // END SDL_GL_SwapBuffers(); #ifndef __EMSCRIPTEN__ SDL_Delay(1500); #endif SDL_Quit(); return 0; }
bool GLWindow::setPerspectiveView(double x, double y, double w, double h) { // we want a perspective view for an area over the entire display bounded by (x,y,w,h) // this windows area is produced by intersection((left_,right_,bottom_,top_), (x,y,w,h)) // in the current coordinate system, bottom is at the top of the screen, top at the bottom... QRectF screenRect = QRectF(left_, bottom_, right_-left_, top_-bottom_); QRectF windowRect = QRectF(x, y, w, h); QRectF boundRect = screenRect.intersected(windowRect); // if bounding rectangle is empty, return false to indicate no rendering should be done if(boundRect.isEmpty() == true) { return false; } if(boundRect != screenRect) { // x,y for viewport is lower-left corner // the y coordinate needs to be shifted from the top of the screen to the bottom, and y-direction inverted int viewPortX = (int)((boundRect.x() - screenRect.x()) / screenRect.width() * width()); int viewPortY = (int)((screenRect.height() - (boundRect.y() + boundRect.height() - screenRect.y())) / screenRect.height() * height()); int viewPortW = (int)(boundRect.width() / screenRect.width() * width()); int viewPortH = (int)(boundRect.height() / screenRect.height() * height()); glViewport(viewPortX, viewPortY, viewPortW, viewPortH); } glMatrixMode(GL_PROJECTION); glLoadIdentity(); double near = 0.001; double far = 100.; double aspect = (double)g_configuration->getTotalHeight() / (double)g_configuration->getTotalWidth() * windowRect.height() / windowRect.width(); double winFovY = 45.0 * aspect; double top = tan(0.5 * winFovY * M_PI/180.) * near; double bottom = -top; double left = 1./aspect * bottom; double right = 1./aspect * top; // this window's portion of the entire view above is bounded by (left_, right_) and (bottom_, top_) // the full frustum would be for this screen: // glFrustum(left + left_ * (right-left), left + right_ * (right-left), top + top_ * (bottom-top), top + bottom_ * (bottom-top), near, far); double fLeft = left + (boundRect.x() - windowRect.x()) / windowRect.width() * (right-left); double fRight = fLeft + boundRect.width() / windowRect.width() * (right-left); double fBottom = top + (boundRect.y() - windowRect.y()) / windowRect.height() * (bottom-top); double fTop = fBottom + boundRect.height() / windowRect.height() * (bottom-top); glFrustum(fLeft, fRight, fTop, fBottom, near, far); glPushMatrix(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // don't clear the GL_COLOR_BUFFER_BIT since this may be an overlay. only clear depth glClear(GL_DEPTH_BUFFER_BIT); // new lookat matrix glLoadIdentity(); gluLookAt(0,0,1, 0,0,0, 0,1,0); // setup lighting GLfloat LightAmbient[] = { 0.01, 0.01, 0.01, 1.0 }; GLfloat LightDiffuse[] = { .5, .5, .5, 1.0 }; GLfloat LightSpecular[] = { .9,.9,.9, 1.0 }; GLfloat LightPosition[] = { 0,0,1000000, 1.0 }; glLightModelfv(GL_LIGHT_MODEL_AMBIENT, LightAmbient); glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 1); glLightfv(GL_LIGHT1, GL_AMBIENT, LightAmbient); glLightfv(GL_LIGHT1, GL_DIFFUSE, LightDiffuse); glLightfv(GL_LIGHT1, GL_SPECULAR, LightSpecular); glLightfv(GL_LIGHT1, GL_POSITION, LightPosition); glEnable(GL_LIGHT1); // glEnable(GL_LIGHTING) needs to be called to actually use lighting. ditto for depth testing. // let other code enable / disable such settings so glPushAttrib() and glPopAttrib() can be used appropriately return true; }
void camara_control(int camara) { //letras de identificacao da camara glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); glEnable(GL_COLOR_MATERIAL); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); gluOrtho2D( 0.0, DIMX, 0.0, DIMY); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); glColor3f(1.0,1.0,0.0); //amarelo glRasterPos2i(3, DIMY-25); glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, 'C'); glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, 'a'); glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, 'm'); glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, 'a'); glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, 'r'); glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, 'a'); glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, ' '); glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, '0'+camara); glDisable(GL_COLOR_MATERIAL); // inicializacoes da matriz de visualizacao glMatrixMode( GL_PROJECTION ); glLoadIdentity(); glFrustum( -xy_aspect*.04, xy_aspect*.04, -.04, .04, .1, 1500.0 );//alcance da camara //inicializacoes da matriz de transformacoes geometricas glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); switch (camara) { case 1: // afasta a cena // ...decorre da utilizacao do botao de afastamento (pseudo-zoom) glTranslatef( obj_pos[0]-225, obj_pos[1]-50, -obj_pos[2]-250 ); // roda a cena para ficar em perspectiva glRotated( 20.0, 1.0,0.0,0.0 ); // 20 graus em torno de X // roda a cena de acordo com o botao (esfera) de rotacao glMultMatrixf( view_rotate ); view_rot->enable(); trans_z->enable(); break; case 2: //vista de cima gluLookAt(225.0, 500.0, -150.0, 225.0, 0.0, -150.0, 0.0, 0.0, -1.0); view_rot->disable(); trans_z->disable(); break; case 3: //vista sempre centrada no heliporto gluLookAt(camara3_x, camara3_y, camara3_z, camara3_ox, camara3_oy, camara3_oz, 0.0, 1.0, 0.0); view_rot->disable(); trans_z->disable(); break; case 4: gluLookAt(225,250,-71,225,0,-70,0,-1,0); view_rot->disable(); trans_z->disable(); break; default: break; } }
void draw_gl(void) { static float r=0, SIZE=1; float Size =(p.size + p.sizeloudness * gloudness)/2; SIZE = (SIZE +3*Size) /4; r++; glClearColor(0,0,0,0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(-1, 1, -1, 1, 1.5, 40); gluLookAt(0, 0, 6, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // BEGIN DRAWING glDisable(GL_TEXTURE_2D); #if DEBUG_BEAT if(beat>0) { beat--; glBegin(GL_QUADS); glColor3f(0.1 , 0.9 , 0.1 );// subliminal beat.. glVertex3f(2,2,0); glVertex3f(-2,2,0); glVertex3f(-2,-2,0); glVertex3f(2,-2,0); glEnd(); } glColor3f(1 , 1 , .3 );// subliminal beat.. glBegin(GL_LINES); for(int i = 0; i < 200; i++) { double x = (i-100); double y = gloudnesses[(200+i+curloudness)%200]; int beat = 0; if(y <0) { y = -y; beat = 1; } y = 4*(y-100)/200; glVertex3f(x/30,y,0); if(beat) { glVertex3f(x/30,-1.9,0); glVertex3f(x/30,-2,0); } if(i>0 && i <199) glVertex3f(x/30,y,0); } double y = maxgloudness; y = 4*(y-100)/200; glVertex3f(-3,y,0); glVertex3f(3,y,0); y = mingloudness; y = 4*(y-100)/200; glVertex3f(-3,y,0); glVertex3f(3,y,0); y = avgloudness; y = 4*(y-100)/200; glVertex3f(-3,y,0); glVertex3f(3,y,0); glEnd(); #else glDisable(GL_DEPTH_TEST); glDepthMask(false); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE); for(int i=0;i<ptsNum;i++) { GLfloat colors[][3]={ {1.,0.2,0.2 } ,{0.2,1.,0.2} ,{0.4,0.4,1}}; if(p.mode < 50) { glBindTexture(GL_TEXTURE_2D, texture[0]); // choose the texture to use. glEnable(GL_TEXTURE_2D); glPushMatrix(); glTranslatef(pts[i][0]/100,pts[i][1]/100,pts[i][2]/100); glBegin(GL_QUADS); glColor3fv(colors[i%3] ); //cout<<i<< " :"<<pts[i][0] << " " <<pts[i][1] << " " << pts[i][2] << endl; glTexCoord2f(0,0); glVertex3f(-SIZE, -SIZE, 0); glTexCoord2f(1,0); glVertex3f(SIZE,-SIZE, 0); glTexCoord2f(1,1); glVertex3f(SIZE, SIZE, 0); glTexCoord2f(0,1); glVertex3f(-SIZE, SIZE, 0); glEnd(); glPopMatrix(); } else { //float SIZE2=SIZE*10; glDisable(GL_TEXTURE_2D); if(pts[(i+1)%ptsNum][0]>pts[i][0]) { glBegin(GL_QUADS); /* if(speed[i][0]>0) { // glColor3fv(colors[0] ); glVertex3f(pts[i][0]/100,1,pts[i][2]/100); glVertex3f(pts[i][0]/100+SIZE2,1,pts[i][2]/100); glVertex3f(pts[i][0]/100+SIZE2, 1+SIZE2, pts[(i+1)%ptsNum][2]/100); glVertex3f(pts[i][0]/100,1+SIZE2,pts[(i+1)%ptsNum][2]/100); glEnd(); glBegin(GL_QUADS); // cout <<"tptp\n"; } */ glColor3fv(colors[2] ); glVertex3f(pts[i][0]/100,pts[i][1]/100,0); glVertex3f(pts[i][0]/100+SIZE,pts[i][1]/100,0); glVertex3f(pts[(i+1)%ptsNum][0]/100+SIZE, pts[(i+1)%ptsNum][1]/100,0); glVertex3f(pts[(i+1)%ptsNum][0]/100,pts[(i+1)%ptsNum][1]/100,0); glEnd(); } } } #endif }
static void draw(void) { float ar; glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0.0, 0.0, -40.0); /* clear whole depth buffer */ glDisable(GL_SCISSOR_TEST); glClear(GL_DEPTH_BUFFER_BIT); glEnable(GL_SCISSOR_TEST); /* clear upper-left corner of color buffer (unused space) */ glScissor(0, TexHeight, TexWidth, WinHeight - TexHeight); glClearColor(0.0, 0.0, 0.0, 0.0); glClear(GL_COLOR_BUFFER_BIT); /* clear lower-left corner of color buffer */ glViewport(0, 0, TexWidth, TexHeight); glScissor(0, 0, TexWidth, TexHeight); glClearColor(1, 1, 1, 0); glClear(GL_COLOR_BUFFER_BIT); /* draw gears in lower-left corner */ glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(-1.0, 1.0, -1.0, 1.0, 5.0, 60.0); glMatrixMode(GL_MODELVIEW); DrawGears(); /* copy color buffer to texture */ glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, TexWidth, TexHeight); /* clear right half of color buffer */ glViewport(TexWidth, 0, WinWidth - TexWidth, WinHeight); glScissor(TexWidth, 0, WinWidth - TexWidth, WinHeight); glClearColor(0.5, 0.5, 0.8, 0.0); glClear(GL_COLOR_BUFFER_BIT); /* draw textured cube in right half of window */ ar = (float) (WinWidth - TexWidth) / WinHeight; glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(-ar, ar, -1.0, 1.0, 5.0, 60.0); glMatrixMode(GL_MODELVIEW); DrawCube(); /* finish up */ glutSwapBuffers(); Frames++; { GLint t = glutGet(GLUT_ELAPSED_TIME); if (t - T0 >= 5000) { GLfloat seconds = (t - T0) / 1000.0; GLfloat fps = Frames / seconds; printf("%d frames in %6.3f seconds = %6.3f FPS\n", Frames, seconds, fps); fflush(stdout); T0 = t; Frames = 0; } } }
void *draw_thread_func(void *arg) { Bool configured = FALSE; if ((window = create_window(640, 480)) == 0) { g_log(NULL, G_LOG_LEVEL_CRITICAL, __FILE__ ": unable to create window"); pthread_exit(NULL); } XMapWindow(dpy, window); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(-1, 1, -1, 1, 1.5, 10); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); #ifdef HAVE_SCHED_SETSCHEDULER if(xmms_check_realtime_priority()) { struct sched_param sparam; sparam.sched_priority = sched_get_priority_max(SCHED_OTHER); pthread_setschedparam(pthread_self(), SCHED_OTHER, &sparam); } #endif while(going) { while(XPending(dpy)) { XEvent event; KeySym keysym; char buf[16]; XNextEvent(dpy, &event); switch(event.type) { case ConfigureNotify: glViewport(0,0,event.xconfigure.width, event.xconfigure.height); if(oglspectrum_cfg.tdfx_mode && !grabbed_pointer) { XGrabPointer(dpy, window, True, ButtonPressMask, GrabModeAsync, GrabModeAsync, window, None, CurrentTime); grabbed_pointer = TRUE; } configured = TRUE; break; case KeyPress: XLookupString (&event.xkey, buf, 16, &keysym, NULL); switch(keysym) { case XK_Escape: /* Ugly hack to get the disable_plugin call in the main thread. */ GDK_THREADS_ENTER(); gtk_idle_add(disable_func, NULL); GDK_THREADS_LEAVE(); break; case XK_z: xmms_remote_playlist_prev(oglspectrum_vp.xmms_session); break; case XK_x: xmms_remote_play(oglspectrum_vp.xmms_session); break; case XK_c: xmms_remote_pause(oglspectrum_vp.xmms_session); break; case XK_v: xmms_remote_stop(oglspectrum_vp.xmms_session); break; case XK_b: xmms_remote_playlist_next(oglspectrum_vp.xmms_session); break; case XK_Up: x_speed -= 0.1; if(x_speed < -3.0) x_speed = -3.0; break; case XK_Down: x_speed += 0.1; if(x_speed > 3.0) x_speed = 3.0; break; case XK_Left: y_speed -= 0.1; if(y_speed < -3.0) y_speed = -3.0; break; case XK_Right: y_speed += 0.1; if(y_speed > 3.0) y_speed = 3.0; break; case XK_w: z_speed -= 0.1; if(z_speed < -3.0) z_speed = -3.0; break; case XK_q: z_speed += 0.1; if(z_speed > 3.0) z_speed = 3.0; break; case XK_Return: x_speed = 0.0; y_speed = 0.5; z_speed = 0.0; x_angle = 20.0; y_angle = 45.0; z_angle = 0.0; break; } break; case ClientMessage: if ((Atom)event.xclient.data.l[0] == wm_delete_window_atom) { GDK_THREADS_ENTER(); gtk_idle_add(disable_func, NULL); GDK_THREADS_LEAVE(); } break; } } if(configured) { x_angle += x_speed; if(x_angle >= 360.0) x_angle -= 360.0; y_angle += y_speed; if(y_angle >= 360.0) y_angle -= 360.0; z_angle += z_speed; if(z_angle >= 360.0) z_angle -= 360.0; draw_bars(); } } if (glxcontext) { glXMakeCurrent(dpy, 0, NULL); glXDestroyContext(dpy, glxcontext); glxcontext = NULL; } if (window) { if (grabbed_pointer) { XUngrabPointer(dpy, CurrentTime); grabbed_pointer = FALSE; } XDestroyWindow(dpy, window); window = 0; } pthread_exit(NULL); }
void Viewer::paintGL() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if(false) { // Default camera: glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(-2, 2, -1.5, 1.5, 1, 40); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0, 0, -3); glRotatef(50, 1, 0, 0); glRotatef(70, 0, 1, 0); // Draw a white grid "floor" for the tetrahedron to sit on. glColor3d(0.8, 0.8, 0.7); glBegin(GL_LINES); for (GLfloat i = -2.5; i <= 2.5; i += 0.25) { glVertex3f(i, 2.5, 0); glVertex3f(i, -2.5, 0); glVertex3f(2.5, i, 0); glVertex3f(-2.5, i, 0); } glEnd(); // Draw the tetrahedron. if(false) { glBegin(GL_TRIANGLE_STRIP); glColor3f(1, 1, 1); glVertex3f(0, 0, 2); glColor3f(1, 0, 0); glVertex3f(-1, 1, 0); glColor3f(0, 1, 0); glVertex3f(1, 1, 0); glColor3f(0, 0, 1); glVertex3f(0, -1.4f, 0); glColor3f(1, 1, 1); glVertex3f(0, 0, 2); glColor3f(1, 0, 0); glVertex3f(-1, 1, 0); glEnd(); } } if( !isReady ) return; // Setup camera Eigen::Vector3d center, eye; { // Bounding volume { Eigen::Vector3d dir( cos(t), sin(t), 0.25); Eigen::AlignedBox3d bbox; for(auto v : vertices) bbox.extend(v); double radius = bbox.sizes().norm() * 2.75; center = bbox.center(); eye = center + (dir.normalized() * radius); } auto projectionMatrix = perspective<double>(20, 1.0, 0.01, 1000); auto cameraMatrix = lookAt< Eigen::Vector3d >(eye, center, Eigen::Vector3d(0,0,1)); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glLoadMatrixd( projectionMatrix.data() ); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glLoadMatrixd( cameraMatrix.data() ); } // Added user rotation { glRotatef(xRot / 16.0, 1.0, 0.0, 0.0); glRotatef(yRot / 16.0, 0.0, 1.0, 0.0); glRotatef(zRot / 16.0, 0.0, 0.0, 1.0); } glColor3d(1,0,0); // Render geometry { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glColor3d(0,0,0); glDisable(GL_LIGHTING); glLineWidth(6); //RenderMesh(); glClear(GL_DEPTH_BUFFER_BIT); //glEnable(GL_LIGHTING); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glColor3d(0,0,0); RenderMesh(); } }
void trBeginTile(TRcontext *tr) { GLint matrixMode; GLint tileWidth, tileHeight, border; GLdouble left, right, bottom, top; if (!tr) return; if (tr->CurrentTile <= 0) { Setup(tr); /* Save user's viewport, will be restored after last tile rendered */ glGetIntegerv(GL_VIEWPORT, tr->ViewportSave); } /* which tile (by row and column) we're about to render */ if (tr->RowOrder==TR_BOTTOM_TO_TOP) { tr->CurrentRow = tr->CurrentTile / tr->Columns; tr->CurrentColumn = tr->CurrentTile % tr->Columns; } else if (tr->RowOrder==TR_TOP_TO_BOTTOM) { tr->CurrentRow = tr->Rows - (tr->CurrentTile / tr->Columns) - 1; tr->CurrentColumn = tr->CurrentTile % tr->Columns; } else { /* This should never happen */ abort(); } assert(tr->CurrentRow < tr->Rows); assert(tr->CurrentColumn < tr->Columns); border = tr->TileBorder; /* Compute actual size of this tile with border */ if (tr->CurrentRow < tr->Rows-1) tileHeight = tr->TileHeight; else tileHeight = tr->ImageHeight - (tr->Rows-1) * (tr->TileHeightNB) + 2 * border; if (tr->CurrentColumn < tr->Columns-1) tileWidth = tr->TileWidth; else tileWidth = tr->ImageWidth - (tr->Columns-1) * (tr->TileWidthNB) + 2 * border; /* Save tile size, with border */ tr->CurrentTileWidth = tileWidth; tr->CurrentTileHeight = tileHeight; glViewport(0, 0, tileWidth, tileHeight); /* tile size including border */ /* save current matrix mode */ glGetIntegerv(GL_MATRIX_MODE, &matrixMode); glMatrixMode(GL_PROJECTION); glLoadIdentity(); /* compute projection parameters */ left = tr->Left + (tr->Right - tr->Left) * (tr->CurrentColumn * tr->TileWidthNB - border) / tr->ImageWidth; right = left + (tr->Right - tr->Left) * tileWidth / tr->ImageWidth; bottom = tr->Bottom + (tr->Top - tr->Bottom) * (tr->CurrentRow * tr->TileHeightNB - border) / tr->ImageHeight; top = bottom + (tr->Top - tr->Bottom) * tileHeight / tr->ImageHeight; if (tr->Perspective) glFrustum(left, right, bottom, top, tr->Near, tr->Far); else glOrtho(left, right, bottom, top, tr->Near, tr->Far); /* restore user's matrix mode */ glMatrixMode(matrixMode); }
void MyWindow::OnCreate() { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR); // clear window first: it might take a moment before image loads glClear(GL_COLOR_BUFFER_BIT); SwapBuffers(); // load image _images[0].Load("left.bmp"); _images[1].Load("right.bmp"); _images[2].Load("top.bmp"); _images[3].Load("bottom.bmp"); _images[4].Load("front.bmp"); _images[5].Load("back.bmp"); _images[6].Load("map.bmp"); glGenTextures(7, &_textures[0]); // build 2D mip-maps from image for (int i = 0; i<7;i++) { glBindTexture(GL_TEXTURE_2D, _textures[i]); _images[i].gluBuild2DMipmaps(); _images[i].Free(); }; // set the projection required glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(-1.0f, +1.0f, -1.0f, +1.0f, 1.0f, +10.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glViewport(0,0, Width(), Height()); glEnable(GL_DEPTH_TEST); // set the background clear colour to black glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // set the shade model to smooth (Gouraud shading) glShadeModel(GL_SMOOTH); // remove back faces glEnable(GL_CULL_FACE); _material1.create(Color::black(), Color(0.8f,0.8f,0.8f,1.0f)); _material2.create(Color::black(), Color(0.7f,0.7f,0.7f,1.0f)); _material3.create(Color::black(), Color::black(), Color::yellow()); // setup some lights (ambient is turned off on all lights) _light1.create(0, Color::black(), Color(0.5f,0.5f,0.5f,1.0f)); _light2.create(1, Color::black(), Color(0.5f,0.5f,0.5f,1.0f)); _light3.create(2, Color::black(), Color(0.5f,0.5f,0.0f,1.0f)); // turn the global ambient off by setting it to zero glLightModelfv(GL_LIGHT_MODEL_AMBIENT, Color::black().rgba()); // Turn on the lights _light1.apply(); _light2.apply(); _light3.apply(); // setup the two spheres _sphere1.create(0.1f, 10, 10, false); //_sphere2.create(1.0f, 20, 20, true); _sphere.create(1.0f, 40, 40, true); _cameraAngle = 30.0; _cameraPosition = -5.0; _cameraRotation = 0.0; _fullscreen = false; }
void init_display() { int surface_type_id, result, i, value, scrn, num_fbconfigs; GLXFBConfig *fbconfigs; XVisualInfo *visInfo; XSetWindowAttributes attributes; Window root; int attrib_pbuffer[6] = {GLX_PBUFFER_WIDTH, 0, GLX_PBUFFER_HEIGHT, 0, GLX_PRESERVED_CONTENTS, 0}; width = horizontal_size; height = vertical_size; if(chroma_format != CHROMA420) error("we only support 4:2:0 chroma formats\n"); display = XOpenDisplay(NULL); root = XDefaultRootWindow(display); scrn = XDefaultScreen(display); if(!GetPortId(display, &portNum, &surface_type_id)) error("couldn't find a suitable port\n"); #ifdef USE_DLOPEN if(!ResolveFunctions(DLFILENAME)) error("couldn't resolve necessary functions\n"); #endif result = XvMCCreateContext(display, portNum, surface_type_id, coded_picture_width, coded_picture_height, XVMC_DIRECT, &context); if(result != Success) error("couldn't create XvMCContext\n"); for(i = 0; i < numsurfaces; i++) { result = XvMCCreateSurface(display, &context, &surfaces[i]); if(result != Success) { if(i < 4) { XvMCDestroyContext(display, &context); error("couldn't create enough XvMCSurfaces\n"); } else { numsurfaces = i; printf("could only allocate %i surfaces\n", numsurfaces); } } surface_info[i].reference = 0; surface_info[i].sequence_number = 0; } slices = slices * mb_width; XvMCCreateBlocks(display, &context, slices * 6, &blocks); XvMCCreateMacroBlocks(display, &context, slices, ¯o_blocks); fbconfigs = glXChooseFBConfig(display, scrn, attr_fbconfig, &num_fbconfigs); gl_fbconfig = *fbconfigs; /* find the first one with no depth buffer */ for(i = 0; i < num_fbconfigs; i++) { glXGetFBConfigAttrib(display, fbconfigs[i], GLX_DEPTH_SIZE, &value); if(value == 0) { gl_fbconfig = fbconfigs[i]; break; } } PrintVisual(); visInfo = glXGetVisualFromFBConfig(display, gl_fbconfig); attrib_pbuffer[1] = width; attrib_pbuffer[3] = bob ? (height/2) : height; gl_pbuffer = glXCreatePbuffer(display, gl_fbconfig, attrib_pbuffer); gl_context = glXCreateNewContext(display, gl_fbconfig, GLX_RGBA_TYPE, NULL, 1); attributes.colormap = XCreateColormap(display, root, visInfo->visual, AllocNone); window = XCreateWindow(display, root, 0, 0, width, height, 0, visInfo->depth, InputOutput, visInfo->visual, CWColormap, &attributes); gl_window = glXCreateWindow(display, gl_fbconfig, window, NULL); XSelectInput(display, window, KeyPressMask | StructureNotifyMask | Button1MotionMask | ButtonPressMask); XMapWindow(display, window); glXMakeContextCurrent(display, gl_window, gl_pbuffer, gl_context); glDrawBuffer(GL_BACK); glReadBuffer(GL_FRONT_LEFT); tex_w = 1 << PowerOfTwo(width); tex_h = 1 << PowerOfTwo(bob ? (height/2) : height); printf("%i x %i texture\n", tex_w, tex_h); glClearColor (0.0, 0.0, 0.0, 0.0); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexImage2D(GL_TEXTURE_2D, 0, 3, tex_w, tex_h, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); glEnable(GL_TEXTURE_2D); glShadeModel(GL_FLAT); glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(-1.0, 1.0, -1.0, 1.0, 2, 18.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0.0, 0.0, -8); #ifdef USE_NV_FENCE glGenFencesNV(1, &nvFence); glSetFenceNV(&nvFence, GL_ALL_COMPLETED_NV); #endif XSync(display, 0); uiclp = uiclip+512; for (i= -512; i<512; i++) uiclp[i] = (i<-128) ? 0 : ((i>127) ? 255 : i+128); iclp = iclip+512; for (i= -512; i<512; i++) iclp[i] = (i<-128) ? -128 : ((i>127) ? 127 : i); niclp = niclip+512; for (i= -512; i<512; i++) niclp[i] = (i<-256) ? -256 : ((i>255) ? 255 : i); }
void Visualizer::paintGL() { QPainter painter; painter.begin(this); // qApp->processEvents(); //cout << "paintGL called" << endl; model->gui_ready = true; model->drawing = true; if (model->paths_mutex) { cout << "Visualizer: paths_mutex is set" << endl; model->paths_mutex_seen = true; return; } if (model->targets_mutex) { cout << "Visualizer: targets_mutex is set" << endl; model->targets_mutex_seen = true; return; } if (model->searchers_mutex) { cout << "Visualizer: searchers_mutex is set" << endl; model->searchers_mutex_seen = true; return; } x_min_bound = getModel()->getSearchSpace()->getXMinBound(); y_min_bound = getModel()->getSearchSpace()->getYMinBound(); z_min_bound = getModel()->getSearchSpace()->getZMinBound(); x_max_bound = getModel()->getSearchSpace()->getXMaxBound(); y_max_bound = getModel()->getSearchSpace()->getYMaxBound(); z_max_bound = getModel()->getSearchSpace()->getZMaxBound(); saveGLState(); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); //glTranslatef(0.0, 0.0, -10.0); glFrustum(-1, 1, -1, 1, 0, 100); glViewport(0, 0, 2*width(), 2*height()); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //glTranslatef(0.0f, 0.0f, -15.0f); glRotatef(xRot / 16.0, 1.0, 0.0, 0.0); glRotatef(yRot / 16.0, 0.0, 1.0, 0.0); glRotatef(zRot / 16.0, 0.0, 0.0, 1.0); glTranslatef(horz_pan, vert_pan, 0.0f); //glScalef (1.0, 1.0, 1.0); /* modeling transformation */ glScalef(scale, scale, scale); glColor4f(1.0, 1.0, 1.0, 0.3); drawRectangularPrism(x_min_bound, y_min_bound, z_min_bound, x_max_bound, y_max_bound, z_max_bound); QPointF pos; QPointF center_pos; SearchSpace* space = model->getSearchSpace(); int n_searchers = space->getNumSearchers(); Searcher* searchers = space->getSearchers(); //cout << "Number of searchers: " << n_searchers << endl; // draw boundary QRect frame_rect = this->contentsRect(); int frame_height = frame_rect.height(); int frame_width = frame_rect.width(); center_pos = frame_rect.center(); for ( int i = 0; i < n_searchers; i++ ) { float scaled_x = searchers[i].getXPos();//*frame_width/2+center_pos.x(); float scaled_y = searchers[i].getYPos();//*frame_height/2+center_pos.y(); float scaled_z = searchers[i].getZPos();//*frame_height/2+center_pos.y(); glColor3f(searchers[i].red/255.0, searchers[i].blue/255.0, searchers[i].green/255.0); GLUquadricObj *quadric=gluNewQuadric(); gluQuadricNormals(quadric, GLU_SMOOTH); glPushMatrix(); glTranslatef( scaled_x, scaled_y, scaled_z ); glPushMatrix(); gluSphere(quadric, target_display_radius, 10,10); glPopMatrix(); gluDeleteQuadric(quadric); //cout << "Raw (" << searchers[i].getXPos() << ", " << searchers[i].getYPos() << ", " << searchers[i].getZPos() <<")" << endl; //cout << "Scaled (" << scaled_x << ", " << scaled_y << ", " << scaled_z << ")" << endl; // Display path vector<Coordinate*> path = searchers[i].getPath(); for(vector<Coordinate*>::iterator it = path.begin(); it != path.end(); ++it) { float scaled_path_x = (*it)->getX();//*frame_width/2;//+center_pos.x(); float scaled_path_y = (*it)->getY();//*frame_height/2;//+center_pos.y(); float scaled_path_z = (*it)->getZ();//*frame_height/2;//+center_pos.y(); // <---- FIX FOR Z Coordinate start, end; start.setX(scaled_path_x); start.setY(scaled_path_y); start.setZ(scaled_path_z); if (it+1 != path.end()) { scaled_path_x = (*(it+1))->getX();//*frame_width/2;//+center_pos.x(); scaled_path_y = (*(it+1))->getY();//*frame_height/2;//+center_pos.y(); scaled_path_z = (*(it+1))->getZ();//*frame_height/2;//+center_pos.y(); } else { break; } end.setX(scaled_path_x); end.setY(scaled_path_y); end.setZ(scaled_path_z); //painter.drawLine(path_segment); glBegin(GL_LINES); glVertex3d(start.getX(), start.getY(), start.getZ()); glVertex3d(end.getX(), end.getY(), end.getZ()); glEnd(); } } // display targets int n_targets = space->getNumTargets(); Target* targets = space->getTargets(); for ( int i = 0; i < n_targets; i++ ) { if ( targets[i].isFound() ) glColor4f( 0.0, 1.0, 1.0, 1.0 ); else glColor4f( 0.0, 1.0, 0.0, 0.2 ); GLUquadricObj *quadric=gluNewQuadric(); gluQuadricNormals(quadric, GLU_SMOOTH); glPushMatrix(); glTranslatef( targets[i].getXPos(),targets[i].getYPos() ,targets[i].getZPos() ); glPushMatrix(); gluSphere(quadric, target_display_radius, 10,10); glPopMatrix(); gluDeleteQuadric(quadric); } restoreGLState(); swapBuffers(); //emit VisFinishedPaintGL(); QString framesPerSecond; framesPerSecond.setNum(frames /(time.elapsed() / 1000.0), 'f', 2); painter.setPen(Qt::white); painter.drawText(20, 40, framesPerSecond + " fps"); painter.end(); swapBuffers(); frames++; if (!(frames % 100)) { time.start(); frames = 0; } model->drawing = false; //glFinish(); //qApp->processEvents(); }
int main (int argc, char * argv[]) { /* initialize glut */ glutInit (&argc, argv); glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutCreateWindow ("texture"); glutDisplayFunc (DrawStuff); glutMotionFunc (MouseMotion); /* create popup menu */ glutCreateMenu (TextureStyle); glutAddMenuEntry ("Texture Off", 301); glutAddMenuEntry ("Texture On", 302); glutAddMenuEntry ("--------------", 9999); glutAddMenuEntry ("Vertex Flat", 501); glutAddMenuEntry ("Normal Flat", 502); glutAddMenuEntry ("Vertex Cylinder", 503); glutAddMenuEntry ("Normal Cylinder", 504); glutAddMenuEntry ("Vertex Sphere", 505); glutAddMenuEntry ("Normal Sphere", 506); glutAddMenuEntry ("--------------", 9999); glutAddMenuEntry ("Model Vertex Flat", 507); glutAddMenuEntry ("Model Normal Flat", 508); glutAddMenuEntry ("Model Vertex Cylinder", 509); glutAddMenuEntry ("Model Normal Cylinder", 510); glutAddMenuEntry ("Model Vertex Sphere", 511); glutAddMenuEntry ("Model Normal Sphere", 512); glutAddMenuEntry ("--------------", 9999); glutAddMenuEntry ("Check Texture", 701); glutAddMenuEntry ("Barberpole Texture", 702); glutAddMenuEntry ("Wild Tooth Texture", 703); glutAddMenuEntry ("Molten Lava Texture", 704); glutAddMenuEntry ("--------------", 9999); glutAddMenuEntry ("Exit", 99); glutAttachMenu (GLUT_MIDDLE_BUTTON); /* initialize GL */ glClearDepth (1.0); glEnable (GL_DEPTH_TEST); glClearColor (0.0, 0.0, 0.0, 0.0); glShadeModel (GL_SMOOTH); glMatrixMode (GL_PROJECTION); /* roughly, measured in centimeters */ glFrustum (-9.0, 9.0, -9.0, 9.0, 50.0, 150.0); glMatrixMode(GL_MODELVIEW); /* initialize lighting */ glLightfv (GL_LIGHT0, GL_POSITION, lightOnePosition); glLightfv (GL_LIGHT0, GL_DIFFUSE, lightOneColor); glEnable (GL_LIGHT0); glLightfv (GL_LIGHT1, GL_POSITION, lightTwoPosition); glLightfv (GL_LIGHT1, GL_DIFFUSE, lightTwoColor); glEnable (GL_LIGHT1); glEnable (GL_LIGHTING); glColorMaterial (GL_FRONT_AND_BACK, GL_DIFFUSE); glEnable (GL_COLOR_MATERIAL); glColor3f (0.8, 0.3, 0.6); /* initialize and enable texturing */ setup_textures (); gluBuild2DMipmaps (GL_TEXTURE_2D, 3, current_texture -> size, current_texture -> size, GL_RGB, GL_UNSIGNED_BYTE, (void *) (current_texture->pixmap)); glMatrixMode (GL_TEXTURE); glLoadIdentity (); glScalef (1.0, 0.1, 1.0); glMatrixMode (GL_MODELVIEW); glEnable (GL_TEXTURE_2D); /* some stuff to play with .... glTexGeni (GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glTexGeni (GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glEnable (GL_TEXTURE_GEN_S); glEnable (GL_TEXTURE_GEN_T); */ gleTextureMode (GLE_TEXTURE_ENABLE | GLE_TEXTURE_VERTEX_CYL); InitStuff (); glutMainLoop (); return 0; /* ANSI C requires main to return int. */ }
//////////////////////////////////////////////////////////// /// Entry point of application /// /// \return Application exit code /// //////////////////////////////////////////////////////////// int main() { // Request a 32-bits depth buffer when creating the window sf::ContextSettings contextSettings; contextSettings.depthBits = 32; // Create the main window sf::RenderWindow window(sf::VideoMode(800, 600), "SFML graphics with OpenGL", sf::Style::Default, contextSettings); window.setVerticalSyncEnabled(true); // Create a sprite for the background sf::Texture backgroundTexture; if (!backgroundTexture.loadFromFile("resources/background.jpg")) return EXIT_FAILURE; sf::Sprite background(backgroundTexture); // Create some text to draw on top of our OpenGL object sf::Font font; if (!font.loadFromFile("resources/sansation.ttf")) return EXIT_FAILURE; sf::Text text("SFML / OpenGL demo", font); text.setColor(sf::Color(255, 255, 255, 170)); text.setPosition(250.f, 450.f); // Make the window the active target for OpenGL calls // Note: If using sf::Texture or sf::Shader with OpenGL, // be sure to call sf::Texture::getMaximumSize() and/or // sf::Shader::isAvailable() at least once before calling // setActive(), as those functions will cause a context switch window.setActive(); // Load an OpenGL texture. // We could directly use a sf::Texture as an OpenGL texture (with its Bind() member function), // but here we want more control on it (generate mipmaps, ...) so we create a new one from an image GLuint texture = 0; { sf::Image image; if (!image.loadFromFile("resources/texture.jpg")) return EXIT_FAILURE; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, image.getSize().x, image.getSize().y, GL_RGBA, GL_UNSIGNED_BYTE, image.getPixelsPtr()); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); } // Enable Z-buffer read and write glEnable(GL_DEPTH_TEST); glDepthMask(GL_TRUE); glClearDepth(1.f); // Disable lighting glDisable(GL_LIGHTING); // Configure the viewport (the same size as the window) glViewport(0, 0, window.getSize().x, window.getSize().y); // Setup a perspective projection glMatrixMode(GL_PROJECTION); glLoadIdentity(); GLfloat ratio = static_cast<float>(window.getSize().x) / window.getSize().y; glFrustum(-ratio, ratio, -1.f, 1.f, 1.f, 500.f); // Bind the texture glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texture); // Define a 3D cube (6 faces made of 2 triangles composed by 3 vertices) GLfloat cube[] = { // positions // texture coordinates -20, -20, -20, 0, 0, -20, 20, -20, 1, 0, -20, -20, 20, 0, 1, -20, -20, 20, 0, 1, -20, 20, -20, 1, 0, -20, 20, 20, 1, 1, 20, -20, -20, 0, 0, 20, 20, -20, 1, 0, 20, -20, 20, 0, 1, 20, -20, 20, 0, 1, 20, 20, -20, 1, 0, 20, 20, 20, 1, 1, -20, -20, -20, 0, 0, 20, -20, -20, 1, 0, -20, -20, 20, 0, 1, -20, -20, 20, 0, 1, 20, -20, -20, 1, 0, 20, -20, 20, 1, 1, -20, 20, -20, 0, 0, 20, 20, -20, 1, 0, -20, 20, 20, 0, 1, -20, 20, 20, 0, 1, 20, 20, -20, 1, 0, 20, 20, 20, 1, 1, -20, -20, -20, 0, 0, 20, -20, -20, 1, 0, -20, 20, -20, 0, 1, -20, 20, -20, 0, 1, 20, -20, -20, 1, 0, 20, 20, -20, 1, 1, -20, -20, 20, 0, 0, 20, -20, 20, 1, 0, -20, 20, 20, 0, 1, -20, 20, 20, 0, 1, 20, -20, 20, 1, 0, 20, 20, 20, 1, 1 }; // Enable position and texture coordinates vertex components glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glVertexPointer(3, GL_FLOAT, 5 * sizeof(GLfloat), cube); glTexCoordPointer(2, GL_FLOAT, 5 * sizeof(GLfloat), cube + 3); // Disable normal and color vertex components glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_COLOR_ARRAY); // Create a clock for measuring the time elapsed sf::Clock clock; // Start game loop while (window.isOpen()) { // Process events sf::Event event; while (window.pollEvent(event)) { // Close window: exit if (event.type == sf::Event::Closed) window.close(); // Escape key: exit if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape)) window.close(); // Adjust the viewport when the window is resized if (event.type == sf::Event::Resized) glViewport(0, 0, event.size.width, event.size.height); } // Draw the background window.pushGLStates(); window.draw(background); window.popGLStates(); // Clear the depth buffer glClear(GL_DEPTH_BUFFER_BIT); // We get the position of the mouse cursor, so that we can move the box accordingly float x = sf::Mouse::getPosition(window).x * 200.f / window.getSize().x - 100.f; float y = -sf::Mouse::getPosition(window).y * 200.f / window.getSize().y + 100.f; // Apply some transformations glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(x, y, -100.f); glRotatef(clock.getElapsedTime().asSeconds() * 50.f, 1.f, 0.f, 0.f); glRotatef(clock.getElapsedTime().asSeconds() * 30.f, 0.f, 1.f, 0.f); glRotatef(clock.getElapsedTime().asSeconds() * 90.f, 0.f, 0.f, 1.f); // Draw the cube glDrawArrays(GL_TRIANGLES, 0, 36); // Draw some text on top of our OpenGL object window.pushGLStates(); window.draw(text); window.popGLStates(); // Finally, display the rendered frame on screen window.display(); } // Don't forget to destroy our texture glDeleteTextures(1, &texture); return EXIT_SUCCESS; }
void Background::render(RenderContext* renderContext) { const AABox& boundingBox = renderContext->scene->getBoundingBox(); // setup fog if ((fogtype != FOG_NONE) && (boundingBox.isValid() )) { // Sphere bsphere(boundingBox); glFogfv(GL_FOG_COLOR, material.colors.getColor(0).getFloatPtr() ); switch(fogtype) { case FOG_LINEAR: glFogi(GL_FOG_MODE, GL_LINEAR); glFogf(GL_FOG_START, renderContext->viewpoint->frustum.znear /*bsphere.radius*2*/); glFogf(GL_FOG_END, renderContext->viewpoint->frustum.zfar /*bsphere.radius*3*/ ); break; case FOG_EXP: glFogi(GL_FOG_MODE, GL_EXP); glFogf(GL_FOG_DENSITY, 1.0f/renderContext->viewpoint->frustum.zfar /*(bsphere.radius*3)*/ ); break; case FOG_EXP2: glFogi(GL_FOG_MODE, GL_EXP2); glFogf(GL_FOG_DENSITY, 1.0f/renderContext->viewpoint->frustum.zfar /*(bsphere.radius*3)*/ ); break; } glEnable(GL_FOG); } else { glDisable(GL_FOG); } // render bg sphere if (sphere) { float fov = renderContext->viewpoint->getFOV(); float rad = deg2radf(fov/2.0f); float hlen = sinf(rad) * cosf(deg2radf(45.0)); float znear = hlen / tanf(rad); float zfar = znear + 1.0f; float hwidth, hheight; float winwidth = (float) renderContext->size.width; float winheight = (float) renderContext->size.height; // aspect ratio if (winwidth >= winheight) { hwidth = hlen; hheight = hlen * (winheight / winwidth); } else { hwidth = hlen * (winwidth / winheight); hheight = hlen; } glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(-hwidth, hwidth, -hheight, hheight, znear, zfar ); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0.0f,0.0f,-znear); renderContext->viewpoint->setupOrientation(renderContext); Shape::render(renderContext); } }
main(int argc, char *argv[]) { toplevel = XtAppInitialize(&app, "Paperplane", NULL, 0, &argc, argv, fallbackResources, NULL, 0); dpy = XtDisplay(toplevel); /* find an OpenGL-capable RGB visual with depth buffer */ vi = glXChooseVisual(dpy, DefaultScreen(dpy), dblBuf); if (vi == NULL) { vi = glXChooseVisual(dpy, DefaultScreen(dpy), snglBuf); if (vi == NULL) XtAppError(app, "no RGB visual with depth buffer"); doubleBuffer = GL_FALSE; } /* create an OpenGL rendering context */ cx = glXCreateContext(dpy, vi, /* no display list sharing */ None, /* favor direct */ GL_TRUE); if (cx == NULL) XtAppError(app, "could not create rendering context"); /* create an X colormap since probably not using default visual */ #ifdef noGLwidget cmap = XCreateColormap(dpy, RootWindow(dpy, vi->screen), vi->visual, AllocNone); /* * Establish the visual, depth, and colormap of the toplevel * widget _before_ the widget is realized. */ XtVaSetValues(toplevel, XtNvisual, vi->visual, XtNdepth, vi->depth, XtNcolormap, cmap, NULL); #endif XtAddEventHandler(toplevel, StructureNotifyMask, False, map_state_changed, NULL); mainw = XmCreateMainWindow(toplevel, "mainw", NULL, 0); XtManageChild(mainw); /* create menu bar */ menubar = XmCreateMenuBar(mainw, "menubar", NULL, 0); XtManageChild(menubar); #ifdef noGLwidget /* Hack around Xt's unfortunate default visual inheritance. */ XtSetArg(menuPaneArgs[0], XmNvisual, vi->visual); menupane = XmCreatePulldownMenu(menubar, "menupane", menuPaneArgs, 1); #else menupane = XmCreatePulldownMenu(menubar, "menupane", NULL, 0); #endif btn = XmCreatePushButton(menupane, "Quit", NULL, 0); XtAddCallback(btn, XmNactivateCallback, quit, NULL); XtManageChild(btn); XtSetArg(args[0], XmNsubMenuId, menupane); cascade = XmCreateCascadeButton(menubar, "File", args, 1); XtManageChild(cascade); #ifdef noGLwidget menupane = XmCreatePulldownMenu(menubar, "menupane", menuPaneArgs, 1); #else menupane = XmCreatePulldownMenu(menubar, "menupane", NULL, 0); #endif btn = XmCreateToggleButton(menupane, "Motion", NULL, 0); XtAddCallback(btn, XmNvalueChangedCallback, (XtCallbackProc)toggle, NULL); XtManageChild(btn); btn = XmCreatePushButton(menupane, "Add plane", NULL, 0); XtAddCallback(btn, XmNactivateCallback, (XtCallbackProc)add_plane, NULL); XtManageChild(btn); btn = XmCreatePushButton(menupane, "Remove plane", NULL, 0); XtAddCallback(btn, XmNactivateCallback, (XtCallbackProc)remove_plane, NULL); XtManageChild(btn); XtSetArg(args[0], XmNsubMenuId, menupane); cascade = XmCreateCascadeButton(menubar, "Planes", args, 1); XtManageChild(cascade); /* create framed drawing area for OpenGL rendering */ frame = XmCreateFrame(mainw, "frame", NULL, 0); XtManageChild(frame); #ifdef noGLwidget glxarea = XtVaCreateManagedWidget("glxarea", xmDrawingAreaWidgetClass, frame, NULL); #else #ifdef noMotifGLwidget /* notice glwDrawingAreaWidgetClass lacks an 'M' */ glxarea = XtVaCreateManagedWidget("glxarea", glwDrawingAreaWidgetClass, #else glxarea = XtVaCreateManagedWidget("glxarea", glwMDrawingAreaWidgetClass, #endif frame, GLwNvisualInfo, vi, NULL); #endif XtAddCallback(glxarea, XmNexposeCallback, (XtCallbackProc)draw, NULL); XtAddCallback(glxarea, XmNresizeCallback, resize, NULL); XtAddCallback(glxarea, XmNinputCallback, input, NULL); /* set up application's window layout */ XmMainWindowSetAreas(mainw, menubar, NULL, NULL, NULL, frame); XtRealizeWidget(toplevel); /* * Once widget is realized (ie, associated with a created X window), we * can bind the OpenGL rendering context to the window. */ glXMakeCurrent(dpy, XtWindow(glxarea), cx); made_current = GL_TRUE; /* setup OpenGL state */ glClearDepth(1.0); glClearColor(0.0, 0.0, 0.0, 0.0); glMatrixMode(GL_PROJECTION); glFrustum(-1.0, 1.0, -1.0, 1.0, 1.0, 20); glMatrixMode(GL_MODELVIEW); /* add three initial random planes */ srandom(getpid()); add_plane(); add_plane(); add_plane(); add_plane(); add_plane(); /* start event processing */ toggle(); XtAppMainLoop(app); }