Exemplo n.º 1
1
int main( int argc, char *argv[] )
{
   glutInit( &argc, argv );
   glutInitWindowPosition( 200, 200 );
   glutInitWindowSize( 800, 500 );
   glutInitDisplayMode( GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH );
   glutCreateWindow("World of Awesome");
   glutReshapeFunc( ReshapeGL );
   glutDisplayFunc( Draw );
   glutKeyboardFunc( keyboard );
   glutMouseFunc( mouse );
   glutMotionFunc( mouseMove );
   glutPassiveMotionFunc( passiveMove );
   glutTimerFunc(TIMER_DELAY, tock, 0);

   g_width = g_height = 200;

#ifdef _WIN32 
   GLenum err = glewInit();
   if (GLEW_OK != err)
   {
      std::cerr << "Error initializing glew! " << glewGetErrorString(err) << std::endl;
      return 1;
   }
#endif
#ifdef __APPLE__
   glutSetCursor(GLUT_CURSOR_NONE); 
#endif

   backShade = glm::vec3(0.2,0.5,0.9);

   Initialize();
   
   //test the openGL version
   getGLversion();
   //install the shader
   if (!InstallShader(textFileRead((char *)"shaders/vert.glsl"), textFileRead((char *)"shaders/frag.glsl")))   {
      printf("Error installing shader!\n");
      return 0;
   }

   InitGeom();


   g_shadeType = PHONG;

   g_pitch = 0;
   g_yaw = M_PI / 2;
   float tx = cos(g_pitch)*cos(g_yaw);
   float ty = sin(g_pitch);
   float tz = cos(g_pitch)*cos(M_PI/2 - g_yaw);
   eye = glm::vec3(0, 2.5, 0);
   target = eye + glm::vec3(tx, ty, tz);
   sunDir = normalize(vec3(-0.2, -1.0, 0.0));


   sunShade = glm::vec3(1.0, 1.0, 0.9);

   glutMainLoop();
   return 0;
}
Exemplo n.º 2
0
int main( int argc, char **argv )
{
	// Parse the arguments
	if (argc < 3) {
		printf("Missing arguments ... use:\n");
		printf("./raycast [-u | -d] step_max <options>\n");
		return -1;
	}
	
	if (strcmp(argv[1], "-u") == 0) {  // user defined scene
		set_up_user_scene();
	} else { // default scene
		set_up_default_scene();
	}

	step_max = atoi(argv[2]); // maximum level of recursions

	// Optional arguments
	for(int i = 3; i < argc; i++)
	{
		if (strcmp(argv[i], "+s") == 0)	shadow_on = 1;
		if (strcmp(argv[i], "+l") == 0) reflect_on = 1;
		if (strcmp(argv[i], "+c") == 0) chessboard_on = 1;
		if (strcmp(argv[i], "+r") == 0) refract_on = 1;
		if (strcmp(argv[i], "+f") == 0) difref_on = 1;
		if (strcmp(argv[i], "+p") == 0) antiAlias_on = 1;
	}

	if(chessboard_on)
		set_up_chessboard();

	//printObjects();

	// ray trace the scene now
	// we have used so many global variables and this function is
	// happy to carry no parameters	
	printf("Rendering scene using my fantastic ray tracer ...\n");
	ray_trace();
	printf("After ray trace\n");

	// we want to make sure that intensity values are normalized
	histogram_normalization();

	// Show the result in glut via texture mapping
	glutInit( &argc, argv );
	glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE );
	glutInitWindowSize( WIN_WIDTH, WIN_HEIGHT );
	glutCreateWindow( "Ray tracing" );
	glewInit();

	#ifndef __NO_DISPLAY__
	init();
	#endif
	printf("After init\n");

	glutDisplayFunc( display );
	glutKeyboardFunc( keyboard );
	glutMainLoop();

	return 0;
}
int main(int argc, char** argv)
{
	if (argc != 7) {
        printf("%d", argc);
        for (int i = 0; i < argc; i++) {
            printf("%s\n", argv[i]);
        }
		usage();
    }

	vertexShader   = std::string(argv[1]);
	fragmentShader = std::string(argv[2]);
    meshOBJ        = std::string(argv[3]);
	normalMap      = std::string(argv[4]);
	displacementMap      = std::string(argv[5]);
	colorMap       =std::string(argv[6]);

    //
    // Initialize GLUT.
    //
    glutInit(&argc, argv);
    glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
    glutInitWindowPosition(20, 20);
    glutInitWindowSize(640, 480);
    glutCreateWindow("CS148 Texturing");
    
    //
    // Initialize GLEW.
    //
#ifndef __APPLE__
    glewInit();
    if(!GLEW_VERSION_2_0) {
        printf("Your graphics card or graphics driver does\n"
			   "\tnot support OpenGL 2.0, trying ARB extensions\n");

        if(!GLEW_ARB_vertex_shader || !GLEW_ARB_fragment_shader) {
            printf("ARB extensions don't work either.\n");
            printf("\tYou can try updating your graphics drivers.\n"
				   "\tIf that does not work, you will have to find\n");
            printf("\ta machine with a newer graphics card.\n");
            exit(1);
        }
    }
#endif

    // Be sure to initialize GLUT (and GLEW for this assignment) before
    // initializing your application.

    Setup();

    glutDisplayFunc(DisplayCallback);
    glutReshapeFunc(ReshapeCallback);
    glutSpecialFunc(SpecialKeyCallback);
    glutKeyboardFunc(KeyCallback);
    glutMouseFunc(MouseCallback);
    glutMotionFunc(MouseMotionCallback);
    glutIdleFunc(DisplayCallback);

    glutMainLoop();

    // Cleanup code should be called here.
    CleanUp();

    return 0;
}
Exemplo n.º 4
0
int
main(int argc, char *argv[])
{

//////////////////////////////////////////// by Chenyi 
    struct shared_use_st *shared = NULL;
    int shmid;  
    // establish memory sharing 
    shmid = shmget((key_t)4567, sizeof(struct shared_use_st), 0666|IPC_CREAT);  
    if(shmid == -1)  
    {  
        fprintf(stderr, "shmget failed\n");  
        exit(EXIT_FAILURE);  
    }  
  
    shm = shmat(shmid, 0, 0);  
    if(shm == (void*)-1)  
    {  
        fprintf(stderr, "shmat failed\n");  
        exit(EXIT_FAILURE);  
    }  
    printf("\n********** Memory sharing started, attached at %X **********\n \n", shm);  
    // set up shared memory 
    shared = (struct shared_use_st*)shm;  
    shared->written = 0;
    shared->control = 0;
    shared->pause = 0;
    shared->fast = 0.0;

    shared->dist_L = 0.0;
    shared->dist_R = 0.0;

    shared->toMarking_L = 0.0;
    shared->toMarking_M = 0.0;
    shared->toMarking_R = 0.0;

    shared->dist_LL = 0.0;
    shared->dist_MM = 0.0;
    shared->dist_RR = 0.0;

    shared->toMarking_LL = 0.0;
    shared->toMarking_ML = 0.0;
    shared->toMarking_MR = 0.0;
    shared->toMarking_RR = 0.0;

    shared->toMiddle = 0.0;
    shared->angle = 0.0;
    shared->speed = 0.0;

    shared->steerCmd = 0.0;
    shared->accelCmd = 0.0;
    shared->brakeCmd = 0.0;

    pwritten=&shared->written;
    pdata=shared->data;
    pcontrol=&shared->control;
    ppause=&shared->pause;

    psteerCmd_ghost=&shared->steerCmd;
    paccelCmd_ghost=&shared->accelCmd;
    pbrakeCmd_ghost=&shared->brakeCmd;

    pspeed_ghost=&shared->speed;
    ptoMiddle_ghost=&shared->toMiddle;
    pangle_ghost=&shared->angle;

    pfast_ghost=&shared->fast;

    pdist_L_ghost=&shared->dist_L;
    pdist_R_ghost=&shared->dist_R;

    ptoMarking_L_ghost=&shared->toMarking_L;
    ptoMarking_M_ghost=&shared->toMarking_M;
    ptoMarking_R_ghost=&shared->toMarking_R;

    pdist_LL_ghost=&shared->dist_LL;
    pdist_MM_ghost=&shared->dist_MM;
    pdist_RR_ghost=&shared->dist_RR;

    ptoMarking_LL_ghost=&shared->toMarking_LL;
    ptoMarking_ML_ghost=&shared->toMarking_ML;
    ptoMarking_MR_ghost=&shared->toMarking_MR;
    ptoMarking_RR_ghost=&shared->toMarking_RR;
/////////////////////////////////////////// by Chenyi

	const char *raceconfig = "";

	init_args(argc, argv, &raceconfig);
	LinuxSpecInit();			/* init specific linux functions */

	if(strlen(raceconfig) == 0) {
		GfScrInit(argc, argv);	/* init screen */
		TorcsEntry();			/* launch TORCS */
		glutMainLoop();			/* event loop of glut */
	} else {
		// Run race from console, no Window, no OpenGL/OpenAL etc.
		// Thought for blind scripted AI training
		ReRunRaceOnConsole(raceconfig);
	}

	return 0;					/* just for the compiler, never reached */
}
Exemplo n.º 5
0
int main(int argc, char *argv[])
{
	elf_firmware_t f;
	const char * fname =  "atmega168_timer_64led.axf";
	//char path[256];

//	sprintf(path, "%s/%s", dirname(argv[0]), fname);
	//printf("Firmware pathname is %s\n", path);
	elf_read_firmware(fname, &f);

	printf("firmware %s f=%d mmcu=%s\n", fname, (int)f.frequency, f.mmcu);

	avr = avr_make_mcu_by_name(f.mmcu);
	if (!avr) {
		fprintf(stderr, "%s: AVR '%s' now known\n", argv[0], f.mmcu);
		exit(1);
	}
	avr_init(avr);
	avr_load_firmware(avr, &f);

	//
	// initialize our 'peripherals'
	//
	hc595_init(avr, &shifter);
	
	button_init(avr, &button[B_START], "button.start");
	avr_connect_irq(
		button[B_START].irq + IRQ_BUTTON_OUT,
		avr_io_getirq(avr, AVR_IOCTL_IOPORT_GETIRQ('C'), 0));
	button_init(avr, &button[B_STOP], "button.stop");
	avr_connect_irq(
		button[B_STOP].irq + IRQ_BUTTON_OUT,
		avr_io_getirq(avr, AVR_IOCTL_IOPORT_GETIRQ('B'), 1));
	button_init(avr, &button[B_RESET], "button.reset");
	avr_connect_irq(
		button[B_RESET].irq + IRQ_BUTTON_OUT,
		avr_io_getirq(avr, AVR_IOCTL_IOPORT_GETIRQ('B'), 0));

	// connects the fake 74HC595 array to the pins
	avr_irq_t * i_mosi = avr_io_getirq(avr, AVR_IOCTL_SPI_GETIRQ(0), SPI_IRQ_OUTPUT),
			* i_reset = avr_io_getirq(avr, AVR_IOCTL_IOPORT_GETIRQ('D'), 4),
			* i_latch = avr_io_getirq(avr, AVR_IOCTL_IOPORT_GETIRQ('D'), 7);
	avr_connect_irq(i_mosi, shifter.irq + IRQ_HC595_SPI_BYTE_IN);
	avr_connect_irq(i_reset, shifter.irq + IRQ_HC595_IN_RESET);
	avr_connect_irq(i_latch, shifter.irq + IRQ_HC595_IN_LATCH);

	avr_irq_t * i_pwm = avr_io_getirq(avr, AVR_IOCTL_TIMER_GETIRQ('0'), TIMER_IRQ_OUT_PWM0);
	avr_irq_register_notify(
		i_pwm,
		pwm_changed_hook, 
		NULL);	
	avr_irq_register_notify(
		shifter.irq + IRQ_HC595_OUT,
		hc595_changed_hook, 
		NULL);

	// even if not setup at startup, activate gdb if crashing
	avr->gdb_port = 1234;
	if (0) {
		//avr->state = cpu_Stopped;
		avr_gdb_init(avr);
	}

	/*
	 *	VCD file initialization
	 *	
	 *	This will allow you to create a "wave" file and display it in gtkwave
	 *	Pressing "r" and "s" during the demo will start and stop recording
	 *	the pin changes
	 */
	avr_vcd_init(avr, "gtkwave_output.vcd", &vcd_file, 10000 /* usec */);

	avr_vcd_add_signal(&vcd_file, 
		avr_get_interrupt_irq(avr, 7), 1 /* bit */ ,
		"TIMER2_COMPA" );
	avr_vcd_add_signal(&vcd_file, 
		avr_get_interrupt_irq(avr, 17), 1 /* bit */ ,
		"SPI_INT" );
	avr_vcd_add_signal(&vcd_file, 
		i_mosi, 8 /* bits */ ,
		"MOSI" );

	avr_vcd_add_signal(&vcd_file, 
		i_reset, 1 /* bit */ ,
		"595_RESET" );
	avr_vcd_add_signal(&vcd_file, 
		i_latch, 1 /* bit */ ,
		"595_LATCH" );
	avr_vcd_add_signal(&vcd_file, 
		button[B_START].irq + IRQ_BUTTON_OUT, 1 /* bits */ ,
		"start" );
	avr_vcd_add_signal(&vcd_file, 
		button[B_STOP].irq + IRQ_BUTTON_OUT, 1 /* bits */ ,
		"stop" );
	avr_vcd_add_signal(&vcd_file, 
		button[B_RESET].irq + IRQ_BUTTON_OUT, 1 /* bits */ ,
		"reset" );

	avr_vcd_add_signal(&vcd_file, 
		shifter.irq + IRQ_HC595_OUT, 32 /* bits */ ,
		"HC595" );
	avr_vcd_add_signal(&vcd_file, 
		i_pwm, 8 /* bits */ ,
		"PWM" );

	// 'raise' it, it's a "pullup"
	avr_raise_irq(button[B_START].irq + IRQ_BUTTON_OUT, 1);
	avr_raise_irq(button[B_STOP].irq + IRQ_BUTTON_OUT, 1);
	avr_raise_irq(button[B_RESET].irq + IRQ_BUTTON_OUT, 1);

	printf( "Demo : This is a real world firmware, a 'stopwatch'\n"
			"   timer that can count up to 99 days. It features a PWM control of the\n"
			"   brightness, blinks the dots, displays the number of days spent and so on.\n\n"
			"   Press '0' to press the 'start' button\n"
			"   Press '1' to press the 'stop' button\n"
			"   Press '2' to press the 'reset' button\n"
			"   Press 'q' to quit\n\n"
			"   Press 'r' to start recording a 'wave' file - with a LOT of data\n"
			"   Press 's' to stop recording\n"
			"  + Make sure to watch the brightness dim once you stop the timer\n\n"
			);

	/*
	 * OpenGL init, can be ignored
	 */
	glutInit(&argc, argv);		/* initialize GLUT system */


	int w = 22, h = 8;
	
	glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
	glutInitWindowSize(w * pixsize, h * pixsize);		/* width=400pixels height=500pixels */
	window = glutCreateWindow("Press 0, 1, 2 or q");	/* create window */

	// Set up projection matrix
	glMatrixMode(GL_PROJECTION); // Select projection matrix
	glLoadIdentity(); // Start with an identity matrix
	glOrtho(0, w * pixsize, 0, h * pixsize, 0, 10);
	glScalef(1,-1,1);
	glTranslatef(0, -1 * h * pixsize, 0);

	glutDisplayFunc(displayCB);		/* set window's display callback */
	glutKeyboardFunc(keyCB);		/* set window's key callback */
	glutTimerFunc(1000 / 24, timerCB, 0);

	// the AVR run on it's own thread. it even allows for debugging!
	pthread_t run;
	pthread_create(&run, NULL, avr_run_thread, NULL);

	glutMainLoop();
}
Exemplo n.º 6
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;
}
Exemplo n.º 7
0
int main(int argc, char *argv[])
{        
    // Initialise OpenGL
    glutInit(&argc, argv); 

    // Set window position, size & create window
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
    glutInitWindowPosition(50,50);
    glutInitWindowSize(width,height);
	windowId = glutCreateWindow("Ray Cast Volume Rendering");
	
	glewInit();

    // Set GLUT callback functions
	glutDisplayFunc(renderScene);
	//glutIdleFunc(updateScene);
	glutKeyboardFunc(keypress);

    // Setup OpenGL state & scene resources 
    init();

	//GLUI
    glui = GLUI_Master.create_glui( "Controls", 0, 865, 50); 

	movement_panel = new GLUI_Panel( glui, "Movement Parameters" );
    
	view_rot = new GLUI_Rotation( movement_panel, "Rotate", view_rotate );
	view_rot->set_spin( 1.0 );

	trans_z = new GLUI_Translation( movement_panel, "Zoom", GLUI_TRANSLATION_Z, &zoom );
	trans_z->set_speed( .05 );

	raycastPGM = new GLUI_Checkbox(glui, "Raycast /w XToon & Alpha Interpolation", &raycastEnable, RAYCAST, controlCB);
	xtoonPGM = new GLUI_Checkbox(glui, "Raycast XToon Shader", &xtoonEnable, XTOONPGM, controlCB);
	gradientPGM = new GLUI_Checkbox(glui, "Gradient", &gradientEnable, GRADIENT, controlCB);
	dvrPGM = new GLUI_Checkbox(glui, "DVR", &dvrEnable, DVR, controlCB);
	rin = new GLUI_Checkbox(glui, "Show Ray Start", &rayinToggle, RAYIN, controlCB);
	rout = new GLUI_Checkbox(glui, "Show Ray Stop", &rayoutToggle, RAYOUT, controlCB);

	column_01 = new GLUI_Column( glui );

	GUIRayCastRoll = new GLUI_Rollout( glui, "Ray Cast Parameters", false);

	raycaster_panel = new GLUI_Panel( GUIRayCastRoll, "" );
	jittering = new GLUI_Checkbox( raycaster_panel, "Stippling", &j, JITTER, controlCB );
	jittering->set_alignment( GLUI_ALIGN_RIGHT );

    GUIsamples = new GLUI_Spinner( raycaster_panel, "N Samples", &nSamples );
	GUIsamples->set_int_limits( 0, 255 );
    GUIsamples->set_alignment( GLUI_ALIGN_RIGHT );

    GUInoise = new GLUI_Spinner( raycaster_panel, "Noise Delta", &noiseDelta );
	GUInoise->set_float_limits( 1.0, 10.0 );
    GUInoise->set_alignment( GLUI_ALIGN_RIGHT );

    GUIstep = new GLUI_Spinner( raycaster_panel, "Step Length", &stepLength );
	GUIstep->set_float_limits( 0.01f, 1.0f );
    GUIstep->set_alignment( GLUI_ALIGN_RIGHT );

    GUIt = new GLUI_Spinner( raycaster_panel, "Threshold", &threshold );
	GUIt->set_float_limits( 0.01f, 1.0f );
    GUIt->set_alignment( GLUI_ALIGN_RIGHT );

    GUIgscale = new GLUI_Spinner( raycaster_panel, "Gradient Scale", &gradientScale );
	GUIgscale->set_float_limits( 0.01f, 1.0f );
    GUIgscale->set_alignment( GLUI_ALIGN_RIGHT );

    GUIgdelta = new GLUI_Spinner( raycaster_panel, "Gradient Delta", &gradientDelta );
	GUIgdelta->set_float_limits( 0.01f, 1.0f );
    GUIgdelta->set_alignment( GLUI_ALIGN_RIGHT );

    GUIfmax = new GLUI_Spinner( raycaster_panel, "Histogram (Alpha) Max", &fMax );
	GUIfmax->set_float_limits( 0.01f, 255.0f );
    GUIfmax->set_alignment( GLUI_ALIGN_RIGHT );

    GUIfmin = new GLUI_Spinner( raycaster_panel, "Histogram (Alpha) Min", &fMin );
	GUIfmin->set_float_limits( 0.0f, 255.0f );
    GUIfmin->set_alignment( GLUI_ALIGN_RIGHT );

    GUIalpha = new GLUI_Spinner( raycaster_panel, "Alpha Value", &alpha );
	GUIalpha->set_float_limits( 0.01f, 1.0f );
    GUIalpha->set_alignment( GLUI_ALIGN_RIGHT );

    GUItscale = new GLUI_Spinner( raycaster_panel, "Transfer Scale", &transferScale );
	GUItscale->set_float_limits( 0.01f, 1.0f );
    GUItscale->set_alignment( GLUI_ALIGN_RIGHT );

    GUIthick = new GLUI_Spinner( raycaster_panel, "Thickness", &thickness );
	GUIthick->set_float_limits( 0.01f, 1.0f );
    GUIthick->set_alignment( GLUI_ALIGN_RIGHT );

	GUIXToonRoll = new GLUI_Rollout( glui, "XTOON Parameters", false );
	
	xtoon_panel = new GLUI_Panel( GUIXToonRoll, "" );

	toneDetailBox = new GLUI_Checkbox(xtoon_panel, "Tone Detail", &toneDetail, XTOONTYPE, controlCB );

    GUIr = new GLUI_Spinner( xtoon_panel, "Coarse Detail", &R );
	GUIr->set_float_limits( 1.0f, 25.0f );
    GUIr->set_alignment( GLUI_ALIGN_RIGHT );

	backlightBOX = new GLUI_Checkbox(xtoon_panel, "Backlighting", &backlight, XTOONTYPE, controlCB );

    GUIR = new GLUI_Spinner( xtoon_panel, "Backlight Detail", &backlight_detail );
	GUIR->set_float_limits( 0.0f, 25.0f );
    GUIR->set_alignment( GLUI_ALIGN_RIGHT );

	specularBOX = new GLUI_Checkbox(xtoon_panel, "Specular Highlight", &specHighlight, XTOONTYPE, controlCB );

    GUIs = new GLUI_Spinner( xtoon_panel, "Shine Factor", &S );
	GUIs->set_float_limits( 1.0f, 25.0f );
    GUIs->set_alignment( GLUI_ALIGN_RIGHT );

	xtoonBOX = new GLUI_Checkbox(xtoon_panel, "Enable / Disable", &xToonFlag, XTOON, controlCB );

	glui->set_main_gfx_window(windowId);
    
	glutInitWindowSize(300, 300);
	subWindowId = glutCreateWindow("Transfer Function 2D Texture");
	glutPositionWindow(865, 350);

	// Set GLUT callback functions
	glutReshapeFunc(setViewport);
	glutDisplayFunc(renderSub);
	glutKeyboardFunc(keypressSub);
	
	// Setup OpenGL state & scene resources 
	initSub();

	GLUI_Master.set_glutIdleFunc(updateScene); 

    // Show window & start update loop
    glutMainLoop();    

	return 0;
}
int main(int argc, char *argv[])
{
    // Init the OpenSG subsystem
    OSG::osgInit(argc, argv);

    {
        // We create a GLUT Window (that is almost the same for most applications)
        int winid = setupGLUT(&argc, argv);
        OSG::GLUTWindowRecPtr gwin = OSG::GLUTWindow::create();
        gwin->setGlutId(winid);
        gwin->init();

        // Create the face
        std::string family = "SANS";
        OSG::TextFace::Style style = OSG::TextFace::STYLE_PLAIN;
        OSG::TextTXFParam txfParam;
        txfParam.size = 46;
        txfParam.gap = 1;
        txfParam.setCharacters("Hello World!");
        txfParam.textureWidth = 0;
        OSG::TextTXFFaceRefPtr face =
            OSG::TextTXFFace::create(family, style, txfParam);
        if (face == 0)
        {
            std::cerr << "ERROR: Cannot create face object!" << std::endl;
            return -1;
        }

        // Lay out one single line of text
        std::string text = "Hello World!"; // Use UTF-8 encoding!
        OSG::TextLayoutParam layoutParam;
        layoutParam.horizontal = true;
        layoutParam.leftToRight = true;
        layoutParam.topToBottom = true;
        layoutParam.majorAlignment = OSG::TextLayoutParam::ALIGN_FIRST;
        layoutParam.minorAlignment = OSG::TextLayoutParam::ALIGN_FIRST;
        layoutParam.spacing = 1.f;
        layoutParam.length.push_back(0.f);
        layoutParam.maxExtend = 0.f;
        OSG::TextLayoutResult layoutResult;
        face->layout(text, layoutParam, layoutResult);

        // Create the text geometry
        OSG::Real32 scale = 1.f;
        OSG::NodeRecPtr scene = face->makeNode(layoutResult, scale);

        // Get the texture that contains the characters of the font
        OSG::ImageRecPtr image = face->getTexture();

        // Create the texture that will hold the image
        OSG::SimpleTexturedMaterialRecPtr tex =
            OSG::SimpleTexturedMaterial::create();
        tex->setImage(image);
        tex->setEnvMode(GL_MODULATE);
        tex->setDiffuse(OSG::Color3f(1, 0, 0));

        // Assign the texture to the geometry
        OSG::GeometryRecPtr geo =
            dynamic_cast<OSG::Geometry *>(scene->getCore());
        geo->setMaterial(tex);

        // Create and setup the SSM
        mgr = new OSG::SimpleSceneManager;
        mgr->setWindow(gwin);
        mgr->setRoot(scene);

        // Create a blue background
        OSG::SolidBackgroundRecPtr bg = OSG::SolidBackground::create();
        bg->setColor(OSG::Color3f(0.1, 0.1, 0.5));

        gwin->getPort(0)->setBackground(bg);

        mgr->showAll();

        OSG::commitChanges();
    }

    // Give Control to the GLUT Main Loop
    glutMainLoop();

    return 0;
}
Exemplo n.º 9
0
int
main(int argc, char *argv[])
{
  int c;
  int i;

  GLfloat mat_specular[] = { 0.7, 0.7, 0.7, 1.0 };
  GLfloat mat_shininess[] = { 40.0 };
  GLfloat light_position[] = { 4.5, 0.0, 4.5, 0.0 };

  glutInit(&argc, argv);

  num_disks = MAX_DISKS;
  while((c = getopt(argc, argv, "n:s:m:")) != -1) {
      switch (c) {
	case 'n':
	  num_disks = atoi(optarg);
	  if (num_disks < 1 || num_disks > MAX_DISKS) {
	      num_disks = MAX_DISKS;
	  }
	  break;
	case 's':
	  spinning = atoi(optarg) ? 1 : 0;
	  break;
	case 'm':
	  motion = atoi(optarg) ? 1 : 0;
	  break;
	default:
	  break;
      }
  }

  glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
  glutCreateWindow("Hanoi");
  glutDisplayFunc(display);
  glutVisibilityFunc(visible);
  glMatrixMode(GL_PROJECTION);
  gluPerspective(40.0, 1.0, 0.1, 10.0);
  glMatrixMode(GL_MODELVIEW);
  gluLookAt(0, 5.5, 3.5,
    0, 0, 0,
    0, 0, 1);
  glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
#ifndef TOOSLOW
  glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
  glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
  glEnable(GL_COLOR_MATERIAL);
#endif
#ifndef TOOSLOW
  glShadeModel(GL_SMOOTH);
#endif
  glEnable(GL_DEPTH_TEST);
  glEnable(GL_CULL_FACE);
#ifndef TOOSLOW
  glLightfv(GL_LIGHT0, GL_POSITION, light_position);
  glEnable(GL_LIGHTING);
  glEnable(GL_LIGHT0);
#endif
  glDepthFunc(GL_LEQUAL);
  glClearColor(0.3, 0.3, 0.3, 0.0);
#ifndef TOOSLOW
  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
#endif

  glPolygonMode(GL_FRONT, GL_FILL);

  glutCreateMenu(menu);
  glutAddMenuEntry("Toggle motion", 2);
  glutAddMenuEntry("Toggle spinning", 3);
  glutAddMenuEntry("Quit", 666);
  glutAttachMenu(GLUT_RIGHT_BUTTON);
#if defined(GL_POLYGON_OFFSET_EXT)
  if (glutExtensionSupported("GL_EXT_polygon_offset")) {
    glPolygonOffsetEXT(0.5, 0.0);
    glEnable(GL_POLYGON_OFFSET_EXT);
  }
#endif

  poledlist(DL_POLE);
  floordlist(DL_FLOOR);
  
  disks_on_poles[0].num_disks = num_disks;
  for (i=0; i<num_disks; i++) {
      diskdlist(DL_DISK+i, 0.3 + i*0.1);
      disks_on_poles[0].disks[num_disks-i-1] = i;
      disk_offset[i][Z] = 0.2*(num_disks-i-1);
  }

  /*
   * start hanoi instruction engine
   */
  {
      int engine_args[2];
      extern void engine(int *);
      int p[2];

      prctl(PR_SETEXITSIG, SIGTERM);
      if (-1 == pipe(p)) {
	  perror("can't pipe");
	  exit(1);
      }
      engine_args[0] = num_disks;
      engine_args[1] = p[1];
      engine_fd = p[0];
      engine_pid = sproc((void(*)(void *))engine, PR_SALL, (void *)engine_args);
      if (engine_pid == -1) {
	  perror("can't sproc");
	  exit(1);
      }
  }

  glutMainLoop();
  /*NOTREACHED*/
  return 0;             /* ANSI C requires main to return int. */
}
Exemplo n.º 10
0
int main(int argc, char **argv)
{
	XnStatus rc = XN_STATUS_OK;

	rc = g_Context.InitFromXmlFile(SAMPLE_XML_PATH);
	CHECK_RC(rc, "InitFromXml");

	rc = g_Context.FindExistingNode(XN_NODE_TYPE_DEPTH, g_DepthGenerator);
	CHECK_RC(rc, "Find depth generator");

	// Create and initialize point tracker
	g_pSessionManager = new XnVSessionManager;
	rc = g_pSessionManager->Initialize(&g_Context, "Wave", "RaiseHand");
	if (rc != XN_STATUS_OK)
	{
		printf("Couldn't initialize the Session Manager: %s\n", xnGetStatusString(rc));
		delete g_pSessionManager;
		return rc;
	}

	g_pSessionManager->RegisterSession(NULL, &SessionStart, &SessionEnd);

	// Start catching signals for quit indications
	CatchSignals(&g_bQuit);

	// Create and initialize the main slider
	g_pMainSlider = new XnVSelectableSlider1D(3);
	g_pMainSlider->RegisterItemHover(NULL, &MainSlider_OnHover);
	g_pMainSlider->RegisterItemSelect(NULL, &MainSlider_OnSelect);
	g_pMainSlider->RegisterActivate(NULL, &MainSlider_OnActivate);
	g_pMainSlider->RegisterDeactivate(NULL, &MainSlider_OnDeactivate);
	g_pMainSlider->RegisterPrimaryPointCreate(NULL, &MainSlider_OnPrimaryCreate);
	g_pMainSlider->RegisterPrimaryPointDestroy(NULL, &MainSlider_OnPrimaryDestroy);
	g_pMainSlider->RegisterValueChange(NULL, &MainSlider_OnValueChange);
	g_pMainSlider->SetValueChangeOnOffAxis(true);

	// Creat the flow manager
	g_pMainFlowRouter = new XnVFlowRouter;

	// Connect flow manager to the point tracker
	g_pSessionManager->AddListener(g_pMainFlowRouter);

	// Create the MyBox objects
	XnPoint3D ptMax, ptMin;
	ptMax.Z = ptMin.Z = 0;
	ptMax.Y = GL_WIN_SIZE_Y-50;
	ptMin.Y = GL_WIN_SIZE_Y-300;

	ptMax.X = 50; ptMin.X = 240;
	g_pBox[0] = new MyBox(ptMax, ptMin);
	ptMax.X = 260; ptMin.X = 450;
	g_pBox[1] = new MyBox(ptMax, ptMin);
	ptMax.X = 470; ptMin.X = 650;
	g_pBox[2] = new MyBox(ptMax, ptMin);

	// Register callback to the MyBox objects for their Leave event.
	g_pBox[0]->RegisterLeave(NULL, &MyBox_Leave);
	g_pBox[1]->RegisterLeave(NULL, &MyBox_Leave);
	g_pBox[2]->RegisterLeave(NULL, &MyBox_Leave);

	g_Context.StartGeneratingAll();

	#ifdef USE_GLUT

	glInit(&argc, argv);
	glutMainLoop();

	#else

	if (!opengles_init(GL_WIN_SIZE_X, GL_WIN_SIZE_Y, &display, &surface, &context))
	{
		printf("Error initing opengles\n");
		CleanupExit();
	}

	glDisable(GL_DEPTH_TEST);
//	glEnable(GL_TEXTURE_2D);
	glEnableClientState(GL_VERTEX_ARRAY);
	glDisableClientState(GL_COLOR_ARRAY);

	while ((!_kbhit()) && (!g_bQuit))
	{
		glutDisplay();
		eglSwapBuffers(display, surface);
	}

	opengles_shutdown(display, surface, context);

	CleanupExit();

	#endif
}
Exemplo n.º 11
0
int main(int argc, char **argv)
{
  int width = 320, height = 240;
  int i; 

  char *name;
  glutInitWindowSize(width, height);
  glutInit(&argc, argv);

  /* process commmand line args */
  for (i = 1; i < argc; ++i) {
    if (!strcmp("-db", argv[i])) {
    useDB = !useDB;
    } else {
      usage();
    }
  }

/* choose visual */

      glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
      name = "MOTH - by Bob Doyle";    
      glutCreateWindow(name);

  glutKeyboardFunc(keyboard);

  myInit();  /* initialize objects in scene */
  glutDisplayFunc(display); 
  glutVisibilityFunc(visible);


  glutCreateMenu(menu_select);
  glutAddMenuEntry("Start motion", 1);
  glutAddMenuEntry("Stop motion", 2);
  glutAddMenuEntry("Quit", 5);
  glutAddMenuEntry("Drink Ed's beer", 5);
  glutAttachMenu(GLUT_RIGHT_BUTTON);

  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();

  glFrustum(-.9, .9, -.9, .9, 1.0, 35.0);

  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
#if 0
  glTranslatef(0.0, 0.0, mvt_zi);
#endif

  glEnable(GL_NORMALIZE);
  glEnable(GL_CULL_FACE);
  glCullFace(GL_BACK);      /* double your fun */
  glShadeModel(GL_SMOOTH);
  glDepthFunc(GL_LESS);
  glDepthMask(GL_TRUE);
  glEnable(GL_DEPTH_TEST);
	myInit();  /* initialize objects in scene */

  glutMainLoop();
  return 0;             /* ANSI C requires main to return int. */
}
Exemplo n.º 12
0
int main( int argc, char **argv)
{
std::string inpf, trif, outf, backf;
adobe::dictionary_t params;

bool use_lab = false;

	try
	{
	po::options_description desc("Allowed options");
	po::variables_map vm;
	po::positional_options_description p;

		p.add( "input" , 1);
		p.add( "trimap", 1);

		desc.add_options()	("help", "produce help message")
							// files
							("input", po::value<std::string>(), "input file")
							("trimap",po::value<std::string>(), "trimap file")
							("output,o", po::value<std::string>(), "output file")
							("background,bg", po::value<std::string>(), "clean background")
							("save_bg", "save estimated background")

							// colors
							("rgb", "use rgb colorspace")

							// sampling
							("kwin", po::value<int>()->default_value( 8), "known window radius")
							("uwin", po::value<int>()->default_value( 8), "unknown window radius")
							("mins", po::value<int>()->default_value( 16), "min samples")
							
							// clusters
							("clusters", po::value<int>()->default_value( 5), "max number of clusters")
							("ctheresh", po::value<double>()->default_value( 0.001), "cluster thereshold")
	
							// optimize
							("cvar", po::value<double>()->default_value( 0.04), "camera variance")

							// gui
							("window,w", "show results in a window")
							; // end

		po::store( po::command_line_parser( argc, argv).options( desc).positional( p).run(), vm);
		po::notify( vm);

		if( vm.count( "help") || !vm.count("input") || !vm.count("trimap"))
			usage();
		
		if( (!vm.count("output")) && (!vm.count("window")))
			usage();
			
		inpf = vm["input"].as<std::string>();
		trif = vm["trimap"].as<std::string>();
		
		if( vm.count("output"))
			outf = vm["output"].as<std::string>();

		use_lab = !vm.count("rgb");
		
		params[adobe::name_t("use_lab")] = adobe::any_regular_t( use_lab);
		
		// load images
		image.reference( read_image( inpf.c_str()));
		trimap.reference( read_trimap( trif.c_str()));

		if( (trimap.rows() != image.rows()) || (trimap.cols() != image.cols()))
		{
			std::cout << "Image & trimap dimensions don't match\n";
			exit( boost::exit_failure);
		}

		if( use_lab)
			convert2lab( image);
		
		if( vm.count( "background"))
		{
			backf = vm["background"].as<std::string>();
			params[adobe::name_t("use_back")] = adobe::any_regular_t( true);

			bg.reference( read_image( backf.c_str()));
			
			if( use_lab)
				convert2lab( bg);
		}
		else
		{
			bg.resize( image.rows(), image.cols());
			params[adobe::name_t("use_back")] = adobe::any_regular_t( false);
		}

		// sampling
		params[ adobe::name_t( "kwin_size")] = adobe::any_regular_t( vm["kwin"].as<int>());
		params[ adobe::name_t( "uwin_size")] = adobe::any_regular_t( vm["uwin"].as<int>());
		params[ adobe::name_t( "min_samples")] = adobe::any_regular_t( vm["mins"].as<int>());

		// cluster
		params[ adobe::name_t( "maxk")] = adobe::any_regular_t( vm["clusters"].as<int>());
		params[ adobe::name_t( "ctheresh")] = adobe::any_regular_t( vm["ctheresh"].as<double>());

		// optimize
		params[ adobe::name_t( "cvar")] = adobe::any_regular_t( vm["cvar"].as<double>());

		fg.resize( image.rows(), image.cols());
		alpha.resize( image.rows(), image.cols());
		
		bmatte bm( image, trimap, fg, bg, alpha, params);
		bm();

		if( use_lab)
		{
			convert2rgb( image);
			convert2rgb( fg);
			convert2rgb( bg);
		}

		if( vm.count( "output"))
		{
			save_image( outf.c_str(), fg, &alpha);
		
			if( vm.count( "save_bg"))
			{
			std::string bgf = "bg_" + outf;

				save_image( bgf.c_str(), bg);
			}
		}

		if( vm.count( "window"))
		{
			comp.resize( image.rows(), image.cols());
		
			for( int j=0;j<image.rows();++j)
			{
				for( int i=0;i<image.cols();++i)
				{
					float t = alpha( j, i);
					comp( j, i) = (fg( j, i) * t) + ( Imath::Color3f( .5f, .5f, .5f) * (1.0f - t));
				}
			}

			glutInit(&argc, argv);
			glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
	
			glutInitWindowPosition( 50, 50);

			glutInitWindowSize( image.cols(), image.rows());
			glutCreateWindow( "BMatte");

			glutKeyboardFunc( key);
			glutMouseFunc( mouse);

			glutDisplayFunc( display);

			gl_init();
			glutMainLoop();
		}
	}
    catch( std::exception& e)
	{
        std::cerr << "error: " << e.what() << "\n";
        return boost::exit_failure;
    }

    catch( ...) { std::cerr << "Exception of unknown type!\n";}
	return boost::exit_success;
}
Exemplo n.º 13
0
 //show the window
 void show(int argc, std::string argv)
 {
     initMainwnd(argc , argv);
     initGL();
     glutMainLoop();
 }
Exemplo n.º 14
0
// Initialize GLUT & OpenSG and set up the scene
int main(int argc, char **argv)
{
    // OSG init
    OSG::osgInit(argc,argv);

    // GLUT init
    int winid = setupGLUT(&argc, argv);

    {
        // the connection between GLUT and OpenSG
        OSG::GLUTWindowRefPtr gwin = OSG::GLUTWindow::create();

        gwin->setGlutId(winid);
        gwin->init();

        // create the scene
        OSG::NodeRefPtr torus = OSG::makeTorus( .5, 2, 16, 32 );
        OSG::NodeRefPtr scene = OSG::Node::create();

        trans = OSG::Transform::create();

        scene->setCore(trans);
        scene->addChild(torus);

        // Create the parts needed for the video background
        OSG::UInt32 width  = 640;
        OSG::UInt32 height = 480;

        // get the desired size from the command line
        if(argc >= 3)
        {
            width  = atoi(argv[1]);
            height = atoi(argv[2]);
        }

        // To check OpenGL extensions, the Window needs to have run through
        // frameInit at least once. This automatically happens when rendering,
        // but we can't wait for that here.

        gwin->activate ();
        gwin->frameInit();

        // Now we can check for OpenGL extensions
        hasNPOT = gwin->hasExtension("GL_ARB_texture_non_power_of_two");

        // Print what we've got
        SLOG << "Got " << (isPOT?"":"non-") << "power-of-two images and "
            << (hasNPOT?"can":"cannot") << " use NPOT textures, changing "
            << (changeOnlyPart?"part":"all")
            << " of the screen"
            << std::endl;

        // Ok, now for the meat of the code...
        // first we need an Image to hold the picture(s) to show
        image = OSG::Image::create();

        // set the image's size and type, and allocate memory
        // this example uses RGB. On some systems (e.g. Windows) BGR
        // or BGRA might be faster, it depends on how the images are
        // acquired

        image->set(OSG::Image::OSG_RGB_PF, width, height);



        // Now create the texture to be used for the background
        texObj = OSG::TextureObjChunk::create();

        // Associate image and texture
        texObj->setImage(image);

        // Set filtering modes. LINEAR is cheap and good if the image size
        // changes very little (i.e. the window is about the same size as
        // the images).

        texObj->setMinFilter(GL_LINEAR);
        texObj->setMagFilter(GL_LINEAR);

        // Set the wrapping modes. We don't need repetition, it might actually
        // introduce artifactes at the borders, so switch it off.

        texObj->setWrapS(GL_CLAMP_TO_EDGE);
        texObj->setWrapT(GL_CLAMP_TO_EDGE);

        // Newer versions of OpenGL can handle NPOT textures directly.
        // OpenSG will do that internally automatically.
        //
        // Older versions need POT textures. By default OpenSG
        // will scale an NPOT texture to POT while defining it.
        // For changing textures that's too slow.
        // So tell OpenSG not to scale the image and adjust the texture
        // coordinates used by the TextureBackground (see below).

        texObj->setScale(false);

        // Create the background

        OSG::TextureBackgroundRefPtr back = OSG::TextureBackground::create();

        // Set the texture to use
        back->setTexture(texObj);

        // if the image is NPOT and we don't have hardware support for it
        // adjust the texture coordinates.
        if(isPOT == false && hasNPOT == false)
        {
            OSG::UInt32 potWidth  = OSG::osgNextPower2(width );
            OSG::UInt32 potHeight = OSG::osgNextPower2(height);

            OSG::Real32 tcRight = OSG::Real32(width ) / OSG::Real32(potWidth );
            OSG::Real32 tcTop   = OSG::Real32(height) / OSG::Real32(potHeight);

            back->editMFTexCoords()->push_back(OSG::Vec2f(    0.f,   0.f));
            back->editMFTexCoords()->push_back(OSG::Vec2f(tcRight,   0.f));
            back->editMFTexCoords()->push_back(OSG::Vec2f(tcRight, tcTop));
            back->editMFTexCoords()->push_back(OSG::Vec2f(    0.f, tcTop));
        }

        OSG::commitChanges();

        // create the SimpleSceneManager helper
        mgr = OSG::SimpleSceneManager::create();

        // tell the manager what to manage
        mgr->setWindow(gwin );
        mgr->setRoot  (scene);
        mgr->setStatistics(true);

        // replace the background
        // This has to be done after the viewport has been created, which the
        // SSM does in setRoot().

        OSG::ViewportRefPtr vp = gwin->getPort(0);

        vp->setBackground(back);
    }

    // show the whole scene
    mgr->showAll();

    // GLUT main loop
    glutMainLoop();

    return 0;

}
Exemplo n.º 15
0
int main ( int argc, char ** argv )
{
	glutInit ( &argc, argv );

	if( argc < 2 ){
                printf("Usage: ./%s integrator=(1-euler, 2-RK2, 3-sympleticEuler, 4-RK4) [N dt d]", argv[0]);
		exit(0);
	}
	
        // decide which integrator to use
        switch ( argv[1][0] )
        {
        case '1':
            integrator = new EulerIntegrator();
            break;

        case '2':
            integrator = new RK2Integrator();
            break;

        case '3':
            integrator = new SymplecticEulerIntegrator();
            break;

        case '4':
            integrator = new RK4Integrator();
            break;

        default:
            integrator = new RK4Integrator();
        }
	
	if ( argc == 2 ) {
		N = 64;
                dt = 0.01f;
		d = 5.f;
		fprintf ( stderr, "Using defaults : N=%d dt=%g d=%g\n",
			N, dt, d );
	} else {
		N = atoi(argv[2]);
		dt = atof(argv[3]);
		d = atof(argv[4]);
	}

	printf ( "\n\nHow to use this application:\n\n" );
	printf ( "\t Toggle construction/simulation display with the spacebar key\n" );
	printf ( "\t Dump frames by pressing the 'd' key\n" );
	printf ( "\t Quit by pressing the 'q' key\n" );

	dsim = 0;
	dump_frames = 0;
	frame_number = 0;
	
	init_system();
	
        win_x = 720;
        win_y = 720;
	open_glut_window ();

	glutMainLoop ();

	exit ( 0 );
}
Exemplo n.º 16
0
int
main(int argc, char* argv[])
{
	///////////////////////////////////////////////////////////////
	// when use GCB, it is still needed to initialize GLUT
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA | GLUT_ALPHA | GLUT_STENCIL );

	// VTK
	// Start by loading some data.
	vtkMultiBlockPLOT3DReader *pl3dReader = vtkMultiBlockPLOT3DReader::New();
	// set data
	{
		char path[256];
		sprintf(path, "%s/curvilinear/combxyz.bin", SAMPLE_DATA_DIR);
		printf("%s\n", path);
		pl3dReader->SetXYZFileName(path);
		sprintf(path, "%s/curvilinear/combq.bin", SAMPLE_DATA_DIR);
		pl3dReader->SetQFileName(path);
	}
	pl3dReader->SetScalarFunctionNumber(100);
	pl3dReader->SetVectorFunctionNumber(202);
	pl3dReader->Update();

	// random points
	//vtkStructuredGrid *grid = pl3dReader->GetOutput();
	//int *dim = grid->GetDimensions();
	vtkSmartPointer<vtkDataSet> sData = vtkDataSet::SafeDownCast(pl3dReader->GetOutput()->GetBlock(0));
	double *bounds = sData->GetBounds();
	printf("bounds: %lf %lf %lf %lf %lf %lf\n", bounds[0], bounds[1], bounds[2], bounds[3], bounds[4], bounds[5]);

	osuflow = new OSUFlow;
	CVectorField *field = new VectorFieldVTK( sData );
	osuflow->SetFlowField( field );

	// openmp
#ifdef _OPENMP
	osuflow->initOpenMP(1);
#endif

	// gen seeds
	minLen[0] = bounds[0]; maxLen[0] = bounds[1];
	minLen[1] = bounds[2]; maxLen[1] = bounds[3];
	minLen[2] = bounds[4]; maxLen[2] = bounds[5];

	center[0] = (minLen[0]+maxLen[0])/2.0;
	center[1] = (minLen[1]+maxLen[1])/2.0;
	center[2] = (minLen[2]+maxLen[2])/2.0;
	printf("center is at %f %f %f \n", center[0], center[1], center[2]);
	len[0] = maxLen[0]-minLen[0];
	len[1] = maxLen[1]-minLen[1];
	len[2] = maxLen[2]-minLen[2];

#if 0
	///////////////////////////////////////////////////////////////
	// initialize OSU flow
	osuflow = new OSUFlow(); 

	// load the scalar field
	LOG(printf("read file %s\n", argv[1])); 

	osuflow->LoadData((const char*)argv[1], true); //true: a steady flow field 

	szVecFilePath = argv[1];	// ADD-BY-LEETEN 09/29/2012

	// comptue the bounding box of the streamlines 
	VECTOR3 minB, maxB; 
	osuflow->Boundary(minLen, maxLen); // get the boundary 
	minB[0] = minLen[0]; minB[1] = minLen[1];  minB[2] = minLen[2];
	maxB[0] = maxLen[0]; maxB[1] = maxLen[1];  maxB[2] = maxLen[2];
	//  osuflow->SetBoundary(minB, maxB);  // set the boundary. just to test
										 // the subsetting feature of OSUFlow
	printf(" volume boundary X: [%f %f] Y: [%f %f] Z: [%f %f]\n", 
								minLen[0], maxLen[0], minLen[1], maxLen[1], 
								minLen[2], maxLen[2]); 

	center[0] = (minLen[0]+maxLen[0])/2.0; 
	center[1] = (minLen[1]+maxLen[1])/2.0; 
	center[2] = (minLen[2]+maxLen[2])/2.0; 
	printf("center is at %f %f %f \n", center[0], center[1], center[2]); 
	len[0] = maxLen[0]-minLen[0]; 
	len[1] = maxLen[1]-minLen[1]; 
	len[2] = maxLen[2]-minLen[2]; 
#endif
	///////////////////////////////////////////////////////////////
	cLineRenderer._SetBoundingBox(
		minLen[0], minLen[1], minLen[2], 
		maxLen[0], maxLen[1], maxLen[2]);
	cLineRenderer._SetDataSource(&sl_list);
	// ADD-BY-LEETEN /2010-BEGIN
	cLineRenderer._SetColorSource(&liv4Colors);
	cLineRenderer._SetInteger(CLineRenderer::COLOR_SCHEME, CLineRenderer::CColorScheme::COLOR_PER_TRACE);
	// ADD-BY-LEETEN 07/07/2010-END

	///////////////////////////////////////////////////////////////
	glutCreateWindow("GCB Streamline");

	// specify the callbacks you really need. Except gcbInit() and gcbDisplayFunc(), other callbacks are optional
	gcbInit(init, quit);
	gcbDisplayFunc(_DisplayFunc);
	gcbKeyboardFunc(_KeyboardFunc);

	// enter the GLUT loop
	glutMainLoop();

	return 0;
}
Exemplo n.º 17
0
void
piglit_framework_glut_run(const struct piglit_gl_test_info *info)
{
	glutMainLoop();
	piglit_report_result(result);
}
Exemplo n.º 18
0
void RenderThread::operator()() {

    RENDER.SetTimeStamp(getElapsedTime());

    // -- Start the Clock ------------------------------------------- //
    g_ullAppStartTime = RENDER.GrabTimeStamp();
    PROF.StartProfiling(g_ullAppStartTime);


    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
    glutInitWindowSize(GAMECONFIG.m_uiWindowWidth,
                       GAMECONFIG.m_uiWindowHeight);

    glutInit(&m_argc, m_argv);

    if (!GAMECONFIG.m_bWindowedMode)
    {
        char temp[64];
        sprintf_s(temp,
                "%dx%d:%d@%d",
                GAMECONFIG.m_uiWindowWidth,
                GAMECONFIG.m_uiWindowHeight,
                32,
                75);

        glutGameModeString(temp);

        // start fullscreen game mode
        glutEnterGameMode();
    }
    else
    {
        glutCreateWindow("Swarm: Rise of the Transactional Tripods");
    }

    atexit(gKillGame);
    glutKeyboardFunc(gKeyboard);
    glutDisplayFunc(gRender);
    glutReshapeFunc(gChangeSize);
    glutIdleFunc(gIdle);

    // -- VSync ----------------------------------------------------- //
    // Note that OpenGL by default blocks
    // rendering to match the actual monitor refresh rate
    //
    // We want to push frames ASAP, perhaps starting a new one
    // before the old one is presented to the monitor. This allows
    // for FPS of thousands on very simple apps.
    //
    // I do not know the linux equivalent of this code
#ifdef _MSC_VER
    if (!GAMECONFIG.m_bVSyncLock)
    {
        typedef bool (APIENTRY *PFNWGLSWAPINTERVALFARPROC)(int);
        PFNWGLSWAPINTERVALFARPROC wglSwapIntervalEXT = 0;

        wglSwapIntervalEXT =
            (PFNWGLSWAPINTERVALFARPROC)wglGetProcAddress("wglSwapIntervalEXT");

        if (wglSwapIntervalEXT)
            wglSwapIntervalEXT(0);
    }
#endif


    // -- Set GL for RENDER ----------------------------------------- //
    RENDER.ConfigureRenderer();

    // -- Give GLUT control of this thread forever ------------------ //
    glutMainLoop();
}
Exemplo n.º 19
0
/**
 * Method for create a window
 */
void Visualizer::createWindow(const char * title)
{
        xnew=0; ynew=0; znew=0;                   /* actual position */
        xold=0; yold=0; zold=0;                   /* old position */
        xx1=0; yy1=0; zz1=0;                      /* mouse position*/
        mouseState=0;                             /* mouse button state */
        xshift=0; yshift=0;                       /* shifting in space*/

        xnew=0; ynew=0; znew=0;                   /* actual position */
        xold=0; yold=0; zold=0;                   /* old position */
        xx1=0; yy1=0; zz1=0;                      /* mouse position*/
        mouseState=0;                             /* mouse button state */
        xshift=0; yshift=0;                       /* shifting in space*/

	fov=45.0;                                 /* field of view */
	near_plane=1;                             /* trim plain */
	far_plane=1000.0;                         /* farther trim plain */
	line_width=1.0;                           /* width of line */
	WindowWidth=1024;                         /* width and height of window */
	WindowHeight=768;
	ObjectType=0;                             /* type of paint object */
	Solid=1;                                  /* fill or wireframe model */

	char * dummy_argv[1];
	dummy_argv[0] = const_cast<char *>("run");
	int dummy_argc = 1;

	glutInit(&dummy_argc, dummy_argv);

	glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH | GLUT_MULTISAMPLE ); /* graphic mod of window */

        glutInitWindowSize(WindowWidth,WindowHeight); /* original window size */
        glutInitWindowPosition(10,10);                /* original window position */
        glutCreateWindow(title);                      /* create window */

        glutDisplayFunc(onDisplay);                   /* set function for redisplay */
        glutReshapeFunc(onReshape);                   /* set function for change of size window */
        glutKeyboardFunc(onKeyboard);                 /* set function for press key */
        glutSpecialFunc(onSpecial);
        glutMouseFunc(onMouseClick);                  /* set function for press mouse button */
        glutMotionFunc(onMouseMotion);                /* set function for mouse move */

        glClearColor(0.0, 0.0, 0.0, 0.0);             /* color for clearing of color-buffer */
        glClearDepth(1.0f);                           /* color for clearing of z-buffer */
        glEnable(GL_DEPTH_TEST);                      /* configure function for testing value in z-buffer */
        glDepthFunc(GL_LESS);                         /* select function */
        glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); /* improvement display */

        glEnable(GL_CULL_FACE);
        glPolygonMode(GL_FRONT, GL_FILL);             /* configure draw of fill polygons */
        //glCullFace(GL_FRONT);

        glLineWidth(line_width);                      /* line width */
	glPointSize(line_width);

	//glEnable(GL_MULTISAMPLE);
#ifdef FREEGLUT
    #ifdef GLUT_AUX
	int *sampleNumbers = NULL;
	int sampleNumbersSize = 0;
	sampleNumbers = glutGetModeValues(GLUT_MULTISAMPLE, &sampleNumbersSize);
	if(sampleNumbers != NULL)
	{
		glutSetOption(GLUT_MULTISAMPLE, sampleNumbers[sampleNumbersSize - 1]);
		printf("Multisampling with %i samples.\n", sampleNumbers[sampleNumbersSize - 1]);
		free(sampleNumbers);
	}
	else
	{
		printf("Multisampling is not available.\n");
	}
    #endif
#endif

        scene_ = glGenLists(1);                        /* get number of calllist */
        createCallList();                             /* initialization */

	glutMainLoop();
}
Exemplo n.º 20
0
int main(int argc, char** argv) {
	// Standard stuff...
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
	glutInitWindowSize(1080, 600);
	glutCreateWindow("Lighted Cube");
	glutReshapeFunc(changeViewport);
	glutKeyboardFunc(keyboardFunc);
	glutDisplayFunc(render);
	glewInit();

	initMatrices(); // New <========================================


	// 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"); // NEW
	lightID1 = glGetUniformLocation(shaderProgramID, "vLight1");    // NEW
	lightID2 = glGetUniformLocation(shaderProgramID, "vLight2");    // NEW

	// ============ 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(normalID, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(sizeof(vertices)));

	glUseProgram(shaderProgramID);
	glEnableVertexAttribArray(positionID);
	glEnableVertexAttribArray(normalID);    // NEW

	glEnable(GL_CULL_FACE);  // NEW! - we're doing real 3D now
	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;
}
Exemplo n.º 21
0
void
start_main_loop() {
	glutMainLoop();
}
Exemplo n.º 22
0
void 
OpenSteer::runGraphics (void)
{
    glutMainLoop ();  
}
Exemplo n.º 23
0
int main(int argc, char **argv) {
	glutInit(&argc, argv);
	InitGL();
	if (glewIsSupported("GL_VERSION_3_1"))
		printf("Ready for OpenGL 3.1.\n");
	else {
		printf("OpenGL 3.1 not supported\n");
		exit(1);
	}

	

	shader = new Shader();
	shader->setShaders("test.vert", "test.frag");
	glBindFragDataLocation(shader->GetProgram(), 0, "out_Color");
	glBindAttribLocation(shader->GetProgram(), 0, "in_Position");
	glBindAttribLocation(shader->GetProgram(), 1, "colors");

	printOpenGLError();

	shader->LinkShaders();

	printOpenGLError();

	GLuint attrloc = glGetAttribLocation(shader->GetProgram(), "in_Position");

	// create vbo
	glGenBuffers(1, &vboID);
	// create vao
	glGenVertexArrays(1, &vertexArrayID);
	// bind vao
	glBindVertexArray(vertexArrayID);
	// enable 0.
	glEnableVertexAttribArray(0);
	
	glBindBuffer(GL_ARRAY_BUFFER, vboID);
	glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 3 * 3 * 2 * 6, g_cube, GL_STATIC_DRAW);
	glVertexAttribPointer((GLuint)0, 3, GL_FLOAT, GL_FALSE, 0, 0);

	glGenBuffers(1, &colorID);
	glBindBuffer(GL_ARRAY_BUFFER, colorID);
	glBufferData(GL_ARRAY_BUFFER, sizeof(g_cube_colors), g_cube_colors, GL_STATIC_DRAW);
	glEnableVertexAttribArray(1);
	glVertexAttribPointer((GLuint)1, 3, GL_FLOAT, GL_FALSE, 0, 0);


	printOpenGLError();

	//GLfloat * data = (GLfloat *)glMapBuffer(GL_ARRAY_BUFFER, GL_READ_ONLY);
	//glUnmapBuffer.

	glm::mat4 model(1.0f);
	glm::mat4 view = glm::lookAt(
		glm::vec3(4,3,3),
		glm::vec3(0,0,0),
		glm::vec3(0,1,0));
	glm::mat4 proj = glm::perspective(45.0f, 1.0f, 0.1f, 100.f);

	GLuint projID = glGetUniformLocation(shader->GetProgram(), "Proj");
	GLuint viewID = glGetUniformLocation(shader->GetProgram(), "View");
	GLuint modelID = glGetUniformLocation(shader->GetProgram(), "Model");

	glUniformMatrix4fv(projID, 1, GL_FALSE, &proj[0][0]);
	glUniformMatrix4fv(viewID, 1, GL_FALSE, &view[0][0]);
	glUniformMatrix4fv(modelID, 1, GL_FALSE, &model[0][0]);


	glutMainLoop();

	EndGL();

	return 0;
}
Exemplo n.º 24
0
Arquivo: main.c Projeto: damora/ivr
//-----------------------------------------------------------------------------------------------------------------------//
// main
//-----------------------------------------------------------------------------------------------------------------------//
int main(int argc,  char * argv[])
{
    int rc=0;
    int rank=0;
#ifdef MPI
    int comsize;

    // init MPI
    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &comsize);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    fprintf(stderr,"rank=%d\n", rank);
#ifdef BGQ
    install_signal_handler();
#endif
#endif

    args = parseargs(argc, argv);

    // init, initcamera, initvolattrs
    if ((rc=init(args, rank) != 0)) {
        fprintf(stderr, "initialization failed: %d\n", rc);
        return 0;
    };

    //---------------------------- Platform Specific Display and Interaction ----------------------------------------//
#if LOCAL

    resettransforms();
    mystate.alpha=0.25f;

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
    glutInitWindowSize(WINDOWWIDTH, WINDOWHEIGHT);
    glutCreateWindow("iVR");
    glutReshapeFunc(reshape);
    glutDisplayFunc(display);
    glutKeyboardFunc(keyboard);
    glutMouseFunc(mousebutton);
    glutMotionFunc(mousemotion);
//    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    glCullFace(GL_BACK);
    glDisable(GL_DEPTH_TEST);
    glutMainLoop();
#elif MPI		// BEGIN MPI CODE
#ifdef REMOTE 	// START OF REMOTE RENDERING HANDSHAKE

    // connect to relay server
    if (rank == 0) {
        sockfd = initconnection(HOSTNAME, PORT);
        if (sockfd == -1) {
            fprintf(stderr,"remote connection failed, sockfd=%d\n",sockfd);
            freeall();
            exit(0);
        }
        fprintf(stderr,"relay connection succeeded\n");
    }
    PRINTDEBUG("%3d: \n", rank);
    boolean_t connected = TRUE;
    int ctr = 0;
    while (connected) {  // main loop when steering
        fprintf(stderr,"%3d: before steering control\n", rank);
        if (rank == 0) {
            rc = recvstate(sockfd, &mystate);
            fprintf(stderr,"bytes recvd=%d\n", rc);
            if (mystate.finish) connected = 0;;
            winwidth = mystate.winwidth;
            winheight=mystate.winheight;
        } // end if rank == 0 for remote visualization
        // wait until we've completed the handshake with steering client before proceeding;
        MPI_Barrier(MPI_COMM_WORLD);
        MPI_Bcast(&connected, 1, MPI_INT, 0, MPI_COMM_WORLD);
        if (!connected) break;
        MPI_Bcast((float *)&winwidth, 1, MPI_FLOAT, 0, MPI_COMM_WORLD);
        MPI_Bcast((float *)&winheight, 1, MPI_FLOAT, 0, MPI_COMM_WORLD);
        MPI_Bcast(&mystate.alpha, 1, MPI_FLOAT, 0, MPI_COMM_WORLD);
        MPI_Bcast(mystate.newconst, 6, MPI_FLOAT, 0, MPI_COMM_WORLD);
        MPI_Bcast(mystate.mvm, 16, MPI_FLOAT, 0, MPI_COMM_WORLD);
        MPI_Bcast(mystate.pm, 16, MPI_FLOAT, 0, MPI_COMM_WORLD);
        MPI_Bcast(mystate.vv, 4, MPI_FLOAT, 0, MPI_COMM_WORLD);
#endif
        float planeconst[6] = {pzero[0], pzero[1], pzero[2], pzero[3], pzero[4], pzero[5]};
        setviewport(&viewport, 0, 0, winwidth, winheight);
        setplaneconst(planeconst, mystate.newconst);
        setmvm(mvm, mystate.mvm);
        setpm(pm, mystate.pm);
        setfrustum(&viewvolume, mystate.vv);
        updatevolbbox();
        initcolbufs(rank);

        // create and display the image
        unsigned long long lstart, lstop;
        for (int i=0; i<1; i++) {
            TIME(RENDER, lstart);
            createlocalimage(rank);
            // can't composite until all ranks have completed local image generation
            MPI_Barrier(MPI_COMM_WORLD);
            compositelocalimage();
            TIME(RENDER, lstop);
            PERFORMANCE(lstart, lstop, framenum, elapsed, avg);
        }
        // wait until all ranks exit composite step before writing image
        MPI_Barrier(MPI_COMM_WORLD);
        writeimage(ctr++);
#ifdef REMOTE
    } // end while remote loop
    if (rank == 0) disconnect(sockfd);
#endif // END OF REMOTE CLIENT  HANDSHAKE


    fprintf(stderr,"%3d: finished\n", rank);
    MPI_Barrier(MPI_COMM_WORLD);
    MPI_Finalize();
#endif
    // clean up
    freeall();
    exit(0);
}
Exemplo n.º 25
0
/* Parse arguments, and set up interface between OpenGL and window system */
int
main(int argc, char *argv[])
{
    GLUquadricObj *sphere, *cone, *base;
    GLfloat v0[3], v1[3], v2[3];
    unsigned *floortex;
    int texcomps, texwid, texht;

    glutInit(&argc, argv);
    glutInitWindowSize(512, 512);
    if(argc > 1)
    {
	char *args = argv[1];
	int done = GL_FALSE;
	while(!done)
	{
	    switch(*args)
	    {
	    case 's': /* single buffer */
		printf("Single Buffered\n");
		dblbuf = GL_FALSE;
		break;
	    case '-': /* do nothing */
		break;
	    case 0:
		done = GL_TRUE;
		break;
	    }
	    args++;
	}
    }
    if(dblbuf)
	glutInitDisplayMode(GLUT_RGBA|GLUT_DEPTH|GLUT_STENCIL|GLUT_DOUBLE);
    else
	glutInitDisplayMode(GLUT_RGBA|GLUT_DEPTH|GLUT_STENCIL);

    (void)glutCreateWindow("projection shadows");
    glutDisplayFunc(redraw);
    glutKeyboardFunc(key);
    glutMouseFunc(mouse);
    glutMotionFunc(motion);
    glutReshapeFunc(reshape);

    glutCreateMenu(menu);
    glutAddMenuEntry("No Shadows", NONE);
    glutAddMenuEntry("Black Shadows", SHADOW_BLACK);
    glutAddMenuEntry("Shadows on Texture", SHADOW);
    glutAttachMenu(GLUT_RIGHT_BUTTON);


    /* draw a perspective scene */
    glMatrixMode(GL_PROJECTION);
    glFrustum(-100., 100., -100., 100., 320., 640.); 
    glMatrixMode(GL_MODELVIEW);

    /* turn on features */
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);

    /* make shadow matricies */

      /* 3 points on floor */
      v0[X] = -100.f; v0[Y] = -100.f; v0[Z] = -320.f;
      v1[X] =  100.f; v1[Y] = -100.f; v1[Z] = -320.f;
      v2[X] =  100.f; v2[Y] = -100.f; v2[Z] = -520.f;
      
      findplane(floorplane, v0, v1, v2);
      shadowmatrix(floorshadow, floorplane, lightpos);

      /* 3 points on left wall */
      v0[X] = -100.f; v0[Y] = -100.f; v0[Z] = -320.f;
      v1[X] = -100.f; v1[Y] = -100.f; v1[Z] = -520.f;
      v2[X] = -100.f; v2[Y] =  100.f; v2[Z] = -520.f;

      findplane(lwallplane, v0, v1, v2);
      shadowmatrix(leftwallshadow, lwallplane, lightpos);

    /* place light 0 in the right place */
    glLightfv(GL_LIGHT0, GL_POSITION, lightpos);

    /* remove back faces to speed things up */
    glCullFace(GL_BACK);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

    /* make display lists for sphere and cone; for efficiency */

    glNewList(WALLS, GL_COMPILE);
    glColor3f(1.f, 1.f, 1.f);
    glBegin(GL_QUADS);
    /* right wall */
    glNormal3f(-1.f, 0.f, 0.f);
    glVertex3f( 100.f, -100.f, -320.f);
    glVertex3f( 100.f,  100.f, -320.f);
    glVertex3f( 100.f,  100.f, -520.f);
    glVertex3f( 100.f, -100.f, -520.f);

    /* ceiling */
    glNormal3f(0.f, -1.f, 0.f);
    glVertex3f(-100.f,  100.f, -320.f);
    glVertex3f(-100.f,  100.f, -520.f);
    glVertex3f( 100.f,  100.f, -520.f);
    glVertex3f( 100.f,  100.f, -320.f);

    /* back wall */
    glNormal3f(0.f, 0.f, 1.f);
    glVertex3f(-100.f, -100.f, -520.f);
    glVertex3f( 100.f, -100.f, -520.f);
    glVertex3f( 100.f,  100.f, -520.f);
    glVertex3f(-100.f,  100.f, -520.f);
    glEnd();
    glEndList();


    glNewList(SPHERE, GL_COMPILE);
    sphere = gluNewQuadric();
    glPushMatrix();
    glTranslatef(60.f, -50.f, -360.f);
    gluSphere(sphere, 20.f, 20, 20);
    gluDeleteQuadric(sphere);
    glPopMatrix();
    glEndList();


    glNewList(LIGHT, GL_COMPILE);
    sphere = gluNewQuadric();
    gluSphere(sphere, 5.f, 20, 20);
    gluDeleteQuadric(sphere);
    glEndList();

    glNewList(CONE, GL_COMPILE);
    cone = gluNewQuadric();
    base = gluNewQuadric();
    glPushMatrix();
    glTranslatef(-40.f, -40.f, -400.f);
    glRotatef(-90.f, 1.f, 0.f, 0.f);
    gluDisk(base, 0., 20., 20, 1);
    gluCylinder(cone, 20., 0., 60., 20, 20);
    gluDeleteQuadric(cone);
    gluDeleteQuadric(base);
    glPopMatrix();
    glEndList();


    glNewList(SHADOWERS, GL_COMPILE);
    glCallList(CONE);
    glCallList(SPHERE);
    glEndList();

    glNewList(FLOOR, GL_COMPILE);
    /* make the floor textured */
    glEnable(GL_TEXTURE_2D);
    glBegin(GL_QUADS);
    glNormal3f(0.f, 1.f, 0.f);
    glTexCoord2i(0, 0);
    glVertex3f(-100.f, -100.f, -320.f);
    glTexCoord2i(1, 0);
    glVertex3f( 100.f, -100.f, -320.f);
    glTexCoord2i(1, 1);
    glVertex3f( 100.f, -100.f, -520.f);
    glTexCoord2i(0, 1);
    glVertex3f(-100.f, -100.f, -520.f);
    glEnd();
    glDisable(GL_TEXTURE_2D);
    glEndList();

    glNewList(LEFTWALL, GL_COMPILE);
    glBegin(GL_QUADS);
    /* left wall */
    glNormal3f(1.f, 0.f, 0.f);
    glVertex3f(-100.f, -100.f, -320.f);
    glVertex3f(-100.f, -100.f, -520.f);
    glVertex3f(-100.f,  100.f, -520.f);
    glVertex3f(-100.f,  100.f, -320.f);
    glEnd();
    glEndList();

    floortex = read_texture("../../data/wood0.rgb",
			    &texwid, &texht, &texcomps);

    gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, texwid, texht, GL_RGBA,
		      GL_UNSIGNED_BYTE, floortex);

    free(floortex);

    glEnable(GL_COLOR_MATERIAL);
    glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);

    glutMainLoop();
    return 0;
}
Exemplo n.º 26
0
int main(int argc, char* argv[])
{
  /****************************************/
  /*   Initialize GLUT and create window  */
  /****************************************/

  glutInit(&argc, argv);
  glutInitDisplayMode( GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH );
  glutInitWindowPosition( 50, 50 );
  glutInitWindowSize( 300, 300 );
 
  main_window = glutCreateWindow( "GLUI Example 2" );
  glutDisplayFunc( myGlutDisplay );
  glutReshapeFunc( myGlutReshape );  
  glutKeyboardFunc( myGlutKeyboard );
  glutMotionFunc( myGlutMotion );
  glutMouseFunc( myGlutMouse );

  /****************************************/
  /*       Set up OpenGL lights           */
  /****************************************/

  GLfloat light0_ambient[] =  {0.1f, 0.1f, 0.3f, 1.0f};
  GLfloat light0_diffuse[] =  {.6f, .6f, 1.0f, 1.0f};
  GLfloat light0_position[] = {1.0f, 1.0f, 1.0f, 0.0f};

  glEnable(GL_LIGHTING);
  glEnable(GL_LIGHT0);
  glLightfv(GL_LIGHT0, GL_AMBIENT, light0_ambient);
  glLightfv(GL_LIGHT0, GL_DIFFUSE, light0_diffuse);
  glLightfv(GL_LIGHT0, GL_POSITION, light0_position);

  /****************************************/
  /*          Enable z-buferring          */
  /****************************************/

  glEnable(GL_DEPTH_TEST);

  /****************************************/
  /*         Here's the GLUI code         */
  /****************************************/

  GLUI *glui = GLUI_Master.create_glui( "GLUI", 0, 400, 50 ); /* name, flags,
								 x, and y */
  new GLUI_StaticText( glui, "GLUI Example 2" );
  new GLUI_Separator( glui );
  checkbox = new GLUI_Checkbox( glui, "Wireframe", &wireframe, 1, control_cb );
  spinner  = new GLUI_Spinner( glui, "Segments:", &segments, 2, control_cb );
  spinner->set_int_limits( 3, 60 );
  edittext = new GLUI_EditText( glui, "Text:", text, 3, control_cb );
  GLUI_Panel *obj_panel = new GLUI_Panel( glui, "Object Type" );
  radio = new GLUI_RadioGroup( obj_panel,&obj,4,control_cb );
  new GLUI_RadioButton( radio, "Sphere" );
  new GLUI_RadioButton( radio, "Torus" );
  new GLUI_RadioButton( radio, "Teapot" );
  new GLUI_Button( glui, "Quit", 0,(GLUI_Update_CB)exit );
 
  glui->set_main_gfx_window( main_window );

  /* We register the idle callback with GLUI, *not* with GLUT */
  GLUI_Master.set_glutIdleFunc( myGlutIdle );
  GLUI_Master.set_glutIdleFunc( NULL );

  glutMainLoop();

  return EXIT_SUCCESS;
}
Exemplo n.º 27
0
int
main(int argc, char **argv)
{
  int i;

  glutInitWindowSize(400, 200);
  glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH | GLUT_MULTISAMPLE);
  glutInit(&argc, argv);

  for (i = 1; i < argc; i++) {
    if (!strcmp("-sb", argv[i])) {
      glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_MULTISAMPLE);
      singleBuffer = 1;
    }
  }

  glutCreateWindow("multilight");

  glClearColor(0.0, 0.0, 0.0, 0.0);

  glMatrixMode(GL_PROJECTION);
  gluPerspective(50.0, 2.0, 0.1, 100.0);
  glMatrixMode(GL_MODELVIEW);
  gluLookAt(
    0.0, 1.0, -16.0,
    0.0, 0.0, 0.0,
    0.0, 1.0, 0.);

  numActiveLights = MIN_VALUE(MAX_LIGHTS, 8);
  for (i = 0; i < numActiveLights; i++) {
    initLight(i);
  }

  glLightModelfv(GL_LIGHT_MODEL_AMBIENT, modelAmb);
  glLightModelf(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
  glLightModelf(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
  glEnable(GL_CULL_FACE);
  glEnable(GL_DEPTH_TEST);

  glMaterialfv(GL_FRONT, GL_AMBIENT, matAmb);
  glMaterialfv(GL_FRONT, GL_DIFFUSE, matDiff);
  glMaterialfv(GL_FRONT, GL_SPECULAR, matSpec);
  glMaterialfv(GL_FRONT, GL_EMISSION, matEmission);
  glMaterialf(GL_FRONT, GL_SHININESS, 10.0);

  glNewList(DL_LIGHT_SPHERE, GL_COMPILE);
  glutSolidSphere(0.2, 4, 4);
  glEndList();

  glNewList(DL_BIG_SPHERE, GL_COMPILE);
  glutSolidSphere(1.5, 20, 20);
  glEndList();

  glNewList(DL_ICO, GL_COMPILE);
  glutSolidIcosahedron();
  glEndList();

  glutDisplayFunc(display);
  glutVisibilityFunc(visible);
  glutKeyboardFunc(key);
  glutMouseFunc(mouse);
  glutMotionFunc(motion);

  glutCreateMenu(menu);
  glutAddMenuEntry("Sphere", M_SPHERE);
  glutAddMenuEntry("Icosahedron", M_ICO);
  glutAddMenuEntry("Linear attenuation", M_LINEAR);
  glutAddMenuEntry("Quadratic attenuation", M_QUAD);
  glutAddMenuEntry("Toggle Light Number Labels", M_LABELS);
  glutAddMenuEntry("Report Light Significance", M_REPORT_SIG);
  glutAddMenuEntry("Lambertian-based Significance", M_LAMBERTIAN);
  glutAddMenuEntry("Distance-based Significance", M_DISTANCE);
  glutAddMenuEntry("Time Frames", M_TIME);
  glutAddMenuEntry("Quit", 666);
  glutAttachMenu(GLUT_RIGHT_BUTTON);

  glutMainLoop();
  return 0;             /* ANSI C requires main to return int. */
}
void
bg_mainloop()
{
    glutMainLoop();
    return;
}
Exemplo n.º 29
0
 void enterWindowRunLoop()
 {
   glutMainLoop();
 }
Exemplo n.º 30
0
void Application::run() {
    glutMainLoop();
}