int main(int argc, char **argv) { static_assert(std::is_pod<FVector3>::value, "FVector must be a POD!"); static_assert(std::is_pod<Oscillator>::value, "Oscillator must be a POD!"); // initialize GLUT glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH); glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT); glutCreateWindow("Fountain"); // textures std::unique_ptr<Texture> pebbleTexture(new Texture); std::unique_ptr<Texture> basinTexture(new Texture); std::unique_ptr<Texture> groundTexture(new Texture); std::unique_ptr<Texture[]> skyTextures(new Texture[SKY_BOX_FACES]); pebbleTexture->load("resource/pebbles.bmp"); basinTexture->load("resource/wall.bmp"); groundTexture->load("resource/grass.bmp"); skyTextures[SKY_FRONT].load("resource/skybox/front.bmp", GL_CLAMP_TO_EDGE); skyTextures[SKY_RIGHT].load("resource/skybox/right.bmp", GL_CLAMP_TO_EDGE); skyTextures[SKY_LEFT].load("resource/skybox/left.bmp", GL_CLAMP_TO_EDGE); skyTextures[SKY_BACK].load("resource/skybox/back.bmp", GL_CLAMP_TO_EDGE); skyTextures[SKY_UP].load("resource/skybox/up.bmp", GL_CLAMP_TO_EDGE); skyTextures[SKY_DOWN].load("resource/skybox/down.bmp", GL_CLAMP_TO_EDGE); // initialize the scene skybox.initialize(-SKY_BOX_SIZE, SKY_BOX_SIZE, -SKY_BOX_SIZE, SKY_BOX_SIZE, -SKY_BOX_SIZE, SKY_BOX_SIZE, std::move(skyTextures)); pool.initialize(OSCILLATORS_NUM_X, OSCILLATORS_NUM_Z, POOL_HEIGHT, OSCILLATOR_DISTANCE, OSCILLATOR_WEIGHT, OSCILLATOR_DAMPING, OSCILLATOR_SPLASH, POOL_TEX_REPEAT_X, POOL_TEX_REPEAT_Z, std::move(pebbleTexture)); fountain.initialize(initializers[0]); basin.initialize(BASIN_BORDER_HEIGHT + POOL_HEIGHT, BASIN_BORDER_WIDTH, BASIN_INNER_X, BASIN_INNER_Z, std::move(basinTexture)); ground.initialize(-GROUND_SIZE, GROUND_SIZE, -GROUND_SIZE, GROUND_SIZE, std::move(groundTexture), GROUND_TEX_REPEAT); // place the fountain in the center of the pool fountain.center.set(BASIN_INNER_X / 2.0f, POOL_HEIGHT, BASIN_INNER_Z / 2.0f); // initialize camera: FVector3 cposition, crotation; cposition.set(CAMERA_POSITION[0], CAMERA_POSITION[1], CAMERA_POSITION[2]); camera.move(cposition); crotation.set(CAMERA_ROTATION[0], CAMERA_ROTATION[1], CAMERA_ROTATION[2]); camera.rotate(crotation); // enable vertex array glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); // solid rendering glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_DEPTH_TEST); // lighting glLightfv(GL_LIGHT1, GL_AMBIENT, LIGHT_AMBIENT_1); glLightfv(GL_LIGHT1, GL_DIFFUSE, LIGHT_DIFFUSE_1); glLightfv(GL_LIGHT1, GL_POSITION, LIGHT_POSITION_1); glEnable(GL_LIGHT1); glLightfv(GL_LIGHT2, GL_AMBIENT, LIGHT_AMBIENT_2); glLightfv(GL_LIGHT2, GL_DIFFUSE, LIGHT_DIFFUSE_2); glLightfv(GL_LIGHT2, GL_POSITION, LIGHT_POSITION_2); glEnable(GL_LIGHT2); glEnable(GL_LIGHTING); glEnable(GL_COLOR_MATERIAL); // settings glClearColor(0.0, 0.0, 0.0, 0.0); glFrontFace(GL_CCW); // orientation should be the front face glShadeModel(GL_SMOOTH); // blending glEnable(GL_BLEND); glEnable(GL_POINT_SMOOTH); glEnable(GL_POLYGON_SMOOTH); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // seed srand((unsigned)time(NULL)); printf("1 - 8:\tChange the shape of the fountain\n"); printf("f:\tToggle fullscreen\n"); printf("c:\tSwitch between mouse mode / keyboard mode\n"); printf("----------- Keyboard Mode -----------------\n"); printf("up, down:\tMove camera forward / backword\n"); printf("left, right:\tTurn camera right / left\n"); printf("r, v:\tTurn camera up / down\n"); printf("w, s:\tMove camera up / down\n"); printf("a, d:\tMove camera left / right\n"); printf("----------- Mouse Mode -----------------\n"); printf("Mouse move:\tRotate camera\n"); printf("Mouse scroll:\tMove forward / backward\n"); printf("ESC:\tExit\n"); // register callbacks glutDisplayFunc(display); glutReshapeFunc(reshape); glutKeyboardFunc(keyDown); glutPassiveMotionFunc(mouseMove); glutSpecialFunc(spKeyDown); glutMouseFunc(mouseButton); glutIdleFunc(idle); // hide cursor glutSetCursor(GLUT_CURSOR_NONE); // start glutMainLoop(); return 0; }
int main(int argc, char* argv[]) { //----------------------------------------------------------------------- // INITIALIZATION //----------------------------------------------------------------------- printf ("\n"); printf ("-----------------------------------\n"); printf ("CHAI 3D\n"); printf ("Demo: 21-object\n"); printf ("Copyright 2003-2010\n"); printf ("-----------------------------------\n"); printf ("\n\n"); printf ("Keyboard Options:\n\n"); printf ("[1] - Texture (ON/OFF)\n"); printf ("[2] - Wireframe (ON/OFF)\n"); printf ("[3] - Collision tree (ON/OFF)\n"); printf ("[+] - Increase collision tree tisplay depth\n"); printf ("[-] - Decrease collision tree tisplay depth\n"); printf ("[x] - Exit application\n"); printf ("\n\n"); // parse first arg to try and locate resources resourceRoot = string(argv[0]).substr(0,string(argv[0]).find_last_of("/\\")+1); //----------------------------------------------------------------------- // 3D - SCENEGRAPH //----------------------------------------------------------------------- // create a new world. world = new cWorld(); // set the background color of the environment // the color is defined by its (R,G,B) components. world->setBackgroundColor(0.0, 0.0, 0.0); // create a camera and insert it into the virtual world camera = new cCamera(world); world->addChild(camera); // position and oriente the camera camera->set( cVector3d (3.0, 0.0, 0.0), // camera position (eye) cVector3d (0.0, 0.0, 0.0), // lookat position (target) cVector3d (0.0, 0.0, 1.0)); // direction of the "up" vector // set the near and far clipping planes of the camera // anything in front/behind these clipping planes will not be rendered camera->setClippingPlanes(0.01, 10.0); // create a light source and attach it to the camera light = new cLight(world); camera->addChild(light); // attach light to camera light->setEnabled(true); // enable light source light->setPos(cVector3d( 2.0, 0.5, 1.0)); // position the light source light->setDir(cVector3d(-2.0, 0.5, 1.0)); // define the direction of the light beam //----------------------------------------------------------------------- // 2D - WIDGETS //----------------------------------------------------------------------- // create a 2D bitmap logo logo = new cBitmap(); // add logo to the front plane camera->m_front_2Dscene.addChild(logo); // load a "chai3d" bitmap image file bool fileload; fileload = logo->m_image.loadFromFile(RESOURCE_PATH("resources/images/chai3d.bmp")); if (!fileload) { #if defined(_MSVC) fileload = logo->m_image.loadFromFile("../../../bin/resources/images/chai3d.bmp"); #endif } // position the logo at the bottom left of the screen (pixel coordinates) logo->setPos(10, 10, 0); // scale the logo along its horizontal and vertical axis logo->setZoomHV(0.4, 0.4); // here we replace all black pixels (0,0,0) of the logo bitmap // with transparent black pixels (0, 0, 0, 0). This allows us to make // the background of the logo look transparent. logo->m_image.replace( cColorb(0, 0, 0), // original RGB color cColorb(0, 0, 0, 0) // new RGBA color ); // enable transparency logo->enableTransparency(true); //----------------------------------------------------------------------- // HAPTIC DEVICES / TOOLS //----------------------------------------------------------------------- // create a haptic device handler handler = new cHapticDeviceHandler(); // get access to the first available haptic device cGenericHapticDevice* hapticDevice; handler->getDevice(hapticDevice, 0); // retrieve information about the current haptic device cHapticDeviceInfo info; if (hapticDevice) { info = hapticDevice->getSpecifications(); } // create a 3D tool and add it to the world tool = new cGeneric3dofPointer(world); world->addChild(tool); // connect the haptic device to the tool tool->setHapticDevice(hapticDevice); // initialize tool by connecting to haptic device tool->start(); // map the physical workspace of the haptic device to a larger virtual workspace. tool->setWorkspaceRadius(1.0); // define a radius for the tool tool->setRadius(0.01); // hide the device sphere. only show proxy. tool->m_deviceSphere->setShowEnabled(false); // set the physical radius of the proxy. for performance reasons, it is // sometimes useful to set this value to zero when dealing with // complex objects. proxyRadius = 0.01; tool->m_proxyPointForceModel->setProxyRadius(proxyRadius); // inform the proxy algorithm to only check front sides of triangles tool->m_proxyPointForceModel->m_collisionSettings.m_checkBothSidesOfTriangles = false; // enable if objects in the scene are going to rotate of translate // or possibly collide against the tool. If the environment // is entirely static, you can set this parameter to "false" tool->m_proxyPointForceModel->m_useDynamicProxy = true; // read the scale factor between the physical workspace of the haptic // device and the virtual workspace defined for the tool double workspaceScaleFactor = tool->getWorkspaceScaleFactor(); // define a maximum stiffness that can be handled by the current // haptic device. The value is scaled to take into account the // workspace scale factor double stiffnessMax = info.m_maxForceStiffness / workspaceScaleFactor; //----------------------------------------------------------------------- // COMPOSE THE VIRTUAL SCENE //----------------------------------------------------------------------- // create a virtual mesh object = new cMesh(world); // add object to world world->addChild(object); // set the position of the object at the center of the world object->setPos(0.0, 0.0, 0.0); // load an object file fileload = object->loadFromFile(RESOURCE_PATH("resources/models/camera/camera.3ds")); if (!fileload) { #if defined(_MSVC) fileload = object->loadFromFile("../../../bin/resources/models/camera/camera.3ds"); #endif } if (!fileload) { printf("Error - 3D Model failed to load correctly.\n"); close(); return (-1); } // compute a boundary box object->computeBoundaryBox(true); // get dimensions of object double size = cSub(object->getBoundaryMax(), object->getBoundaryMin()).length(); // resize object to screen if (size > 0) { object->scale( 2.0 * tool->getWorkspaceRadius() / size); } // compute collision detection algorithm object->createAABBCollisionDetector(1.01 * proxyRadius, true, false); // define a default stiffness for the object object->setStiffness(stiffnessMax, true); // define some haptic friction properties object->setFriction(0.1, 0.2, true); //----------------------------------------------------------------------- // OPEN GL - WINDOW DISPLAY //----------------------------------------------------------------------- // initialize GLUT glutInit(&argc, argv); // retrieve the resolution of the computer display and estimate the position // of the GLUT window so that it is located at the center of the screen int screenW = glutGet(GLUT_SCREEN_WIDTH); int screenH = glutGet(GLUT_SCREEN_HEIGHT); int windowPosX = (screenW - WINDOW_SIZE_W) / 2; int windowPosY = (screenH - WINDOW_SIZE_H) / 2; // initialize the OpenGL GLUT window glutInitWindowPosition(windowPosX, windowPosY); glutInitWindowSize(WINDOW_SIZE_W, WINDOW_SIZE_H); glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE); glutCreateWindow(argv[0]); glutDisplayFunc(updateGraphics); glutKeyboardFunc(keySelect); glutReshapeFunc(resizeWindow); glutSetWindowTitle("CHAI 3D"); // create a mouse menu (right button) glutCreateMenu(menuSelect); glutAddMenuEntry("full screen", OPTION_FULLSCREEN); glutAddMenuEntry("window display", OPTION_WINDOWDISPLAY); glutAttachMenu(GLUT_RIGHT_BUTTON); //----------------------------------------------------------------------- // START SIMULATION //----------------------------------------------------------------------- // simulation in now running simulationRunning = true; // create a thread which starts the main haptics rendering loop cThread* hapticsThread = new cThread(); hapticsThread->set(updateHaptics, CHAI_THREAD_PRIORITY_HAPTICS); // start the main graphics rendering loop glutMainLoop(); // close everything close(); // exit return (0); }
int ProgramManager::Run(int argc, char **argv) { DoSomeTests(); int x, y; glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT); int window_id = glutCreateWindow(PROGRAM_NAME); glEnable(GL_TEXTURE_2D); // Enable Texture Mapping ( NEW ) glDisable(GL_BLEND); //just killing to be sure //glBlendFunc (GL_SRC_ALPHA, GL_DST_ALPHA); glShadeModel(GL_SMOOTH); // Enable Smooth Shading glClearDepth(1.0f); // Depth Buffer Setup glEnable(GL_DEPTH_TEST); // Enables Depth Testing glDepthFunc(GL_LESS); // The Type Of Depth Testing To Do glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice Perspective Calculations //glEnable(GL_CULL_FACE); //glCullFace(GL_BACK); //glFrontFace(GL_CCW); glEnable(GL_NORMALIZE); //set up key state tracking glutIgnoreKeyRepeat(true); GLUI_Master.set_glutKeyboardFunc(ProgramManager::KeyboardDown); glutKeyboardUpFunc(ProgramManager::KeyboardUp); GLUI_Master.set_glutSpecialFunc(ProgramManager::SpecialFunc); GLUI_Master.set_glutMouseFunc( ProgramManager::mousebutton ); GLUI_Master.set_glutReshapeFunc( ProgramManager::reshape ); glutMotionFunc(ProgramManager::mousemove); glutDisplayFunc(ProgramManager::display); GLUI *glui = GLUI_Master.create_glui_subwindow(window_id, GLUI_SUBWINDOW_RIGHT); glui->set_main_gfx_window(window_id); GLUI_Master.set_glutIdleFunc(ProgramManager::tick); m_gui.Initialize(window_id, glui); GLUI_Master.get_viewport_area(&x, &y, &width, &height); m_gui.SetViewportSize(width, height); //char sdf[100]; //sprintf_s(sdf, "width: %d", WINDOW_WIDTH - width); //UserPromptUtil::UserMessageBox(sdf, "ARAR"); m_gui.SetDefaults(); glutMainLoop(); return 0; }
int main(int argc, char **argv) { GLenum type; GLuint arg_mode = Args(argc, argv); if (arg_mode & QUIT) exit(0); read_surface( "isosurf.dat" ); glutInitWindowSize(400, 400); glutInit( &argc, argv); type = GLUT_DEPTH; type |= GLUT_RGB; type |= (doubleBuffer) ? GLUT_DOUBLE : GLUT_SINGLE; glutInitDisplayMode(type); if (glutCreateWindow("Isosurface") <= 0) { exit(0); } glewInit(); /* Make sure server supports the vertex array extension */ if (!GLEW_EXT_vertex_array) { printf("Vertex arrays not supported by this renderer\n"); allowed &= ~(LOCKED|DRAW_ARRAYS|DRAW_ELTS|ARRAY_ELT); } else if (!GLEW_EXT_compiled_vertex_array) { printf("Compiled vertex arrays not supported by this renderer\n"); allowed &= ~LOCKED; } Init(argc, argv); ModeMenu(arg_mode); glutCreateMenu(ModeMenu); glutAddMenuEntry("GL info", GLINFO); glutAddMenuEntry("", 0); glutAddMenuEntry("Lit", LIT); glutAddMenuEntry("Unlit", UNLIT); glutAddMenuEntry("Reflect", REFLECT); glutAddMenuEntry("", 0); glutAddMenuEntry("Smooth", SHADE_SMOOTH); glutAddMenuEntry("Flat", SHADE_FLAT); glutAddMenuEntry("", 0); glutAddMenuEntry("Fog", FOG); glutAddMenuEntry("No Fog", NO_FOG); glutAddMenuEntry("", 0); glutAddMenuEntry("Stipple", STIPPLE); glutAddMenuEntry("No Stipple", NO_STIPPLE); glutAddMenuEntry("", 0); glutAddMenuEntry("Polygon Mode Fill", POLYGON_FILL); glutAddMenuEntry("Polygon Mode Line", POLYGON_LINE); glutAddMenuEntry("Polygon Mode Points", POLYGON_POINT); glutAddMenuEntry("", 0); glutAddMenuEntry("Point Filtered", POINT_FILTER); glutAddMenuEntry("Linear Filtered", LINEAR_FILTER); glutAddMenuEntry("", 0); glutAddMenuEntry("GL_TRIANGLES", TRIANGLES); glutAddMenuEntry("GL_TRIANGLE_STRIPS", STRIPS); glutAddMenuEntry("GL_POINTS", POINTS); glutAddMenuEntry("", 0); glutAddMenuEntry("Displaylist", DISPLAYLIST); glutAddMenuEntry("Immediate", IMMEDIATE); glutAddMenuEntry("", 0); if (allowed & LOCKED) { glutAddMenuEntry("Locked Arrays (CVA)", LOCKED); glutAddMenuEntry("Unlocked Arrays", UNLOCKED); glutAddMenuEntry("", 0); } glutAddMenuEntry("glVertex", GLVERTEX); if (allowed & DRAW_ARRAYS) { glutAddMenuEntry("glDrawElements", DRAW_ELTS); glutAddMenuEntry("glDrawArrays", DRAW_ARRAYS); glutAddMenuEntry("glArrayElement", ARRAY_ELT); } glutAddMenuEntry("", 0); glutAddMenuEntry("Quit", QUIT); glutAttachMenu(GLUT_RIGHT_BUTTON); glutReshapeFunc(Reshape); glutKeyboardFunc(Key); glutSpecialFunc(SpecialKey); glutDisplayFunc(Display); glutMainLoop(); return 0; }
void main(int argc, char **argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(500, 500); glutCreateWindow("wave"); if(argc > 1 && argv[1] != 0) TexFilename1 = argv[1]; if(argc > 2 && argv[2] != 0) TexFilename2 = argv[2]; glEnable (GL_DEPTH_TEST); glDepthFunc (GL_LEQUAL); glClearColor (0.0, 0.0, 0.0, 0.0); glPolygonOffset (1.0, 1.0); glEnable (GL_CULL_FACE); glHint (GL_LINE_SMOOTH_HINT, GL_NICEST); glHint (GL_POLYGON_SMOOTH_HINT, GL_NICEST); glHint (GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); glEnable (GL_COLOR_MATERIAL); glColorMaterial (GL_FRONT, GL_DIFFUSE); glLightfv (GL_LIGHT0, GL_POSITION, lightPosition); glEnable (GL_LIGHT0); loadImageTexture(); setSize (MEDIUM); setSpeed (NORMAL); setDisplay(FLATSHADED); setOther (ENVMAP); reset (HILLFOUR); glutReshapeFunc(reshape); glutDisplayFunc(display); glutVisibilityFunc(visibility); glutKeyboardFunc(keyboard); glutMouseFunc (mouse); glutMotionFunc (motion); displayMenu = glutCreateMenu(setDisplay); glutAddMenuEntry("Wireframe", WIREFRAME); glutAddMenuEntry("Hidden Line", HIDDENLINE); glutAddMenuEntry("Flat Shaded", FLATSHADED); glutAddMenuEntry("Smooth Shaded", SMOOTHSHADED); glutAddMenuEntry("Textured", TEXTURED); otherMenu = glutCreateMenu(setOther); glutAddMenuEntry("Full Screen", FULLSCREEN); glutAddMenuEntry("Face Normals", FACENORMALS); glutAddMenuEntry("Antialias", ANTIALIAS); glutAddMenuEntry("Environment Map", ENVMAP); speedMenu = glutCreateMenu(setSpeed); glutAddMenuEntry("Weak", WEAK); glutAddMenuEntry("Normal", NORMAL); glutAddMenuEntry("Strong", STRONG); sizeMenu = glutCreateMenu(setSize); glutAddMenuEntry("Small", SMALL); glutAddMenuEntry("Medium", MEDIUM); glutAddMenuEntry("Large", LARGE); glutAddMenuEntry("Extra Large", XLARGE); resetMenu = glutCreateMenu(reset); glutAddMenuEntry("Current", CURRENT); glutAddMenuEntry("Spike", SPIKE); glutAddMenuEntry("Hole", HOLE); glutAddMenuEntry("Diagonal Wall", DIAGONALWALL); glutAddMenuEntry("Side Wall", SIDEWALL); glutAddMenuEntry("Middle Block", MIDDLEBLOCK); glutAddMenuEntry("Diagonal Block",DIAGONALBLOCK); glutAddMenuEntry("Corner Block", CORNERBLOCK); glutAddMenuEntry("Hill", HILL); glutAddMenuEntry("Hill Four", HILLFOUR); mainMenu = glutCreateMenu(setMain); glutAddMenuEntry("Go", 2); glutAddMenuEntry("Stop", 3); glutAddMenuEntry("Reverse", 4); glutAddSubMenu("Display", displayMenu); glutAddSubMenu("Reset", resetMenu); glutAddSubMenu("Size", sizeMenu); glutAddSubMenu("Speed", speedMenu); glutAddSubMenu("Other", otherMenu); glutAddMenuEntry("Exit", 5); glutAttachMenu(GLUT_RIGHT_BUTTON); glutMainLoop(); }
/***************************************************************************** Routine: VideoOutInit( char *name, int argc, char **argv, int width, int height, int displaywidth, int displayheight ) returns : void Description : Initializes the display process. Display process will there after call the necessary functions through callback functions to generate the output. *****************************************************************************/ void VideoOutInit( char *name, int argc, char *argv[], int width, int height, int displaywidth, int displayheight ) { int i, size; /* Initialize texture width to nearest power of 2 */ size = 1; while(size<width) size = (size << 1); texwidth = size; /* Initialize texture height to nearest power of 2 */ size = 1; while(size<height) size = (size << 1); texheight = size; relwidth = (float)width/(float)texwidth; relheight = (float)height/(float)texheight; rgba_buffer = (unsigned char *)malloc(texwidth*texheight*4); if(rgba_buffer != NULL) { memset(rgba_buffer, 0xFF, texwidth*texheight*4); // Gridlines if(gridOn) { // Horizontal gridlines for(int j=15; j<texheight; j+=16) { for(int i=0; i<texwidth; i++) rgba_buffer[(j*texwidth+i)*4+3] = 0x00; } // Vertical gridlines for(int i=15; i<texwidth; i+=16) { for(int j=0; j<texheight; j++) rgba_buffer[(j*texwidth+i)*4+3] = 0x00; } } } else { printf("\nAllocating Buffers failed! Not Enough Memory."); printf("\nExiting !!!"); exit(4); } nTime = 0; nLastTime = -frameinterval; /* Create Window */ glutInitWindowSize(displaywidth, displayheight); glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGBA|GLUT_DOUBLE); (void)glutCreateWindow(name); /* Map GLUT callback functions */ glutDisplayFunc(event_display); glutKeyboardFunc(event_key); glutSpecialFunc(event_specialkey); glutReshapeFunc(event_reshape); glutIdleFunc(event_animate); /* Run Callback Loop */ glutMainLoop(); }
// Main. int main(int argc, char* argv[]) { // Create a glut window glutInit(&argc, argv); #ifdef FREEGLUT glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION); #endif glutInitWindowSize( 640, 480 ); glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH ); int window_id = glutCreateWindow( "FeedbackBufferCollectorExample" ); glutSetWindow( window_id ); // set up GLUT callback functions glutDisplayFunc ( display ); glutReshapeFunc (reshape); glutIdleFunc( display ); // container to put the triangles in. vector< HAPI::Collision::Triangle > triangles; // start collecting OpenGL primitives HAPI::FeedbackBufferCollector::startCollecting(); // draw object draw(); // stop collecting and transfer the rendered // triangles to the triangles vector. HAPI::FeedbackBufferCollector::endCollecting( triangles ); // Get a connected device. hd.reset( new HAPI::AnyHapticsDevice() ); // The haptics renderer to use. hd->setHapticsRenderer( new HAPI::GodObjectRenderer() ); // Init the device. if( hd->initDevice() != HAPI::HAPIHapticsDevice::SUCCESS ) { cerr << hd->getLastErrorMsg() << endl; return 0; } // Enable the device hd->enableDevice(); // Create the haptic shape to be rendered. HAPI::Collision::AABBTree *the_tree = new HAPI::Collision::AABBTree( triangles ); HAPI::HAPISurfaceObject * my_surface = new HAPI::FrictionSurface(); HAPI::HapticTriangleTree *tree_shape = new HAPI::HapticTriangleTree( the_tree, my_surface, HAPI::Collision::FRONT ); // Transfer shape to the haptics loop. hd->addShape( tree_shape ); hd->transferObjects(); // Start gluts mainloop. glutMainLoop(); // This will only be called if freeglut is found and used. hd->disableDevice(); hd->releaseDevice(); }
int main(int argc, char* argv[]) { //----------------------------------------------------------------------- // INITIALIZATION //----------------------------------------------------------------------- printf ("\n"); printf ("-----------------------------------\n"); printf ("CHAI3D\n"); printf ("Demo: 43-ODE-tool\n"); printf ("Copyright 2003-2011\n"); printf ("-----------------------------------\n"); printf ("\n\n"); printf ("Instructions:\n\n"); printf ("- Use haptic device and user switch to manipulate cubes \n"); printf ("\n\n"); printf ("Keyboard Options:\n\n"); printf ("[h] - Display help menu\n");; printf ("[1] - Enable gravity\n"); printf ("[2] - Disable gravity\n"); printf ("\n"); printf ("[3] - decrease linear haptic gain\n"); printf ("[4] - increase linear haptic gain\n"); printf ("[5] - decrease angular haptic gain\n"); printf ("[6] - increase angular haptic gain\n"); printf ("\n"); printf ("[7] - decrease linear stiffness\n"); printf ("[8] - increase linear stiffness\n"); printf ("[9] - decrease angular stiffness\n"); printf ("[0] - increase angular stiffness\n"); printf ("\n"); printf ("[x] - Exit application\n"); printf ("\n\n"); // parse first arg to try and locate resources resourceRoot = string(argv[0]).substr(0,string(argv[0]).find_last_of("/\\")+1); //----------------------------------------------------------------------- // 3D - SCENEGRAPH //----------------------------------------------------------------------- // create a new world. world = new cWorld(); // set the background color of the environment // the color is defined by its (R,G,B) components. world->setBackgroundColor(0.0, 0.0, 0.0); // create a camera and insert it into the virtual world camera = new cCamera(world); world->addChild(camera); // position and oriente the camera camera->set( cVector3d (3.0, 0.0, 0.3), // camera position (eye) cVector3d (0.0, 0.0, 0.0), // lookat position (target) cVector3d (0.0, 0.0, 1.0)); // direction of the "up" vector // set the near and far clipping planes of the camera // anything in front/behind these clipping planes will not be rendered camera->setClippingPlanes(0.01, 10.0); camera->setUseShadowCasting(false); // create a light source and attach it to the camera light = new cSpotLight(world); camera->addChild(light); // attach light to camera light->setEnabled(true); // enable light source light->setLocalPos(cVector3d( 0.0, 0.5, 0.0)); // position the light source light->setDir(cVector3d(-3.0,-0.5, 0.0)); // define the direction of the light beam light->m_ambient.set(0.6, 0.6, 0.6); light->m_diffuse.set(0.8, 0.8, 0.8); light->m_specular.set(0.8, 0.8, 0.8); frame = new cGenericObject(); //world->addChild(frame); frame->setShowFrame(true); line = new cShapeLine(cVector3d(0,0,0), cVector3d(0,0,0)); //world->addChild(line); //----------------------------------------------------------------------- // 2D - WIDGETS //----------------------------------------------------------------------- // create a 2D bitmap logo logo = new cBitmap(); // add logo to the front plane camera->m_frontLayer->addChild(logo); // load a "chai3d" bitmap image file logo->setImage (NEW_CHAI3D_LOGO()); // position the logo at the bottom left of the screen (pixel coordinates) logo->setLocalPos(10, 10, 0); // scale the logo along its horizontal and vertical axis logo->setZoom(0.25, 0.25); // here we replace all black pixels (0,0,0) of the logo bitmap // with transparent black pixels (0, 0, 0, 0). This allows us to make // the background of the logo look transparent. logo->m_image->setTransparentColor(0x00, 0x00, 0x00, 0x00); // enable transparency logo->setUseTransparency(true); //----------------------------------------------------------------------- // HAPTIC DEVICES / TOOLS //----------------------------------------------------------------------- // create a haptic device handler handler = new cHapticDeviceHandler(); // get access to the first available haptic device handler->getDevice(hapticDevice, 0); // retrieve information about the current haptic device cHapticDeviceInfo info; if (hapticDevice) { info = hapticDevice->getSpecifications(); } // read the scale factor between the physical workspace of the haptic // device and the virtual workspace defined for the tool workspaceScaleFactor = 1.5 / info.m_workspaceRadius; //----------------------------------------------------------------------- // COMPOSE THE VIRTUAL SCENE //----------------------------------------------------------------------- // create an ODE world to simulate dynamic bodies ODEWorld = new cODEWorld(world); // add ODE world as a node inside world world->addChild(ODEWorld); // set some gravity ODEWorld->setGravity(cVector3d(0.0, 0.0, -9.81)); // create a new ODE object that is automatically added to the ODE world ODEBody0 = new cODEGenericBody(ODEWorld); ODEBody1 = new cODEGenericBody(ODEWorld); ODEBody2 = new cODEGenericBody(ODEWorld); // create a virtual mesh that will be used for the geometry // representation of the dynamic body cMesh* object0 = new cMesh(); cMesh* object1 = new cMesh(); cMesh* object2 = new cMesh(); // crate a cube mesh double boxSize = 0.4; createCube(object0, boxSize); createCube(object1, boxSize); createCube(object2, boxSize); // define some material properties for each cube cMaterial mat0, mat1, mat2; mat0.m_ambient.set(0.8, 0.1, 0.4); mat0.m_diffuse.set(1.0, 0.15, 0.5); mat0.m_specular.set(1.0, 0.2, 0.8); mat0.setDynamicFriction(0.8); mat0.setStaticFriction(0.8); object0->setMaterial(mat0); mat1.m_ambient.set(0.2, 0.6, 0.0); mat1.m_diffuse.set(0.2, 0.8, 0.0); mat1.m_specular.set(0.2, 1.0, 0.0); mat1.setDynamicFriction(0.8); mat1.setStaticFriction(0.8); object1->setMaterial(mat1); mat2.m_ambient.set(0.0, 0.2, 0.6); mat2.m_diffuse.set(0.0, 0.2, 0.8); mat2.m_specular.set(0.0, 0.2, 1.0); mat2.setDynamicFriction(0.8); mat2.setStaticFriction(0.8); object2->setMaterial(mat2); // add mesh to ODE object ODEBody0->setImageModel(object0); ODEBody1->setImageModel(object1); ODEBody2->setImageModel(object2); // create a dynamic model of the ODE object. Here we decide to use a box just like // the object mesh we just defined ODEBody0->createDynamicBox(boxSize, boxSize, boxSize); ODEBody1->createDynamicBox(boxSize, boxSize, boxSize, false, cVector3d(1,1,1)); ODEBody2->createDynamicBox(boxSize, boxSize, boxSize); // define some mass properties for each cube ODEBody0->setMass(0.05); ODEBody1->setMass(0.05); ODEBody2->setMass(0.05); // set position of each cube cVector3d tmpvct; tmpvct = cVector3d(0.0,-0.6, -0.5); ODEBody0->setPosition(tmpvct); tmpvct = cVector3d(0.0, 0.6, -0.5); ODEBody1->setPosition(tmpvct); tmpvct = cVector3d(0.0, 0.0, -0.5); ODEBody2->setPosition(tmpvct); // rotate central cube of 45 degrees (just to show hoe this works!) cMatrix3d rot; rot.identity(); rot.rotateAboutGlobalAxisRad(cVector3d(0,0,1), cDegToRad(45)); ODEBody0->setRotation(rot); // we create 6 static walls to contains the 3 cubes within a limited workspace ODEGPlane0 = new cODEGenericBody(ODEWorld); ODEGPlane1 = new cODEGenericBody(ODEWorld); ODEGPlane2 = new cODEGenericBody(ODEWorld); ODEGPlane3 = new cODEGenericBody(ODEWorld); ODEGPlane4 = new cODEGenericBody(ODEWorld); ODEGPlane5 = new cODEGenericBody(ODEWorld); double size = 1.0; ODEGPlane0->createStaticPlane(cVector3d(0.0, 0.0, 2.0 *size), cVector3d(0.0, 0.0 ,-1.0)); ODEGPlane1->createStaticPlane(cVector3d(0.0, 0.0, -size), cVector3d(0.0, 0.0 , 1.0)); ODEGPlane2->createStaticPlane(cVector3d(0.0, size, 0.0), cVector3d(0.0,-1.0, 0.0)); ODEGPlane3->createStaticPlane(cVector3d(0.0, -size, 0.0), cVector3d(0.0, 1.0, 0.0)); ODEGPlane4->createStaticPlane(cVector3d( size, 0.0, 0.0), cVector3d(-1.0,0.0, 0.0)); ODEGPlane5->createStaticPlane(cVector3d(-0.8 * size, 0.0, 0.0), cVector3d( 1.0,0.0, 0.0)); // create a virtual tool ODETool = new cODEGenericBody(ODEWorld); cMesh* objectTool = new cMesh(); createCube(objectTool, boxSize); // define some material properties for each cube cMaterial matTool; matTool.m_ambient.set(0.4, 0.4, 0.4); matTool.m_diffuse.set(0.8, 0.8, 0.8); matTool.m_specular.set(1.0, 1.0, 1.0); matTool.setDynamicFriction(0.8); matTool.setStaticFriction(0.8); objectTool->setMaterial(matTool); // add mesh to ODE object ODETool->setImageModel(objectTool); ODETool->createDynamicBox(boxSize, boxSize, boxSize); // define some mass properties for each cube ODETool->setMass(0.01); dBodySetAngularDamping(ODETool->m_ode_body, 0.04); dBodySetLinearDamping(ODETool->m_ode_body, 0.04); ////////////////////////////////////////////////////////////////////////// // Create some reflexion ////////////////////////////////////////////////////////////////////////// // we create an intermediate node to which we will attach // a copy of the object located inside the world cGenericObject* reflexion = new cGenericObject(); // set this object as a ghost node so that no haptic interactions or // collision detecting take place within the child nodes added to the // reflexion node. reflexion->setGhostEnabled(true); // add reflexion node to world world->addChild(reflexion); // turn off culling on each object (objects now get rendered on both sides) object0->setUseCulling(false, true); object1->setUseCulling(false, true); object2->setUseCulling(false, true); // create a symmetry rotation matrix (z-plane) cMatrix3d rotRefexion; rotRefexion.set(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, -1.0); reflexion->setLocalRot(rotRefexion); reflexion->setLocalPos(0.0, 0.0, -2.005); // add objects to the world reflexion->addChild(ODEWorld); ////////////////////////////////////////////////////////////////////////// // Create a Ground ////////////////////////////////////////////////////////////////////////// // create mesh to model ground surface cMesh* ground = new cMesh(); world->addChild(ground); // create 4 vertices (one at each corner) double groundSize = 2.0; int vertices0 = ground->newVertex(-groundSize, -groundSize, 0.0); int vertices1 = ground->newVertex( groundSize, -groundSize, 0.0); int vertices2 = ground->newVertex( groundSize, groundSize, 0.0); int vertices3 = ground->newVertex(-groundSize, groundSize, 0.0); // compose surface with 2 triangles ground->newTriangle(vertices0, vertices1, vertices2); ground->newTriangle(vertices0, vertices2, vertices3); // compute surface normals ground->computeAllNormals(); // position ground at the right level ground->setLocalPos(0.0, 0.0, -1.0); // define some material properties and apply to mesh cMaterial matGround; matGround.setDynamicFriction(0.7); matGround.setStaticFriction(1.0); matGround.m_ambient.set(0.0, 0.0, 0.0); matGround.m_diffuse.set(0.0, 0.0, 0.0); matGround.m_specular.set(0.0, 0.0, 0.0); ground->setMaterial(matGround); // enable and set transparency level of ground ground->setTransparencyLevel(0.7); ground->setUseTransparency(true); //----------------------------------------------------------------------- // OPEN GL - WINDOW DISPLAY //----------------------------------------------------------------------- // initialize GLUT glutInit(&argc, argv); // retrieve the resolution of the computer display and estimate the position // of the GLUT window so that it is located at the center of the screen int screenW = glutGet(GLUT_SCREEN_WIDTH); int screenH = glutGet(GLUT_SCREEN_HEIGHT); int windowPosX = (screenW - WINDOW_SIZE_W) / 2; int windowPosY = (screenH - WINDOW_SIZE_H) / 2; // initialize the OpenGL GLUT window glutInitWindowPosition(windowPosX, windowPosY); glutInitWindowSize(WINDOW_SIZE_W, WINDOW_SIZE_H); glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE); glutCreateWindow(argv[0]); glutDisplayFunc(updateGraphics); glutKeyboardFunc(keySelect); glutReshapeFunc(resizeWindow); glutSetWindowTitle("CHAI3D"); // create a mouse menu (right button) glutCreateMenu(menuSelect); glutAddMenuEntry("full screen", OPTION_FULLSCREEN); glutAddMenuEntry("window display", OPTION_WINDOWDISPLAY); glutAttachMenu(GLUT_RIGHT_BUTTON); //----------------------------------------------------------------------- // START SIMULATION //----------------------------------------------------------------------- // simulation in now running simulationRunning = true; // create a thread which starts the main haptics rendering loop cThread* hapticsThread = new cThread(); hapticsThread->start(updateHaptics, CTHREAD_PRIORITY_HAPTICS); // start the main graphics rendering loop glutTimerFunc(30, graphicsTimer, 0); glutMainLoop(); // close everything close(); // exit return (0); }
int main(int argc, char *argv[]) { // inicjalizacja biblioteki GLUT glutInit(&argc, argv); // inicjalizacja bufora ramki glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); // rozmiary głównego okna programu glutInitWindowSize(550, 550); // utworzenie głównego okna programu glutCreateWindow("Zadanie 1"); // dołączenie funkcji generującej scenę 3D glutDisplayFunc(DisplayScene); // dołączenie funkcji wywoływanej przy zmianie rozmiaru okna glutReshapeFunc(Reshape); // utworzenie podmenu - Tekstura int MenuTexture = glutCreateMenu(Menu); glutAddMenuEntry("white_skin_guy_black_hairs.tga (kompresja)", TEXTURE_LENA); glutAddMenuEntry("white_skin_guy_black_hairs.tga (bez kompresji)", TEXTURE_LENA_UNC); glutAddMenuEntry("white_skin_guy_black_hairs_gray.tga (kompresja)", TEXTURE_LENA_GRAY); glutAddMenuEntry("white_skin_guy_black_hairs_gray.tga (bez kompresji)", TEXTURE_LENA_GRAY_UNC); // utworzenie podmenu - GL_TEXTURE_COMPRESSION_HINT int MenuTextureCompressionHint = glutCreateMenu(Menu); glutAddMenuEntry("GL_FASTEST", TEXTURE_COMPRESSION_FASTEST); glutAddMenuEntry("GL_DONT_CARE", TEXTURE_COMPRESSION_DONT_CARE); glutAddMenuEntry("GL_NICEST", TEXTURE_COMPRESSION_NICEST); // utworzenie podmenu - Aspekt obrazu int MenuAspect = glutCreateMenu(Menu); #ifdef WIN32 glutAddMenuEntry("Aspekt obrazu - całe okno", FULL_WINDOW); #else glutAddMenuEntry("Aspekt obrazu - cale okno", FULL_WINDOW); #endif glutAddMenuEntry("Aspekt obrazu 1:1", ASPECT_1_1); // menu główne glutCreateMenu(Menu); glutAddSubMenu("Tekstura", MenuTexture); glutAddSubMenu("GL_TEXTURE_COMPRESSION_HINT", MenuTextureCompressionHint); glutAddSubMenu("Aspekt obrazu", MenuAspect); #ifdef WIN32 glutAddMenuEntry("Wyjście", EXIT); #else glutAddMenuEntry("Wyjscie", EXIT); #endif // określenie przycisku myszki obsługującego menu podręczne glutAttachMenu(GLUT_RIGHT_BUTTON); // utworzenie tekstur GenerateTextures(); // sprawdzenie i przygotowanie obsługi wybranych rozszerzeń ExtensionSetup(); // wprowadzenie programu do obsługi pętli komunikatów glutMainLoop(); return 0; }
void InitGraphics( ) { //init proj2 data for (int i = 0; i < NX; i++) { for (int j = 0; j < NY; j++) { for (int k = 0; k < NZ; k++) { Nodes[i][j][k].x = -1. + 2. * (float)i / (float)(NX - 1); Nodes[i][j][k].y = -1. + 2. * (float)j / (float)(NY - 1); Nodes[i][j][k].z = -1. + 2. * (float)k / (float)(NZ - 1); Nodes[i][j][k].t = Temperature(Nodes[i][j][k].x, Nodes[i][j][k].y, Nodes[i][j][k].z); } } } //init proj3 data for (int i = 0; i < NX; i++) { for (int j = 0; j < NY; j++) { for (int k = 0; k < NZ; k++) { float hsv[3], rgb[3]; hsv[0] = 240. - 240.*((Nodes[i][j][k].t - TEMPMIN) / (TEMPMAX - TEMPMIN)); hsv[1] = 1.; hsv[2] = 1.; HsvRgb(hsv, rgb); Nodes[i][j][k].rgb[0] = rgb[0]; Nodes[i][j][k].rgb[1] = rgb[1]; Nodes[i][j][k].rgb[2] = rgb[2]; Nodes[i][j][k].rad = sqrt(SQR(Nodes[i][j][k].x) + SQR(Nodes[i][j][k].y) + SQR(Nodes[i][j][k].z)); if (i == 0) Nodes[i][j][k].dTdx = (Nodes[i + 1][j][k].t - Nodes[i][j][k].t) / (Nodes[i + 1][j][k].x - Nodes[i][j][k].x); else if (i + 1 == NX) Nodes[i][j][k].dTdx = (Nodes[i][j][k].t - Nodes[i - 1][j][k].t) / (Nodes[i][j][k].x - Nodes[i - 1][j][k].x); else Nodes[i][j][k].dTdx = (Nodes[i + 1][j][k].t - Nodes[i - 1][j][k].t) / (Nodes[i + 1][j][k].x - Nodes[i - 1][j][k].x); if (j == 0) Nodes[i][j][k].dTdy = (Nodes[i][j + 1][k].t - Nodes[i][j][k].t) / (Nodes[i][j + 1][k].y - Nodes[i][j][k].y); else if (j + 1 == NY) Nodes[i][j][k].dTdy = (Nodes[i][j][k].t - Nodes[i][j - 1][k].t) / (Nodes[i][j][k].y - Nodes[i][j - 1][k].y); else Nodes[i][j][k].dTdy = (Nodes[i][j + 1][k].t - Nodes[i][j - 1][k].t) / (Nodes[i][j + 1][k].y - Nodes[i][j - 1][k].y); if (k == 0) Nodes[i][j][k].dTdz = (Nodes[i][j][k + 1].t - Nodes[i][j][k].t) / (Nodes[i][j][k + 1].z - Nodes[i][j][k].z); else if (k + 1 == NZ) Nodes[i][j][k].dTdz = (Nodes[i][j][k].t - Nodes[i][j][k - 1].t) / (Nodes[i][j][k].z - Nodes[i][j][k - 1].z); else Nodes[i][j][k].dTdz = (Nodes[i][j][k + 1].t - Nodes[i][j][k - 1].t) / (Nodes[i][j][k + 1].z - Nodes[i][j][k - 1].z); Nodes[i][j][k].grad = sqrt(SQR(Nodes[i][j][k].dTdx) + SQR(Nodes[i][j][k].dTdy) + SQR(Nodes[i][j][k].dTdz)); } } } // setup the display mode: // ( *must* be done before call to glutCreateWindow( ) ) // ask for color, double-buffering, and z-buffering: glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH ); // set the initial window configuration: glutInitWindowPosition( 0, 0 ); glutInitWindowSize( INIT_WINDOW_SIZE, INIT_WINDOW_SIZE ); // open the window and set its title: MainWindow = glutCreateWindow( WINDOWTITLE ); glutSetWindowTitle( WINDOWTITLE ); // setup the clear values: glClearColor( BACKCOLOR[0], BACKCOLOR[1], BACKCOLOR[2], BACKCOLOR[3] ); // setup the callback functions: // DisplayFunc -- redraw the window // ReshapeFunc -- handle the user resizing the window // KeyboardFunc -- handle a keyboard input // MouseFunc -- handle the mouse button going down or up // MotionFunc -- handle the mouse moving with a button down // PassiveMotionFunc -- handle the mouse moving with a button up // VisibilityFunc -- handle a change in window visibility // EntryFunc -- handle the cursor entering or leaving the window // SpecialFunc -- handle special keys on the keyboard // SpaceballMotionFunc -- handle spaceball translation // SpaceballRotateFunc -- handle spaceball rotation // SpaceballButtonFunc -- handle spaceball button hits // ButtonBoxFunc -- handle button box hits // DialsFunc -- handle dial rotations // TabletMotionFunc -- handle digitizing tablet motion // TabletButtonFunc -- handle digitizing tablet button hits // MenuStateFunc -- declare when a pop-up menu is in use // TimerFunc -- trigger something to happen a certain time from now // IdleFunc -- what to do when nothing else is going on glutSetWindow( MainWindow ); glutDisplayFunc( Display ); glutReshapeFunc( Resize ); glutKeyboardFunc( Keyboard ); glutMouseFunc( MouseButton ); glutMotionFunc( MouseMotion ); glutPassiveMotionFunc( NULL ); glutVisibilityFunc( Visibility ); glutEntryFunc( NULL ); glutSpecialFunc( NULL ); glutSpaceballMotionFunc( NULL ); glutSpaceballRotateFunc( NULL ); glutSpaceballButtonFunc( NULL ); glutButtonBoxFunc( NULL ); glutDialsFunc( NULL ); glutTabletMotionFunc( NULL ); glutTabletButtonFunc( NULL ); glutMenuStateFunc( NULL ); glutTimerFunc( 0, NULL, 0 ); // DO NOT SET THE GLUT IDLE FUNCTION HERE !! // glutIdleFunc( NULL ); // let glui take care of it in InitGlui( ) }
static void init_glut(void) { const struct piglit_gl_test_config *test_config = glut_fw.gl_fw.test_config; char *argv[] = {"piglit"}; int argc = 1; unsigned flags = GLUT_RGB; if (test_config->window_visual & PIGLIT_GL_VISUAL_RGBA) flags |= GLUT_ALPHA; if (test_config->window_visual & PIGLIT_GL_VISUAL_DEPTH) flags |= GLUT_DEPTH; if (test_config->window_visual & PIGLIT_GL_VISUAL_STENCIL) flags |= GLUT_STENCIL; if (test_config->window_visual & PIGLIT_GL_VISUAL_ACCUM) flags |= GLUT_ACCUM; if (test_config->window_visual & PIGLIT_GL_VISUAL_DOUBLE) flags |= GLUT_DOUBLE; else flags |= GLUT_SINGLE; /* * MacOSX GLUT. * * This will request a core profile. It will always return the highest * version supported. * * See: * /System/Library/Frameworks/GLUT.framework/Headers/glut.h * https://developer.apple.com/opengl/capabilities/ */ #if GLUT_MACOSX_IMPLEMENTATION >= 4 if (test_config->supports_gl_core_version >= 31) { flags |= GLUT_3_2_CORE_PROFILE; } #endif glutInit(&argc, argv); glutInitWindowPosition(0, 0); glutInitWindowSize(test_config->window_width, test_config->window_height); glutInitDisplayMode(flags); /* * FreeGLUT */ #ifdef PIGLIT_USE_GLUT_INIT_ERROR_FUNC glutInitErrorFunc(error_func); #else (void)error_func; #endif #ifdef GLUT_CORE_PROFILE if (test_config->supports_gl_core_version) { glutInitContextVersion(test_config->supports_gl_core_version / 10, test_config->supports_gl_core_version % 10); if (test_config->supports_gl_core_version >= 32) { glutInitContextProfile(GLUT_CORE_PROFILE); } } else { glutInitContextVersion(test_config->supports_gl_compat_version / 10, test_config->supports_gl_compat_version % 10); if (test_config->supports_gl_compat_version >= 32) { glutInitContextProfile(GLUT_COMPATIBILITY_PROFILE); } } int context_flags = 0; /* There are no 3.1 core profiles -- the closest is 3.1 context without * ARB_compatibility or a 3.2 core context --, and setting * forward-compatible flag should ensure we don't get a 3.1 context w/ * ARB_compatibility. */ if (test_config->require_forward_compatible_context || test_config->supports_gl_core_version == 31) { context_flags |= GLUT_FORWARD_COMPATIBLE; } if (test_config->require_debug_context) { context_flags |= GLUT_DEBUG; } if (context_flags) { glutInitContextFlags(context_flags); } #endif glut_fw.window = glutCreateWindow("Piglit"); glutDisplayFunc(display); glutReshapeFunc(default_reshape_func); glutKeyboardFunc(piglit_escape_exit_key); #ifdef PIGLIT_USE_OPENGL piglit_dispatch_default_init(PIGLIT_DISPATCH_GL); #endif }
int main(int argc, char* argv[]) { //----------------------------------------------------------------------- // INITIALIZATION //----------------------------------------------------------------------- printf ("\n"); printf ("-----------------------------------\n"); printf ("CHAI 3D\n"); printf ("Demo: 11-effects\n"); printf ("Copyright 2003-2009\n"); printf ("-----------------------------------\n"); printf ("\n\n"); printf ("Keyboard Options:\n\n"); printf ("[x] - Exit application\n"); printf ("\n\n"); // parse first arg to try and locate resources resourceRoot = string(argv[0]).substr(0,string(argv[0]).find_last_of("/\\")+1); //----------------------------------------------------------------------- // 3D - SCENEGRAPH //----------------------------------------------------------------------- // create a new world. world = new cWorld(); // set the background color of the environment // the color is defined by its (R,G,B) components. world->setBackgroundColor(0.0, 0.0, 0.0); // create a camera and insert it into the virtual world camera = new cCamera(world); world->addChild(camera); // position and oriente the camera camera->set( cVector3d (3.0, 0.0, 0.0), // camera position (eye) cVector3d (0.0, 0.0, 0.0), // lookat position (target) cVector3d (0.0, 0.0, 1.0)); // direction of the "up" vector // set the near and far clipping planes of the camera // anything in front/behind these clipping planes will not be rendered camera->setClippingPlanes(0.01, 10.0); // enable higher quality rendering for transparent objects camera->enableMultipassTransparency(true); // create a light source and attach it to the camera light = new cLight(world); camera->addChild(light); // attach light to camera light->setEnabled(true); // enable light source light->setPos(cVector3d( 2.0, 0.5, 1.0)); // position the light source light->setDir(cVector3d(-2.0, 0.5, 1.0)); // define the direction of the light beam //----------------------------------------------------------------------- // 2D - WIDGETS //----------------------------------------------------------------------- // create a 2D bitmap logo logo = new cBitmap(); // add logo to the front plane camera->m_front_2Dscene.addChild(logo); // load a "chai3d" bitmap image file bool fileload; fileload = logo->m_image.loadFromFile(RESOURCE_PATH("resources/images/chai3d.bmp")); if (!fileload) { #if defined(_MSVC) fileload = logo->m_image.loadFromFile("../../../bin/resources/images/chai3d.bmp"); #endif } // position the logo at the bottom left of the screen (pixel coordinates) logo->setPos(10, 10, 0); // scale the logo along its horizontal and vertical axis logo->setZoomHV(0.4, 0.4); // here we replace all black pixels (0,0,0) of the logo bitmap // with transparent black pixels (0, 0, 0, 0). This allows us to make // the background of the logo look transparent. logo->m_image.replace( cColorb(0, 0, 0), // original RGB color cColorb(0, 0, 0, 0) // new RGBA color ); // enable transparency logo->enableTransparency(true); //----------------------------------------------------------------------- // HAPTIC DEVICES / TOOLS //----------------------------------------------------------------------- // create a haptic device handler handler = new cHapticDeviceHandler(); // get access to the first available haptic device cGenericHapticDevice* hapticDevice; handler->getDevice(hapticDevice, 0); // retrieve information about the current haptic device cHapticDeviceInfo info; if (hapticDevice) { info = hapticDevice->getSpecifications(); } // create a 3D tool and add it to the world tool = new cGeneric3dofPointer(world); world->addChild(tool); // connect the haptic device to the tool tool->setHapticDevice(hapticDevice); // initialize tool by connecting to haptic device tool->start(); // map the physical workspace of the haptic device to a larger virtual workspace. tool->setWorkspaceRadius(1.0); // define a radius for the tool tool->setRadius(0.03); // read the scale factor between the physical workspace of the haptic // device and the virtual workspace defined for the tool double workspaceScaleFactor = tool->getWorkspaceScaleFactor(); // define a maximum stiffness that can be handled by the current // haptic device. The value is scaled to take into account the // workspace scale factor double stiffnessMax = info.m_maxForceStiffness / workspaceScaleFactor; double forceMax = info.m_maxForce; // define the maximum damping factor that can be handled by the // current haptic device. The The value is scaled to take into account the // workspace scale factor double dampingMax = info.m_maxLinearDamping / workspaceScaleFactor; //----------------------------------------------------------------------- // COMPOSE THE VIRTUAL SCENE //----------------------------------------------------------------------- // temp variable cGenericEffect* newEffect; ///////////////////////////////////////////////////////////////////////// // OBJECT 0: "MAGNET" ///////////////////////////////////////////////////////////////////////// // create a sphere and define its radius object0 = new cShapeSphere(0.3); // add object to world world->addChild(object0); // set the position of the object at the center of the world object0->setPos(0.0, -0.5, 0.0); // set graphic properties object0->m_texture = new cTexture2D(); fileload = object0->m_texture->loadFromFile(RESOURCE_PATH("resources/images/chrome.bmp")); if (!fileload) { #if defined(_MSVC) fileload = object0->m_texture->loadFromFile("../../../bin/resources/images/chrome.bmp"); #endif } if (!fileload) { printf("Error - Texture image failed to load correctly.\n"); close(); return (-1); } object0->m_texture->setSphericalMappingEnabled(true); object0->m_material.m_ambient.set(1.0, 1.0, 1.0); object0->m_material.m_diffuse.set(1.0, 1.0, 1.0); object0->m_material.m_specular.set(1.0, 1.0, 1.0); object0->m_material.setShininess(100); object0->setUseTexture(true); // set haptic properties object0->m_material.setStiffness(0.4 * stiffnessMax); object0->m_material.setMagnetMaxForce(0.4 * forceMax); object0->m_material.setMagnetMaxDistance(0.12); object0->m_material.setViscosity(0.2 * dampingMax); // create a haptic surface effect newEffect = new cEffectSurface(object0); object0->addEffect(newEffect); // create a haptic magnetic effect newEffect = new cEffectMagnet(object0); object0->addEffect(newEffect); ///////////////////////////////////////////////////////////////////////// // OBJECT 1: "FLUID" //////////////////////////////////////////////////////////////////////// // create a sphere and define its radius object1 = new cShapeSphere(0.3); // add object to world world->addChild(object1); // set the position of the object at the center of the world object1->setPos(0.0, 0.5, 0.0); // set graphic properties object1->m_texture = new cTexture2D(); fileload = object1->m_texture->loadFromFile(RESOURCE_PATH("resources/images/water.bmp")); if (!fileload) { #if defined(_MSVC) fileload = object1->m_texture->loadFromFile("../../../bin/resources/images/water.bmp"); #endif } if (!fileload) { printf("Error - Texture image failed to load correctly.\n"); close(); return (-1); } object1->m_material.m_ambient.set(0.1, 0.1, 0.6, 0.5); object1->m_material.m_diffuse.set(0.3, 0.3, 0.9, 0.5); object1->m_material.m_specular.set(1.0, 1.0, 1.0, 0.5); object1->setTransparencyLevel(0.5); object1->setUseTexture(true); // set haptic properties object1->m_material.setViscosity(dampingMax); // create a haptic viscous effect newEffect = new cEffectViscosity(object1); object1->addEffect(newEffect); ///////////////////////////////////////////////////////////////////////// // OBJECT 2: "STICK-SLIP" ///////////////////////////////////////////////////////////////////////// // create a sphere and define its radius object2 = new cShapeSphere(0.3); // add object to world world->addChild(object2); // set the position of the object at the center of the world object2->setPos(0.0, 0.0, 0.5); // set graphic properties object2->m_texture = new cTexture2D(); fileload = object2->m_texture->loadFromFile(RESOURCE_PATH("resources/images/stone.bmp")); if (!fileload) { #if defined(_MSVC) fileload = object2->m_texture->loadFromFile("../../../bin/resources/images/stone.bmp"); #endif } if (!fileload) { printf("Error - Texture image failed to load correctly.\n"); close(); return (-1); } object2->m_material.m_ambient.set(0.1, 0.1, 0.6, 0.5); object2->m_material.m_diffuse.set(0.3, 0.3, 0.9, 0.5); object2->m_material.m_specular.set(1.0, 1.0, 1.0, 0.5); object2->setTransparencyLevel(0.5); object2->setUseTexture(true); // set haptic properties object2->m_material.setStickSlipForceMax(0.5 * forceMax); object2->m_material.setStickSlipStiffness(0.7 * stiffnessMax); // create a haptic stick-slip effect newEffect = new cEffectStickSlip(object2); object2->addEffect(newEffect); ///////////////////////////////////////////////////////////////////////// // OBJECT 3: "VIBRATIONS" //////////////////////////////////////////////////////////////////////// // create a sphere and define its radius object3 = new cShapeSphere(0.3); // add object to world world->addChild(object3); // set the position of the object at the center of the world object3->setPos(0.0, 0.0, -0.5); // set graphic properties object3->m_texture = new cTexture2D(); fileload = object3->m_texture->loadFromFile(RESOURCE_PATH("resources/images/plastic.bmp")); if (!fileload) { #if defined(_MSVC) fileload = object3->m_texture->loadFromFile("../../../bin/resources/images/plastic.bmp"); #endif } if (!fileload) { printf("Error - Texture image failed to load correctly.\n"); close(); return (-1); } object3->m_texture->setSphericalMappingEnabled(true); object3->m_material.m_ambient.set(0.6, 0.1, 0.1, 0.5); object3->m_material.m_diffuse.set(0.9, 0.3, 0.3, 0.5); object3->m_material.m_specular.set(1.0, 1.0, 1.0, 0.5); object3->setTransparencyLevel(0.8); object3->setUseTexture(true); // set haptic properties object3->m_material.setVibrationFrequency(50); object3->m_material.setVibrationAmplitude(0.1 * forceMax); object3->m_material.setStiffness(0.1 * stiffnessMax); // create a haptic viscous effect newEffect = new cEffectVibration(object3); object3->addEffect(newEffect); newEffect = new cEffectSurface(object3); object3->addEffect(newEffect); //----------------------------------------------------------------------- // OPEN GL - WINDOW DISPLAY //----------------------------------------------------------------------- // initialize GLUT glutInit(&argc, argv); // retrieve the resolution of the computer display and estimate the position // of the GLUT window so that it is located at the center of the screen int screenW = glutGet(GLUT_SCREEN_WIDTH); int screenH = glutGet(GLUT_SCREEN_HEIGHT); int windowPosX = (screenW - WINDOW_SIZE_W) / 2; int windowPosY = (screenH - WINDOW_SIZE_H) / 2; // initialize the OpenGL GLUT window glutInitWindowPosition(windowPosX, windowPosY); glutInitWindowSize(WINDOW_SIZE_W, WINDOW_SIZE_H); glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE); glutCreateWindow(argv[0]); glutDisplayFunc(updateGraphics); glutKeyboardFunc(keySelect); glutReshapeFunc(resizeWindow); glutSetWindowTitle("CHAI 3D"); // create a mouse menu (right button) glutCreateMenu(menuSelect); glutAddMenuEntry("full screen", OPTION_FULLSCREEN); glutAddMenuEntry("window display", OPTION_WINDOWDISPLAY); glutAttachMenu(GLUT_RIGHT_BUTTON); //----------------------------------------------------------------------- // START SIMULATION //----------------------------------------------------------------------- // simulation in now running simulationRunning = true; // create a thread which starts the main haptics rendering loop cThread* hapticsThread = new cThread(); hapticsThread->set(updateHaptics, CHAI_THREAD_PRIORITY_HAPTICS); // start the main graphics rendering loop glutMainLoop(); // close everything close(); // exit return (0); }
int main(int argc, char** argv) { std::cout << "Initial number of atoms: " << numberOfAtoms << std::endl; std::cout << "Initial steps per frame: " << numberOfSteps << std::endl; srand(time(NULL)); generateAtoms(atomTable, numberOfAtoms, diameter, atomMass); glutInit(&argc, argv); // Initialize GLUT glutInitWindowSize(width, height); // Set the window's initial width & height glutCreateWindow("Klaster atomowy"); // Create a window with the given title float mat_specular[] = { 1.0, 1.0, 1.0, 1.0 }; float mat_shininess[] = { 90.0 }; float light_position[] = { 1., 1., 1., 0.0 }; glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess); glLightfv(GL_LIGHT0, GL_POSITION, light_position); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_DEPTH_TEST); glEnable(GL_NORMALIZE); glutDisplayFunc(display); // Register display callback handler for window re-paint glutReshapeFunc(reshape); glutTimerFunc(1, update, 0); glutMouseFunc(handleMouseButton); // process mouse button push/release int atomMenu = glutCreateMenu(processMenuEvents); glutAddMenuEntry("2", 20); glutAddMenuEntry("5", 21); glutAddMenuEntry("10", 22); glutAddMenuEntry("15", 23); glutAddMenuEntry("20", 24); glutAddMenuEntry("50", 25); glutAddMenuEntry("100", 26); int stepMenu = glutCreateMenu(processMenuEvents); glutAddMenuEntry("1", 30); glutAddMenuEntry("5", 31); glutAddMenuEntry("10", 32); glutAddMenuEntry("30", 33); glutAddMenuEntry("50", 34); glutAddMenuEntry("100", 35); glutAddMenuEntry("1000", 36); int readMenu = glutCreateMenu(processMenuEvents); glutAddMenuEntry("Random", 40); glutAddMenuEntry("5", 41); glutAddMenuEntry("10", 42); glutAddMenuEntry("15", 43); glutAddMenuEntry("20", 44); glutAddMenuEntry("2D", 45); glutCreateMenu(processMenuEvents); glutAddMenuEntry("Pause (Space Bar)", 0); glutAddMenuEntry("Monte Carlo (Enter)", 1); glutAddMenuEntry("System evolution over time", 2); glutAddMenuEntry("Reset", 3); glutAddMenuEntry("Save to file", 4); glutAddMenuEntry("Enable/disable axes", 5); glutAddMenuEntry("Enable/disable rotate", 6); //glutAddMenuEntry("Read", 7); glutAddSubMenu("Read from file", readMenu); glutAddSubMenu("Number of atoms", atomMenu); glutAddSubMenu("Number of steps per frame", stepMenu); glutAttachMenu(GLUT_RIGHT_BUTTON); //pliku.open("Energy.txt"); /* pliku2.open("1500.txt"); double tempu = 1500; for(int i=1; i <=20000;i++){ pliku2 << i << " " << tempu << std::endl; tempu = tempu * exp(-0.0002); } pliku2.close(); */ glutMainLoop(); // Enter the infinitely event-processing loop //pliku.close(); }
int main(int argc, char** argv) { getInputSegments(); //initialize the path planner glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH | GLUT_RGB); glutInitWindowSize(640, 480); if (argc < 2) { usage(1); } grid.load(argv[1]); if (grid.empty()) { std::cerr << "Error loading grid: " << argv[1] << "\n"; exit(1); } glutCreateWindow("Biped plan demo"); glutDisplayFunc(display); glutReshapeFunc(reshape); glutKeyboardFunc(keyboard); glutMouseFunc(mouse); glutMotionFunc(motion); glClearColor(1,1,1,1); glViewport(0, 0, 640, 480); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, 640, 0, 480, 1, -1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glGenTextures(1, &grid_texture); glBindTexture(GL_TEXTURE_2D, grid_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); std::vector<unsigned char> rgbbuf(grid.nx() * grid.ny() * 4); int offs = 0; for (size_t y=0; y<grid.ny(); ++y) { for (size_t x=0; x<grid.nx(); ++x) { rgbbuf[offs++] = grid(x,y); rgbbuf[offs++] = grid(x,y); rgbbuf[offs++] = grid(x,y); rgbbuf[offs++] = 255; } } glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, grid.nx(), grid.ny(), 0, GL_RGBA, GL_UNSIGNED_BYTE, &(rgbbuf[0])); quadric = gluNewQuadric(); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); searchTrajectory(); glutMainLoop(); return 0; }
int main(int argc, char **argv) { int c; int pol,conv; int option1 = 0, option2 = 0, option3 = 0, option4 = 0; int nbPoints = 50; vertex *v; opterr = 0; while ((c = getopt(argc, argv, "1i:2o:34n:")) != EOF) { switch (c) { case '1': option1 = 1; break; case '2': option2 = 1; break; case '3': option3 = 1; break; case '4': option4 = 1; break; case 'n': if ((sscanf(optarg, "%d", &nbPoints) != 1) || nbPoints <= 0) nbPoints = 50; break; case 'o': /*verifier non null*/ out = optarg; break; case 'i': /*verifier non null*/ in = optarg; break; case 'h': case '?': printf("-1 partie 1 du tp\n"); printf("-2 partie 2 du tp\n"); printf("-3 partie 3 du tp\n"); printf("-ichaine ouvre le fichier \"chaine\" en lecture \n"); printf("-ochaine ouvre le fichier \"chaine\" en écriture \n"); return EXIT_SUCCESS; break; default : printf("Shouldn't be here, really...\n"); break; } } glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA); glutInitWindowPosition(5,5); glutInitWindowSize(500,500); glutCreateWindow("fenetre"); definitionFenetre(0, 500, 0, 500, 10); winInit(); if(option1 && out != NULL) { glutDisplayFunc(display); glutMouseFunc(coordonnesPoint); ecrireFichier(out, &P); } else if(option2 && in != NULL) { lireFichier(in, &P); assert(P.p != NULL); pol = controlePolygoneSimple(); printf("controlePolygoneSimple : %d\n", pol); //glutDisplayFunc(displayPolygone); } else if(option3 && in != NULL) { lireFichier(in, &P); assert(P.p != NULL); if(controlePolygoneSimple()) conv = estConvexe(); } else if(option4 && in != NULL) { lireFichier(in, &P); assert(P.p != NULL); ALLOUER(v,nbPoints); selectPoints (v, nbPoints); if(controlePolygoneSimple() && estConvexe()) positionPointsParRapportPolygone(v, nbPoints); free(v); } glutMainLoop(); clearFenetre(); return EXIT_SUCCESS; }
int main( int argc, char* argv[] ) { ll_init_apr(); // Set up llerror logging { LLError::initForApplication("."); LLError::setDefaultLevel(LLError::LEVEL_INFO); } std::string launcher_name; std::string plugin_name; if(argc >= 3) { launcher_name = argv[1]; plugin_name = argv[2]; } else { #if LL_DARWIN // hardcoding the testbed arguments by default launcher_name = "plugin_process_host"; plugin_name = "libdemo_media_plugin_quicktime.dylib"; #elif LL_WINDOWS // hardcoding the testbed arguments by default launcher_name = "plugin_process_host.exe"; plugin_name = "demo_media_plugin_quicktime.dll"; #else LL_ERRS("plugin_process_launcher") << "usage: " << argv[0] << " launcher_filename plugin_filename" << LL_ENDL; #endif } gApplication = new mediaPluginTest(launcher_name, plugin_name); if ( gApplication ) { glutInit( &argc, argv ); glutInitDisplayMode( GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGB ); glutInitWindowPosition( 80, 0 ); glutInitWindowSize( gApplication->getAppWindowWidth(), gApplication->getAppWindowHeight() ); glutCreateWindow( gApplication->getAppWindowName().c_str() ); glutKeyboardFunc( glutKeyboard ); glutMouseFunc( glutMouseButton ); glutPassiveMotionFunc( glutMouseMove ); glutMotionFunc( glutMouseMove ); glutDisplayFunc( glutDisplay ); glutReshapeFunc( glutReshape ); glutIdleFunc( glutIdle ); gApplication->initGL(); glutMainLoop(); delete gApplication; }; ll_cleanup_apr(); return 0; }
int main(int argc, char *argv[]) { glutInit(&argc, argv); glutInitWindowSize(winWidth, winHeight); glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE); (void) glutCreateWindow("npr"); glutDisplayFunc(redraw); glutReshapeFunc(reshape); glutMouseFunc(mouse); glutMotionFunc(motion); glutKeyboardFunc(key); create_menu(); glClearColor(.5f, .5f, .5f, 1.f); /* * draw a perspective scene */ glMatrixMode(GL_PROJECTION); glFrustum(-100., 100., -100., 100., 300., 600.); glMatrixMode(GL_MODELVIEW); /* * look at scene from (0, 0, 450) */ gluLookAt(0., 0., 450., 0., 0., 0., 0., 1., 0.); glEnable(GL_DEPTH_TEST); glEnable(GL_LIGHTING); /* * Normal light */ glLightfv(GL_LIGHT0, GL_POSITION, light0pos); /* * Two-tone lights */ glLightfv(GL_LIGHT1, GL_AMBIENT, lightambient); glLightfv(GL_LIGHT1, GL_DIFFUSE, light1diffuse); glLightfv(GL_LIGHT1, GL_SPECULAR, zero); glLightfv(GL_LIGHT1, GL_POSITION, light1pos); glLightfv(GL_LIGHT2, GL_AMBIENT, lightambient); glLightfv(GL_LIGHT2, GL_DIFFUSE, light2diffuse); glLightfv(GL_LIGHT2, GL_SPECULAR, zero); glLightfv(GL_LIGHT2, GL_POSITION, light2pos); glCullFace(GL_BACK); glReadBuffer(GL_BACK); glDisable(GL_DITHER); /* * The cylinder body */ glNewList(1, GL_COMPILE); glPushMatrix(); glTranslatef(0.f, -80.f, 0.f); cylinder(40, 10, 20, 160); glTranslatef(0.f, 20.f, 0.f); cylinder(40, 3, 60, 20); glTranslatef(0.f, 20.f, 0.f); cylinder(40, 3, 30, 20); glTranslatef(0.f, 60.f, 0.f); cylinder(40, 3, 30, 20); glTranslatef(0.f, 20.f, 0.f); cylinder(40, 3, 60, 20); glPopMatrix(); glEndList(); /* * The cylinder edges */ glNewList(2, GL_COMPILE); glPushMatrix(); glTranslatef(0.f, -80.f, 0.f); cylinder_edges(40, 20, 20); glTranslatef(0.f, 20.f, 0.f); cylinder_edges(40, 60, 20); glTranslatef(0.f, 20.f, 0.f); cylinder_edges(40, 30, 20); glTranslatef(0.f, 20.f, 0.f); cylinder_edges(40, 30, 40); glTranslatef(0.f, 40.f, 0.f); cylinder_edges(40, 30, 20); glTranslatef(0.f, 20.f, 0.f); cylinder_edges(40, 60, 20); glTranslatef(0.f, 20.f, 0.f); cylinder_edges(40, 20, 20); glPopMatrix(); glEndList(); make_stripes(); material(TWOTONE); CHECK_ERROR("end of main"); glutMainLoop(); return 0; }
int main(int argc, char** argv) { // Initializarea bibliotecii GLUT. Argumentele argc // si argv sunt argumentele din linia de comanda si nu // trebuie modificate inainte de apelul functiei // void glutInit(int *argcp, char **argv) // Se recomanda ca apelul oricarei functii din biblioteca // GLUT sa se faca dupa apelul acestei functii. glutInit(&argc, argv); // Argumentele functiei // void glutInitWindowSize (int latime, int latime) // reprezinta latimea, respectiv inaltimea ferestrei // exprimate in pixeli. Valorile predefinite sunt 300, 300. glutInitWindowSize(300, 300); // Argumentele functiei // void glutInitWindowPosition (int x, int y) // reprezinta coordonatele varfului din stanga sus // al ferestrei, exprimate in pixeli. // Valorile predefinite sunt -1, -1. glutInitWindowPosition(100, 100); // Functia void glutInitDisplayMode (unsigned int mode) // seteaza modul initial de afisare. Acesta se obtine // printr-un SAU pe biti intre diverse masti de display // (constante ale bibliotecii GLUT) : // 1. GLUT_SINGLE : un singur buffer de imagine. Reprezinta // optiunea implicita ptr. nr. de buffere de // de imagine. // 2. GLUT_DOUBLE : 2 buffere de imagine. // 3. GLUT_RGB sau GLUT_RGBA : culorile vor fi afisate in // modul RGB. // 4. GLUT_INDEX : modul indexat de selectare al culorii. // etc. (vezi specificatia bibliotecii GLUT) glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); // Functia int glutCreateWindow (char *name) // creeaza o fereastra cu denumirea data de argumentul // name si intoarce un identificator de fereastra. glutCreateWindow (argv[0]); Init(); // Functii callback : functii definite in program si // inregistrate in sistem prin intermediul unor functii // GLUT. Ele sunt apelate de catre sistemul de operare // in functie de evenimentul aparut // Functia // void glutReshapeFunc (void (*Reshape)(int width, int height)) // inregistreaza functia callback Reshape care este apelata // oridecate ori fereastra de afisare isi modifica forma. glutReshapeFunc(Reshape); // Functia // void glutKeyboardFunc (void (*KeyboardFunc)(unsigned char,int,int)) // inregistreaza functia callback KeyboardFunc care este apelata // la actionarea unei taste. glutKeyboardFunc(KeyboardFunc); // Functia // void glutMouseFunc (void (*MouseFunc)(int,int,int,int)) // inregistreaza functia callback MouseFunc care este apelata // la apasarea sau la eliberarea unui buton al mouse-ului. glutMouseFunc(MouseFunc); // Functia // void glutDisplayFunc (void (*Display)(void)) // inregistreaza functia callback Display care este apelata // oridecate ori este necesara desenarea ferestrei: la // initializare, la modificarea dimensiunilor ferestrei // sau la apelul functiei // void glutPostRedisplay (void). glutDisplayFunc(Display); // Functia void glutMainLoop() lanseaza bucla de procesare // a evenimentelor GLUT. Din bucla se poate iesi doar prin // inchiderea ferestrei aplicatiei. Aceasta functie trebuie // apelata cel mult o singura data in program. Functiile // callback trebuie inregistrate inainte de apelul acestei // functii. // Cand coada de evenimente este vida atunci este executata // functia callback IdleFunc inregistrata prin apelul functiei // void glutIdleFunc (void (*IdleFunc) (void)) glutMainLoop(); return 0; }
//////////main関数///////////// int main(int argc, char** argv){ cubeSize_ = cubeSize/2.; int i=0, j=0, k=0; clock_t start_time_total,end_time_total; clock_t start_time[fileTotal]; clock_t end_time[fileTotal]; //char * filename[fileTotal]; //並列用 char * model_filename[fileTotal]; char * data_filename[fileTotal]; //Mat shape[fileTotal]; Mat shape_reg[fileTotal]; //Mat shape_temp[fileTotal]; Mat shape_fixed[fileTotal]; //並列用 Mat model_shape[fileTotal]; Mat data_shape[fileTotal]; Mat shape_temp[fileTotal][fileTotal]; Mat my_model_corr[fileTotal]; int myIndex[fileTotal][rows]; float myDist[fileTotal][rows]; RT<float> my_rt[fileTotal]; Mat_<float> model_mean; //modelファイルのデータ数 //model_rows = 16128; //dataファイルのデータ数 //data_rows = 16128; start_time_total = clock(); cout << "-------------" << endl; cout << "ICP Algorithm" << endl; cout << "-------------" << endl; #pragma omp parallel for for(fileCount=0;fileCount<fileTotal;fileCount++) { #pragma region // --- 点群のCSVファイルをcv::Matに取り込む --- if(fileCount>=1){ ///model //csvファイル名 model_filename[fileCount] = (char *)malloc(sizeof(char *) * 100); //sprintf(model_filename[fileCount],"%s/%s/%d.csv",filedir,dir,fileCount); sprintf(model_filename[fileCount],"%s/%s/points%02d.csv",filedir,dir,fileCount); //csvファイルのデータ数 model_rows[fileCount] = rows; //CSVファイル読み込み model_shape[fileCount] = csvread(model_filename[fileCount], model_rows[fileCount], cols); //コンソールにファイル名表示 //cout << "model点群データファイル名 " << model_filename[fileCount] << endl; } ///data //csvファイル名 data_filename[fileCount] = (char *)malloc(sizeof(char *) * 100); //sprintf(data_filename[fileCount],"%s/%s/%d.csv",filedir,dir,(fileCount+1)); sprintf(data_filename[fileCount],"%s/%s/points%02d.csv",filedir,dir,(fileCount+1)); //csvファイルのデータ数 data_rows[fileCount] = rows; //CSVファイル読み込み data_shape[fileCount] = csvread(data_filename[fileCount], data_rows[fileCount], cols); //コンソールにファイル名表示 cout << "点群データファイル名 " << data_filename[fileCount] << endl; #pragma endregion if(fileCount>=1){ #pragma region // --- ICPによるレジストレーション --- #if 1 // --- ICP実行する --- //実行時間計測開始 start_time[fileCount] = clock(); cout << "\t標準ICP開始" << endl; //ICP with flann search and unit quaternion method //cout << "kd-tree探索+クォータニオンにより[R/t]を推定します" << endl << endl; ClosestPointFlann model_shape_flann (model_shape[fileCount]); RT_L2 <float, SolveRot_eigen<float>> rt_solver; ICP <ClosestPointFlann> icp (model_shape_flann, rt_solver); icp.set(data_shape[fileCount]); icp.reg(100, 1.0e-6); //実行時間計測終了 end_time[fileCount] = clock(); //cout << "icp result : [R/t] =" << endl << (icp.rt) << endl << endl; cout << "\t" << data_filename[fileCount] << " icp error =" << icp.dk << endl; cout << "\t" << data_filename[fileCount] << " 実行時間 = " << (float)(end_time[fileCount] - start_time[fileCount])/CLOCKS_PER_SEC << "秒" << endl << endl; //データをローカル変数に格納 //my_model_corr[fileCount] = Mat::zeros(rows, cols, CV_32F); my_model_corr[fileCount].create(rows, cols, CV_32F); icp.model_corr.copyTo(my_model_corr[fileCount]); icp.rt.copyTo(my_rt[fileCount]); for(int k=0;k<data_rows[fileCount];k++){ myIndex[fileCount][k] = icp.index[k]; myDist[fileCount][k] = icp.distance[k]; } #else // --- ICP実行しない場合 --- shape_reg[fileCount] = data_shape[fileCount]; #endif #pragma endregion }else{ shape_reg[fileCount] = data_shape[fileCount]; } } #pragma region // --- 座標変換 --- //平均値の計算 reduce(shape_reg[0], model_mean, 0, CV_REDUCE_AVG); #pragma omp parallel for private(i,j,k) for(fileCount=0;fileCount<fileTotal;fileCount++) { if(fileCount>=1){ //得られたrtをdatashapeに適用 //その前にshape_tempの初期化 for(k=0;k<fileTotal;k++) { shape_temp[fileCount][k] = cv::Mat::zeros(data_rows[fileCount], cols, CV_32F); } shape_temp[fileCount][fileCount] = data_shape[fileCount]; for(k=0;k<fileCount;k++) { shape_temp[fileCount][fileCount-(k+1)] = my_rt[(fileCount-k)].transform(shape_temp[fileCount][fileCount-k]); } shape_reg[fileCount] = shape_temp[fileCount][0]; } shape_fixed[fileCount] = shape_reg[fileCount] - repeat(model_mean, shape_reg[fileCount].rows, 1); /* //メモリ割り当て points[fileCount] = (GLfloat *)malloc(sizeof(float)*data_rows[fileCount]*cols); //座標値をGLpointsに入れる for(i=0;i<data_rows[fileCount];i++){ for(j=0;j<cols;j++){ points[fileCount][i*cols+j] = shape_fixed[fileCount].at<float>(i,j); } }*/ #pragma endregion } #pragma region // --- OpenGLにデータ渡す --- //メモリ割り当て allpoints = (GLfloat *)malloc(sizeof(float)*rows*fileTotal*cols); for(fileCount=0;fileCount<fileTotal;fileCount++) { //座標値をallpointsに入れる for(int i=0;i<rows;i++){ for(int j=0;j<cols;j++){ allpoints[fileCount*rows*cols+i*cols+j] = shape_fixed[fileCount].at<float>(i,j); } } } #pragma endregion #pragma region // --- カメラRTの計算 --- Mat cameraRT[fileTotal]; Mat cameraR[fileTotal]; Mat cameraT[fileTotal]; cameraRT[0] = Mat::eye(4,4,CV_32F); cameraR[0] = Mat::eye(3,3,CV_32F); cameraT[0] = Mat::zeros(1,3,CV_32F); for(i=1;i<fileTotal;i++){ cameraRT[i] = Mat::eye(4,4,CV_32F); cameraR[i] = Mat::eye(3,3,CV_32F); cameraT[i] = Mat::zeros(1,3,CV_32F); Mat r = my_rt[i].operator()(Range(0,3),Range(0,3)); cameraR[i] = cameraR[i-1]*r.t(); Mat t = my_rt[i].operator()(Range(3,4),Range(0,3)); cameraT[i] = t*cameraR[i-1].t() + cameraT[i-1]; cameraRT[i].at<float>(0,0) = cameraR[i].at<float>(0,0); cameraRT[i].at<float>(0,1) = cameraR[i].at<float>(0,1); cameraRT[i].at<float>(0,2) = cameraR[i].at<float>(0,2); cameraRT[i].at<float>(1,0) = cameraR[i].at<float>(1,0); cameraRT[i].at<float>(1,1) = cameraR[i].at<float>(1,1); cameraRT[i].at<float>(1,2) = cameraR[i].at<float>(1,2); cameraRT[i].at<float>(2,0) = cameraR[i].at<float>(2,0); cameraRT[i].at<float>(2,1) = cameraR[i].at<float>(2,1); cameraRT[i].at<float>(2,2) = cameraR[i].at<float>(2,2); cameraRT[i].at<float>(3,0) = cameraT[i].at<float>(0,0); cameraRT[i].at<float>(3,1) = cameraT[i].at<float>(0,1); cameraRT[i].at<float>(3,2) = cameraT[i].at<float>(0,2); } #pragma endregion // --- データ出力 --- #if FILEOUTPUT /////////////////////////////// // 全ての点群(shape_fixed)をまとめて書き出し // pcd // FILE *outfp; char outfilename[100]; sprintf(outfilename,"%s/%s/result_xyz.pcd",outdir,dir); outfp = fopen(outfilename,"w"); if(outfp == NULL){ printf("%sファイルが開けません\n",outfilename); return -1; } int red = 255*256*256; int green = 255*256*256 + 255*256; int white = 255*256*256 + 255*256 + 255; fprintf(outfp,"# .PCD v.7 - Point Cloud Data file format\nVERSION .7\nFIELDS x y z rgb\nSIZE 4 4 4 4\nTYPE F F F F\nCOUNT 1 1 1 1\nWIDTH %d\nHEIGHT 1\nVIEWPOINT 0 0 0 1 0 0 0\nPOINTS %d\nDATA ascii\n", rows*fileTotal, rows*fileTotal); for(i=0;i<fileTotal;i++){ for(j=0;j<data_rows[i];j++){ fprintf(outfp,"%f %f %f %d\n", shape_reg[i].at<float>(j,0), shape_reg[i].at<float>(j,1), shape_reg[i].at<float>(j,2), green+(int)floor(255.*(i+1)/fileTotal)); } } fclose(outfp); /////////////////////////////// // 全ての点群(shape_fixed)をまとめて書き出し // csv // sprintf(outfilename,"%s/%s/allpoints.csv",outdir,dir); outfp = fopen(outfilename,"w"); if(outfp == NULL){ printf("%sファイルが開けません\n",outfilename); return -1; } for(i=0;i<fileTotal;i++){ for(j=0;j<data_rows[i];j++){ fprintf(outfp,"%f %f %f\n", shape_reg[i].at<float>(j,0), shape_reg[i].at<float>(j,1), shape_reg[i].at<float>(j,2)); } } fclose(outfp); /////////////////////////////// // 全ての点群(shape_fixed)をまとめて書き出し // result_xyz.csv // sprintf(outfilename,"%s/%s/result_xyz_icp.csv",outdir,dir); outfp = fopen(outfilename,"w"); if(outfp == NULL){ printf("%sファイルが開けません\n",outfilename); return -1; } for(i=0;i<fileTotal;i++){ for(j=0;j<data_rows[i];j++){ fprintf(outfp,"%f,%f,%f\n", shape_reg[i].at<float>(j,0), shape_reg[i].at<float>(j,1), shape_reg[i].at<float>(j,2)); } } fclose(outfp); ////////////////////////////////// // Corr(対応点), Index(対応点の要素番号), Distance(対応点間距離)の書き出し // FILE *outfp_corr; char outfilename_corr[100]; for(fileCount=1;fileCount<fileTotal;fileCount++){ ///Indexファイル sprintf(outfilename_corr,"%s/%s/index%02d.csv",outdir,dir,(fileCount)); outfp_corr = fopen(outfilename_corr,"w"); if(outfp_corr == NULL){ printf("%sファイルが開けません\n",outfilename_corr); return -1; } for(j=0;j<data_rows[fileCount];j++){ fprintf(outfp_corr,"%d\n", myIndex[fileCount][j]); } fclose(outfp_corr); ///Distanceファイル sprintf(outfilename_corr,"%s/%s/dist%02d.csv",outdir,dir,(fileCount)); outfp_corr = fopen(outfilename_corr,"w"); if(outfp_corr == NULL){ printf("%sファイルが開けません\n",outfilename_corr); return -1; } for(j=0;j<data_rows[fileCount];j++){ fprintf(outfp_corr,"%f\n", myDist[fileCount][j]); } fclose(outfp_corr); } for(fileCount=0;fileCount<fileTotal;fileCount++){ if(fileCount<(fileTotal-1)){ ///Corr点群ファイル sprintf(outfilename_corr,"%s/%s/corr%02d.csv",outdir,dir,(fileCount+1)); outfp_corr = fopen(outfilename_corr,"w"); if(outfp_corr == NULL){ printf("%sファイルが開けません\n",outfilename_corr); return -1; } for(j=0;j<data_rows[fileCount];j++){ //fprintf(outfp_corr,"%f %f %f\n", my_model_corr[fileCount].at<float>(j,0), my_model_corr[fileCount].at<float>(j,1), my_model_corr[fileCount].at<float>(j,2)); fprintf(outfp_corr,"%f %f %f\n", shape_reg[fileCount].at<float>(myIndex[fileCount+1][j],0), shape_reg[fileCount].at<float>(myIndex[fileCount+1][j],1), shape_reg[fileCount].at<float>(myIndex[fileCount+1][j],2)); } fclose(outfp_corr); }else{ ///Corr点群ファイル sprintf(outfilename_corr,"%s/%s/corr%02d.csv",outdir,dir,(fileCount+1)); outfp_corr = fopen(outfilename_corr,"w"); if(outfp_corr == NULL){ printf("%sファイルが開けません\n",outfilename_corr); return -1; } for(j=0;j<data_rows[fileCount];j++){ //fprintf(outfp_corr,"%f %f %f\n", my_model_corr[fileCount].at<float>(j,0), my_model_corr[fileCount].at<float>(j,1), my_model_corr[fileCount].at<float>(j,2)); fprintf(outfp_corr,"%f %f %f\n", shape_reg[fileCount].at<float>(j,0), shape_reg[fileCount].at<float>(j,1), shape_reg[fileCount].at<float>(j,2)); } fclose(outfp_corr); } } ///////////////////// // RTの書き出し // //my_rt[0]に恒等変換を代入 //Mat rt0 = (Mat_<float>(4,4) << 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); Mat rt0 = Mat::eye(4,4,CV_32F); rt0.copyTo(my_rt[0]); // Open File Storage char rtfilename[100]; sprintf(rtfilename,"%s/%s/rt.xml",outdir,dir); cv::FileStorage cvfs(rtfilename,CV_STORAGE_WRITE); cv::WriteStructContext ws(cvfs, "mat_rt", CV_NODE_SEQ); // create node for(int i=0; i<fileTotal; i++){ cv::write(cvfs,"",cameraRT[i]); } cvfs.release(); #endif //--- OpenGLで表示 --- #if GLVIEW // --- GLUT initialize --- initFlag(); initParam(); //window1 glutInit(&argc, argv); glutInitWindowPosition(0, 0); glutInitWindowSize(window_w, window_h); glutInitDisplayMode( GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE ); window1 = glutCreateWindow("Window1"); glutMouseFunc(mouse); glutMotionFunc(drag); glutPassiveMotionFunc(passive); glutMouseWheelFunc ( MouseWheel ) ;//ホイールコールバック glutDisplayFunc(disp); glutIdleFunc(myGlutIdle); glutKeyboardFunc(glut_keyboard); glutIdleFunc(animate); glClearColor(0.0, 0.0, 0.0, 0.5); //背景色 glutMainLoop(); #endif //実行時間計測終了 end_time_total = clock(); cout << "-------------" << endl; cout << " Finish " << endl; cout << "-------------" << endl; cout << "プログラム実行時間 = " << (float)(end_time_total - start_time_total)/CLOCKS_PER_SEC << "秒" << endl << endl; //cvNamedWindow ("WaitKey", CV_WINDOW_AUTOSIZE); //cvWaitKey(0); return 0; }
int main(int argc,char *argv[] ){ uint obj_index=0; uint coords_index=0; glutInit(&argc,argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH | GLUT_RGBA | GLUT_MULTISAMPLE | GLUT_ALPHA | GLUT_STENCIL); glutInitWindowSize(600,600); glutInitWindowPosition(100,100); glutCreateWindow("partViewer3D"); int err = glewInit(); if (GLEW_OK != err) { // problem: glewInit failed, something is seriously wrong printf("GLEW Error: %s\n", glewGetErrorString(err)); return 1; } //////////* Command line argument processing *///////////// for(uint i=0;i<argc;i++){ if(strcmp(argv[i],"-obj")==0){ obj_index=i+1; use_obj=true; break; } } for(uint i=0;i<argc;i++){ if(strcmp((argv[i]+strlen(argv[i])-4),".dat")==0){ coords_index=i; break; } } if(argc > 4){ animation=true; ani_files=argc-3; printf("ani_files:%d\n",ani_files); ani_matrix=malloc(ani_files*sizeof(*ani_matrix)); for(uint i=0;i<ani_files;i++){ ani_matrix[i]=malloc(strlen(argv[i+3])*sizeof(ani_matrix)); strcpy(ani_matrix[i], argv[i+coords_index]); } } ///////////////////////////////////////////////////////////// if(!animation) parseCoords(argv[coords_index],"\t"); else parseCoords(ani_matrix[0],"\t"); for(uint i = 0; i < nPart; i++){ particle[i].selected = 0; particle[i].hidden = 0; particle[i].solid = 0; } if(use_obj)parseObj(argv[obj_index]); init(); glutDisplayFunc(display); glutIdleFunc(idle); glutReshapeFunc(reshape); glutKeyboardFunc(keyDown); glutKeyboardUpFunc(keyUp); glutSpecialFunc(specialDown); glutSpecialUpFunc(specialUp); glutMouseFunc(onMouse); glutMotionFunc(onMotion); glutMainLoop(); return 1; }
int main(int argc, char** argv) { /* standard GLUT initialization */ glutInit(&argc,argv); // Set up model Window glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); /* default, not needed */ glutInitWindowSize(W_MODEL, H_MODEL); glutInitWindowPosition(X_MODEL, Y_MODEL); modelWindow = glutCreateWindow("Mimicry"); /* window title */ glClearColor(0.5, 0.5, 0.5, 1); glutDisplayFunc(displayModel); glutReshapeFunc(reshapeModel); glutIdleFunc(0); // Set up statistics Window /* glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); glutInitWindowSize(W_STATS, H_STATS); glutInitWindowPosition(X_STATS, Y_STATS); statsWindow = glutCreateWindow("Statistics"); glClearColor(0, 0, 0, 1); glutDisplayFunc(displayStats); glutReshapeFunc(reshapeStats); */ glutKeyboardFunc(keyboard); // GLUI initialization glui = GLUI_Master.create_glui("Controls", 0, X_GLUI, Y_GLUI); // Initialization panel GLUI_Panel *initializationPanel = glui->add_panel("Initialization"); ctlGeneBankName = glui->add_edittext_to_panel(initializationPanel, "File ", GLUI_EDITTEXT_TEXT); ctlGeneBankName->set_w(150); ctlGeneBankName->enable(); ctlGeneBankName->set_text("initialconfig.xml"); glui->add_column_to_panel(initializationPanel, true); ctlStart = glui->add_button_to_panel(initializationPanel, "Start", START, control); ctlStop = glui->add_button_to_panel(initializationPanel, "Stop", STOP, control); ctlStop->disable(); ctlPause = glui->add_button_to_panel(initializationPanel, "Pause/Continue", PAUSE, control); ctlPause->disable(); // Run-time controls panel GLUI_Panel *runtimePanel = glui->add_panel("Runtime Parameters"); // Prey Runtime configuration panel GLUI_Panel *preyConfigPanel = glui->add_panel_to_panel(runtimePanel, "Prey Configuration"); GLUI_Spinner *preySize = glui->add_spinner_to_panel( preyConfigPanel, "Prey Size", GLUI_SPINNER_INT, &System::PREY_SIZE, PREY_SIZE, control); preySize->set_int_limits(1, 5); GLUI_Panel *preyReprodConfigPanel = glui->add_panel_to_panel(preyConfigPanel, "Reproduction"); GLUI_Spinner *preyReproductionAgeLimit = glui->add_spinner_to_panel( preyReprodConfigPanel, "Age Limit", GLUI_SPINNER_INT, &System::PREY_REPRODUCTION_AGE_LIMIT, PREY_REPRODUCTION_AGE_LIMIT, control); preyReproductionAgeLimit->set_int_limits(100, 10000); GLUI_Spinner *preyReproductionInterval = glui->add_spinner_to_panel( preyReprodConfigPanel, "Interval", GLUI_SPINNER_INT, &System::PREY_REPRODUCTION_INTERVAL, PREY_REPRODUCTION_INTERVAL, control); preyReproductionInterval->set_int_limits(100, 10000); GLUI_Panel *preyMutationRatePanel = glui->add_panel_to_panel(preyConfigPanel, "Mutation Rate"); GLUI_Spinner *patternMutationRate = glui->add_spinner_to_panel( preyMutationRatePanel, "Pattern", GLUI_SPINNER_FLOAT, &System::PATTERN_MUTATION_RATE, PATTERN_MUTATION_RATE, control); patternMutationRate->set_int_limits(0.01, 1.0); GLUI_Spinner *preyGenomeMutationRate = glui->add_spinner_to_panel( preyMutationRatePanel, "Genome", GLUI_SPINNER_FLOAT, &System::PREY_GENOME_MUTATION_RATE, PREY_GENOME_MUTATION_RATE, control); preyGenomeMutationRate->set_int_limits(0.01, 1.0); GLUI_Spinner *preyDemiseAge = glui->add_spinner_to_panel( preyConfigPanel, "Demise Age", GLUI_SPINNER_INT, &System::PREY_DEMISE_AGE, PREY_DEMISE_AGE, control); preyDemiseAge->set_int_limits(100, 10000); glui->add_column_to_panel(runtimePanel, true); // Predator Runtime configuration panel GLUI_Panel *predatorConfigPanel = glui->add_panel_to_panel(runtimePanel, "Predator Configuration"); GLUI_Panel *predatorReprodConfigPanel = glui->add_panel_to_panel(predatorConfigPanel, "Reproduction"); GLUI_Spinner *predatorReproductionAgeLimit = glui->add_spinner_to_panel( predatorReprodConfigPanel, "Age Limit", GLUI_SPINNER_INT, &System::PREDATOR_REPRODUCTION_AGE_LIMIT, PREDATOR_REPRODUCTION_AGE_LIMIT, control); predatorReproductionAgeLimit->set_int_limits(100, 10000); GLUI_Spinner *predatorReproductionInterval = glui->add_spinner_to_panel( predatorReprodConfigPanel, "Interval", GLUI_SPINNER_INT, &System::PREDATOR_REPRODUCTION_INTERVAL, PREDATOR_REPRODUCTION_INTERVAL, control); predatorReproductionInterval->set_int_limits(100, 10000); GLUI_Panel *hopfieldNetworkConfg = glui->add_panel_to_panel(predatorConfigPanel, "Memory Configurations"); GLUI_Spinner *predatorMinMemorySize = glui->add_spinner_to_panel( hopfieldNetworkConfg, "Minimum", GLUI_SPINNER_INT, &System::MIN_MEMORY_SIZE, MIN_MEMORY_SIZE, control); predatorMinMemorySize->set_int_limits(1, 20); GLUI_Spinner *predatorMaxMemorySize = glui->add_spinner_to_panel( hopfieldNetworkConfg, "Maximum", GLUI_SPINNER_INT, &System::MAX_MEMORY_SIZE, MAX_MEMORY_SIZE, control); predatorMaxMemorySize->set_int_limits(2, 20); GLUI_Spinner *predatorGenomeMutationRate = glui->add_spinner_to_panel( predatorConfigPanel, "Mutation Rate", GLUI_SPINNER_FLOAT, &System::PREDATOR_GENOME_MUTATION_RATE, PREDATOR_GENOME_MUTATION_RATE, control); predatorGenomeMutationRate->set_int_limits(0.01, 1.0); GLUI_Spinner *predatorDemiseAge = glui->add_spinner_to_panel( predatorConfigPanel, "Demise Age", GLUI_SPINNER_INT, &System::PREDATOR_DEMISE_AGE, PREDATOR_DEMISE_AGE, control); predatorDemiseAge->set_int_limits(100, 10000); glui->add_column(true); // Model view panel GLUI_Panel *modelViewPanel = glui->add_panel("Model view"); ctlRot = glui->add_rotation_to_panel(modelViewPanel, "Orientation", gluiRotation); //glui->add_column_to_panel(modelViewPanel, true); GLUI_Translation *ctlTranslateXY = glui->add_translation_to_panel( modelViewPanel, "XY position", GLUI_TRANSLATION_XY, gluiPosition); //glui->add_column_to_panel(modelViewPanel, true); GLUI_Translation *ctlTranslateZ = glui->add_translation_to_panel( modelViewPanel, "Zoom", GLUI_TRANSLATION_Z, &gluiPosition[2], ZOOM, control); glui->add_separator_to_panel(modelViewPanel); glui->add_button_to_panel(modelViewPanel, "Reset view", RESET, control); glui->add_checkbox_to_panel(modelViewPanel, "Update model", &updateModel); glui->add_checkbox_to_panel(modelViewPanel, "Update statistics", &updateStats); // Run-time controls panel GLUI_Panel *controlsPanel = glui->add_panel("Runtime Controls"); // View Selection panel GLUI_Panel *viewSelectionPanel = glui->add_panel_to_panel(controlsPanel, "View Selection"); glui->add_checkbox_to_panel(viewSelectionPanel, "Outline", &System::showOutline); glui->add_checkbox_to_panel(viewSelectionPanel, "View Cells", &System::showCells); // Reports panel GLUI_Panel *reportPanel = glui->add_panel_to_panel(controlsPanel, "Reports"); glui->add_button_to_panel(reportPanel, "Rings", RING_REPORT, control); ctlTranslateXY->set_speed(0.1); ctlTranslateZ->set_speed(0.1); /* display callback invoked when window opened */ glutMainLoop(); /* enter event loop */ return 0; }
int main (int argc, char** argv) { // Standard stuff... glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGBA|GLUT_DOUBLE|GLUT_DEPTH); glutInitWindowSize(800, 600); glutCreateWindow("Diffuse Lighting"); glutReshapeFunc(changeViewport); glutDisplayFunc(render); glewInit(); initMatrices(); // Make a shader char* vertexShaderSourceCode = readFile("vertexShader.vsh"); char* fragmentShaderSourceCode = readFile("fragmentShader.fsh"); GLuint vertShaderID = makeVertexShader(vertexShaderSourceCode); GLuint fragShaderID = makeFragmentShader(fragmentShaderSourceCode); shaderProgramID = makeShaderProgram(vertShaderID, fragShaderID); // Create the "remember all" glGenVertexArrays(1, &vao); glBindVertexArray(vao); glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); // Create the buffer, but don't load anything yet //glBufferData(GL_ARRAY_BUFFER, 7*NUM_VERTICES*sizeof(GLfloat), NULL, GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, 6*NUM_VERTICES*sizeof(GLfloat), NULL, GL_STATIC_DRAW); // NEW!! - We're only loading vertices and normals (6 elements, not 7) // Load the vertex points glBufferSubData(GL_ARRAY_BUFFER, 0, 3*NUM_VERTICES*sizeof(GLfloat), vertices); // Load the colors right after that //glBufferSubData(GL_ARRAY_BUFFER, 3*NUM_VERTICES*sizeof(GLfloat),4*NUM_VERTICES*sizeof(GLfloat), colors); glBufferSubData(GL_ARRAY_BUFFER, 3*NUM_VERTICES*sizeof(GLfloat),3*NUM_VERTICES*sizeof(GLfloat), normals); #ifdef USING_INDEX_BUFFER glGenBuffers(1, &indexBufferID); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferID); glBufferData(GL_ELEMENT_ARRAY_BUFFER, NUM_INDICES*sizeof(GLuint), indices, GL_STATIC_DRAW); #endif // Find the position of the variables in the shader positionID = glGetAttribLocation(shaderProgramID, "s_vPosition"); normalID = glGetAttribLocation(shaderProgramID, "s_vNormal"); lightID = glGetUniformLocation(shaderProgramID, "vLight"); // NEW // ============ glUniformLocation is how you pull IDs for uniform variables=============== perspectiveMatrixID = glGetUniformLocation(shaderProgramID, "mP"); viewMatrixID = glGetUniformLocation(shaderProgramID, "mV"); modelMatrixID = glGetUniformLocation(shaderProgramID, "mM"); allRotsMatrixID = glGetUniformLocation(shaderProgramID, "mRotations"); // NEW //============================================================================================= glVertexAttribPointer(positionID, 3, GL_FLOAT, GL_FALSE, 0, 0); //glVertexAttribPointer(colorID, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(sizeof(vertices))); glVertexAttribPointer(normalID, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(sizeof(vertices))); glUseProgram(shaderProgramID); glEnableVertexAttribArray(positionID); glEnableVertexAttribArray(normalID); glEnable(GL_CULL_FACE); // NEW! - we're doing real 3D now... Cull (don't render) the backsides of triangles glCullFace(GL_BACK); // Other options? GL_FRONT and GL_FRONT_AND_BACK glEnable(GL_DEPTH_TEST);// Make sure the depth buffer is on. As you draw a pixel, update the screen only if it's closer than previous ones glutMainLoop(); return 0; }
main(int argc, char *argv[]) { GLuint *tex; int texwid, texht, texcomps; GLUquadricObj *quadric; glutInitWindowSize(winWidth, winHeight); glutInit(&argc, argv); if(argc > 1) { char *args = argv[1]; int done = FALSE; while(!done) { switch(*args) { case 's': /* single buffer */ printf("Single Buffered\n"); dblbuf = FALSE; break; case '-': /* do nothing */ break; case 0: done = TRUE; break; } args++; } } if(dblbuf) glutInitDisplayMode(GLUT_RGBA|GLUT_DEPTH|GLUT_DOUBLE); else glutInitDisplayMode(GLUT_RGBA|GLUT_DEPTH); (void)glutCreateWindow("example program"); glutDisplayFunc(redraw_original); glutReshapeFunc(reshape); glutMouseFunc(mouse); glutMotionFunc(motion); glutKeyboardFunc(key); /* draw a perspective scene */ glMatrixMode(GL_PROJECTION); glFrustum(-100., 100., -100., 100., 300., 600.); glMatrixMode(GL_MODELVIEW); /* look at scene from (0, 0, 450) */ gluLookAt(0., 0., 450., 0., 0., 0., 0., 1., 0.); /* turn on features */ glEnable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_2D); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP); glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP); glMateriali(GL_FRONT, GL_SHININESS, 128); /* cosine power */ /* remove back faces to speed things up */ glCullFace(GL_BACK); glBlendFunc(GL_ONE, GL_ONE); lightchanged[UPDATE_TEX] = GL_TRUE; lightchanged[UPDATE_OGL] = GL_TRUE; /* load pattern for current 2d texture */ tex = read_texture("../data/wood.rgb", &texwid, &texht, &texcomps); gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, texwid, texht, GL_RGBA, GL_UNSIGNED_BYTE, tex); free(tex); CHECK_ERROR("end of main"); lighttex = (GLfloat *)malloc(texdim * texdim * sizeof(GL_FLOAT) * 3); /* XXX TODO use display list to avoid retesselating */ glNewList(1, GL_COMPILE); glutSolidSphere((GLdouble)texdim/2., 50, 50); glEndList(); glNewList(2, GL_COMPILE); glutSolidTeapot(70.); glEndList(); quadric = gluNewQuadric(); gluQuadricTexture(quadric, GL_TRUE); glNewList(3, GL_COMPILE); gluSphere(quadric, 70., 20, 20); glEndList(); gluDeleteQuadric(quadric); maxobject = 3; glutMainLoop(); return 0; }
void setup(int argc, char *argv[]) { // Put the file paths back to a flatter system because I do not know if // Windows will barf at the forward slashes and I do not have time to make this // code check which OS it's using. // char temp[256]; // string vertFileName(getcwd(temp, 255)); // string fragFileName(getcwd(temp, 255)); // vertFileName.append("/source/sample2d.vert"); // fragFileName.append("/source/sample2d.frag"); string vertFileName("sample3d.vert"); string fragFileName("sample3d.frag"); tx = ty = tz = axis = 0.0; glutInit( &argc, argv ); glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH ); glutInitWindowSize( 800, 600 ); glutCreateWindow( "Craig McCulloch's Project 4" ); // Resolves which OpenGL extensions are supported by hardware if( glewInit() != GLEW_OK ) { cerr << "Error reported by glewInit" << endl; exit(1); } // Orthographic projection // Projection glMatrixMode( GL_PROJECTION ); glLoadIdentity(); gluPerspective( fov, aspect, nearClip, farClip ); gluLookAt(1.7, 1.5, 2.3, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 ); // Viewing glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); glTranslatef(-0.5, -0.5, -0.7); // Specify 3D RGBA texture glPixelStorei( GL_UNPACK_ALIGNMENT, 1 ); glGenTextures( (unsigned int)1, (unsigned int *)&texName ); glBindTexture( (unsigned int)GL_TEXTURE_3D, (unsigned int)texName ); glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE ); glTexParameteri( GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexImage3D( GL_TEXTURE_3D, 0, GL_RGBA, dr->getX(), dr->getY(), dr->getZ(), 0, GL_RGBA, GL_UNSIGNED_BYTE, texels ); // Create shader program shaderProgram1 = CreateProgram( vertFileName.c_str(), fragFileName.c_str() ); // Locate address of shader sampler variable TexUnitLocation = glGetUniformLocation( shaderProgram1, "TexUnit" ); // Assign sampler variable value texture unit 0 glUniform1i( TexUnitLocation, TexUnit ); // Callbacks glutDisplayFunc( myDraw ); glutKeyboardFunc( keyboard ); glutSpecialFunc( specialKeyFunc ); glutCreateMenu( menu ); glutAddMenuEntry( "View XY plane (or 'z' key)", 0 ); glutAddMenuEntry( "View XZ plane (or 'y' key)", 1 ); glutAddMenuEntry( "View YZ plane (or 'x' key)", 2 ); glutAddMenuEntry( "Quit (or 'q' key)", 3 ); glutAttachMenu( GLUT_RIGHT_BUTTON ); showMenu(); // Main loop glutMainLoop(); }
int main(int argc, char** argv) { image = glmReadPPM((char*)"../textures/fishermen.ppm", &iwidth, &iheight); if (!image) exit(0); glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE); glutInitWindowSize((512+GAP*3)*3/2, 512+GAP*3); glutInitWindowPosition(50, 50); glutInit(&argc, argv); window = glutCreateWindow("Texture"); glutReshapeFunc(main_reshape); glutDisplayFunc(main_display); glutKeyboardFunc(main_keyboard); world = glutCreateSubWindow(window, GAP, GAP, 256, 256); glutReshapeFunc(world_reshape); glutDisplayFunc(world_display); glutKeyboardFunc(main_keyboard); glutCreateMenu(world_menu); glutAddMenuEntry("Textures", 0); glutAddMenuEntry("", 0); glutAddMenuEntry("Fishermen", 'f'); glutAddMenuEntry("OpenGL Logo", 'o'); glutAddMenuEntry("Checker", 'c'); glutAddMenuEntry("Marble", 'm'); glutAddMenuEntry("Train", 't'); glutAttachMenu(GLUT_RIGHT_BUTTON); texture(); screen = glutCreateSubWindow(window, GAP+256+GAP, GAP, 256, 256); glutReshapeFunc(screen_reshape); glutDisplayFunc(screen_display); glutKeyboardFunc(main_keyboard); glutMotionFunc(screen_motion); glutMouseFunc(screen_mouse); texture(); command = glutCreateSubWindow(window, GAP+256+GAP, GAP+256+GAP, 256, 256); glutReshapeFunc(command_reshape); glutMotionFunc(command_motion); glutDisplayFunc(parameters_display); glutMouseFunc(parameters_mouse); glutKeyboardFunc(main_keyboard); glutCreateMenu(command_menu); glutAddMenuEntry("Texture", 0); glutAddMenuEntry("", 0); glutAddMenuEntry("Matrix", 'm'); glutAddMenuEntry("Environment/Parameters", 'p'); glutAddMenuEntry("Reset parameters (r)", 'r'); glutAddMenuEntry("", 0); glutAddMenuEntry("Quit", 27); glutAttachMenu(GLUT_RIGHT_BUTTON); redisplay_all(); glutTimerFunc(500, timer, 0); glutMainLoop(); return 0; }
//------------------------------------------------------------------------------ void npInitGlut (int argc, char **argv, void* dataRef) { GLboolean stereoSupport = false; int depth = 0; int result = 0; int gMainWindow = 0; char msg[256]; pData data = (pData) dataRef; pNPgl gl = &data->io.gl; // init glut app framework glutInit (&argc, argv); //zz debug stereo3D not yet supported on OSX //zz debug move OS specific code to npos.h ? nposPostFramework() #ifndef NP_OSX_ sprintf (msg, "freeglut ver: %d", glutGet(GLUT_VERSION)); npPostMsg (msg, kNPmsgCtrl, data); glGetBooleanv (GL_STEREO, (GLboolean*)&gl->stereo3D); #else npPostMsg ("Apple GLUT", kNPmsgCtrl, data); gl->stereo3D = false; #endif if (gl->stereo3D) sprintf (msg, "OpenGL Stereo 3D: YES"); else sprintf (msg, "OpenGL Stereo 3D: NO"); npPostMsg (msg, kNPmsgCtrl, data); /// OpenGL stereo 3D is ONLY supported by Quadro and AMD Fire Pro if (gl->stereo3D) glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH | GLUT_STEREO); else glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowPosition (gl->position.x, gl->position.y); glutInitWindowSize (gl->windowSize.x, gl->windowSize.y); gl->windowID = glutCreateWindow (gl->name); glutSetWindow (gl->windowID); //S3D glutHideWindow(); //S3D //zz stereo 3D and GameMode stripped out on 2016-07-03 /// register keyboard, mouse and display events with GLUT npGlutEventFuncs(); /// init OpenGL npInitGL (dataRef); /// show the window glutShowWindow (); if (gl->fullscreen) { npPostMsg ("FullScreen Window", kNPmsgCtrl, data); glutFullScreen (); } /// System Ready... data->ctrl.startup = false; npPostMsg( "www.openANTz.com", kNPmsgCtrl, data); npPostMsg( "System Ready...", kNPmsgCtrl, data); npPostMsg( data->map.startupMsg, kNPmsgCtrl, data); }
int main(int argc, char **argv) { #ifdef WIN32 SetPriorityClass( GetCurrentProcess(), REALTIME_PRIORITY_CLASS ); //! set priority to windows #endif if (argc<2) { cout << "Usage : roadtrac [image file] [titlefile] [annotationfile]" << endl; cout << "exp : roadtrac template.jpg [label.txt] [annotations.txt]" << endl; exit(0); } else { char paperlist[100]; sprintf_s(paperlist,100, "paperlist.%s.txt", argv[1]); ifstream paperfile(paperlist); if (!paperfile) //if doesnt exist { IplImage *templ = cvLoadImage(argv[1]); reg.ExtractRegions(templ); m_tracker.CreateBlobSeq(®); m_tracker.SaveBlobSeq(paperlist); reg.Clear(); m_tracker.Clear(); } m_tracker.LoadBlobSeq(paperlist); if (argv[2]) m_tracker.LoadBlobName(argv[2]); if (argv[3]) m_tracker.LoadBlobLabels(argv[3]); } cap = cvCaptureFromCAM(CAMERAID); cvSetCaptureProperty(cap,CV_CAP_PROP_FRAME_WIDTH, IMG_WIDTH); cvSetCaptureProperty(cap,CV_CAP_PROP_FRAME_HEIGHT, IMG_HEIGHT); if (!cap) return 0; glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE| GLUT_RGBA | GLUT_DEPTH | GLUT_MULTISAMPLE); glutInitWindowPosition(100, 100); glutInitWindowSize(IMG_WIDTH, IMG_HEIGHT); if (argv[1]) wid = glutCreateWindow(argv[1]); else wid = glutCreateWindow("RoadTrac"); texture = new GLuint[1]; glGenTextures(1, texture); glBindTexture(GL_TEXTURE_2D, texture[0]); glPixelStorei(GL_UNPACK_ALIGNMENT, 4); 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); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, FRAMESIZE, FRAMESIZE, 0, GL_BGR_EXT, GL_UNSIGNED_BYTE, 0); glutReshapeFunc(resize); glutDisplayFunc(display); m_text.t3dInit(DATA_CHARSET); glutIdleFunc(idle); glutKeyboardFunc(keyboard); setprojection(); if (LIGHT) setlight(); glutMainLoop(); close(); return 0; }
void SimulatorSingleton::run_sim() { int argc = 0; char *argv[1]; unsigned width, height; read_common_mv_setting ("IMG_WIDTH_COMMON", width); read_common_mv_setting ("IMG_HEIGHT_COMMON", height); glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_DEPTH | GLUT_RGB | GLUT_DOUBLE); glutInitWindowSize (width, height); glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION); glutInitWindowPosition(10, 0); dwn_window = glutCreateWindow ("Down Cam"); glutPositionWindow(0, 400); glutReshapeFunc (::sim_reshape); glutDisplayFunc (::sim_display); glutIdleFunc (::sim_idle); glutKeyboardFunc (::sim_keyboard); glutCloseFunc (::sim_close_window); init_sim(); fwd_window = glutCreateWindow ("Forwards Cam"); glutReshapeFunc (::sim_reshape); glutDisplayFunc (::sim_display); glutIdleFunc (::sim_idle); glutKeyboardFunc (::sim_keyboard); glutCloseFunc (::sim_close_window); init_sim(); img_fwd = cvCreateImage (cvSize(width,height), IPL_DEPTH_8U, 3); img_dwn = cvCreateImage (cvSize(width,height), IPL_DEPTH_8U, 3); // set initial position std::string start_at; read_mv_setting(SIM_SETTINGS_FILE, "START_AT", start_at); float start_x = 0.f; float start_y = 0.f; float start_z = 0.f; float start_yaw = 0.f; if (start_at == "GATE") { start_x = -3.f; start_y = 7.5f; start_z = 16.f; } else if (start_at == "BUOY") { start_x = -3.3f; start_y = 4.5f; start_z = 3.f; start_yaw = 18.f; } else if (start_at == "GOALPOST") { start_x = 1.f; start_y = 2.5f; start_z = -4.2f; start_yaw = 80.f; } else if (start_at == "MULTIPATH") { start_x = 7.f; start_y = 2.5f; start_z = -5.f; start_yaw = 80.f; } else if (start_at == "TORPEDO_TARGET") { start_x = 10.1f; start_y = 2.35f; start_z = -1.9f; start_yaw = -170.f; } else if (start_at == "MARKER_DROPPER") { start_x = 10.8f; start_y = 2.5f; start_z = -7.1f; start_yaw = -4.f; } model.position.x = start_x; model.position.y = start_y; model.position.z = start_z; model.angle.yaw = start_yaw; set_target_depth(POOL_HEIGHT - start_y); set_target_yaw(start_yaw); // Sim has initialized sem_post(&sema); glutMainLoop(); }
/*!***************************************************************************** ******************************************************************************* \note initOscWindow \date May 2010 \remarks initializes the oscilloscope window ******************************************************************************* Function Parameters: [in]=input,[out]=output none ******************************************************************************/ int initOscWindow(void) { int i,j; int x = 600; int y = 20; int width = 600; int height = 400; char string[100]; char xstring[100]; Display *disp; int screen_num; int display_width; int display_height; double aux; // is the oscilloscope enabled? if (read_parameter_pool_int(config_files[PARAMETERPOOL],"osc_enabled", &i)) osc_enabled = macro_sign(abs(i)); if (!osc_enabled) return TRUE; // how many oscilloscope graphs? if (read_parameter_pool_int(config_files[PARAMETERPOOL],"n_osc_plots", &i)) { if (i > 0) n_oscilloscope_plots = i; } // #periods of oscilloscope A/D plot if (read_parameter_pool_int(config_files[PARAMETERPOOL],"osc_periods_ad", &i)) { if (i > 0) periods_window_AD = i; } // window size of variable display if (read_parameter_pool_double(config_files[PARAMETERPOOL],"osc_time_window_vars", &aux)) { if (aux > 0) time_window_vars = aux; } // allocate memory for the plots and initialize osc_data = (OscData *) my_calloc(n_oscilloscope_plots+1,sizeof(OscData),MY_STOP); for (i=0; i<=n_oscilloscope_plots; ++i) { for (j=1; j<=MAX_VARS_PER_PLOT; ++j) { osc_data[i].current_index[j] = 1; } osc_data[i].max = -1.e10; osc_data[i].min = 1.e10; } // connect to X server using the DISPLAY environment variable if ( (disp=XOpenDisplay(NULL)) == NULL ) { printf("Cannot connect to X servo %s\n",XDisplayName(NULL)); exit(-1); } // get screen size from display structure macro screen_num = DefaultScreen(disp); display_width = DisplayWidth(disp, screen_num); display_height = DisplayHeight(disp, screen_num); // overwrite the default window options from ParameterPool.cf if (read_parameter_pool_string(config_files[PARAMETERPOOL], "osc_window_geometry", string)) parseWindowSpecs(string, display_width,display_height,xstring, &x, &y, &width, &height); // create the window glutInitWindowPosition(x,y); glutInitWindowSize(width,height); openGLId_osc = glutCreateWindow("Oscilloscope"); // makes window current, too // attach appropriate OpenGL functions to the current window glutDisplayFunc(osc_display); glutReshapeFunc(osc_reshape); /* glutIdleFunc(idle); glutKeyboardFunc(keyboard); glutMouseFunc(mouse); glutMotionFunc(motion); glutSpecialFunc(special); glutMenu(wptr); */ return TRUE; }
int main(int ac, char **av) { float fogcolor[4]={0.025,0.025,0.025,1.0}; fprintf(stderr,"Teapot V1.2\nWritten by David Bucciarelli ([email protected])\n"); /* if(!SetPriorityClass(GetCurrentProcess(),REALTIME_PRIORITY_CLASS)) { fprintf(stderr,"Error setting the process class.\n"); return 0; } if(!SetThreadPriority(GetCurrentThread(),THREAD_PRIORITY_TIME_CRITICAL)) { fprintf(stderr,"Error setting the process priority.\n"); return 0; } */ glutInitWindowPosition(0,0); glutInitWindowSize(WIDTH,HEIGHT); glutInit(&ac,av); glutInitDisplayMode(GLUT_RGB|GLUT_DEPTH|GLUT_DOUBLE); glutCreateWindow("Teapot"); reshape(WIDTH,HEIGHT); glShadeModel(GL_SMOOTH); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glEnable(GL_TEXTURE_2D); glEnable(GL_FOG); glFogi(GL_FOG_MODE,GL_EXP2); glFogfv(GL_FOG_COLOR,fogcolor); glFogf(GL_FOG_DENSITY,0.04); #ifdef FX glHint(GL_FOG_HINT,GL_NICEST); #endif glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); calcposobs(); inittextures(); initlight(); #ifndef FX glDisable(GL_TEXTURE_2D); usetex=0; #endif initdlists(); glClearColor(fogcolor[0],fogcolor[1],fogcolor[2],fogcolor[3]); glutReshapeFunc(reshape); glutDisplayFunc(draw); glutKeyboardFunc(key); glutSpecialFunc(special); glutIdleFunc(draw); glutMainLoop(); return 0; /* ANSI C requires main to return int. */ }