void Gource::mousetrace(Frustum& frustum, float dt) { GLuint buffer[512]; GLint viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); glSelectBuffer(512, buffer); glDepthFunc(GL_LEQUAL); glEnable(GL_DEPTH_TEST); (void) glRenderMode(GL_SELECT); glInitNames(); glPushName(0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPickMatrix((GLdouble) mousepos.x, (GLdouble) (viewport[3]-mousepos.y), 1.0f, 1.0f, viewport); gluPerspective(90.0f, (GLfloat)display.width/(GLfloat)display.height, 0.1f, camera.getZFar()); camera.look(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); for(std::map<std::string,RUser*>::iterator it = users.begin(); it!=users.end(); it++) { it->second->drawSimple(dt); } glDisable(GL_TEXTURE_2D); glColor4f(1.0, 1.0, 1.0, 1.0); root->drawSimple(frustum, dt); glMatrixMode(GL_MODELVIEW); mouse_hits = glRenderMode(GL_RENDER); RFile* fileSelection = 0; RUser* userSelection = 0; if (mouse_hits > 0) { int choice = buffer[3]; GLuint depth = buffer[1]; for (int loop = 1; loop < mouse_hits; loop++) { if (buffer[loop*4+1] < depth) { choice = buffer[loop*4+3]; depth = buffer[loop*4+1]; } } if(choice != 0) { selectionDepth = depth; std::map<int, RFile*>::iterator filetest; std::map<int, RUser*>::iterator usertest; if((filetest = tagfilemap.find(choice)) != tagfilemap.end()) { fileSelection = filetest->second; } else if((usertest = tagusermap.find(choice)) != tagusermap.end()) { userSelection = usertest->second; } } } glDisable(GL_DEPTH_TEST); // is over a file if(fileSelection != 0) { // un hover a user if(hoverUser != 0) { hoverUser->setMouseOver(false); hoverUser = 0; } if(fileSelection != hoverFile) { //deselect previous selection if(hoverFile !=0) hoverFile->setMouseOver(false); //select new fileSelection->setMouseOver(true); hoverFile = fileSelection; } // is over a user } else if(userSelection != 0) { // un hover a file if(hoverFile != 0) { hoverFile->setMouseOver(false); hoverFile = 0; } if(userSelection != hoverUser) { //deselect previous selection if(hoverUser !=0) hoverUser->setMouseOver(false); //select new userSelection->setMouseOver(true); hoverUser = userSelection; } } else { if(hoverFile!=0) hoverFile->setMouseOver(false); if(hoverUser!=0) hoverUser->setMouseOver(false); hoverFile=0; hoverUser=0; } if(mouseclicked) { if(hoverUser!=0) selectUser(hoverUser); else if(hoverFile!=0) selectFile(hoverFile); else { selectBackground(); } } }
int main(int argc, char *argv[]) try { physics_driftmax = 0.0025f; GLWin glwin("point cloud push interaction"); RSCam dcam; dcam.Init((argc == 2) ? argv[1] : NULL); Image<unsigned short> dimage(dcam.dcamera()); glwin.ViewAngle = dcam.fov().y; float viewdist = 2.0f; float yaw = 120; int mousexold = 0; Mesh mesh; bool pause = false; bool debuglines=false; int center = 0; bool chains = true; bool usehull = false; std::vector<RigidBody*> rigidbodies; std::vector < std::pair<RigidBody*, RigidBody*>> links; for (float x = -0.2f; x < 0.2f; x+= 0.07f) for(float z: {0.350f}) for (float y = -0.2f; y <= 0.2f; y += 0.07f) { rigidbodies.push_back(new RigidBody({ AsShape(WingMeshDual(WingMeshCube(0.025f),0.028f)) }, { x,y,z })); //rigidbodies.push_back(new RigidBody({ AsShape(WingMeshCube(0.025f) ) }, { x,y,z })); links.push_back({(y > -0.2f)?rigidbodies[rigidbodies.size() - 2]:NULL , rigidbodies.back()}); } //rigidbodies.push_back(new RigidBody({ AsShape(WingMeshCube(0.05f)) }, { 0,0,0.50f })); auto seesaw = new RigidBody({ AsShape(WingMeshBox({ 0.20f, 0.015f, 0.05f })) }, { 0,0,0.45f }); rigidbodies.push_back(seesaw); glwin.keyboardfunc = [&](unsigned char key, int x, int y)->void { switch (std::tolower(key)) { case 'q': case 27: exit(0); break; // 27 is ESC case ' ': pause = !pause; break; case 'c': chains = !chains; break; case 'd': debuglines = !debuglines; break; case 'h': usehull = !usehull; break; case 'r': for (auto &rb : rigidbodies) { rb->angular_momentum = rb->linear_momentum = float3(0.0f);rb->pose() = { rb->position_start,rb->orientation_start }; } break; default: std::cout << "unassigned key (" << (int)key << "): '" << key << "'\n"; break; } }; if (dcam.dev->supports_option(rs::option::r200_lr_auto_exposure_enabled)) dcam.dev->set_option(rs::option::r200_lr_auto_exposure_enabled, 1); while (glwin.WindowUp()) { if (glwin.MouseState) { yaw += glwin.mousepos.x - mousexold; } mousexold = glwin.mousepos.x; viewdist *= powf(1.1f, (float)glwin.mousewheel); if (!pause) dimage = dcam.GetDepth(); glPushAttrib(GL_ALL_ATTRIB_BITS); glViewport(0, 0, glwin.res.x, glwin.res.y); glClearColor(0.1f, 0.1f, 0.15f, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); gluPerspective(glwin.ViewAngle, (double)glwin.aspect_ratio(), 0.01f, 50.0f); glMatrixMode(GL_MODELVIEW); glPushMatrix(); gluLookAt(0, 0, viewdist, 0, 0, 0, 0, -1, 0); glEnable(GL_DEPTH_TEST); glTranslatef(0, 0, 0.35f); glRotatef(yaw, 0, 1, 0); glTranslatef(0, 0, -0.35f); std::vector<float3> pts; std::vector<float3> outliers; std::vector<float3> vpts; glDisable(GL_BLEND); float2 wrange = { 0.20f,0.60f }; auto dp_image_c = Transform(dimage, [](unsigned short s) {return byte3((unsigned char)clamp(255 - s / 4, 0, 255)); }); drawimage(dp_image_c, { 0.78f,0.22f }, { 0.2f,-0.2f }, 3); float depth_scale = (dcam.dev) ? dcam.dev->get_depth_scale() : 0.001f; // to put into meters // if file assume file is mm for (auto p : rect_iteration(dimage.dim())) // p is int2 from 0,0 to w,h of dcam { float d = dimage.pixel(p) * depth_scale; // d is in meters, whereas depth[i] is in camera units mm for R200, .125mm for SR300 ivycam if (p.x<5 || p.x> dimage.dim().x - 5 || p.y<5 || p.y>dimage.dim().y - 5) continue; // crop, seems to be lots of noise at the edges if (d > 1.0f) // just too far continue; float3 v = dimage.cam.deprojectz(asfloat2(p), d); if (d>wrange.x && d < wrange.y) pts.push_back(v); else outliers.push_back(v); } vpts = ObtainVoxelPointCloud(pts, 0.0082f, 8); std::vector<std::pair<float3, float3>> lines; std::vector<std::pair<float3, float3>> glines; if (1)// && pts.size()) { std::vector<LimitLinear> linears; std::vector<LimitAngular> angulars; physics_gravity = { 0, (float) chains,0 }; // ugg y is down if(!usehull) for(auto rb:rigidbodies) { if (!rb->shapes[0].planes.size()) rb->shapes[0].planes = Planes(rb->shapes[0].verts, rb->shapes[0].tris); auto planes = Transform(rb->shapes[0].planes, [&](float4 p) { return rb->pose().TransformPlane(p);}); rb->gravscale = (float)chains; float separation = FLT_MAX; float3 pushpoint = float3(0, 0, 0); // float4 pushplane; for (auto p : vpts) { auto plane = mostabove(planes, p); float sep; if ((sep = dot(plane, float4(p, 1))) < separation) { pushpoint = p; pushplane = plane; separation = sep; } } if (separation > 0.1f) continue; float3 closestpoint = ProjectOntoPlane(pushplane, pushpoint); pushplane = float4({ -pushplane.xyz(), -dot(-pushplane.xyz(),pushpoint) }); linears.push_back(ConstrainAlongDirection(NULL, pushpoint, rb, rb->pose().inverse()*closestpoint, pushplane.xyz(), 0, 100.0f)); // FLT_MAX)); lines.push_back({ closestpoint,pushpoint }); auto cp=Separated(rb->shapes[0].verts, rb->position, rb->orientation, { pushpoint }, { 0,0,0 }, { 0,0,0,1 }, 1); glines.push_back({ cp.p0w, cp.p1w }); } Append(linears, ConstrainPositionNailed(NULL, seesaw->position_start, seesaw, { 0, 0, 0 })); Append(angulars, ConstrainAngularRange(NULL, seesaw, { 0, 0, 0, 1 }, { 0, 0,-20 }, { 0, 0,20 })); if (chains) for (auto link : links) Append(linears, ConstrainPositionNailed(link.first,link.first? float3(0, 0.035f, 0) : link.second->position_start-float3(0, -0.035f, 0) , link.second, { 0,-0.035f,0 })); if(!pause) if(usehull && vpts.size()>5) PhysicsUpdate(rigidbodies, linears, angulars, { &vpts }); else PhysicsUpdate(rigidbodies, linears, angulars, std::vector<std::vector<float3>*>()); } glColor3f(1, 1, 1); glwirefrustumz(dcam.deprojectextents(), { 0.1f,1.0f }); // draw the camera frustum volume glPushAttrib(GL_ALL_ATTRIB_BITS); glPointSize(1); glBegin(GL_POINTS); glColor3f(0, 1, 0.5f); for (auto p : pts) glVertex3fv(p); glColor3f(1, 0.15f, 0.15f); for (auto p : outliers) glVertex3fv(p); glEnd(); glPointSize(3); glBegin(GL_POINTS); glColor3f(1, 1, 1); for (auto p : vpts) // was: spts glVertex3fv(p); glEnd(); glPopAttrib(); if (debuglines) { glBegin(GL_LINES); glColor3f(0, 1, 1); if (0)for (auto line : lines) glVertex3fv(line.first), glVertex3fv(line.second); glColor3f(1, 1, 0); for (auto line : glines) glVertex3fv(line.first), glVertex3fv(line.second); glEnd(); } if (usehull && vpts.size() > 5) { auto tris = calchull(vpts, 0); glBegin(GL_LINES); glColor3f(1, 1, 1); for (auto t : tris) for( int i : {0,1,1,2,2,0}) glVertex3fv(vpts[t[i]]); glEnd(); } if (chains) { glBegin(GL_LINES); glColor3f(1, 0, 1); for (auto link : links) { if(link.first) glVertex3fv(link.first->pose()* float3(0, 0, 0)), glVertex3fv(link.first->pose()* float3(0, 0.035f, 0)); glVertex3fv(link.second->pose()* float3(0, 0, 0)) , glVertex3fv(link.second->pose()* float3(0, -0.035f, 0)); } glEnd(); } glPushAttrib(GL_ALL_ATTRIB_BITS); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_TEXTURE_2D); glColor3f(0.5f, 0.5f, 0.5f); for (auto &rb : rigidbodies) rbdraw(rb); glPopAttrib(); // Restore state // Restore state glPopMatrix(); //should be currently in modelview mode glMatrixMode(GL_PROJECTION); glPopMatrix(); glPopAttrib(); glMatrixMode(GL_MODELVIEW); glwin.PrintString({ 0,0 }, "esc to quit."); glwin.PrintString({ 0,1 }, "[h] collision %s ",(usehull)?"hull":"points"); glwin.SwapBuffers(); } return 0; } catch (const char *c) { MessageBox(GetActiveWindow(), c, "FAIL", 0); } catch (std::exception e) { MessageBox(GetActiveWindow(), e.what(), "FAIL", 0); }
static void RenderCallback() { if(pScene == NULL) { #ifdef _DEBUG std::cout << "pScene == NULL" << std::endl; #endif //_DEBUG return; } // Start simulation if (isSimulate) { pScene->simulate(1.0f/60.0f); } // Clear buffers glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); // Setup projection matrix glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0f, (float)glutGet(GLUT_WINDOW_WIDTH)/(float)glutGet(GLUT_WINDOW_HEIGHT), 1.0f, 10000.0f); gluLookAt(gEye.x, gEye.y, gEye.z, gEye.x + gDir.x, gEye.y + gDir.y, gEye.z + gDir.z, 0.0f, 1.0f, 0.0f); // Setup modelview matrix glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // Render all actors int nbActors = pScene->getNbActors(); NxActor** actors = pScene->getActors(); while(nbActors--) { NxActor* actor = *actors++; if(actor->userData == NULL) { // draw grid glBegin(GL_LINES); int y = 0; for(int i=-100; i<=100; ++i) { glVertex3f(i*10,y,-1000); glVertex3f(i*10,y,1000); glVertex3f(1000,y,i*10); glVertex3f(-1000,y,i*10); } glEnd(); } // Render actor glPushMatrix(); float glMat[16]; actor->getGlobalPose().getColumnMajor44(glMat); glMultMatrixf(glMat); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glutSolidCube(size_t(actor->userData)*10.0f); glPopMatrix(); // Render shadow glPushMatrix(); const static float shadowMat[]= { 1,0,0,0, 0,0,0,0, 0,0,1,0, 0,0,0,1 }; glMultMatrixf(shadowMat); glMultMatrixf(glMat); glDisable(GL_LIGHTING); glColor4f(0.1f, 0.2f, 0.3f, 1.0f); glutSolidCube(size_t(actor->userData)*10.0f); glEnable(GL_LIGHTING); glPopMatrix(); } // Fetch simulation results if(isSimulate) { pScene->flushStream(); pScene->fetchResults(NX_RIGID_BODY_FINISHED, true); } glutSwapBuffers(); }
void TrackMap::resizeGL(int w, int h){ glViewport(0,0,w,h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45, w/h, 0.1, 5000); }
void mainmenu_draw(int width,int height) { float lightpos2[4]={0,0,1000,0}; float tmpls[4]={1.0F,1.0F,1.0F,1.0}; float tmpld[4]={0.6F,0.6F,0.6F,1.0}; float tmpla[4]={0.2F,0.2F,0.2F,1.0}; float ratio; if (nethertittle==0) { nethertittle=new C3DObject("/usr/local/share/netherearth/models/tittle.asc","/usr/local/share/netherearth/textures/"); nethertittle->normalize(7.0); } /* if */ /* Enable Lights, etc.: */ glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice Perspective Calculations glEnable(GL_LIGHT0); glLightfv(GL_LIGHT0,GL_AMBIENT,tmpla); glLightfv(GL_LIGHT0,GL_DIFFUSE,tmpld); glLightfv(GL_LIGHT0,GL_SPECULAR,tmpls); glEnable(GL_LIGHTING); glEnable(GL_COLOR_MATERIAL); glShadeModel( GL_SMOOTH ); glCullFace( GL_BACK ); glFrontFace( GL_CCW ); glEnable( GL_CULL_FACE ); glDisable( GL_SCISSOR_TEST ); glEnable( GL_DEPTH_TEST ); glLightfv(GL_LIGHT0,GL_POSITION,lightpos2); glClearColor(0,0,0,0.0); glViewport(0,0,width,height); ratio=(float)width/float(height); glMatrixMode( GL_PROJECTION ); glLoadIdentity( ); gluPerspective( 30.0, ratio, 1.0, 1024.0 ); gluLookAt(0,0,30,0,0,0,0,1,0); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); switch(mainmenu_status) { case 0: glTranslatef(0,3,40-mainmenu_substatus); nethertittle->draw(1.0,1.0,1.0); break; case 1: glTranslatef(0,3,0); glPushMatrix(); glRotatef(sin(mainmenu_substatus*0.02)*5.0f,0,1,0); nethertittle->draw(1.0,1.0,1.0); glPopMatrix(); glColor3f(0.5,0.5,1.0); glTranslatef(-6,-6,0); scaledglprintf2(0.005,0.005,"1 - START NEW GAME "); glTranslatef(0,-1,0); scaledglprintf2(0.005,0.005,"2 - REDEFINE KEYBOARD"); glTranslatef(0,-1,0); scaledglprintf2(0.005,0.005,"3 - OPTIONS "); glTranslatef(0,-1,0); scaledglprintf2(0.005,0.005,"4 - MAP: %s",mapname); glTranslatef(0,-1,0); scaledglprintf2(0.005,0.005,"5 - EXIT GAME "); break; case 2: case 4: case 5: case 6: glTranslatef(0,3,mainmenu_substatus); nethertittle->draw(1.0,1.0,1.0); break; case 3: glColor3f(0.5,0.5,1.0); glTranslatef(0,3.5,0); if (SCREEN_X== 320) scaledglprintf(0.005,0.005,"1 - RESOLUTION: 320x240"); if (SCREEN_X== 400) scaledglprintf(0.005,0.005,"1 - RESOLUTION: 400x300"); if (SCREEN_X== 640) scaledglprintf(0.005,0.005,"1 - RESOLUTION: 640x480"); if (SCREEN_X== 800) scaledglprintf(0.005,0.005,"1 - RESOLUTION: 800x600"); if (SCREEN_X==1024) scaledglprintf(0.005,0.005,"1 - RESOLUTION: 1024x768"); glTranslatef(0,-1,0); if (COLOUR_DEPTH== 8) scaledglprintf(0.005,0.005,"2 - COLOR DEPTH: 8bit "); if (COLOUR_DEPTH==16) scaledglprintf(0.005,0.005,"2 - COLOR DEPTH: 16bit "); if (COLOUR_DEPTH==24) scaledglprintf(0.005,0.005,"2 - COLOR DEPTH: 24bit "); if (COLOUR_DEPTH==32) scaledglprintf(0.005,0.005,"2 - COLOR DEPTH: 32bit "); glTranslatef(0,-1,0); if (fullscreen) scaledglprintf(0.005,0.005,"3 - FULLSCREEN "); else scaledglprintf(0.005,0.005,"3 - WINDOWED "); glTranslatef(0,-1,0); if (shadows==0) scaledglprintf(0.005,0.005,"4 - SHADOWS: OFF "); if (shadows==1) scaledglprintf(0.005,0.005,"4 - SHADOWS: ON - DIAG "); if (shadows==2) scaledglprintf(0.005,0.005,"4 - SHADOWS: ON - VERT "); glTranslatef(0,-1,0); if (detaillevel==0) scaledglprintf(0.005,0.005,"5 - DETAIL: LOWEST "); if (detaillevel==1) scaledglprintf(0.005,0.005,"5 - DETAIL: LOW "); if (detaillevel==2) scaledglprintf(0.005,0.005,"5 - DETAIL: MEDIUM "); if (detaillevel==3) scaledglprintf(0.005,0.005,"5 - DETAIL: HIGH "); if (detaillevel==4) scaledglprintf(0.005,0.005,"5 - DETAIL: HIGHEST "); glTranslatef(0,-1,0); if (sound) scaledglprintf(0.005,0.005,"6 - SOUND: ON "); else scaledglprintf(0.005,0.005,"6 - SOUND: OFF "); glTranslatef(0,-1,0); if (level==0) scaledglprintf(0.005,0.005,"7 - LEVEL: EASY "); if (level==1) scaledglprintf(0.005,0.005,"7 - LEVEL: NORMAL "); if (level==2) scaledglprintf(0.005,0.005,"7 - LEVEL: HARD "); if (level==3) scaledglprintf(0.005,0.005,"7 - LEVEL: IMPOSSIBLE "); glTranslatef(0,-1,0); if (show_radar) scaledglprintf(0.005,0.005,"8 - RADAR: ON "); else scaledglprintf(0.005,0.005,"8 - RADAR: OFF "); glTranslatef(0,-1,0); scaledglprintf(0.005,0.005,"9 - BACK "); break; case 7: { char tmp[256]; glColor3f(0.5,0.5,1.0); glTranslatef(0,5,0); scaledglprintf(0.005,0.005,"REDEFINE KEYBOARD"); glTranslatef(0,-2,0); if (mainmenu_substatus!=0) glColor3f(0.5,0.5,1.0); else glColor3f(1.0,0.0,0.0); sprintf(tmp,"PRESS A KEY FOR UP: %s",strupr(SDL_GetKeyName((SDLKey)up_key))); scaledglprintf(0.005,0.005,tmp); glTranslatef(0,-1,0); if (mainmenu_substatus!=1) glColor3f(0.5,0.5,1.0); else glColor3f(1.0,0.0,0.0); sprintf(tmp,"PRESS A KEY FOR DOWN: %s",strupr(SDL_GetKeyName((SDLKey)down_key))); scaledglprintf(0.005,0.005,tmp); glTranslatef(0,-1,0); if (mainmenu_substatus!=2) glColor3f(0.5,0.5,1.0); else glColor3f(1.0,0.0,0.0); sprintf(tmp,"PRESS A KEY FOR LEFT: %s",strupr(SDL_GetKeyName((SDLKey)left_key))); scaledglprintf(0.005,0.005,tmp); glTranslatef(0,-1,0); if (mainmenu_substatus!=3) glColor3f(0.5,0.5,1.0); else glColor3f(1.0,0.0,0.0); sprintf(tmp,"PRESS A KEY FOR RIGHT: %s",strupr(SDL_GetKeyName((SDLKey)right_key))); scaledglprintf(0.005,0.005,tmp); glTranslatef(0,-1,0); if (mainmenu_substatus!=4) glColor3f(0.5,0.5,1.0); else glColor3f(1.0,0.0,0.0); sprintf(tmp,"PRESS A KEY FOR FIRE: %s",strupr(SDL_GetKeyName((SDLKey)fire_key))); scaledglprintf(0.005,0.005,tmp); glTranslatef(0,-1,0); if (mainmenu_substatus!=5) glColor3f(0.5,0.5,1.0); else glColor3f(1.0,0.0,0.0); sprintf(tmp,"PRESS A KEY FOR PAUSE/MENU: %s",strupr(SDL_GetKeyName((SDLKey)pause_key))); scaledglprintf(0.005,0.005,tmp); glColor3f(0.5,0.5,1.0); glTranslatef(0,-2,0); scaledglprintf(0.005,0.005,"PG.UP/PG.DOWN CHANGE THE ZOOM"); if (mainmenu_substatus>5) { glColor3f(1,1,1); glTranslatef(0,-2,0); scaledglprintf(0.005,0.005,"PRESS ANY KEY TO RETURN TO MAIN MENU"); } /* if */ } break; } /* switch */ SDL_GL_SwapBuffers(); } /* NETHER::draw */
void gl_renderer::init() { const SDL_VideoInfo* info = NULL; bpp = 0; flags = SDL_OPENGL | SDL_RESIZABLE; //width = 640; //height = 480; width = 1024; height = 786; angle = 0; GLint stencil = 0; current_camera = game_camera[0] = new desktop_camera(); /* ----- SDL init --------------- */ if(SDL_Init(SDL_INIT_VIDEO) < 0) { fprintf(stderr, "Video initialization failed: %s\n", SDL_GetError()); exit(-1); } atexit(SDL_Quit); info = SDL_GetVideoInfo(); bpp = info->vfmt->BitsPerPixel; /* ----- OpenGL attribute setting via SDL --------------- */ SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); /* ----- Setting up the screen surface --------------- */ screen = SDL_SetVideoMode(width, height, bpp, flags); if (screen == 0) { fprintf(stderr, "Video mode set failed: %s\n", SDL_GetError()); exit(-1); } glGetIntegerv(GL_STENCIL_BITS, &stencil); if(stencil == 0){ printf("Stencil buffer not available!\n"); exit(-1); } SDL_WM_SetCaption("Norbit fridge in space simulator", NULL); light1 = (Light){{ 0.0f, 1.5f,-1.5f, 1.0f}, { 0.7f, 0.7f, 0.7f, 1.0f}, { 0.7f, 0.7f, 0.7f, 1.0f}, { 1.0f, 1.0f, 1.0f, 1.0f}}; light2 = (Light){{-1.5f,-1.8f, 0.0f, 1.0f}, { 0.4f, 0.4f, 0.4f, 1.0f}, { 0.4f, 0.4f, 0.4f, 1.0f}, { 1.0f, 1.0f, 1.0f, 1.0f}}; /* ----- OpenGL init --------------- */ glMatrixMode(GL_PROJECTION); glLoadIdentity(); /* The following function replaces gluPerspective */ gluPerspective(45.0f, (GLfloat)width/(GLfloat)height, 0.001f, 100000.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glEnable(GL_TEXTURE_2D); glEnable(GL_COLOR_MATERIAL); glShadeModel(GL_SMOOTH); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClearDepth(1.0f); glDepthFunc(GL_LEQUAL); glEnable(GL_DEPTH_TEST); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); glEnable(GL_LIGHTING); glEnable(GL_LIGHT1); glEnable(GL_LIGHT2); ship_shape = new obj_shape(new string("ptr_mk1.obj")); star_shape = new sphere_shape(5.0f); background_stars = new skybox(); background_stars->init(200.0f); }
void Engine::display(bool select) { // Setup a perspective projection glMatrixMode(GL_PROJECTION); glLoadIdentity(); if (select) { GLint viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); gluPickMatrix(static_cast<GLdouble>(lastMouseX), static_cast<GLdouble>(viewport[3] - lastMouseY), cfg::selectTolerance, cfg::selectTolerance, viewport); } gluPerspective(90.f, app->GetWidth()/static_cast<float>(app->GetHeight()), 1.f, 10000.f); // Clear color and depth buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Apply some transformations glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(cameraPositionX, cameraPositionY, -cameraDistance); glRotatef(cameraRotationX, 1.f, 0.f, 0.f); glRotatef(cameraRotationY, 0.f, 1.f, 0.f); // 3D artists normally use (0,0,1) UP vector instead of (0,1,0) glRotatef(-90, 1.f, 0.f, 0.f); // Axes if (!select && drawAxes) { glDisable(GL_LIGHTING); glLineWidth(2.f); glBegin(GL_LINES); glColor3f(1.f, 0.f, 0.f); glVertex3f(0.f, 0.f, 0.f); glVertex3f(cameraDistance, 0.f, 0.f); glColor3f(0.f, 1.f, 0.f); glVertex3f(0.f, 0.f, 0.f); glVertex3f(0.f, cameraDistance, 0.f); glColor3f(0.f, 0.f, 1.f); glVertex3f(0.f, 0.f, 0.f); glVertex3f(0.f, 0.f, cameraDistance); glEnd(); glEnable(GL_LIGHTING); } // Draw model->draw(); // Finally, display rendered frame on screen if (!select) app->Display(); ++frames; if (frames >= 1000) { elapsedTime = clock->GetElapsedTime(); cout << "FPS: " << (frames/(elapsedTime-lastTime)) << endl; lastTime = elapsedTime; frames = 0; } }
static PyObject* cube_draw( PyObject* self, PyObject* args ) { PyObject* dict; double aspect, alpha; double x, theta; if ( !PyArg_ParseTuple( args, "Odd", &dict, &aspect, &alpha ) ) return NULL; // "dict" is a dictionary containing the diagram's parameter values. // "aspect" is the aspect ratio of the viewport. // "alpha" is the alpha value to multiply all of your drawing // colors by, if you want your diagram to respond to Slithy's // normal fade_in() and fade_out() functions. // if you want to use mark_projection() to save the coordinate // system for later use with unproject(), do that here. // now we'll get started setting up our projection. When this // function is called, the corners of the viewport will be at // (-aspect,-1) and (aspect,1). glMatrixMode( GL_PROJECTION ); // we'll stretch things out so that the viewport corners are at // (-1,-1) and (1,1). this corresponds to the normal OpenGL // default projection. Do this if you want to use the normal // projection setup functions like gluPerspective() or // glFrustum(). glScaled( aspect, 1.0, 1.0 ); // if you want to use depth testing, you MUST call either // opengl_clear_blank() or opengl_clear_color() at this point in // order to initialize the depth buffer. // // opengl_clear_color() will clear the viewport to the current // OpenGL color; opengl_clear_blank() will have not alter the // color buffer. glColor4d( 0.2, 0.2, 0.3, alpha ); opengl_clear_color(); // now you can set up your normal OpenGL projection, just as with // any other OpenGL drawing. note that you do NOT do a // glLoadIdentity first. // // you should not push or pop the projection matrix stack. many // OpenGL implementations have only 2 entries on this stack, and // Slithy uses both of them. gluPerspective( 25.0, aspect, 0.1, 30.0 ); // Slithy will initialize the model-view matrix to the identity // before calling your function. you are free to push and pop // this matrix stack normally. glMatrixMode( GL_MODELVIEW ); glTranslated( 0.0, 0.0, -12.0 ); // note that to use depth testing, you have to explicitly turn it // on. glEnable( GL_DEPTH_TEST ); // use the get_*() functions to retrieve parameter // values from the dictionary. x = get_scalar( dict, "x" ); theta = get_scalar( dict, "theta" ); // // now we will draw a rotated cube with open faces. // glRotated( theta, 0.7, 0.4, -0.1 ); glPushMatrix(); glColor3d( 1.0, 0.0, 0.0 ); draw_face( x ); glColor3d( 0.0, 1.0, 1.0 ); glRotated( 180.0, 1.0, 0.0, 0.0 ); draw_face( x ); glPopMatrix(); glPushMatrix(); glColor3d( 0.0, 1.0, 0.0 ); glRotated( 90.0, 0.0, 1.0, 0.0 ); draw_face( x ); glColor3d( 1.0, 0.0, 1.0 ); glRotated( 180.0, 1.0, 0.0, 0.0 ); draw_face( x ); glPopMatrix(); glPushMatrix(); glColor3d( 0.0, 0.0, 1.0 ); glRotated( 90.0, 1.0, 0.0, 0.0 ); draw_face( x ); glColor3d( 1.0, 1.0, 0.0 ); glRotated( 180.0, 0.0, 1.0, 0.0 ); draw_face( x ); glPopMatrix(); // // end of the drawing code. // // the return value is discarded, but we have to return something, // so return the "None" object. // to raise an exception, use PyErr_SetString() and return NULL. Py_INCREF( Py_None ); return Py_None; }
/** * Initialize the project, doing any necessary opengl initialization. * @param camera An already-initialized camera. * @param scene The scene to render. * @return true on success, false on error. */ bool OpenglProject::initialize(Camera* camera, Scene* scene) { // copy scene this->scene = *scene; // TODO opengl initialization code and precomputation of mesh/heightmap //Enabling features of opengl glEnable(GL_DEPTH_TEST); glEnable(GL_NORMALIZE); glEnable(GL_LIGHTING); // Enables lighting glEnable(GL_LIGHT0); // Enables light 0 //i,j to help with looping int i = 0; int j = 0; //Array to hold the normals of the mesh data masterNormal = (Vector3 *)malloc(this->scene.mesh.num_vertices * sizeof(Vector3)); //Arrays to help create the calcuation of the normals Vector3 *masterNormalTotal = (Vector3 *)calloc( this->scene.mesh.num_vertices , sizeof(Vector3)); //Some temporary variables to help with organzing the calcuation Triangle triTemp; Vector3 temp; Vector3 tempNormal; Vector3 a, b, c; Vector3 cMinusb,aMinusb; //Loop to calculate normals for mesh data for (i = 0; i < this->scene.mesh.num_triangles; i++) { triTemp = this->scene.mesh.triangles[i]; a = this->scene.mesh.vertices[triTemp.vertices[0]]; b = this->scene.mesh.vertices[triTemp.vertices[1]]; c = this->scene.mesh.vertices[triTemp.vertices[2]]; cMinusb = c - b; aMinusb = a - b; tempNormal = cross(cMinusb, aMinusb); tempNormal = normalize(tempNormal); for (j = 0; j < 3; j++) { masterNormalTotal[triTemp.vertices[j]] = masterNormalTotal[triTemp.vertices[j]] + tempNormal; } } for (i = 0; i < this->scene.mesh.num_vertices; i++) { masterNormal[i] = normalize(masterNormalTotal[i]); } //Freeing the arrays that helped calculate //the normals no need for them anymore free(masterNormalTotal); //creation of helper variables to help with incrementing and looping double increment = 2.0 / (NUMVERTS-1); double x = -1.0; double z = -1.0; double y = 0; unsigned int index = 0; Vector3 tempHolder; //Creation of the inital heightmap mesh for (i = 0; i < NUMVERTS; i++) { for (j = 0; j < NUMVERTS; j++) { y = this->scene.heightmap->compute_height(Vector2(x, z)); tempHolder = Vector3(x, y, z); masterHeightMap[index] = tempHolder; x = x + increment; index++; } z = z + increment; x = -1; } //resetn index; index = 0; //creation of the array that holds the order of indicies of the //heightmap mesh for (i = 0; i < (NUMVERTS - 1); i++) { for (j = 0; j < (NUMVERTS - 1); j++) { //First triangle masterHIndex[index] = (i * NUMVERTS) + j; masterHIndex[index + 1] = ((i + 1) * NUMVERTS) + (j + 1); masterHIndex[index + 2] = ((i + 1) * NUMVERTS) + j; //Second Triangle masterHIndex[index + 3] = (i * NUMVERTS) + j; masterHIndex[index + 4] = (i * NUMVERTS) + (j + 1); masterHIndex[index + 5] = ((i + 1) * NUMVERTS) + (j + 1); index = index + 6; } } //This is the function call to calculate normal for the heightmap calculateNormalH(); GLfloat light_ambient[] = { 0.0, 0.0, 0.0, 1.0 }; GLfloat light_diffuse[] = { 1.0, 1.0, 1.0, 1.0 }; GLfloat light_specular[] = { 1.0, 1.0, 1.0, 1.0 }; GLfloat light_position[] = { 5.0, 5.0, 5.0, 0.0 }; glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient); glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse); glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular); glLightfv(GL_LIGHT0, GL_POSITION, light_position); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(camera->get_fov_degrees(), camera->get_aspect_ratio(), camera->get_near_clip(), camera->get_far_clip()); glMatrixMode(GL_MODELVIEW); initialize_triangle(); return true; }
static void renderFrame() { glClearColor(0 / 255.0f, 0x2b / 255.0f, 0x36 / 255.0f, 1.0f); glClearDepth(1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // ---- UI imguiBeginFrame(mouseX, height - 1 - mouseY, mouseButtons, 0); static const int paramSize = 120; static int paramScroll = 0; imguiBeginScrollArea("Params", 0, height - paramSize, width, paramSize, ¶mScroll); static float depth = 8.0f; imguiSlider("Depth", &depth, 0.0f, 12.0f, 1.0f); static float draw_ratio = 1.0f; imguiSlider("Draw ratio", &draw_ratio, 0.0f, 1.0f, 0.001f); static bool showWire = false; showWire ^= imguiCheck("Wireframe", showWire); static bool showPoints = false; showPoints ^= imguiCheck("Points", showPoints); static bool showPath = true; showPath ^= imguiCheck("Path", showPath); static bool showPathPoints = true; showPathPoints ^= imguiCheck("Path points", showPathPoints); imguiEndScrollArea(); imguiEndFrame(); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_LINE_SMOOTH); glLineWidth(1.2f); // prepare to render octahedron glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0f, 1.333f, 0.01f, 10.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0.5f, 0.5f, 2.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); // model rot unsigned int loop_len = 30 * 1000; float phase = 1.0f * (timeGetTime() % loop_len) / loop_len; glRotatef(phase * 360.0f, 0.0f, 1.0f, 0.0f); // gen mesh Mesh octa; genSubdOctahedron(octa, (int) depth); spherize(octa.verts); // draw mesh as wireframe glEnable(GL_CULL_FACE); if (showWire) { glColor4ub(0xfd, 0xf6, 0xe3, 255); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); octa.draw(); } // draw vertices if (showPoints) { glPolygonMode(GL_FRONT_AND_BACK, GL_POINT); glEnable(GL_POINT_SMOOTH); glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); for (int pass=0; pass < 2; ++pass) { if (!pass) { glColor3ub(0x00, 0x2b, 0x36); glPointSize(4.0f); } else { glColor3ub(0xcb, 0x4b, 0x16); glPointSize(2.0f); } octa.draw(); } glColor4ub(255, 0, 0, 255); glPointSize(2.0f); octa.draw(); glDisable(GL_POINT_SMOOTH); } glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // draw path if (showPath || showPathPoints) { std::vector<Vec3f> verts; sphereTraverseOcta(verts, (int) depth); //triTraverse(verts, Vec3f(1.0f, -1.0f, 0.0f), Vec3f(-1.0f, 1.0f, 0.0f), Vec3f(-1.0f, -1.0f, 0.0f), (int) depth, false); //triTraverse(verts, Vec3f(-1.0f, 1.0f, 0.0f), Vec3f(1.0f, -1.0f, 0.0f), Vec3f( 1.0f, 1.0f, 0.0f), (int) depth, false); glEnable(GL_POINT_SMOOTH); glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); static const float bgcol[4] = { 0.0f, 0x2b / 255.0f, 0x36 / 255.0f, 1.0f }; glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 0, &verts[0]); glEnable(GL_FOG); glFogi(GL_FOG_MODE, GL_EXP2); glFogfv(GL_FOG_COLOR, bgcol); glFogf(GL_FOG_DENSITY, 0.4f); if (showPath) { glLineWidth(1.8f); glColor3ub(255, 127, 0); glDrawArrays(GL_LINE_STRIP, 0, (GLsizei) (draw_ratio * verts.size())); } if (showPathPoints) { glPointSize(4.0f); glColor3ub(255, 0, 0); glDrawArrays(GL_POINTS, 0, (GLsizei) (draw_ratio * verts.size())); } glDisableClientState(GL_VERTEX_ARRAY); glDisable(GL_FOG); glDisable(GL_POINT_SMOOTH); } // back to GUI glDisable(GL_DEPTH_TEST); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, width, 0, height, -1.0f, 1.0f); imguiRenderGLDraw(); glDisable(GL_BLEND); SwapBuffers(hDC); }
void myDisplay(void){ glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0, 1.0 * screenWidth / screenHeight, 0.1, 100.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(cameraX, cameraY, cameraZ, coiX, coiY, coiZ, 0.0, 1.0, 0.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); //set the light source properties glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient0); glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse0); glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular0); glLightfv(GL_LIGHT0, GL_POSITION, light_position0); glLightfv(GL_LIGHT1, GL_AMBIENT, light_ambient1); glLightfv(GL_LIGHT1, GL_DIFFUSE, light_diffuse1); glLightfv(GL_LIGHT1, GL_SPECULAR, light_specular1); glLightfv(GL_LIGHT1, GL_POSITION, light_position1); //set the remaining light sources - write your code here glLightfv(GL_LIGHT2, GL_AMBIENT, light_ambient2); glLightfv(GL_LIGHT2, GL_DIFFUSE, light_diffuse2); glLightfv(GL_LIGHT2, GL_SPECULAR, light_specular2); glLightfv(GL_LIGHT2, GL_POSITION, light_position2); glLightfv(GL_LIGHT3, GL_AMBIENT, light_ambient3); glLightfv(GL_LIGHT3, GL_DIFFUSE, light_diffuse3); glLightfv(GL_LIGHT3, GL_SPECULAR, light_specular3); glLightfv(GL_LIGHT3, GL_POSITION, light_position3); glLightfv(GL_LIGHT4, GL_AMBIENT, light_ambient4); glLightfv(GL_LIGHT4, GL_DIFFUSE, light_diffuse4); glLightfv(GL_LIGHT4, GL_SPECULAR, light_specular4); glLightfv(GL_LIGHT4, GL_POSITION, light_position4); //turn on or off the fog - write your code here if(fogSetting){ glEnable(GL_FOG); } else { glDisable(GL_FOG); } glColor3d(0.0, 0.0, 0.0); /////////////////////////////////////////floor//////////////////////////////////////// glMaterialfv(GL_FRONT, GL_AMBIENT, floor_ambient); glMaterialfv(GL_FRONT, GL_DIFFUSE, floor_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, floor_specular); glMaterialfv(GL_FRONT, GL_SHININESS, floor_shininess); glRotatef(theta,0,1,0); //draw the bottom floor glPushMatrix(); glTranslatef(0,floorHeight/2.0,0); glScaled(floorWidth, floorHeight, floorWidth); glutSolidCube(1.0); glPopMatrix(); //draw the left wall glPushMatrix(); glTranslated(-floorWidth / 2.0, floorWidth / 2.0, 0.0); glRotated(90.0, 0.0, 0.0, 1.0); glScaled(floorWidth, floorHeight, floorWidth); glutSolidCube(1.0); glPopMatrix(); //draw the right wall glPushMatrix(); glTranslated(0.0, floorWidth / 2.0, -floorWidth / 2.0); glRotated(90.0, 1.0, 0.0, 0.0); glScaled(floorWidth, floorHeight, floorWidth); glutSolidCube(1.0); glPopMatrix(); if (textureSetting == ON) glEnable(GL_TEXTURE_2D); //map an image texture on the left wall glBindTexture(GL_TEXTURE_2D, texImage1Name); glBegin(GL_QUADS); glNormal3f(1.0, 0.0, 0.0); glTexCoord2f(0.0, 0.0); glVertex3d(-floorWidth / 2.0 + floorHeight, 1.5, floorWidth / 2.0 - 1.25); glTexCoord2f(1.0, 0.0); glVertex3d(-floorWidth / 2.0 + floorHeight, 1.5, -floorWidth / 2.0 + 1.25); glTexCoord2f(1.0, 1.0); glVertex3d(-floorWidth / 2.0 + floorHeight, floorWidth - 0.5, -floorWidth / 2.0 + 1.25); glTexCoord2f(0.0, 1.0); glVertex3d(-floorWidth / 2.0 + floorHeight, floorWidth - 0.5, floorWidth / 2.0 - 1.25); glEnd(); //map another image texture on the right wall - write your code here glBindTexture(GL_TEXTURE_2D, texImage2Name); glBegin(GL_QUADS); glNormal3f(0.0, 0.0, 1.0); glTexCoord2f(0.0, 0.0); glVertex3d(-floorWidth / 2.0 + 0.5, 1.5, -floorWidth / 2.0 + floorHeight); glTexCoord2f(1.0, 0.0); glVertex3d( floorWidth / 2.0 - 0.5, 1.5, -floorWidth / 2.0 + floorHeight); glTexCoord2f(1.0, 1.0); glVertex3d( floorWidth / 2.0 - 0.5, floorWidth - 0.5,-floorWidth / 2.0 + floorHeight); glTexCoord2f(0.0, 1.0); glVertex3d(-floorWidth / 2.0 + 0.5, floorWidth - 0.5,-floorWidth / 2.0 + floorHeight); glEnd(); //map the checkerboard texture on the bottom floor - write your code here glBindTexture(GL_TEXTURE_2D, texCheckerBoardName); glBegin(GL_QUADS); glNormal3f(0.0, 1.0, 0.0); glTexCoord2f(0.0, 0.0); glVertex3d(-floorWidth / 2.0 , floorHeight+0.001, floorWidth / 2.0 ); glTexCoord2f(1.0, 0.0); glVertex3d( floorWidth / 2.0 , floorHeight+0.001, floorWidth / 2.0 ); glTexCoord2f(1.0, 1.0); glVertex3d( floorWidth / 2.0 , floorHeight+0.001, -floorWidth / 2.0 ); glTexCoord2f(0.0, 1.0); glVertex3d(-floorWidth / 2.0 , floorHeight+0.001, -floorWidth / 2.0 ); glEnd(); if (textureSetting == ON) glDisable(GL_TEXTURE_2D); //////////////////////////////////////////floor//////////////////////////////////////// glTranslated(0.0, floorHeight, 0.0); //set up furniture (table, chairs) material properties glMaterialfv(GL_FRONT, GL_AMBIENT, furniture_ambient); glMaterialfv(GL_FRONT, GL_DIFFUSE, furniture_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, furniture_specular); glMaterialfv(GL_FRONT, GL_SHININESS, furniture_shininess); //draw the two chairs - write your code here glPushMatrix(); glTranslatef(-floorWidth / 4.0, 0, floorWidth / 4.0); glRotatef(-90,0,1,0); chair(); glPopMatrix(); glPushMatrix(); glTranslatef(floorWidth / 4.0, 0, -floorWidth / 4.0); chair(); glPopMatrix(); //shift to the quad on the floor which the table will be placed glPushMatrix(); glTranslated(-1.0, 0.0, -1.0); //draw the table drawTable(); //raise to the table top: all the remaining objects are above the table glTranslated(0.0, tableTopHeight, 0.0); //set up teapot/teacup material properties - write your code here glMaterialfv(GL_FRONT, GL_AMBIENT, teapot_ambient); glMaterialfv(GL_FRONT, GL_DIFFUSE, teapot_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, teapot_specular); glMaterialfv(GL_FRONT, GL_SHININESS, teapot_shininess); //draw the teapot - write your code here glPushMatrix(); glTranslatef(0,0.15,0); glRotatef(45,0,1,0); tpot(); glPopMatrix(); //draw the teacup - write your code here glPushMatrix(); glTranslatef(0, 0, tableTopWidth / 4.0); tcup(); glPopMatrix(); glPushMatrix(); glTranslatef(tableTopWidth / 4.0, 0, 0); tcup(); glPopMatrix(); //set up lamp material properties - write your code here glMaterialfv(GL_FRONT, GL_AMBIENT, lamp_ambient); glMaterialfv(GL_FRONT, GL_DIFFUSE, lamp_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, lamp_specular); glMaterialfv(GL_FRONT, GL_SHININESS, lamp_shininess); //draw the lamp - write your code here glPushMatrix(); glTranslatef(-tableTopWidth / 4.0, 0, -tableTopWidth / 4.0); lamp(); glPopMatrix(); glPopMatrix(); //set up dustbin material properties - write your code here glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glMaterialfv(GL_FRONT, GL_AMBIENT, dustbin_ambient); glMaterialfv(GL_FRONT, GL_DIFFUSE, dustbin_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, dustbin_specular); glMaterialfv(GL_FRONT, GL_SHININESS, dustbin_shininess); //draw the dustbin - write your code here glPushMatrix(); glTranslated(floorWidth / 4.0, dustbinHeight/2.0, floorWidth / 4.0); glScaled(dustbinWidth, dustbinHeight, dustbinWidth); glutSolidCube(1.0); glPopMatrix(); glDisable(GL_BLEND); glutSwapBuffers(); }
/* * This function sets up the SDL surface and gl options. Some of this has been * borrowed from Ti Leggett's SDL port of Jeff Molofee's opengl examples at * http://nehe.gamedev.net. */ void SdlApp::init() { /* Flags to pass to SDL_SetVideoMode */ int videoFlags; const SDL_VideoInfo *videoInfo; if ( SDL_Init( SDL_INIT_VIDEO ) < 0 ) { throw std::runtime_error(std::string("Video initialization failed: ") + SDL_GetError( )); } /* Fetch the video info */ videoInfo = SDL_GetVideoInfo( ); if ( !videoInfo ) { throw std::runtime_error(std::string("Video query failed: ") + SDL_GetError( )); } /* the flags to pass to SDL_SetVideoMode */ videoFlags = SDL_OPENGL; /* Enable OpenGL in SDL */ videoFlags |= SDL_GL_DOUBLEBUFFER; /* Enable double buffering */ videoFlags |= SDL_HWPALETTE; /* Store the palette in hardware */ videoFlags |= SDL_RESIZABLE; /* Enable window resizing */ /* This checks to see if surfaces can be stored in memory */ if ( videoInfo->hw_available ) videoFlags |= SDL_HWSURFACE; else videoFlags |= SDL_SWSURFACE; /* This checks if hardware blits can be done */ if ( videoInfo->blit_hw ) videoFlags |= SDL_HWACCEL; videoFlags |= SDL_FULLSCREEN; /* Sets up OpenGL double buffering */ SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); /* get a SDL surface */ surface = SDL_SetVideoMode( 0, 0, 32, videoFlags ); /* Verify there is a surface */ if ( !surface ) { throw std::runtime_error(std::string("Video mode set failed: ") + SDL_GetError( )); } /* initialize OpenGL */ /* Enable smooth shading */ glShadeModel( GL_SMOOTH ); /* Set the background black */ glClearColor( 0.0f, 0.0f, 0.0f, 0.0f ); /* Depth buffer setup */ glClearDepth( 1.0f ); /* Enables Depth Testing */ glEnable( GL_DEPTH_TEST ); /* The Type Of Depth Test To Do */ glDepthFunc( GL_LEQUAL ); /* Really Nice Perspective Calculations */ glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ); glEnable (GL_POINT_SMOOTH); glEnable (GL_POLYGON_SMOOTH); glEnable (GL_LINE_SMOOTH); glHint (GL_POINT_SMOOTH_HINT, GL_NICEST); glHint (GL_POLYGON_SMOOTH_HINT, GL_NICEST); glHint (GL_LINE_SMOOTH_HINT, GL_NICEST); glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); /* Height / width ration */ GLfloat ratio = (GLfloat) videoInfo->current_w / (GLfloat) videoInfo->current_h; /* Setup our viewport. */ glViewport( 0, 0, ( GLsizei )videoInfo->current_w, ( GLsizei )videoInfo->current_h); /* change to the projection matrix and set our viewing volume. */ glMatrixMode( GL_PROJECTION ); glLoadIdentity( ); /* Set our perspective */ gluPerspective( 45.0f, ratio, 0.1f, 100.0f ); /* Make sure we're changing the model view and not the projection */ glMatrixMode( GL_MODELVIEW ); /* Reset The View */ glLoadIdentity( ); running = true; }
void InitGL(void) { GLvoid *image_data; int i, width, height; glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45.0f, (GLfloat) 640 / (GLfloat) 480, 0.1f, 1000.0f); glClearColor(0.7, 0.7, 1, 1); glDepthFunc(GL_LEQUAL); glEnable(GL_DEPTH_TEST); glCullFace(GL_BACK); glEnable(GL_COLOR_MATERIAL); glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient); glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, mat_no_specular); glMaterialfv(GL_FRONT, GL_SHININESS, mat_no_shininess); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient); glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); // Using GL_REPLACE will effectively disable lighting. // The default mode, GL_MODULATE, will use the texture color to // module the shaded material color, so the end result still // contains the shading. //glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); // generate texture objects for (i = 0; texture_files[i].filename != NULL; i++) ; texture_names = malloc(i * sizeof(GLuint)); glGenTextures(i, texture_names); glCheckError("glGenTextures"); // create textures from image files GLint texture_internal_format; GLenum texture_format, texture_type; for (i = 0; texture_files[i].filename != NULL; i++) { image_data = (GLvoid *) readppm(texture_files[i].filename, &width, &height); if (image_data) { printf("texture %d (OpenGL name = %d): %s, %d x %d\n", i, texture_names[i], texture_files[i].filename, width, height); if (texture_files[i].contains_transparency) { // Convert the RGB image to RGBA, by replacing // red pixels with transparent ones // Allocate a temporary RGBA image unsigned char *temp_image = (unsigned char*) malloc(width*height*4); unsigned char *input = image_data; unsigned char *output = temp_image; // Convert image to RGBA for (int pix = 0; pix < width*height; pix++) { if (*input == 255 && *(input+1) == 0 && *(input+2) == 0) { // Input pixel is pure red, make output pixel // white color and fully transparent *output++ = 255; *output++ = 255; *output++ = 255; *output++ = 0; // alpha } else { // Copy image color, make fully opaque *output++ = *input; *output++ = *(input + 1); *output++ = *(input + 2); *output++ = 255; } input += 3; } // Replace the RGB image data with the generated RGBA data free(image_data); image_data = temp_image; // This also influences some texture properties texture_internal_format = GL_RGBA8; texture_format = GL_RGBA; texture_type = GL_UNSIGNED_BYTE; } else { texture_internal_format = GL_RGB8; texture_format = GL_RGB; texture_type = GL_UNSIGNED_BYTE; } glBindTexture(GL_TEXTURE_2D, texture_names[i]); glCheckError("glBindTexture"); // Use GL_REPEAT to repeat the textures glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Chooses the two mipmaps that most closely match the size of the // pixel being textured and uses the GL_LINEAR criterion (a // weighted average of the texture elements that are closest to the // specified texture coordinates) to produce a texture value from // each mipmap. The final texture value is a weighted average of // those two values. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glCheckError("glTexParameteri"); // Use mipmaps gluBuild2DMipmaps(GL_TEXTURE_2D, texture_internal_format, width, height, texture_format, texture_type, image_data); glCheckError("glTexImage2D"); // Free the image data, as OpenGL will have made its internal copy by now free(image_data); } else { perror(texture_files[i].filename); exit(0); } } }
void camera() { CamMatrix rotx; CamMatrix roty; CamMatrix rotz; CamMatrix tmp1; CamMatrix tmp2; CamMatrix res; CamMatrix vect; cam_allocate_matrix(&rotx, 3, 3); cam_allocate_matrix(&roty, 3, 3); cam_allocate_matrix(&rotz, 3, 3); cam_allocate_matrix(&tmp1, 3, 3); cam_allocate_matrix(&tmp2, 3, 3); cam_allocate_matrix(&res, 1, 3); cam_allocate_matrix(&vect, 1, 3); cam_matrix_set_value(&vect, 0, 0, (POINTS_TYPE)0.0f); cam_matrix_set_value(&vect, 0, 1, (POINTS_TYPE)0.0f); cam_matrix_set_value(&vect, 0, 2, (POINTS_TYPE)1.0f); /* Rx */ cam_matrix_set_value(&rotx, 0, 0, (POINTS_TYPE)1.0f); cam_matrix_set_value(&rotx, 1, 0, (POINTS_TYPE)0.0f); cam_matrix_set_value(&rotx, 2, 0, (POINTS_TYPE)0.0f); cam_matrix_set_value(&rotx, 0, 1, (POINTS_TYPE)0.0f); cam_matrix_set_value(&rotx, 1, 1, (POINTS_TYPE)cos(rotX)); cam_matrix_set_value(&rotx, 2, 1, (POINTS_TYPE)sin(rotX)); cam_matrix_set_value(&rotx, 0, 2, (POINTS_TYPE)0.0f); cam_matrix_set_value(&rotx, 1, 2, (POINTS_TYPE)-sin(rotX)); cam_matrix_set_value(&rotx, 2, 2, (POINTS_TYPE)cos(rotX)); /* Ry */ cam_matrix_set_value(&roty, 0, 0, (POINTS_TYPE)cos(rotY)); cam_matrix_set_value(&roty, 1, 0, (POINTS_TYPE)0.0f); cam_matrix_set_value(&roty, 2, 0, (POINTS_TYPE)-sin(rotY)); cam_matrix_set_value(&roty, 0, 1, (POINTS_TYPE)0.0f); cam_matrix_set_value(&roty, 1, 1, (POINTS_TYPE)1.0f); cam_matrix_set_value(&roty, 2, 1, (POINTS_TYPE)0.0f); cam_matrix_set_value(&roty, 0, 2, (POINTS_TYPE)sin(rotY)); cam_matrix_set_value(&roty, 1, 2, (POINTS_TYPE)0.0f); cam_matrix_set_value(&roty, 2, 2, (POINTS_TYPE)cos(rotY)); /* Rz */ cam_matrix_set_value(&rotz, 0, 0, (POINTS_TYPE)cos(rotZ)); cam_matrix_set_value(&rotz, 1, 0, (POINTS_TYPE)sin(rotZ)); cam_matrix_set_value(&rotz, 2, 0, (POINTS_TYPE)0.0f); cam_matrix_set_value(&rotz, 0, 1, (POINTS_TYPE)-sin(rotZ)); cam_matrix_set_value(&rotz, 1, 1, (POINTS_TYPE)cos(rotZ)); cam_matrix_set_value(&rotz, 2, 1, (POINTS_TYPE)0.0f); cam_matrix_set_value(&rotz, 0, 2, (POINTS_TYPE)0.0f); cam_matrix_set_value(&rotz, 1, 2, (POINTS_TYPE)0.0f); cam_matrix_set_value(&rotz, 2, 2, (POINTS_TYPE)1.0f); cam_matrix_multiply(&tmp1, &rotx, &roty); cam_matrix_multiply(&tmp2, &tmp1, &rotz); cam_matrix_copy(¤tRotation, &tmp2); cam_matrix_multiply(&res, ¤tRotation, &vect); cam_matrix_copy(¤tNormal, &res); glLoadIdentity(); gluLookAt(posX, posY, posZ, posX + cam_matrix_get_value(¤tNormal, 0, 0), posY + cam_matrix_get_value(¤tNormal, 0, 1), posZ + cam_matrix_get_value(¤tNormal, 0, 2), 0.0f, 1.0f, 0.0f); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glViewport(0, 0, width, height); gluPerspective(fov, width / height, zNear, zFar); glMatrixMode(GL_MODELVIEW); cam_disallocate_matrix(&rotx); cam_disallocate_matrix(&roty); cam_disallocate_matrix(&rotz); cam_disallocate_matrix(&tmp1); cam_disallocate_matrix(&tmp2); cam_disallocate_matrix(&res); cam_disallocate_matrix(&vect); }
void Camera::setPerspective(){ glEnable(GL_DEPTH_TEST); glMatrixMode(GL_PROJECTION); gluPerspective(getFovy(),getAspect(),getZNear(),getZFar()); glutSetCursor(GLUT_CURSOR_NONE); }
void DebuggingView::draw() { if( raytracer == 0 || !raytracer->sceneLoaded() ) return; glShadeModel( GL_SMOOTH ); glEnable( GL_DEPTH_TEST ); glEnable( GL_LIGHTING ); glEnable( GL_LIGHT0 ); glEnable( GL_LIGHT1 ); glEnable( GL_NORMALIZE ); glViewport( 0, 0, w(), h() ); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(30.0,-float(w())/float(h()),0.001,1000.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); m_camera->applyViewingTransform(); // Need to apply an extra transform so that our camera 'approximately' // lines up with the scene camera, initially, and to correct for our // definition of "up." Vec3d uAxis = raytracer->getScene().getCamera().getU(); Vec3d vAxis = raytracer->getScene().getCamera().getV(); Vec3d wAxis = uAxis ^ vAxis; uAxis = wAxis ^ vAxis; uAxis.normalize(); vAxis.normalize(); wAxis.normalize(); GLdouble rotMat[16]; rotMat[0] = uAxis[0]; rotMat[1] = vAxis[0]; rotMat[2] = wAxis[0]; rotMat[3] = 0.0; rotMat[4] = uAxis[1]; rotMat[5] = vAxis[1]; rotMat[6] = wAxis[1]; rotMat[7] = 0.0; rotMat[8] = uAxis[2]; rotMat[9] = vAxis[2]; rotMat[10] = wAxis[2]; rotMat[11] = 0.0; rotMat[12] = 0.0; rotMat[13] = 0.0; rotMat[14] = 0.0; rotMat[15] = 1.0; glMultMatrixd( rotMat ); if( m_showAxes ) drawAxes(); if( m_showLights ) drawLights(); if( m_showGeometry ) { lightScene(); drawScene(); } drawRays(); if( m_showCamera ) drawCamera(); }
int gl_renderer::render() { int running = 1; /* ----- Event cycle --------------- */ while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: running = 0; break; case SDL_KEYDOWN: switch( event.key.keysym.sym ){ case SDLK_ESCAPE: case SDLK_q: running = 0; break; case SDLK_F1: SDL_WM_ToggleFullScreen(screen); break; case SDLK_s: control1->toggleEngineL(); break; case SDLK_d: control1->toggleEngineR(); break; case SDLK_k: control2->toggleEngineL(); break; case SDLK_l: control2->toggleEngineR(); break; case SDLK_1: switch_camera(0); break; case SDLK_2: switch_camera(1); break; case SDLK_3: switch_camera(2); break; default: break; } break; case SDL_VIDEORESIZE: if((screen = SDL_SetVideoMode(event.resize.w, event.resize.h, bpp, flags)) == 0) { fprintf(stderr, "Video resize failed: %s\n", SDL_GetError()); exit(-1); } glPushAttrib(GL_TRANSFORM_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(90.0f, (GLfloat)event.resize.w/(GLfloat)event.resize.h, 0.1, 100000.0); glViewport(0.0f, 0.0f, event.resize.w, event.resize.h); glPopAttrib(); break; case SDL_ACTIVEEVENT: if(event.active.state != SDL_APPMOUSEFOCUS && event.active.gain == 0) while(1){ SDL_WaitEvent(&event); if(event.type == SDL_ACTIVEEVENT && event.active.state != SDL_APPMOUSEFOCUS && event.active.gain == 1); break; } break; default: break; } } interval = FrameTiming(); /* apply control movement */ /* ----- Blitting on the screen --------------- */ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); glLoadIdentity(); current_camera->apply_rotation(); //glutSolidCube(50.0); //draw_skybox(200.0); background_stars->draw(); current_camera->apply_translation(); /* ----- Light ----- */ angle += 0.001f * interval; light1.Position[0] = sinf(angle) * 1.5f; light1.Position[2] = cosf(angle) * 1.5f; light2.Position[1] = sinf(angle) * 1.5f; light2.Position[2] = cosf(angle) * 1.5f; UpdateLight(&light1, GL_LIGHT1, 0.1f); UpdateLight(&light2, GL_LIGHT2, 0.1f); /* ----- Objects ----- */ for(list<gl_drawable*>::const_iterator it = drawables->begin(); it != drawables->end(); ++it) { (*it)->draw(); } SDL_GL_SwapBuffers(); /* SDL_Delay(25); */ /* Decomment this if you want 1/50th screen update */ return running; }
void display() { GLfloat lightPosition[4] = { -15.0f, -15.0f, 5.0f, 1.0f }; glEnable(GL_DEPTH_TEST); glClearColor(1,1,1,1); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60, 1, 1, 100); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glLightfv(GL_LIGHT0, GL_POSITION, lightPosition); gluLookAt(0,0,5,0,0,0,0,1,0); glRotatef(x_angle, 0, 1,0); glRotatef(y_angle, 1,0,0); glScalef(scale_size, scale_size, scale_size); draw_streamlines(); /* glTranslatef(0,0,-1); //if (toggle_draw_streamlines == true) drawBounds_inner(); glDepthMask(GL_FALSE); drawBounds_outter(); glDepthMask(GL_TRUE); */ //draw_triangulation(); // else if (toggle_animate_streamlines == true) // animate_streamlines(); //printf(" len %f %f %f\n", len[0], len[1], len[2]); /* glPushMatrix(); glScalef(1/(float)len[0], 1/(float)len[0], 1/(float)len[0]); //glScalef(1/110,1/110,1/110); glTranslatef(-len[0]/2.0, -len[1]/2.0, -len[2]/2.0); glColor3f(1,1,1); glBegin(GL_LINES); glVertex3f(0,0,0); glVertex3f(len[0],0,0); glVertex3f(0,0,0); glVertex3f(0,len[1],0); glVertex3f(0,0,0); glVertex3f(0,0,1); glVertex3f(len[0],len[1],0); glVertex3f(len[0],0,0); glVertex3f(len[0],len[1],0); glVertex3f(0,len[1],0); glEnd(); glPopMatrix(); */ glutSwapBuffers(); }
int main(int argc, char **argv) { int i; glutInit(&argc, argv); for (i=1; i<argc; i++) { if (!strcmp("-linear", argv[i])) { linearFiltering = 1; } else if (!strcmp("-mipmap", argv[i])) { useMipmaps = 1; } else if (!strcmp("-ext", argv[i])) { forceExtension = 1; } } glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH | GLUT_STENCIL | GLUT_MULTISAMPLE); #if 1 /* In GLUT 4.0, you'll be able to do this an be sure to get 2 bits of stencil if the machine has it for you. */ glutInitDisplayString("samples stencil>=3 rgb double depth"); #endif glutCreateWindow("OpenGL Halo Magic (hit Space)"); if (glutGet(GLUT_WINDOW_STENCIL_SIZE) < 3) { printf("halomagic: Sorry, I need at least 3 bits of stencil.\n"); exit(1); } /* Register GLUT callbacks. */ glutDisplayFunc(redraw); glutMouseFunc(mouse); glutMotionFunc(motion); glutVisibilityFunc(visible); glutKeyboardFunc(key); glutSpecialFunc(special); glutCreateMenu(controlLights); glutAddMenuEntry("Toggle halo blending", M_BLENDED_HALO); glutAddMenuEntry("Show halo", M_SHOW_HALO); glutAddMenuEntry("Switch model", M_SWITCH_MODEL); glutAddMenuEntry("Toggle motion", M_MOTION); glutAddMenuEntry("-----------------------", M_NONE); glutAddMenuEntry("Toggle light", M_LIGHT); glutAddMenuEntry("Toggle texture", M_TEXTURE); glutAddMenuEntry("Toggle shadows", M_SHADOWS); glutAddMenuEntry("Toggle reflection", M_REFLECTION); glutAddMenuEntry("Toggle object", M_DINOSAUR); glutAddMenuEntry("-----------------------", M_NONE); glutAddMenuEntry("Toggle reflection stenciling", M_STENCIL_REFLECTION); glutAddMenuEntry("Toggle shadow stenciling", M_STENCIL_SHADOW); glutAddMenuEntry("Toggle shadow offset", M_OFFSET_SHADOW); glutAddMenuEntry("----------------------", M_NONE); glutAddMenuEntry("Positional light", M_POSITIONAL); glutAddMenuEntry("Directional light", M_DIRECTIONAL); glutAddMenuEntry("-----------------------", M_NONE); glutAddMenuEntry("Toggle performance", M_PERFORMANCE); glutAttachMenu(GLUT_RIGHT_BUTTON); makeDinosaur(); #ifdef GL_VERSION_1_1 if (supportsOneDotOne() && !forceExtension) { polygonOffsetVersion = ONE_DOT_ONE; glPolygonOffset(-2.0, -1.0); } else #endif { #ifdef GL_EXT_polygon_offset /* check for the polygon offset extension */ if (glutExtensionSupported("GL_EXT_polygon_offset")) { polygonOffsetVersion = EXTENSION; glPolygonOffsetEXT(-0.1, -0.002); } else #endif { polygonOffsetVersion = MISSING; printf("\ndinoshine: Missing polygon offset.\n"); printf(" Expect shadow depth aliasing artifacts.\n\n"); } } glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glLineWidth(3.0); glMatrixMode(GL_PROJECTION); gluPerspective( /* field of view in degree */ 40.0, /* aspect ratio */ 1.0, /* Z near */ 20.0, /* Z far */ 100.0); glMatrixMode(GL_MODELVIEW); gluLookAt(0.0, 8.0, 60.0, /* eye is at (0,0,30) */ 0.0, 8.0, 0.0, /* center is at (0,0,0) */ 0.0, 1.0, 0.); /* up is in postivie Y direction */ glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, 1); glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColor); glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0.1); glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.05); glEnable(GL_LIGHT0); glEnable(GL_LIGHTING); makeFloorTexture(); /* Setup floor plane for projected shadow calculations. */ findPlane(floorPlane, floorVertices[1], floorVertices[2], floorVertices[3]); glutMainLoop(); return 0; /* ANSI C requires main to return int. */ }
int main( int argc, char *argv[] ) { osgInit(argc, argv); glutInit(&argc, argv); glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE); glutCreateWindow("OpenSG"); glutKeyboardFunc(key); // glutReshapeFunc(resize); glutDisplayFunc(display); // glutMouseFunc(mouse); // glutMotionFunc(motion); glutIdleFunc(display); pImage = Image::create(); // create the dummy structures // the window is needed for the chunks that access GLObjects win = GLUTWindow::create(); win->frameInit(); // test for preliminary calls not messing up GLexts win->init(); dact = DrawAction::create(); dact->setWindow(get_pointer(win)); win->init(); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); gluPerspective( 60, 1, 0.1, 10 ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); gluLookAt( 3, 3, 3, 0, 0, 0, 0, 1, 0 ); glEnable( GL_DEPTH_TEST ); glEnable( GL_LIGHTING ); glEnable( GL_LIGHT0 ); glPixelStorei( GL_UNPACK_ALIGNMENT, 1 ); dlid = glGenLists( 1 ); glNewList( dlid, GL_COMPILE ); glutSolidSphere( .8, 8, 8 ); glEndList(); dlid2 = glGenLists( 1 ); glNewList( dlid2, GL_COMPILE ); glBegin( GL_POLYGON ); glNormal3f( 0, 1, 0 ); glColor3f( 1, 1, 1 ); glTexCoord2f( 0, 0 ); glVertex3f( -1.5, -1, -1.5 ); glTexCoord2f( 2, 0 ); glVertex3f( 1.5, -1, -1.5 ); glTexCoord2f( 2, 2 ); glVertex3f( 1.5, -1, 1.5 ); glTexCoord2f( 0, 2 ); glVertex3f( -1.5, -1, 1.5 ); glEnd(); glEndList(); Matrix m; tchunk1 = TransformChunk::create(); m.setTranslate( 0, 1, 0 ); tchunk1->setMatrix( m ); tchunk2 = TransformChunk::create(); tchunk2->setMatrix( Matrix::identity() ); mchunk1 = MaterialChunk::create(); mchunk1->setDiffuse( Color4f( 1,0,0,0 ) ); mchunk1->setAmbient( Color4f( 1,0,0,0 ) ); mchunk1->setShininess( 20 ); mchunk2 = MaterialChunk::create(); mchunk2->setDiffuse( Color4f( 0,1,0,0 ) ); mchunk2->setAmbient( Color4f( 0,1,0,0 ) ); mchunk2->setShininess( 50 ); // Texture chunk // UChar8 imgdata[] = // { 255,0,0,0, 0,255,0,0, 0,0,255,255, 255,255,255,255 }; UChar8 imgdata[] = { 255,0,0, 255,0,0, 255,0,255, 255,0,0, 255,0,0, 255,0,255, 255,255,0, 255,255,0, 255,255,255, 255,255,0, 255,255,0, 255,255,255, }; // UChar8 limgdata[] = // { 0, 128, 64, 255 }; pImage->set( Image::OSG_RGB_PF, 2, 2, 1, 1, 1, 0, imgdata ); if ( argc > 1 ) pImage->read( argv[1] ); xchunk1 = TextureChunk::create(); beginEditCP(xchunk1); xchunk1->setImage( pImage ); // NOTE: the image is NOT copied, the variable // needs to be kept around as long as the // texture is used xchunk1->setMinFilter( GL_LINEAR ); xchunk1->setMagFilter( GL_NEAREST ); xchunk1->setWrapS( GL_REPEAT ); xchunk1->setWrapT( GL_REPEAT ); xchunk1->setEnvMode( GL_REPLACE ); xchunk1->setEnvColor( Color4f(.5,.5,.5,0) ); xchunk1->setScale( false ); // xchunk1->setShaderOperation(GL_PASS_THROUGH_NV); endEditCP(xchunk1); xchunk1->imageContentChanged(); beginEditCP(xchunk1); xchunk1->setImage( pImage ); endEditCP(xchunk1); // blend chunk blchunk = BlendChunk::create(); #ifdef GL_EXT_blend_color blchunk->setSrcFactor( GL_CONSTANT_ALPHA ); blchunk->setDestFactor( GL_ONE_MINUS_CONSTANT_ALPHA ); #endif blchunk->setColor( Color4f( .5,.5,.5,0.1 ) ); blchunk->setEquation(GL_FUNC_SUBTRACT); std::cout << "BlendChunk is trans:" << blchunk->isTransparent() << std::endl; // texture transform chunk txchunk = TextureTransformChunk::create(); beginEditCP(txchunk); txchunk->setMatrix( Matrix(4,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1) ); endEditCP(txchunk); // polygon chunk pchunk1 = PolygonChunk::create(); { UInt32 stipple[32] = { 0xffff0000, 0x0000ffff, 0xffff0000, 0x0000ffff, 0xffff0000, 0x0000ffff, 0xffff0000, 0x0000ffff, 0xffff0000, 0x0000ffff, 0xffff0000, 0x0000ffff, 0xffff0000, 0x0000ffff, 0xffff0000, 0x0000ffff, 0xffff0000, 0x0000ffff, 0xffff0000, 0x0000ffff, 0xffff0000, 0x0000ffff, 0xffff0000, 0x0000ffff, 0xffff0000, 0x0000ffff, 0xffff0000, 0x0000ffff, 0xffff0000, 0x0000ffff, 0xffff0000, 0x0000ffff }; pchunk1->editMFStipple()->clear(); for ( int i = 0; i < 32; i++ ) pchunk1->editMFStipple()->push_back( stipple[i] ); } pchunk1->setFrontMode(GL_LINE); pchunk1->setBackMode(GL_FILL); pchunk2 = PolygonChunk::create(); { UInt32 stipple[32] = { 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; pchunk2->editMFStipple()->clear(); for ( int i = 0; i < 32; i++ ) pchunk2->editMFStipple()->push_back( stipple[i] ); } lichunk1 = LineChunk::create(); lichunk1->setSmooth(true); lichunk1->setStipplePattern(0xf0f0); lichunk2 = LineChunk::create(); lichunk2->setStippleRepeat(5); lichunk2->setStipplePattern(0xaaaa); glutMainLoop(); return 0; }
/* Render::renderSceneShadowMap: shadow mapping */ void Render::renderSceneShadowMap(PMDObject *objs, const short *order, int num, Stage *stage, bool useMMDLikeCartoon, bool useCartoonRendering, float lightIntensity, const float *lightDirection, const float *lightColor, int shadowMappingTextureSize, bool shadowMappingLightFirst, float shadowMappingSelfDensity) { short i; GLint viewport[4]; /* store viewport */ GLdouble modelview[16]; /* store model view transform */ GLdouble projection[16]; /* store projection transform */ bool toonLight = true; #ifdef RENDER_SHADOWAUTOVIEW float eyeDist; btVector3 v; #endif /* RENDER_SHADOWAUTOVIEW */ static GLfloat lightdim[] = { 0.2f, 0.2f, 0.2f, 1.0f }; static const GLfloat lightblk[] = { 0.0f, 0.0f, 0.0f, 1.0f }; /* render the depth texture */ /* store the current viewport */ glGetIntegerv(GL_VIEWPORT, viewport); /* store the current projection matrix */ glGetDoublev(GL_PROJECTION_MATRIX, projection); /* switch to FBO for depth buffer rendering */ glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fboID); /* clear the buffer */ /* clear only the depth buffer, since other buffers will not be used */ glClear(GL_DEPTH_BUFFER_BIT); /* set the viewport to the required texture size */ glViewport(0, 0, shadowMappingTextureSize, shadowMappingTextureSize); /* reset the projection matrix */ glMatrixMode(GL_PROJECTION); glLoadIdentity(); /* set the model view matrix to make the light position as eye point and capture the whole scene in the view */ glMatrixMode(GL_MODELVIEW); glLoadIdentity(); #ifdef RENDER_SHADOWAUTOVIEW /* set the distance to cover all the model range */ eyeDist = m_shadowMapAutoViewRadius / sinf(RENDER_SHADOWAUTOVIEWANGLE * 0.5f * 3.1415926f / 180.0f); /* set the perspective */ gluPerspective(RENDER_SHADOWAUTOVIEWANGLE, 1.0, 1.0, eyeDist + m_shadowMapAutoViewRadius + 50.0f); /* +50.0f is needed to cover the background */ /* the viewpoint should be at eyeDist far toward light direction from the model center */ v = m_lightVec * eyeDist + m_shadowMapAutoViewEyePoint; gluLookAt(v.x(), v.y(), v.z(), m_shadowMapAutoViewEyePoint.x(), m_shadowMapAutoViewEyePoint.y(), m_shadowMapAutoViewEyePoint.z(), 0.0, 1.0, 0.0); #else /* fixed view */ gluPerspective(25.0, 1.0, 1.0, 120.0); gluLookAt(30.0, 77.0, 30.0, 0.0, 17.0, 0.0, 0.0, 1.0, 0.0); #endif /* RENDER_SHADOWAUTOVIEW */ /* keep the current model view for later process */ glGetDoublev(GL_MODELVIEW_MATRIX, modelview); /* do not write into frame buffer other than depth information */ glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); /* also, lighting is not needed */ glDisable(GL_LIGHTING); /* disable rendering the front surface to get the depth of back face */ glCullFace(GL_FRONT); /* disable alpha test */ glDisable(GL_ALPHA_TEST); /* we are now writing to depth texture using FBO, so disable the depth texture mapping here */ glActiveTextureARB(GL_TEXTURE3_ARB); glDisable(GL_TEXTURE_2D); glActiveTextureARB(GL_TEXTURE0_ARB); /* set polygon offset to avoid "moire" */ glEnable(GL_POLYGON_OFFSET_FILL); glPolygonOffset(4.0, 4.0); /* render objects for depth */ /* only objects that wants to drop shadow should be rendered here */ for (i = 0; i < num; i++) { if (objs[order[i]].isEnable() == true) { objs[order[i]].getPMDModel()->renderForShadow(); } } /* reset the polygon offset */ glDisable(GL_POLYGON_OFFSET_FILL); /* switch to default FBO */ glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); /* revert configurations to normal rendering */ glViewport(viewport[0], viewport[1], viewport[2], viewport[3]); glMatrixMode(GL_PROJECTION); glLoadMatrixd(projection); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glEnable(GL_LIGHTING); glCullFace(GL_BACK); glEnable(GL_ALPHA_TEST); /* clear all the buffers */ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); /* render the full scene */ /* set model view matrix, as the same as normal rendering */ glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glMultMatrixf(m_rotMatrix); /* render the whole scene */ if (shadowMappingLightFirst) { /* render light setting, later render only the shadow part with dark setting */ stage->renderBackground(); stage->renderFloor(); for (i = 0; i < num; i++) { if (objs[order[i]].isEnable() == true) { if (objs[order[i]].getPMDModel()->getToonFlag() == false && toonLight == true) { /* disable toon lighting */ updateLight(true, false, lightIntensity, lightDirection, lightColor); toonLight = false; } else if (objs[order[i]].getPMDModel()->getToonFlag() == true && toonLight == false) { /* enable toon lighting */ updateLight(useMMDLikeCartoon, useCartoonRendering, lightIntensity, lightDirection, lightColor); toonLight = true; } objs[order[i]].getPMDModel()->renderModel(); objs[order[i]].getPMDModel()->renderEdge(); } } if (toonLight == false) { /* restore toon lighting */ updateLight(useMMDLikeCartoon, useCartoonRendering, lightIntensity, lightDirection, lightColor); } } else { /* render in dark setting, later render only the non-shadow part with light setting */ /* light setting for non-toon objects */ lightdim[0] = lightdim[1] = lightdim[2] = 0.55f - 0.2f * shadowMappingSelfDensity; glLightfv(GL_LIGHT0, GL_DIFFUSE, lightdim); glLightfv(GL_LIGHT0, GL_AMBIENT, lightdim); glLightfv(GL_LIGHT0, GL_SPECULAR, lightblk); /* render the non-toon objects (back, floor, non-toon models) */ stage->renderBackground(); stage->renderFloor(); for (i = 0; i < num; i++) { if (objs[order[i]].isEnable() == true && objs[order[i]].getPMDModel()->getToonFlag() == false) objs[order[i]].getPMDModel()->renderModel(); } /* for toon objects, they should apply the model-defined toon texture color at texture coordinates (0, 0) for shadow rendering */ /* so restore the light setting */ if (useCartoonRendering == true) updateLight(useMMDLikeCartoon, useCartoonRendering, lightIntensity, lightDirection, lightColor); /* render the toon objects */ for (i = 0; i < num; i++) { if (objs[order[i]].isEnable() == true && objs[order[i]].getPMDModel()->getToonFlag() == true) { /* set texture coordinates for shadow mapping */ objs[order[i]].getPMDModel()->updateShadowColorTexCoord(shadowMappingSelfDensity); /* tell model to render with the shadow corrdinates */ objs[order[i]].getPMDModel()->setSelfShadowDrawing(true); /* render model and edge */ objs[order[i]].getPMDModel()->renderModel(); objs[order[i]].getPMDModel()->renderEdge(); /* disable shadow rendering */ objs[order[i]].getPMDModel()->setSelfShadowDrawing(false); } } if (useCartoonRendering == false) updateLight(useMMDLikeCartoon, useCartoonRendering, lightIntensity, lightDirection, lightColor); } /* render the part clipped by the depth texture */ /* activate the texture unit for shadow mapping and make it current */ glActiveTextureARB(GL_TEXTURE3_ARB); /* set texture matrix (note: matrices should be set in reverse order) */ glMatrixMode(GL_TEXTURE); glLoadIdentity(); /* move the range from [-1,1] to [0,1] */ glTranslated(0.5, 0.5, 0.5); glScaled(0.5, 0.5, 0.5); /* multiply the model view matrix when the depth texture was rendered */ glMultMatrixd(modelview); /* multiply the inverse matrix of current model view matrix */ glMultMatrixf(m_rotMatrixInv); /* revert to model view matrix mode */ glMatrixMode(GL_MODELVIEW); /* enable texture mapping with texture coordinate generation */ glEnable(GL_TEXTURE_2D); glEnable(GL_TEXTURE_GEN_S); glEnable(GL_TEXTURE_GEN_T); glEnable(GL_TEXTURE_GEN_R); glEnable(GL_TEXTURE_GEN_Q); /* bind the depth texture rendered at the first step */ glBindTexture(GL_TEXTURE_2D, m_depthTextureID); /* depth texture set up was done, now switch current texture unit to default */ glActiveTextureARB(GL_TEXTURE0_ARB); /* set depth func to allow overwrite for the same surface in the following rendering */ glDepthFunc(GL_LEQUAL); if (shadowMappingLightFirst) { /* the area clipped by depth texture by alpha test is dark part */ glAlphaFunc(GL_GEQUAL, 0.1f); /* light setting for non-toon objects */ lightdim[0] = lightdim[1] = lightdim[2] = 0.55f - 0.2f * shadowMappingSelfDensity; glLightfv(GL_LIGHT0, GL_DIFFUSE, lightdim); glLightfv(GL_LIGHT0, GL_AMBIENT, lightdim); glLightfv(GL_LIGHT0, GL_SPECULAR, lightblk); /* render the non-toon objects (back, floor, non-toon models) */ stage->renderBackground(); stage->renderFloor(); for (i = 0; i < num; i++) { if (objs[order[i]].isEnable() == true && objs[order[i]].getPMDModel()->getToonFlag() == false) objs[order[i]].getPMDModel()->renderModel(); } /* for toon objects, they should apply the model-defined toon texture color at texture coordinates (0, 0) for shadow rendering */ /* so restore the light setting */ if (useCartoonRendering == true) updateLight(useMMDLikeCartoon, useCartoonRendering, lightIntensity, lightDirection, lightColor); /* render the toon objects */ for (i = 0; i < num; i++) { if (objs[order[i]].isEnable() == true && objs[order[i]].getPMDModel()->getToonFlag() == true) { /* set texture coordinates for shadow mapping */ objs[order[i]].getPMDModel()->updateShadowColorTexCoord(shadowMappingSelfDensity); /* tell model to render with the shadow corrdinates */ objs[order[i]].getPMDModel()->setSelfShadowDrawing(true); /* render model and edge */ objs[order[i]].getPMDModel()->renderModel(); /* disable shadow rendering */ objs[order[i]].getPMDModel()->setSelfShadowDrawing(false); } } if (useCartoonRendering == false) updateLight(useMMDLikeCartoon, useCartoonRendering, lightIntensity, lightDirection, lightColor); } else { /* the area clipped by depth texture by alpha test is light part */ glAlphaFunc(GL_GEQUAL, 0.001f); stage->renderBackground(); stage->renderFloor(); for (i = 0; i < num; i++) { if (objs[order[i]].isEnable() == true) { if (objs[order[i]].getPMDModel()->getToonFlag() == false && toonLight == true) { /* disable toon lighting */ updateLight(true, false, lightIntensity, lightDirection, lightColor); toonLight = false; } else if (objs[order[i]].getPMDModel()->getToonFlag() == true && toonLight == false) { /* enable toon lighting */ updateLight(useMMDLikeCartoon, useCartoonRendering, lightIntensity, lightDirection, lightColor); toonLight = true; } objs[order[i]].getPMDModel()->renderModel(); } } if (toonLight == false) { /* restore toon lighting */ updateLight(useMMDLikeCartoon, useCartoonRendering, lightIntensity, lightDirection, lightColor); } } /* reset settings */ glDepthFunc(GL_LESS); glAlphaFunc(GL_GEQUAL, 0.05f); glActiveTextureARB(GL_TEXTURE3_ARB); glDisable(GL_TEXTURE_GEN_S); glDisable(GL_TEXTURE_GEN_T); glDisable(GL_TEXTURE_GEN_R); glDisable(GL_TEXTURE_GEN_Q); glDisable(GL_TEXTURE_2D); glActiveTextureARB(GL_TEXTURE0_ARB); }
static void realize (GtkWidget *widget, gpointer data) { GLUquadricObj *qobj; static GLfloat light_diffuse[] = {1.0, 0.0, 0.0, 1.0}; static GLfloat light_position[] = {1.0, 1.0, 1.0, 0.0}; /* * Create GdkGLWindow for widget->window. */ glwindow = gdk_gl_window_new (glconfig, widget->window, NULL); /* Set a background of "None" on window to avoid AIX X server crash */ gdk_window_set_back_pixmap (widget->window, NULL, FALSE); /* * Create OpenGL rendering context. */ if (glcontext == NULL) { glcontext = gdk_gl_context_new (GDK_GL_DRAWABLE (glwindow), NULL, TRUE, GDK_GL_RGBA_TYPE); if (glcontext == NULL) { g_print ("Connot create the OpenGL rendering context\n"); exit (1); } g_print ("The OpenGL rendering context is created\n"); } /*** OpenGL BEGIN ***/ if (!gdk_gl_drawable_gl_begin (GDK_GL_DRAWABLE (glwindow), glcontext)) return; qobj = gluNewQuadric (); gluQuadricDrawStyle (qobj, GLU_FILL); glNewList (1, GL_COMPILE); gluSphere (qobj, 1.0, 20, 20); glEndList (); glLightfv (GL_LIGHT0, GL_DIFFUSE, light_diffuse); glLightfv (GL_LIGHT0, GL_POSITION, light_position); glEnable (GL_LIGHTING); glEnable (GL_LIGHT0); glEnable (GL_DEPTH_TEST); glClearColor (1.0, 1.0, 1.0, 1.0); glClearDepth (1.0); glViewport (0, 0, widget->allocation.width, widget->allocation.height); glMatrixMode (GL_PROJECTION); glLoadIdentity (); gluPerspective (40.0, 1.0, 1.0, 10.0); glMatrixMode (GL_MODELVIEW); glLoadIdentity (); gluLookAt (0.0, 0.0, 3.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); glTranslatef (0.0, 0.0, -3.0); gdk_gl_drawable_gl_end (GDK_GL_DRAWABLE (glwindow)); /*** OpenGL END ***/ }
void Init(void) { int i; struct timeval t; struct timezone tz; float top_y = 1.0; float bottom_y = 0.0; float top_z = 0.15; float bottom_z = 0.69; float spacing = 2.5; static float lmodel_ambient[] = {0.0, 0.0, 0.0, 0.0}; static float lmodel_twoside[] = {GL_FALSE}; static float lmodel_local[] = {GL_FALSE}; static float light0_ambient[] = {0.1, 0.1, 0.1, 1.0}; static float light0_diffuse[] = {1.0, 1.0, 1.0, 0.0}; static float light0_position[] = {0.8660254, 0.5, 1, 0}; static float light0_specular[] = {1.0, 1.0, 1.0, 0.0}; static float bevel_mat_ambient[] = {0.0, 0.0, 0.0, 1.0}; static float bevel_mat_shininess[] = {40.0}; static float bevel_mat_specular[] = {1.0, 1.0, 1.0, 0.0}; static float bevel_mat_diffuse[] = {1.0, 0.0, 0.0, 0.0}; gettimeofday(&t, &tz); srand48(t.tv_usec); ReInit(); for (i = 0; i < RINGS; i++) { rgb_colors[i][0] = rgb_colors[i][1] = rgb_colors[i][2] = 0; } rgb_colors[BLUERING][2] = 255; rgb_colors[REDRING][0] = 255; rgb_colors[GREENRING][1] = 255; rgb_colors[YELLOWRING][0] = 255; rgb_colors[YELLOWRING][1] = 255; mapped_colors[BLUERING] = BLUE; mapped_colors[REDRING] = RED; mapped_colors[GREENRING] = GREEN; mapped_colors[YELLOWRING] = YELLOW; mapped_colors[BLACKRING] = BLACK; dests[BLUERING][0] = -spacing; dests[BLUERING][1] = top_y; dests[BLUERING][2] = top_z; dests[BLACKRING][0] = 0.0; dests[BLACKRING][1] = top_y; dests[BLACKRING][2] = top_z; dests[REDRING][0] = spacing; dests[REDRING][1] = top_y; dests[REDRING][2] = top_z; dests[YELLOWRING][0] = -spacing / 2.0; dests[YELLOWRING][1] = bottom_y; dests[YELLOWRING][2] = bottom_z; dests[GREENRING][0] = spacing / 2.0; dests[GREENRING][1] = bottom_y; dests[GREENRING][2] = bottom_z; theTorus = glGenLists(1); glNewList(theTorus, GL_COMPILE); FillTorus(0.1, 8, 1.0, 25); glEndList(); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glEnable(GL_DEPTH_TEST); glClearDepth(1.0); if (rgb) { glClearColor(0.5, 0.5, 0.5, 0.0); glLightfv(GL_LIGHT0, GL_AMBIENT, light0_ambient); glLightfv(GL_LIGHT0, GL_DIFFUSE, light0_diffuse); glLightfv(GL_LIGHT0, GL_SPECULAR, light0_specular); glLightfv(GL_LIGHT0, GL_POSITION, light0_position); glEnable(GL_LIGHT0); glLightModelfv(GL_LIGHT_MODEL_LOCAL_VIEWER, lmodel_local); glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, lmodel_twoside); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient); glEnable(GL_LIGHTING); glMaterialfv(GL_FRONT, GL_AMBIENT, bevel_mat_ambient); glMaterialfv(GL_FRONT, GL_SHININESS, bevel_mat_shininess); glMaterialfv(GL_FRONT, GL_SPECULAR, bevel_mat_specular); glMaterialfv(GL_FRONT, GL_DIFFUSE, bevel_mat_diffuse); glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE); glEnable(GL_COLOR_MATERIAL); glShadeModel(GL_SMOOTH); } else { glClearIndex(BACKGROUND); glShadeModel(GL_FLAT); } glMatrixMode(GL_PROJECTION); gluPerspective(45, 1.33, 0.1, 100.0); glMatrixMode(GL_MODELVIEW); }
int main() { // Create the main window sf::ContextSettings Settings; Settings.depthBits = 24; // Request a 24 bits depth buffer Settings.stencilBits = 8; // Request a 8 bits stencil buffer Settings.antialiasingLevel = 16; // Request 2 levels of antialiasing sf::RenderWindow App(sf::VideoMode(1280, 720, 32), "Terrain Assignment", sf::Style::Close, Settings); int width=600,height=600; // Create a clock for measuring time elapsed sf::Clock Clock; aiVector3D position(0,10,-30); Camera camera; camera.Init(&App, position); //create a camera //prepare OpenGL surface for HSR glClearDepth(1.f); glClearColor(0.0f, 0.0f, 0.0f, 0.f); //background colour glEnable(GL_DEPTH_TEST); // check for depth glEnable(GL_NORMALIZE); // automatically convert normals to unit normals glEnable(GL_LIGHTING); //This enables the possibility of lighting glEnable(GL_LIGHT0); //This enables a single light glEnable(GL_DEPTH_TEST); glDepthMask(GL_TRUE); glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); //Giving the light positions GLfloat light_color[] = { 1.0, 1.0, 1.0, 1.0 }; GLfloat light_position[] = { 10.0, 10.0, -100.0, 0.0 }; GLfloat light_amb[] = { 3.0, 3.0, 3.0, 1.0 }; GLfloat materialSpecular[] = { 1.0f, 1.0f, 1.0f, 1.0f }; // create an array of RGBA values (White) GLfloat materialShininess[] = { 128.0f }; // select value between 0-128, 128=shiniest //// Setup a perspective projection & Camera position glMatrixMode(GL_PROJECTION); glLoadIdentity(); //set up a 3D Perspective View volume gluPerspective(90.f, (float)width/height, 1.f, 300.0f);//fov, aspect, zNear, zFar //load & bind the shader sf::Shader shader; //all the lighting & texture blending code should be put in 'fragment.glsl' if(!shader.loadFromFile("vertex.glsl","fragment.glsl")){ exit(1); } #pragma region Textures // Textures sf::Texture waterTexture; if (!waterTexture.loadFromFile("water.png")) { std::cout << "Could not load water image"; } sf::Texture grassTexture; if (!grassTexture.loadFromFile("grass.png")){ std::cout << "Could not load grass image"; } sf::Texture snowTexture; if (!snowTexture.loadFromFile("snowy rock.png")) { std::cout << "Could not load rock image"; } #pragma endregion shader.setParameter("waterTex", waterTexture); shader.setParameter("grassTex", grassTexture); shader.setParameter("snowTex", snowTexture); //Create our Terrain Terrain terrain; terrain.InitWithFileName("heightmap.bmp"); shader.setParameter("tallestPoint", terrain.tallestPoint); // Start game loop while (App.isOpen()) { // Process events sf::Event Event; while (App.pollEvent(Event)) { // Close window : exit if (Event.type == sf::Event::Closed) App.close(); // Escape key : exit if ((Event.type == sf::Event::KeyPressed) && (Event.key.code == sf::Keyboard::Escape)) App.close(); if ((Event.type == sf::Event::KeyPressed) && (Event.key.code == sf::Keyboard::I)) { terrain.swapWireFrame(); } //update the camera camera.Update(Event, &App); } camera.UpdatePosition(); // Clear color and depth buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Apply some transformations //initialise the worldview matrix glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //get the viewing transform from the camera camera.ViewingTransform(); //make the world spin //TODO:probably should remove this in final static float ang = 0.0; ang += 0.01f; glRotatef(ang * 2, 0, 1, 0);//spin about y-axis sf::Shader::bind(&shader); glLightfv(GL_LIGHT0, GL_AMBIENT, light_amb); // set color of diffuse component glLightfv(GL_LIGHT0, GL_DIFFUSE, light_color); // set color of diffuse component glLightfv(GL_LIGHT0, GL_SPECULAR, light_color); // set color of specular component glLightfv(GL_LIGHT0, GL_POSITION, light_position); // set position //make the world spin //TODO:probably should remove this in final //static float ang=0.0; //ang+=0.01f; //glRotatef(ang*2,0,1,0);//spin about y-axis //draw the world terrain.Draw(); // Finally, display rendered frame on screen App.display(); } return EXIT_SUCCESS; }
//////////////////////////////////////////////////////////// /// Entry point of application /// /// \return Application exit code /// //////////////////////////////////////////////////////////// int main() { // Create the main window sf::Window window(sf::VideoMode(640, 480, 32), "SFML Window"); // Create a clock for measuring the time elapsed sf::Clock clock; // Set the color and depth clear values glClearDepth(1.f); glClearColor(0.f, 0.f, 0.f, 0.f); // Enable Z-buffer read and write glEnable(GL_DEPTH_TEST); glDepthMask(GL_TRUE); // Setup a perspective projection glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(90.f, 1.f, 1.f, 500.f); // Start the game loop while (window.IsOpened()) { // Process events sf::Event event; while (window.GetEvent(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::Key::Escape)) window.Close(); // Resize event : adjust viewport if (event.Type == sf::Event::Resized) glViewport(0, 0, event.Size.Width, event.Size.Height); } // Activate the window before using OpenGL commands. // This is useless here because we have only one window which is // always the active one, but don't forget it if you use multiple windows window.SetActive(); // Clear color and depth buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Apply some transformations glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0.f, 0.f, -200.f); glRotatef(clock.GetElapsedTime() * 50, 1.f, 0.f, 0.f); glRotatef(clock.GetElapsedTime() * 30, 0.f, 1.f, 0.f); glRotatef(clock.GetElapsedTime() * 90, 0.f, 0.f, 1.f); // Draw a cube glBegin(GL_QUADS); glColor3f(1.f, 0.f, 0.f); glVertex3f(-50.f, -50.f, -50.f); glVertex3f(-50.f, 50.f, -50.f); glVertex3f( 50.f, 50.f, -50.f); glVertex3f( 50.f, -50.f, -50.f); glColor3f(1.f, 0.f, 0.f); glVertex3f(-50.f, -50.f, 50.f); glVertex3f(-50.f, 50.f, 50.f); glVertex3f( 50.f, 50.f, 50.f); glVertex3f( 50.f, -50.f, 50.f); glColor3f(0.f, 1.f, 0.f); glVertex3f(-50.f, -50.f, -50.f); glVertex3f(-50.f, 50.f, -50.f); glVertex3f(-50.f, 50.f, 50.f); glVertex3f(-50.f, -50.f, 50.f); glColor3f(0.f, 1.f, 0.f); glVertex3f(50.f, -50.f, -50.f); glVertex3f(50.f, 50.f, -50.f); glVertex3f(50.f, 50.f, 50.f); glVertex3f(50.f, -50.f, 50.f); glColor3f(0.f, 0.f, 1.f); glVertex3f(-50.f, -50.f, 50.f); glVertex3f(-50.f, -50.f, -50.f); glVertex3f( 50.f, -50.f, -50.f); glVertex3f( 50.f, -50.f, 50.f); glColor3f(0.f, 0.f, 1.f); glVertex3f(-50.f, 50.f, 50.f); glVertex3f(-50.f, 50.f, -50.f); glVertex3f( 50.f, 50.f, -50.f); glVertex3f( 50.f, 50.f, 50.f); glEnd(); // Finally, display the rendered frame on screen window.Display(); } return EXIT_SUCCESS; }
void init(void) { static unsigned *explosionimage, *smokeimage; static int width, height, components; explode(); glGenTextures(2, texnames); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); /* * Load the explosion texture */ explosionimage = read_texture("../../data/explosion0.rgba", &width, &height, &components); if (explosionimage == NULL) { fprintf(stderr, "Error: Can't load image file \"../../data/explosion0.rgba\".\n"); exit(EXIT_FAILURE); } else printf("%d x %d image loaded\n", width, height); if (components != 2 && components != 4) printf("warning: texture should be an RGBA or LA image\n"); glBindTexture(GL_TEXTURE_2D, texnames[0]); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, components, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, explosionimage); /* * Load the smoke texture */ smokeimage = read_texture("../../data/smoke.la", &width, &height, &components); if (explosionimage == NULL) { fprintf(stderr, "Error: Can't load image file \"../../data/smoke.la\".\n"); exit(EXIT_FAILURE); } else printf("%d x %d image loaded\n", width, height); if (components != 2 && components != 4) printf("warning: texture should be an RGBA or LA image\n"); glBindTexture(GL_TEXTURE_2D, texnames[1]); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, components, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, smokeimage); glEnable(GL_TEXTURE_2D); /* * Setup other OpenGL stuff */ glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(50., 1., .1, 20.); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0., 0., -5.5); glClearColor(.25f, .25f, .75f, .25f); glAlphaFunc(GL_GREATER, 0.016f); glEnable(GL_ALPHA_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_DEPTH_TEST); glEnable(GL_LIGHT0); glEnable(GL_COLOR_MATERIAL); glEnable(GL_NORMALIZE); }
int main(int argc, char *argv[]) { SDL_Event event; double cam[3] = {240,240,240}; SDL_Init(SDL_INIT_VIDEO); atexit(SDL_Quit); SDL_WM_SetCaption("BOIDS", NULL); SDL_SetVideoMode(1200, 900, 32, SDL_OPENGL); //SDL_EnableKeyRepeat(10,10); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); gluPerspective(70,(double)1200/900,1,1000); glEnable(GL_DEPTH_TEST); Boids test(220,220,220, NOMBRE_BOIDS); Dessiner(test,cam); lastTime = SDL_GetTicks(); for (;;) { SDL_PollEvent(&event); int startTime = SDL_GetTicks(); switch(event.type) { case SDL_QUIT: exit(0); break; case SDL_KEYDOWN: switch (event.key.keysym.sym) { case SDLK_q: cam[0] += 5; break; case SDLK_a: cam[0] -= 5; break; case SDLK_w: cam[1] += 5; break; case SDLK_s: cam[1] -= 5; break; case SDLK_e: cam[2] += 5; break; case SDLK_d: cam[2] -= 5; break; case SDLK_SPACE: pause = !pause; break; case SDLK_BACKSPACE: test.xa = 0; test.ya = 0; test.za = 0; break; case SDLK_DELETE: test.genereArrive(); break; case SDLK_PLUS: if(intervalle>1) intervalle--; break; case SDLK_MINUS: intervalle++; break; case SDLK_UP: cam[0]--; break; case SDLK_DOWN: cam[0]++; break; case SDLK_LEFT: if ((event.key.keysym.mod & KMOD_LSHIFT) == KMOD_LSHIFT) { cam[0]+=0.1; } else { cam[0]+=10; } break; case SDLK_RIGHT: if ((event.key.keysym.mod & KMOD_LSHIFT) == KMOD_LSHIFT) { cam[0]-=0.1; } else { cam[0]-=10; } break; } break; } Dessiner(test, cam); int timeElapsed = SDL_GetTicks()-startTime; if(1000/nbImageSec>timeElapsed) SDL_Delay(1000/nbImageSec-timeElapsed);//*/ } return 0; }
void SetupCameraMatrix() { glLoadIdentity(); gluPerspective(gFOV, ((float)glutGet(GLUT_WINDOW_WIDTH))/((float)glutGet(GLUT_WINDOW_HEIGHT)), 1.0f, 10000.0f); gluLookAt(gEye.x, gEye.y, gEye.z, gEye.x + gDir.x, gEye.y + gDir.y, gEye.z + gDir.z, 0.0f, 1.0f, 0.0f); }
//inicjalizuj GL void init_gl(int &argc, char *argv[]) { glutInit(&argc, argv); // tryb rgba + przezroczystosc + bufor z + podwojne buforowanie glutInitDisplayMode(GLUT_RGB | GL_DOUBLE | GLUT_DEPTH); // ustaw okno glutInitWindowSize(screenw, screenh); glutInitWindowPosition(0, 0); window = glutCreateWindow("Apollo"); glClearColor(0.0, 0.0, 10.0*b_atm, 0.0); glClearDepth(1.0); // tryb cieniowania glShadeModel(GL_SMOOTH); // korekcja perspektywiczna glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST); // wlacz testowanie z glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); //obcinaj tylne sciany poligonow glCullFace(GL_BACK); // ustaw widok // projekcja glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(fov, (double)screenw / (double)screenh, 0.1, 100000.0); // widok glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // ustaw parametry swiatla glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient); glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse); glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular); glLightfv(GL_LIGHT0, GL_POSITION, light_position); glEnable(GL_LIGHT0); // tryb tekstury glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); // zastap kolor tekstura a nie zmiksuj // wczytaj tekstury //texture_moon = load_texture("moon.bmp"); //wczytaj modele if(!SetCurrentDirectory("data")) { MessageBox(NULL, "Nie znaleziono katalogu!", "B³¹d", MB_OK); exit(-1); } stack_model.load("lander.obj"); aps_model.load("lander2.obj"); SetCurrentDirectory(".."); // wyczysc stany klawiszy for(int i = 0; i < 256; ++i) keys[i] = false; // ignoruj automatyczne powtarzanie klawiszy glutIgnoreKeyRepeat(1); // wlacz przenikanie glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //okragle punkty glEnable(GL_POINT_SMOOTH); glPointSize(10.0); }
bool Visualization::update() { if (!m_initialized) { printf("Visualization has not been yet initialized."); return false; } // Compute the time since last update (in seconds). Uint32 time = SDL_GetTicks(); float dt = (time - m_lastTickCount) / 1000.0f; m_lastTickCount = time; bool singleSimulationStep = false; bool scrollForward = false; bool scrollBackward = false; int mscroll = 0; SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: // Handle any key presses here. if (event.key.keysym.sym == SDLK_ESCAPE) //Escape. { m_stopRequested = true; } else if (event.key.keysym.sym == SDLK_SPACE) { m_paused = !m_paused; } else if (event.key.keysym.sym == SDLK_TAB) { singleSimulationStep = true; } else if (event.key.keysym.sym == SDLK_r) { float pos[3] = {-15, 0, 15}; m_crowd->pushAgentPosition(0, pos); } else if (event.key.keysym.sym == SDLK_KP7) { float pos[3] = {-19, 0, -19}; dtVnormalize(pos); dtVscale(pos, pos, 2.f); dtCrowdAgent ag; m_crowd->fetchAgent(ag, 0); dtVcopy(ag.velocity, pos); m_crowd->pushAgent(ag); } else if (event.key.keysym.sym == SDLK_KP9) { float pos[] = {19, 0, -19}; dtVnormalize(pos); dtVscale(pos, pos, 2.f); dtCrowdAgent ag; m_crowd->fetchAgent(ag, 0); dtVcopy(ag.velocity, pos); m_crowd->pushAgent(ag); } else if (event.key.keysym.sym == SDLK_KP3) { float pos[3] = {19, 0, 19}; dtVnormalize(pos); dtVscale(pos, pos, 2.f); dtCrowdAgent ag; m_crowd->fetchAgent(ag, 0); dtVcopy(ag.velocity, pos); m_crowd->pushAgent(ag); } else if (event.key.keysym.sym == SDLK_KP1) { float pos[3] = {-19, 0, 19}; dtVnormalize(pos); dtVscale(pos, pos, 2.f); dtCrowdAgent ag; m_crowd->fetchAgent(ag, 0); dtVcopy(ag.velocity, pos); m_crowd->pushAgent(ag); } else if (event.key.keysym.sym == SDLK_KP5) { float pos[3] = {0, 0, 0}; dtVnormalize(pos); dtVscale(pos, pos, 2.f); dtCrowdAgent ag; m_crowd->fetchAgent(ag, 0); dtVcopy(ag.velocity, pos); m_crowd->pushAgent(ag); } break; case SDL_MOUSEBUTTONDOWN: if (event.button.button == SDL_BUTTON_RIGHT) { // Rotate view m_rotating = true; m_initialMousePosition[0] = m_mousePosition[0]; m_initialMousePosition[1] = m_mousePosition[1]; m_intialCameraOrientation[0] = m_cameraOrientation[0]; m_intialCameraOrientation[1] = m_cameraOrientation[1]; m_intialCameraOrientation[2] = m_cameraOrientation[2]; } else if (event.button.button == SDL_BUTTON_WHEELUP) { scrollForward = true; } else if (event.button.button == SDL_BUTTON_WHEELDOWN) { scrollBackward = true; } break; case SDL_MOUSEBUTTONUP: if (event.button.button == SDL_BUTTON_RIGHT) { m_rotating = false; } else if (event.button.button == SDL_BUTTON_LEFT) { float pickedPosition[3]; int index = 0; pick(pickedPosition, &index); } break; case SDL_MOUSEMOTION: m_mousePosition[0] = event.motion.x; m_mousePosition[1] = m_winHeight-1 - event.motion.y; if (m_rotating) { int dx = m_mousePosition[0] - m_initialMousePosition[0]; int dy = m_mousePosition[1] - m_initialMousePosition[1]; m_cameraOrientation[0] = m_intialCameraOrientation[0] - dy*0.25f; m_cameraOrientation[1] = m_intialCameraOrientation[1] + dx*0.25f; } break; case SDL_QUIT: m_stopRequested = true; break; default: break; } } unsigned char mbut = 0; if (SDL_GetMouseState(0,0) & SDL_BUTTON_LMASK) mbut |= IMGUI_MBUT_LEFT; if (SDL_GetMouseState(0,0) & SDL_BUTTON_RMASK) mbut |= IMGUI_MBUT_RIGHT; // Update the camera velocity from keyboard state. Uint8* keystate = SDL_GetKeyState(NULL); #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4800) #endif updateCameraVelocity( dt, keystate[SDLK_w] || keystate[SDLK_UP] || scrollForward, keystate[SDLK_s] || keystate[SDLK_DOWN] || scrollBackward, keystate[SDLK_a] || keystate[SDLK_LEFT], keystate[SDLK_d] || keystate[SDLK_RIGHT], SDL_GetModState() & KMOD_SHIFT); #ifdef _MSC_VER #pragma warning(pop) #endif //Update the camera position updateCameraPosition(dt); //Update the crowd if (m_crowd) { if (singleSimulationStep) { m_paused = true; m_debugInfo->startUpdate(); m_crowd->update(m_crowdDt); m_debugInfo->endUpdate(m_crowdDt); m_crowdAvailableDt = 0.f; } else if (!m_paused) { m_crowdAvailableDt += dt; while(m_crowdAvailableDt > m_crowdDt) { m_debugInfo->startUpdate(); m_crowd->update(m_crowdDt); m_debugInfo->endUpdate(m_crowdDt); m_crowdAvailableDt -= m_crowdDt; } } else { m_crowdAvailableDt = 0.f; } } // Set rendering context glViewport(0, 0, m_winWidth, m_winHeight); glClearColor(0.3f, 0.3f, 0.32f, 1.0f); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_TEXTURE_2D); // Render 3D glEnable(GL_DEPTH_TEST); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(50.0f, (float)m_winWidth/(float)m_winHeight, m_zNear, m_zFar); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glRotatef(m_cameraOrientation[0],1,0,0); glRotatef(m_cameraOrientation[1],0,1,0); glRotatef(m_cameraOrientation[2],0,0,1); glTranslatef(-m_cameraPosition[0], -m_cameraPosition[1], -m_cameraPosition[2]); // Extract OpenGL view properties glGetDoublev(GL_PROJECTION_MATRIX, m_projection); glGetDoublev(GL_MODELVIEW_MATRIX, m_modelView); glGetIntegerv(GL_VIEWPORT, m_viewport); renderScene(); renderCrowd(); // Render 2D Overlay glDisable(GL_DEPTH_TEST); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0, m_winWidth, 0, m_winHeight); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); imguiBeginFrame(m_mousePosition[0], m_mousePosition[1], mbut,mscroll); renderDebugInfoOverlay(); imguiEndFrame(); imguiRenderGLDraw(); glEnable(GL_DEPTH_TEST); SDL_GL_SwapBuffers(); return true; }