Exemplo n.º 1
0
void* render_thread(void* p)
{
    /* egl init */    
    int width = 512, height = 512;
    struct wl_egl_window* p_wl_egl_window
        = (struct wl_egl_window*)wl_egl_window_create(window->p_wl_surface, width, height);
    if (!p_wl_egl_window) {
        printf("wl_egl_window_create error\n");
    }
    egl = egl_init((EGLNativeDisplayType)window->p_wl_display,
                   (EGLNativeWindowType)p_wl_egl_window);

    /* init */
    init_gl();
    print_gles_env();

    while(1) {
        draw();
        eglSwapBuffers(egl->display, egl->surface);
        FPS();
    }

    return NULL;
}
Exemplo n.º 2
0
ENTRYPOINT void init_cube21(ModeInfo *mi) 
{
  cube21_conf *cp;
  if(!cube21) {
    cube21 = (cube21_conf *)calloc(MI_NUM_SCREENS(mi), sizeof(cube21_conf));
    if(!cube21) return;
  }
  cp = &cube21[MI_SCREEN(mi)];

  cp->trackball = gltrackball_init (False);

  if(!cp->texp) {
    init_posc(cp);
    make_texture(cp);
  }

  if ((cp->glx_context = init_GL(mi)) != NULL) {
    init_gl(mi);
    init_cp(cp);
    reshape_cube21(mi, MI_WIDTH(mi), MI_HEIGHT(mi));
  } else {
    MI_CLEARWINDOW(mi);
  }
}
Exemplo n.º 3
0
static int Init()
{
	nInitedSubsytems = SDL_WasInit(SDL_INIT_VIDEO);

	if (!(nInitedSubsytems & SDL_INIT_VIDEO)) {
		SDL_InitSubSystem(SDL_INIT_VIDEO);
	}

	nGamesWidth = nVidImageWidth;
	nGamesHeight = nVidImageHeight;

	nRotateGame = 0;

	if (bDrvOkay) {
		// Get the game screen size
		BurnDrvGetVisibleSize(&nGamesWidth, &nGamesHeight);

		if (BurnDrvGetFlags() & BDF_ORIENTATION_VERTICAL) {
			printf("Vertical\n");
			nRotateGame = 1;
		}

		if (BurnDrvGetFlags() & BDF_ORIENTATION_FLIPPED) {
			printf("Flipped\n");
			bFlipped = true;
		} 
	}

	if (!nRotateGame) {
		nTextureWidth = GetTextureSize(nGamesWidth);
		nTextureHeight = GetTextureSize(nGamesHeight);
	} else {
		nTextureWidth = GetTextureSize(nGamesHeight);
		nTextureHeight = GetTextureSize(nGamesWidth);
	}

	nSize = 2;
	bVidScanlines = 0;

	RECT test_rect;
	test_rect.left = 0;
	test_rect.right = nGamesWidth;
	test_rect.top = 0;
	test_rect.bottom = nGamesHeight;

	printf("correctx before %d, %d\n", test_rect.right, test_rect.bottom);
	VidSScaleImage(&test_rect);
	printf("correctx after %d, %d\n", test_rect.right, test_rect.bottom);

	screen = SDL_SetVideoMode(test_rect.right * nSize,
				  test_rect.bottom * nSize, 32, SDL_OPENGL);
	SDL_WM_SetCaption("FB Alpha", NULL);

	// Initialize the buffer surfaces
	BlitFXInit();

	// Init opengl
	init_gl();

	return 0;
}
Exemplo n.º 4
0
/*! initializes the engine in console + graphical mode
 */
void engine::init(const char* ico) {
	engine::mode = engine::GRAPHICAL;
	m->print(msg::MDEBUG, "engine.cpp", "initializing albion 2 engine in console + graphical mode");

	// initialize sdl
	atexit(SDL_Quit);
	if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE) == -1) {
		m->print(msg::MERROR, "engine.cpp", "can't init SDL: %s", SDL_GetError());
		exit(1);
	}
	else {
		m->print(msg::MDEBUG, "engine.cpp", "sdl initialized");
	}

	// load opengl library
	SDL_GL_LoadLibrary(NULL);

	// get video info
	video_info = SDL_GetVideoInfo();
	if(!video_info) {
		m->print(msg::MDEBUG, "engine.cpp", "video query failed: %s", SDL_GetError());
		exit(1);
	}

	// not working any more?
	//m->print(msg::MDEBUG, "engine.cpp", "amount of available video memory: %u kb", video_info->video_mem);

	// set some flags
	engine::flags |= SDL_HWPALETTE;
	engine::flags |= SDL_OPENGL;
	engine::flags |= SDL_DOUBLEBUF;
	/*if(video_info->hw_available) {
		//engine::flags |= SDL_HWSURFACE;
		m->print(msg::MDEBUG, "engine.cpp", "using hardware surface");
	}
	else {
		//engine::flags |= SDL_SWSURFACE;
		m->print(msg::MDEBUG, "engine.cpp", "using software surface");
	}*/
	engine::flags |= SDL_HWSURFACE;

	if(fullscreen) {
		engine::flags |= SDL_FULLSCREEN;
		m->print(msg::MDEBUG, "engine.cpp", "fullscreen enabled");
	}
	else {
		m->print(msg::MDEBUG, "engine.cpp", "fullscreen disabled");
	}
	engine::flags |= SDL_HWACCEL;

	// gl attributes
	switch(depth) {
		case 16:
			SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
			SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6);
			SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
			break;
		case 24:
			SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
			SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
			SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
			break;
		case 32:
			SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
			SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
			SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
			break;
		default:
			if(depth < 16) {
				m->print(msg::MERROR, "engine.cpp", "init(): to low depth, please use at least a depth of 16bit!");
				return;
			}
			else { // depth > 16
				m->print(msg::MERROR, "engine.cpp", "init(): unknown depth of %ubit! engine will run in 16bit mode!", depth);
				depth = 16;
				SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
				SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6);
				SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
			}
			break;
	}

	SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, depth);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, zbuffer);
	SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, stencil);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1);

	// ... load icon before SDL_SetVideoMode
	if(ico != NULL) load_ico(ico);

	// create screen
	engine::height = height;
	engine::width = width;
	engine::depth = depth;
	screen = SDL_SetVideoMode(width, height, depth, flags);
	if(screen == NULL) {
		m->print(msg::MERROR, "engine.cpp", "can't set video mode: %s", SDL_GetError());
		exit(1);
	}
	else {
		m->print(msg::MDEBUG, "engine.cpp", "video mode set: w%u h%u d%u", width,
			height, depth);
	}

	int tmp = 0;
	SDL_GL_GetAttribute(SDL_GL_BUFFER_SIZE, &tmp);
	m->print(msg::MDEBUG, "engine.cpp", "color depth set to %d bits", tmp);
	SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &tmp);
	m->print(msg::MDEBUG, "engine.cpp", "z buffer set to %d bits", tmp);
	SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, &tmp);
	m->print(msg::MDEBUG, "engine.cpp", "stencil buffer set to %d bits", tmp);
	SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &tmp);
	m->print(msg::MDEBUG, "engine.cpp", "double buffering %s", tmp == 1 ? "enabled" : "disabled");

	g->set_surface(screen);

	// print out some opengl informations
	m->print(msg::MDEBUG, "engine.cpp", "vendor: %s", glGetString(GL_VENDOR));
	m->print(msg::MDEBUG, "engine.cpp", "renderer: %s", glGetString(GL_RENDERER));
	m->print(msg::MDEBUG, "engine.cpp", "version: %s", glGetString(GL_VERSION));

	// enable key repeat
	if((SDL_EnableKeyRepeat(key_repeat, SDL_DEFAULT_REPEAT_INTERVAL))) {
		m->print(msg::MDEBUG, "engine.cpp", "setting keyboard repeat failed: %s",
				SDL_GetError());
		exit(1);
	}
	else {
		m->print(msg::MDEBUG, "engine.cpp", "keyboard repeat set");
	}

	// initialize ogl
	init_gl();
	m->print(msg::MDEBUG, "engine.cpp", "opengl initialized");

	// resize stuff
	resize_window();

	// reserve memory for position and rotation ...
	engine::position = new vertex3();
	engine::rotation = new vertex3();

	// create extension class object
	exts = new ext(engine::mode, m);

	// set flip state of core class to true if fbos are supported
	if(exts->is_fbo_support()) {
		c->set_flip(true);
	}

	// create render to texture object
	r = new rtt(m, c, g, exts, screen->w, screen->h);

	// print out informations about additional threads
	omp_set_num_threads(thread_count);
	thread_count = omp_get_max_threads();
	thread_count == 1 ? m->print(msg::MDEBUG, "engine.cpp", "using one single thread!") :
		m->print(msg::MDEBUG, "engine.cpp", "using %u threads!", thread_count);

	// if GL_RENDERER is that damn m$ gdi driver, exit a2e ...
	// no official support for this crappy piece of software ...
	if(strcmp((const char*)glGetString(GL_RENDERER), "GDI Generic") == 0) {
		m->print(msg::MERROR, "engine.cpp", "A2E doesn't support the MS GDI Generic driver!\nGo and install one of these (that match your grapic card):\nhttp://www.ati.com  http://www.nvidia.com  http://www.matrox.com  http://www.3dlabs.com http://www.intel.com");
		SDL_Delay(10000);
		exit(1);
	}

	// set standard texture filtering
	t->set_filtering(engine::filtering);

	// check if hdrr is technically possible
	if(hdr && !exts->is_shader_support() && !exts->is_fbo_support()) {
		hdr = false;
	}
	m->print(msg::MDEBUG, "engine.cpp", "HDR-Rendering is %s!", (hdr ? "enabled" : "disabled"));
}
Exemplo n.º 5
0
int main(int argc, char** argv)
{
	if(argc != 2)
		usage(argv[0]);

	FILE* infile = fopen(argv[1], "r");
	if(infile == NULL)
	{
		perror("Error opening input file");
		return EXIT_FAILURE;
	}
	System* sys = load_system(infile);
	if(sys == NULL)
	{
		printf("Loading input file failed\n");
		return EXIT_FAILURE;
	}
	init_simulation(sys);
	state.sys = sys;
	state.views = malloc(sys->nplanets * sizeof(PlanetView));
	for(int i = 0; i < sys->nplanets; i++)
		state.views[i].radius = pow(sys->planets[i].mass / DENSITY_FACTOR, 1.0f/3.0f);
	state.scale = 1.0f;
	Vector* fst_pos = &sys->planets[0].position;
	vector_copy(state.pos, *fst_pos);
	state.pos[1] += 1.1f*get_planet_radius(0);
	state.pos[0] -= get_planet_radius(0);
	state.rot_x = 90.0f;
	state.locked_planet = -1;
	state.hours_per_sec = DEFAULT_SIMULATION_SPEED;
	state.time_step = sys->time_step;
	state.paused = true;
	state.trails_enabled = true;

	if(SDL_Init(SDL_INIT_VIDEO) < 0)
		die("SDL initialization failed");
	atexit(SDL_Quit);
	const SDL_VideoInfo* videoInfo = SDL_GetVideoInfo();
	if(!videoInfo)
		die("Could not get video information");
	int videoFlags = SDL_OPENGL | SDL_HWPALETTE | SDL_RESIZABLE | SDL_HWSURFACE | SDL_HWACCEL;

	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
	SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
	surface = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, videoFlags);
	if(!surface)
	{
		printf("Surface creation failed, trying to disable anti-aliasing...\n");
		SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
		SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
		surface = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, videoFlags);
	}
	if(!surface)
		die("Changing video mode failed");

	init_gl();
	init_viewport();
	SDL_ShowCursor(0);
	SDL_WM_GrabInput(SDL_GRAB_ON);

	SDL_Event event;
	while(SDL_PollEvent(&event))
		;  /* ignore spurious mouse events at startup */

	bool window_is_active = true;
	int step = 0;
	while (true)
	{
		Uint32 next_update = SDL_GetTicks() + FRAME_INTERVAL;
		while (SDL_PollEvent(&event))
		{
			switch(event.type)
			{
				case SDL_ACTIVEEVENT:
					window_is_active = event.active.gain;
					break;			    
				case SDL_VIDEORESIZE:
					surface = SDL_SetVideoMode(event.resize.w,
							event.resize.h,
							SCREEN_BPP, videoFlags);
					if(!surface)
						die("Lost video surface during resize");
					init_viewport();
					break;
				case SDL_KEYDOWN:
					handle_keypress(&event.key.keysym);
					break;
				case SDL_MOUSEMOTION:
					handle_mouse(&event.motion);
					break;
				case SDL_QUIT:
					goto out;
				default:
					break;
			}
		}
		update();
		if(window_is_active)
		{
			draw_scene();
			glFlush();
			SDL_GL_SwapBuffers();
		}
		if(!state.paused)
		{
			for(int i = 0; i < (state.hours_per_sec * 3600.0f / FRAME_INTERVAL) / state.time_step; i++)
			{
				if((step % TRAILS_INTERVAL) == 0)
					update_trails();
				simulate_one_step(sys, step++, state.time_step);
			}
		}
		Sint32 delta = next_update - SDL_GetTicks();
		if(delta > 0)
			SDL_Delay(delta);
	}
out:

	return 0;
}
Exemplo n.º 6
0
BOOL create_gl_window(LPCWSTR title, int width, int height, int bits, bool is_fullscreen)
{
	GLuint pixel_format;
	WNDCLASS wc;

	DWORD dwExStyle;
	DWORD dwStyle;

	RECT windowRect;
	windowRect.left = 0L;
	windowRect.right = (long)width;
	windowRect.top = 0L;
	windowRect.bottom = (long)height;

	fullscreen = is_fullscreen;

	hInstance = GetModuleHandle(nullptr);
	wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
	wc.lpfnWndProc = (WNDPROC)WndProc;
	wc.cbClsExtra = 0;
	wc.cbWndExtra = 0;
	wc.hInstance = hInstance;
	wc.hIcon = LoadIcon(nullptr, IDI_WINLOGO);
	wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
	wc.hbrBackground = nullptr;
	wc.lpszMenuName = nullptr;
	wc.lpszClassName = WND_CLASSNAME;

	if (!RegisterClass(&wc))
	{
		MessageBox(nullptr, L"Could not register window class", L"Create window Error", MB_OK | MB_ICONINFORMATION);
		return FALSE;
	}

	if (fullscreen)
	{
		DEVMODE dmScreenSettings;
		memset(&dmScreenSettings, 0, sizeof(DEVMODE));
		dmScreenSettings.dmSize = sizeof(dmScreenSettings);
		dmScreenSettings.dmPelsWidth = width;
		dmScreenSettings.dmPelsHeight = height;
		dmScreenSettings.dmBitsPerPel = bits;
		dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;

		if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
		{
			if (MessageBox(nullptr, L"The requested fullscreen mode not supported by\nyour video card.\nUse windowed mode instead?",
				L"Create window Error", MB_YESNO | MB_ICONEXCLAMATION) == IDYES)
				fullscreen = false;
			else
			{
				MessageBox(nullptr, L"Program will now close", L"Create window Error", MB_OK | MB_ICONSTOP);
				return FALSE;
			}
		}
	}

	if (fullscreen)
	{
		dwExStyle = WS_EX_APPWINDOW;
		dwStyle = WS_POPUP;
		ShowCursor(FALSE);
	}
	else
	{
		dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
		dwStyle = WS_OVERLAPPEDWINDOW;
	}

	AdjustWindowRectEx(&windowRect, dwStyle, FALSE, dwExStyle);

	/* Creating window */
	if (!(hWnd = CreateWindowEx(dwExStyle,
		WND_CLASSNAME,
		title,
		dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
		0UL, 0UL,
		windowRect.right - windowRect.left,
		windowRect.bottom - windowRect.top,
		nullptr,
		nullptr,
		hInstance,
		nullptr)))
	{
		kill_gl_window();
		MessageBox(nullptr, L"Window creation failed", L"Create window Error", MB_OK | MB_ICONEXCLAMATION);
		return FALSE;
	}

	/* Pixel Format Descriptor */

	static PIXELFORMATDESCRIPTOR pfd =
	{
		sizeof(PIXELFORMATDESCRIPTOR),
		1,
		PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
		PFD_TYPE_RGBA,
		bits,
		0, 0, 0, 0, 0, 0,
		0,
		0,
		0,
		0, 0, 0, 0,
		DEPTH_BITS,		// 32-bit Z-buffer (depth buffer)
		0,
		0,
		PFD_MAIN_PLANE,
		0,
		0, 0, 0
	};

	if (!(hDC = GetDC(hWnd)))
	{
		kill_gl_window();
		MessageBox(nullptr, L"Can't create a GL Device Context.", L"Create window Error", MB_OK | MB_ICONEXCLAMATION);
		return FALSE;
	}

	if (!(pixel_format = ChoosePixelFormat(hDC, &pfd)))
	{
		kill_gl_window();
		MessageBox(nullptr, L"Can't find suitable pixel format.", L"Create window Error", MB_OK | MB_ICONEXCLAMATION);
		return FALSE;
	}

	if (!SetPixelFormat(hDC, pixel_format, &pfd))
	{
		kill_gl_window();
		MessageBox(nullptr, L"Can't set pixel format.", L"Create window Error", MB_OK | MB_ICONEXCLAMATION);
		return FALSE;
	}

	if (!(hRC = wglCreateContext(hDC)))
	{
		kill_gl_window();
		MessageBox(nullptr, L"Can't create GL Rendering Context.", L"Create window Error", MB_OK | MB_ICONEXCLAMATION);
		return FALSE;
	}

	if (!wglMakeCurrent(hDC, hRC))
	{
		kill_gl_window();
		MessageBox(nullptr, L"Can't activate GL Rendering Context.", L"Create window Error", MB_OK | MB_ICONEXCLAMATION);
		return FALSE;
	}

	ShowWindow(hWnd, SW_SHOW);
	SetForegroundWindow(hWnd);
	SetFocus(hWnd);
	resize_gl_scene((GLsizei)width, (GLsizei)height);

	if (!init_gl())
	{
		kill_gl_window();
		MessageBox(nullptr, L"Initialization failed", L"Create window Error", MB_OK | MB_ICONEXCLAMATION);
		return FALSE;
	}

	return TRUE;
}
Exemplo n.º 7
0
Arquivo: opengl.c Projeto: cheque/s3d
void setup_scene_gl(Scene *s)
{
  init_gl(s);
  setup_programs_gl(s, s->objs);
}
Exemplo n.º 8
0
int 
main( int argc, char *argv[ ] )
{
	cmd_args args;
	if( !args.parse( argc, (const char**)argv ) ) {
		return 1;
	}

	//setup glut
	glutInit( &argc, argv );
	glutInitDisplayMode( GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA );
	glutInitWindowSize( 640, 480 );
	glutCreateWindow( "Flock of Birds Demo" );

	//setup gl
	init_gl( );

	//set callbacks
	glutKeyboardFunc( handle_keyboard );
	glutReshapeFunc( handle_resize );
	glutDisplayFunc( render );
	glutIdleFunc( render );

#if ENABLE_FBB
	fob::hemisphere hemisphere = fob::DOWN;
	fob::port_speed speed = args.speed;
	
	//talk to flock
	flock.open( args.serial, hemisphere, speed, args.sleep_ms );
	if( !flock ) {
		std::cerr << "fatal: " << flock.get_error( ) << std::endl;
		return 1;
	}

	//get a list of birds connected to the machine
	fob::bird_list& birds = flock.get_birds( );
	p_birds = &flock.get_birds( );
	num_birds = birds.size( );
	if( num_birds > MAX_ENTS ) num_birds = MAX_ENTS;
#else
	unsigned int num_birds = 1;
#endif
	
#if ENABLE_FBB
	//for each bird, set that we want position and orientation
	for( unsigned int i = 0; i < birds.size( ); ++i ) {
		if( !birds[ i ]->set_mode( fob::POSITION | fob::ORIENTATION | fob::BUTTONS ) ) {
			std::cerr << "fatal: " << flock.get_error( ) << std::endl;
			return 1;
		}
	}
#endif

	//setup the camera
	cam.set_position( 0.0, 100.0, 0.0 );
	cam.set_look_right( math::vector3( 0.0, 0.0, 0.0 ), math::vector3::X_AXIS );
	
#if ENABLE_FBB
	//set the flock flying
	flock.fly( );
	atexit( handle_exit );

	//let the bird start up . . .
	sleep( 1 );
#endif

	//create the button sphere
	sphere = gluNewQuadric( );

	//start glut
	glutMainLoop( );

	//no errors
	return 0;
}
Exemplo n.º 9
0
int main( int argc, char **argv )
{
    if ( use_gui )
    {
        printf("init_sdl()\n");
        if ( init_sdl() ) return 1;

        printf("init_gl()\n");
        init_gl();
    }

    printf("init_fft()\n");
    init_fft();

#ifdef USE_FIFO
    printf("init_mpd()\n");
    if ( init_mpd() ) return 1;
#endif
#ifdef USE_ALSA
    printf("init_alsa()\n");
    if ( init_alsa() ) return 1;
#endif

    if ( use_serial )
    {
        printf("init_serial()\n");
        if ( init_serial() ) use_serial = FALSE;
    }

    init_lights();
    init_table();

    pthread_t sample_thread;

    pthread_create(&sample_thread, NULL, &get_samples, NULL);

    while ( !done )
    {

        // check to see if we have a new sample
        if (new_sample == 1)
        {
            // we are going to process this sample, it is no longer new
            pthread_mutex_lock(&sample_mutex);
            new_sample = 0;
            pthread_mutex_unlock(&sample_mutex);

            do_fft();

            detect_beats();

            assign_lights();

            //assign_cells();

            if ( use_gui )
            {
                if (handle_sdl_events()) return 1;
                draw_all();
            }

            if ( use_serial ) send_serial_fpga();
        }

        usleep(5000);
    }

    return 0;
}
Exemplo n.º 10
0
int main(int argc, char *argv[])
{
	struct opt_data opts; optproc(argc, argv, &opts);
	if(audio_init(&opts) < 0) exit(1);
	if(opts.w < 0 && opts.h < 0) opts.w = opts.h = 512;
	else if(opts.w < 0) opts.w = opts.h;
	else if(opts.h < 0) opts.h = opts.w;
	
	int ret;

	ret = init_drm(&opts, 512);
	if (ret) {
		printf("failed to initialize DRM\n");
		return ret;
	}

	ret = init_gbm();
	if (ret) {
		printf("failed to initialize GBM\n");
		return ret;
	}

	ret = init_egl();
	if (ret) {
		printf("failed to initialize EGL\n");
		return ret;
	}
	
	// call init_gl
	//init_gl(&opts, drm.mode->hdisplay, drm.mode->vdisplay);
	init_gl(&opts, opts.w, opts.h); //TODO: better dealing with our great big screen
	
	eglSwapBuffers(gl.display, gl.surface);
	struct gbm_bo *bo = gbm_surface_lock_front_buffer(gbm.surface);
	fb = drm_fb_get_from_bo(bo);

	/* set mode: */
	ret = drmModeSetCrtc(drm.fd, drm.crtc_id, fb->fb_id, 0, 0,
			&drm.connector_id, 1, drm.mode);
	if (ret) {
		printf("failed to set mode: %s\n", strerror(errno));
		return ret;
	}
	
	// turn off line buffering on input and echoing of characters
	struct termios term;
	tcgetattr(STDIN_FILENO, &save_term);
    tcgetattr(STDIN_FILENO, &term);
    term.c_lflag &= ~(ICANON|ECHO);
    tcsetattr(STDIN_FILENO, TCSANOW, &term);
    
    atexit(shutdown_cleanup);
	
	drmVBlank vbl;
	/* Get current count first hopefully also sync up with blank too*/
	vbl.request.type = DRM_VBLANK_RELATIVE;
	vbl.request.sequence = 1;
	ret = drmWaitVBlank(drm.fd, &vbl);
	if (ret != 0) {
		printf("drmWaitVBlank (relative, event) failed ret: %i\n", ret);
		return -1;
	}
	printf("starting msc: %d\n", vbl.request.sequence);
	
	/* Queue an event for frame + 1 */
	vbl.request.type = DRM_VBLANK_RELATIVE | DRM_VBLANK_EVENT;
	vbl.request.sequence = 1;
	vbl.request.signal = NULL;
	ret = drmWaitVBlank(drm.fd, &vbl);
	if (ret != 0) {
		printf("drmWaitVBlank (relative, event) failed ret: %i\n", ret);
		return -1;
	}
	
	struct pollfd pfds[] = {
		{drm.fd, POLLIN | POLLPRI, 0 },
		{STDIN_FILENO, POLLIN, 0 },
	};

	int debug_maxsrc = 0, debug_pal = 0, show_mandel = 0, show_fps_hist = 0;
	bool done = false;
	while (!done) {

		render_frame(debug_maxsrc, debug_pal, show_mandel, show_fps_hist);

		while (waiting_for_flip) { // TODO: input handling			
			ret = poll(pfds, 2, -1);
			if (ret < 0) {
				printf("poll err: %s\n", strerror(errno));
				return ret;
			} else if (ret == 0) {
				printf("poll timeout!\n");
				done = true;
				break;
			} 
			
			if (pfds[1].revents) {
				char buf[128];
				int cnt = read(STDIN_FILENO, buf, sizeof(buf));
				if(buf[0] == 27) done = true;
				else if(buf[0] == '1') debug_maxsrc = !debug_maxsrc;
				else if(buf[0] == '2') debug_pal = !debug_pal;
				else if(buf[0] == '3') show_mandel = !show_mandel;
				else if(buf[0] == '4') show_fps_hist = !show_fps_hist;
				//continue;
			}
			
			if(pfds[0].revents)
				drmHandleEvent(drm.fd, &evctx);
		}

		/* release last buffer to render on again: */
		gbm_surface_release_buffer(gbm.surface, bo);
		bo = next_bo;
	}
	
	audio_shutdown();

	return ret;
}
Exemplo n.º 11
0
// ---------------------------------------------------------------------------
void OSXWindowImpl::on_init()
{
  init_gl();
  init_glfont();
  aglUpdateContext(mGLContext);
}
Exemplo n.º 12
0
int
main (int argc, char **argv)
{
	int i;
	double now;

	feenableexcept(FE_INVALID|FE_DIVBYZERO|FE_OVERFLOW);

	init_sdl_gl_flags (WIDTH, HEIGHT, 0);

	srandom (time (NULL));

	init_gl (&argc, argv);

	glEnable (GL_LIGHTING);
	glEnable (GL_DEPTH_TEST);
	glEnable (GL_AUTO_NORMAL);
	glEnable (GL_NORMALIZE);

	glClearDepth (1);
	
	glViewport (0, 0, WIDTH, HEIGHT);
	glMatrixMode (GL_PROJECTION);
	glLoadIdentity ();
	gluPerspective (60, (GLfloat) WIDTH/(GLfloat) HEIGHT, .1, 1000);
	glClearColor (0, 0, 0, 0);
	glMatrixMode (GL_MODELVIEW);

	SDL_ShowCursor (1);

	makeImages ();

	glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
	glGenTextures (1, texName);
	
	makeTexture (texName[0], groundtexture.texturesize,
		     (GLubyte ***) groundtexture.tex);

	glTexGeni (GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
	glTexGeni (GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);

	glBlendFunc (GL_SRC_ALPHA, GL_ONE);

	gndcounter = 1;
	read_terrain ();

	player.p.x = 0;
	player.p.y = 0;
	player.p.z = ground_height (&player.p);

	player.loc = detect_plane (&player.p);

	player.movtype = GROUNDED;

	player.speed = 100;
	player.mass = 1;

	vset (&player.vel, 0, 0, 0);

	player.turnspeed = DTOR (180);
	player.theta = DTOR (0);
	player.camdist = 15;

	player.lasttime = get_secs ();
	player.moving = NO;

	playercamera.phi = DTOR (0);
	playercamera.theta_difference = 0;
	
	while (1) {
		process_input ();
		
		if (mousebutton[1] == 0
		    && mousebutton[2] == 0
		    && mousebutton[3] == 0) {
			SDL_ShowCursor (1);
		} else {
			SDL_ShowCursor (0);
		}

		movement ();
		if (paused == NO) {
			for (i = 0; i < 1; i++) {
				moving ();
				now = get_secs ();
				player.lasttime = now;
			}
		}

		process_mouse ();

		draw ();
		
		now = get_secs ();
		
		player.lasttime = now;

		SDL_Delay (10);
	}

	return (0);
}
Exemplo n.º 13
0
int main(int argc, char **argv) {
  init_glut(&argc, argv);
  init_gl();
  glutMainLoop();
  return 0;
}
Exemplo n.º 14
0
		void init()
		{
			input_handler = 0;
			init_keytable();

			//_ui_events.reserve(40);

			_ui_key = 0;

			WNDCLASS wc = { 0 };
			wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
			wc.lpfnWndProc = wnd_proc;
			wc.hInstance = GetModuleHandle(0);
			wc.hIcon = LoadIcon(0, IDI_WINLOGO);
			wc.hCursor = LoadCursor(0, IDC_ARROW);
			wc.lpszClassName = "shiva_wc";

			if (!RegisterClass(&wc)) {
				TRACE("Failed to register window class\n");
				return;
			}

			init_gl();

			DWORD style = WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_OVERLAPPEDWINDOW;
			DWORD xstyle = WS_EX_APPWINDOW;

			PIXELFORMATDESCRIPTOR pfd = {
				sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
				PFD_TYPE_RGBA, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, PFD_MAIN_PLANE, 0, 0, 0, 0
			};



			if (0/*fulscreen*/) {
				style = WS_POPUP | WS_MAXIMIZE;
				xstyle |= WS_EX_TOPMOST;

				DEVMODE deviceMode = { 0 };
				deviceMode.dmSize = sizeof(DEVMODE);
				EnumDisplaySettings(0, ENUM_CURRENT_SETTINGS, &deviceMode);

				if (ChangeDisplaySettings(&deviceMode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) {
					TRACE("Failed to set fullscreen window");
				}
			}

			RECT wr = { 0, 0, 800, 600 };
			AdjustWindowRectEx(&wr, style, 0, xstyle);
			int w = wr.right - wr.left;
			int h = wr.bottom - wr.top;

			wnd = CreateWindowEx(xstyle, wc.lpszClassName, "OpenVG", style, 10, 10, w, h, 0, 0, wc.hInstance, 0);
			if (!wnd) {
				TRACE("Failed to create system window!\n");
				return;
			}

			dc = GetDC(wnd);

			int pixelFormat;
			BOOL valid;
			UINT numFormats;
			int iAttributes[] = {
				WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
				WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
				WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB,
				WGL_COLOR_BITS_ARB, 24,
				WGL_ALPHA_BITS_ARB, 8,
				WGL_DEPTH_BITS_ARB, 24,
				WGL_STENCIL_BITS_ARB, 8,
				WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
				0, 0 };

			    // WGL_SAMPLE_BUFFERS_ARB, GL_TRUE,
				// WGL_SAMPLES_ARB, 4,                        // Check For 4x Multisampling


			if (wglChoosePixelFormatARB == NULL)
			{
				if (wglGetCurrentContext() == NULL) {
					// 
					MessageBoxA(0, (char*)glGetString(GL_VERSION), "Context lost", 0);

				}


				MessageBoxA(0, (char*)glGetString(GL_VERSION), "Cannot find extension, wglChoosePixelFormatARB", 0);
			}
			else
			{

				valid = wglChoosePixelFormatARB(dc, iAttributes, 0, 1, &pixelFormat, &numFormats);

				int pf = ChoosePixelFormat(dc, &pfd);
				BOOL ok = SetPixelFormat(dc, pixelFormat, &pfd);

			}

			int attr[] = {
				WGL_CONTEXT_MAJOR_VERSION_ARB, 1,
				WGL_CONTEXT_MINOR_VERSION_ARB, 2,
				WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
				WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
				WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_DEBUG_BIT_ARB,
				0
			};

			                                                                 
			if (wglCreateContextAttribsARB == NULL)
			{
				MessageBoxA(0, (char*)glGetString(GL_VERSION), "Cannot find extension, wglCreateContextAttribsARB", 0);
				return;
			}


			glrc = wglCreateContextAttribsARB(dc, 0, attr);

			/*
			for (int i = 0; i < 2; ++i) {
			GLuint swap_group = 1;
			if (!wglJoinSwapGroupNV(context.channels[i].dc, swap_group)) {
			TRACE("ERROR: failed to join sawp group");
			}
			if (!wglBindSwapBarrierNV(swap_group, 1)) {
			TRACE("ERROR: failed to bind sawp barrier");
			}
			}
			*/

			// set channel 0 to current so graphics can initiate correctly
			wglMakeCurrent(dc, glrc);

			glDebugMessageCallbackARB = (PFGLDEBUGMESSAGECALLBACKARB) wglGetProcAddress("glDebugMessageCallbackARB");
			if (glDebugMessageCallbackARB == NULL)
			{
				MessageBoxA(0, (char*)glGetString(GL_VERSION), "Unimplemented glDebugMessageCallbackARB", 0);
			}
			else
			{
				glDebugMessageCallbackARB(&gl_debug_msg_proc, 0);
				glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
			}

			ShowWindow(wnd, SW_SHOW);
			UpdateWindow(wnd);

			vgCreateContextSH(800, 600);
		}
Exemplo n.º 15
0
int
main(int argc, char **argv)
{
	struct sigaction sigint;
	struct display display = { 0 };
	struct window  window  = { 0 };
	int i, ret = 0;

	window.display = &display;
	display.window = &window;
	window.window_size.width  = 250;
	window.window_size.height = 250;

	for (i = 1; i < argc; i++) {
		if (strcmp("-f", argv[i]) == 0)
			window.fullscreen = 1;
		else if (strcmp("-o", argv[i]) == 0)
			window.opaque = 1;
		else if (strcmp("-h", argv[i]) == 0)
			usage(EXIT_SUCCESS);
		else
			usage(EXIT_FAILURE);
	}

	display.display = wl_display_connect(NULL);
	assert(display.display);

	display.registry = wl_display_get_registry(display.display);
	wl_registry_add_listener(display.registry,
				 &registry_listener, &display);

	wl_display_dispatch(display.display);

	init_egl(&display, window.opaque);
	create_surface(&window);
	init_gl(&window);

	display.cursor_surface =
		wl_compositor_create_surface(display.compositor);

	sigint.sa_handler = signal_int;
	sigemptyset(&sigint.sa_mask);
	sigint.sa_flags = SA_RESETHAND;
	sigaction(SIGINT, &sigint, NULL);

	while (running && ret != -1)
		ret = wl_display_dispatch(display.display);

	fprintf(stderr, "simple-egl exiting\n");

	destroy_surface(&window);
	fini_egl(&display);

	wl_surface_destroy(display.cursor_surface);
	if (display.cursor_theme)
		wl_cursor_theme_destroy(display.cursor_theme);

	if (display.shell)
		wl_shell_destroy(display.shell);

	if (display.compositor)
		wl_compositor_destroy(display.compositor);

	wl_registry_destroy(display.registry);
	wl_display_flush(display.display);
	wl_display_disconnect(display.display);

	return 0;
}
Exemplo n.º 16
0
int main(int argc, char **argv)
{
	opt_data opts; optproc(argc, argv, &opts);
	if(audio_init(&opts) < 0) exit(1);
	int x = 0, y = 0, w, h;
	if(opts.w < 0 && opts.h < 0) opts.w = opts.h = 512;
	else if(opts.w < 0) opts.w = opts.h;
	else if(opts.h < 0) opts.h = opts.w;
	w = opts.w; h = opts.h;
	
	XEvent event;
	
	dpy = XOpenDisplay( NULL );
	if(dpy == NULL) {
        printf("Error: couldn't open display %s\n", getenv("DISPLAY"));
        exit(EXIT_FAILURE);
    }
    
    int glx_major, glx_minor;
    if(!glXQueryVersion(dpy, &glx_major, &glx_minor)) {
    	printf("GLX extension missing!\n");
    	XCloseDisplay(dpy);
    	exit(EXIT_FAILURE); 
    }
    printf("GLX version %i.%i\n", glx_major, glx_minor);

    int glxErrBase, glxEventBase;
    glXQueryExtension(dpy, &glxErrBase, &glxEventBase);
    printf("GLX: errorBase = %i, eventBase = %i\n", glxErrBase, glxEventBase);
    
    
    Window xwin, root;
    int numReturned;
    GLXFBConfig *fbConfigs;
    fbConfigs = glXChooseFBConfig( dpy, DefaultScreen(dpy), fbattrib, &numReturned );
    
   	if(fbConfigs == NULL) {  //TODO: handle this?
   		printf("No suitable fbconfigs!\n");
   		exit(EXIT_FAILURE);
   	}
   	
   	XVisualInfo  *vinfo = glXGetVisualFromFBConfig( dpy, fbConfigs[0] );
   	
	root = DefaultRootWindow(dpy);
   	
   	/* window attributes */
   	XSetWindowAttributes attrs;
	attrs.background_pixel = 0;
	attrs.border_pixel = 0;
	attrs.colormap = XCreateColormap(dpy, root, vinfo->visual, AllocNone);
	//attrs.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask;
	attrs.event_mask = StructureNotifyMask | KeyPressMask;
	unsigned long mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
	xwin = XCreateWindow(dpy, root, x, y, w, h,
		                 0, vinfo->depth, InputOutput,
		                 vinfo->visual, mask, &attrs);
	XFree(vinfo);
	
	// Set hints and properties:
	{
		XSizeHints sizehints;
		sizehints.x = x;
		sizehints.y = y;
		sizehints.width  = w;
		sizehints.height = h;
		sizehints.flags = USSize | USPosition;
		XSetNormalHints(dpy, xwin, &sizehints);
		XSetStandardProperties(dpy, xwin, "Julia-vis", "Julia-vis",
				               None, (char **)NULL, 0, &sizehints);
	}
   	
   	/* Create a GLX context for OpenGL rendering */
    GLXContext context = glXCreateNewContext(dpy, fbConfigs[0], GLX_RGBA_TYPE, NULL, True );
    
#if 0
	GLXContext context = 0;
	
	glXCreateContextAttribsARBProc glXCreateContextAttribsARB = 0;
	glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc)glXGetProcAddressARB( (const GLubyte *) "glXCreateContextAttribsARB" );

	if(strstr(glXQueryExtensionsString(dpy, 0), "GLX_ARB_create_context") || !glXCreateContextAttribsARB) {
		printf("glXCreateContextAttribsARB() not found ... using old-style GLX context\n");
		context = glXCreateNewContext(dpy, fbConfigs[0], GLX_RGBA_TYPE, 0, True);
	} else {
		const int context_attribs[] = {
			GLX_RENDER_TYPE, GLX_RGBA_TYPE,
			GLX_CONTEXT_MAJOR_VERSION_ARB, 2,
			GLX_CONTEXT_MINOR_VERSION_ARB, 1,
			None
		};
		context = glXCreateContextAttribsARB(dpy, fbConfigs[0], NULL, True, context_attribs);
    }
    
    if(context == NULL) {
    	printf("Failed to create context!\n");
    	return EXIT_FAILURE;
    }
#endif
    
    glxWin = glXCreateWindow(dpy, fbConfigs[0], xwin, NULL );
    
    XMapWindow(dpy, xwin);
    XIfEvent(dpy, &event, WaitForNotify, (XPointer) xwin);
    
    glXMakeContextCurrent(dpy, glxWin, glxWin, context);
	
	init_gl(&opts, w, h);
	
	if(strstr(glXQueryExtensionsString(dpy, 0), "GLX_MESA_swap_control")) {
		PFNGLXSWAPINTERVALMESAPROC swap_interval = glXGetProcAddressARB("glXSwapIntervalMESA");
		swap_interval(1);
		opts.draw_rate = 300;
	}
	
	if(strstr(glXQueryExtensionsString(dpy, 0), "GLX_INTEL_swap_event")) {
    	glXSelectEvent(dpy, glxWin, GLX_BUFFER_SWAP_COMPLETE_INTEL_MASK);
    	have_intel_swap_event = GL_TRUE;
    }

	int debug_maxsrc = 0, debug_pal = 0, show_mandel = 0, show_fps_hist = 0;
	
	if(have_intel_swap_event)
		render_frame(debug_maxsrc, debug_pal, show_mandel, show_fps_hist);
	
	while(1) {
		if(!have_intel_swap_event) render_frame(debug_maxsrc, debug_pal, show_mandel, show_fps_hist);
		
		int clear_key = 1;
		while (XPending(dpy) > 0) 
		{
			XNextEvent(dpy, &event);
			
			if(event.type == glxEventBase + GLX_BufferSwapComplete) {
				render_frame(debug_maxsrc, debug_pal, show_mandel, show_fps_hist);
				continue;
			}
			
			switch (event.type) {
				case Expose:
				/* we'll redraw below */
				break;
				/*case ConfigureNotify:
				window_w = event.xconfigure.width;
				window_h = event.xconfigure.height;
				if (surface_type == EGL_WINDOW_BIT)
				reshape(window_w, window_h);
				break;*/
				case KeyPress:
				{
					clear_key = 0;
					char buffer[10];
					int r, code;
					code = XLookupKeysym(&event.xkey, 0);
					if (code == XK_F1) {
						debug_maxsrc = !debug_maxsrc;
					} else if (code == XK_F2) {
						debug_pal = !debug_pal;
					} else if (code == XK_F3) {
						show_mandel = !show_mandel;
					} else if (code == XK_F4) {
						show_fps_hist = !show_fps_hist;
					} else {
						code = XLookupKeysym(&event.xkey, 1);
						if(code == XK_Escape) {
							goto glx_main_loop_quit;
						}
					}
				}
				break;
				
				default:
					//printf("Bar %i!\n", event.type);
					
					break;
			}
		}
	}
glx_main_loop_quit:
	audio_shutdown();
	
	XDestroyWindow(dpy, xwin);
	XCloseDisplay(dpy);
	
	return 0;
}
Exemplo n.º 17
0
//----------------------------------------------------------------------
int main(int argc, char** argv)
{
    printf("Hello, OpenCL\n");

    // Parse command line options
    //
    int use_gpu = 1;
    for(int i = 0; i < argc && argv; i++)
    {
        if(!argv[i])
            continue;
            
        if(strstr(argv[i], "cpu"))
            use_gpu = 0;        

        else if(strstr(argv[i], "gpu"))
            use_gpu = 1;
    }

    printf("Parameter detect %s device\n",use_gpu==1?"GPU":"CPU");

    //Setup our GLUT window and OpenGL related things
    //glut callback functions are setup here too
    init_gl(argc, argv);

    //initialize our CL object, this sets up the context
    example = new CL(use_gpu);
    
    //load and build our CL program from the file
    //#include "part2.cl" //std::string kernel_source is defined in this file
    example->loadProgram("part2.cl");

    //initialize our particle system with positions, velocities and color
    int num = NUM_PARTICLES;
    std::vector<Vec4> pos(num);
    std::vector<Vec4> vel(num);
    std::vector<Vec4> color(num);

    //fill our vectors with initial data
    for(int i = 0; i < num; i++)
    {
        //distribute the particles in a random circle around z axis
        float rad = rand_float(.2, .5);
        float x = rad*sin(2*3.14 * i/num);
        float z = 0.0f;// -.1 + .2f * i/num;
        float y = rad*cos(2*3.14 * i/num);
        pos[i] = Vec4(x, y, z, 1.0f);
        
        //give some initial velocity 
        //float xr = rand_float(-.1, .1);
        //float yr = rand_float(1.f, 3.f);
        //the life is the lifetime of the particle: 1 = alive 0 = dead
        //as you will see in part2.cl we reset the particle when it dies
        float life_r = rand_float(0.f, 1.f);
        vel[i] = Vec4(0.0, 0.0, 3.0f, life_r);

        //just make them red and full alpha
        color[i] = Vec4(1.0f, 0.0f,0.0f, 1.0f);
    }

    //our load data function sends our initial values to the GPU
    example->loadData(pos, vel, color);
    //initialize the kernel
    example->popCorn();
    
    //this starts the GLUT program, from here on out everything we want
    //to do needs to be done in glut callback functions
    glutMainLoop();

}
Exemplo n.º 18
0
int main(int argc, char** argv)
{
	// Create a configuration object, and set the values to the defaults
	configuration config;

	config.num_threads = NUM_THREADS;

	config.video.screen_width = SCREEN_WIDTH;
	config.video.screen_height = SCREEN_HEIGHT;
	config.video.screen_depth = SCREEN_DEPTH;
	config.video.frames_per_second = FPS;

	config.input.influence_radius = INFLUENCE_RADIUS;

	config.flock.size = NUM_BOIDS;
	config.flock.max_velocity = MAX_BOID_VELOCITY;
	config.flock.min_separation = MIN_BOID_SEPARATION;
	config.flock.max_steering_force = MAX_BOID_STEERING_FORCE;
	config.flock.neighborhood_radius = NEIGHBORHOOD_RADIUS;

	// Parse arguments
	int i;
	for(i = 1; i < argc; i++)
	{
		if(strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0)
			return print_help();
		else if(strcmp(argv[i], "--width") == 0)
			config.video.screen_width = atoi(argv[++i]);
		else if(strcmp(argv[i], "--height") == 0)
			config.video.screen_height = atoi(argv[++i]);
		else if(strcmp(argv[i], "--depth") == 0)
			config.video.screen_depth = atoi(argv[++i]);
		else if(strcmp(argv[i], "--fps") == 0)
			config.video.frames_per_second = atoi(argv[++i]);
		else if(strcmp(argv[i], "-ir") == 0 || strcmp(argv[i], "--influence-radius") == 0)
			config.input.influence_radius = atoi(argv[++i]);
		else if(strcmp(argv[i], "-fc") == 0 || strcmp(argv[i], "--flock-count") == 0)
			config.flock.size = atoi(argv[++i]);
		else if(strcmp(argv[i], "-fs") == 0 || strcmp(argv[i], "--flock-separation") == 0)
			config.flock.min_separation = atoi(argv[++i]);
		else if(strcmp(argv[i], "-fv") == 0 || strcmp(argv[i], "--flock-velocity") == 0)
			config.flock.max_velocity = atoi(argv[++i]);
		else if(strcmp(argv[i], "-fn") == 0 || strcmp(argv[i], "--flock-neighborhood") == 0)
			config.flock.neighborhood_radius = atoi(argv[++i]);
		else if(strcmp(argv[i], "-t") == 0 || strcmp(argv[i], "--num-threads") == 0)
			config.num_threads = atoi(argv[++i]);
	}

	srand(time(NULL));

	// Init SDL and create our screen
	if(SDL_Init(SDL_INIT_VIDEO) < 0) printf("Unable to initialize SDL. %s\n", SDL_GetError());
	SDL_Event event;

	int flags = SDL_OPENGL;

	// Attempt to set the video mode
	SDL_Surface* screen = SDL_SetVideoMode(config.video.screen_width, config.video.screen_height,
					       config.video.screen_depth, flags);

	if(!screen) printf("Unable to set video mode.\n");

	// Set the window caption
	SDL_WM_SetCaption("tinyflock", NULL);

	// Create our flock
	boid* flock = create_flock(&config);

	init_gl(config.video.screen_width, config.video.screen_height);

	vector cursor_pos;
	vector_init_scalar(&cursor_pos, 0);

	int cursor_interaction = 0;
	int run = 1;

	int update_count = 0;
	int frame_count = 0;

	flock_update_args update_args = {&run, flock, &config, &cursor_pos, &cursor_interaction, &update_count };
	SDL_Thread* update = SDL_CreateThread(flock_update_thread, (void*)&update_args);

	status_args stat_args = {&run, &frame_count, &update_count};
	SDL_Thread* status = SDL_CreateThread(status_thread, (void*)&stat_args);

	// If the frame limit is not greater than 0, don't delay between frames at all.
	float delay = (1000 / config.video.frames_per_second);

	while(run)
	{
		run = handle_events(&event, &cursor_pos, &cursor_interaction);
		flock_render(flock, &config, screen);

		SDL_Delay(delay);
		frame_count++;
	}

	SDL_WaitThread(update, NULL);
	SDL_WaitThread(status, NULL);

	destroy_flock(flock);
	SDL_Quit();

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

	/*---------------------- Initialize OpenGL and OpenCL ----------------------*/

	if (init_gl(argc,argv,&glinfo, window_size, "RT") != 0){
		std::cerr << "Failed to initialize GL" << std::endl;
		exit(1);
	} else { 
		std::cout << "Initialized GL succesfully" << std::endl;
	}

	if (init_cl(glinfo,&clinfo) != CL_SUCCESS){
		std::cerr << "Failed to initialize CL" << std::endl;
		exit(1);
	} else { 
		std::cout << "Initialized CL succesfully" << std::endl;
	}
	print_cl_info(clinfo);

        /* Initialize device interface */
        if (device.initialize(clinfo)) {
                std::cerr << "Failed to initialize device interface" << std::endl;
                exit(1);
        }
        /* Initialize generic gpu library */
        DeviceFunctionLibrary::initialize(clinfo);

	/*---------------------- Create shared GL-CL texture ----------------------*/
	gl_tex = create_tex_gl(window_size[0],window_size[1]);
        tex_id = device.new_memory();
        DeviceMemory& tex_mem = device.memory(tex_id);
        if (tex_mem.initialize_from_gl_texture(gl_tex)) {
                std::cerr << "Failed to create memory object from gl texture" << std::endl;
                exit(1);
        }

	/*---------------------- Set up scene ---------------------------*/
	frames = 15;
	const std::string pack = "pack1OBJ";
	// const std::string pack = "pack2OBJ";
	double wave_attenuation = 1.f;

        scenes.resize(frames);
	for (uint32_t i = 0; i < frames ; ++i) {

                scenes[i].initialize();
		std::stringstream grid_path,visual_path;
		grid_path << "models/obj/" << pack << "/gridFluid" << i+1 << ".obj";
		mesh_id grid_mid = scenes[i].load_obj_file_as_aggregate(grid_path.str());
		object_id grid_oid = scenes[i].add_object(grid_mid);
		Object& grid = scenes[i].object(grid_oid);
		grid.mat.diffuse = White;
		grid.mat.reflectiveness = 0.95f;
		grid.mat.refractive_index = 1.5f;
		grid.geom.setScale(makeVector(1.f,wave_attenuation,1.f));

		/* ---- Solids ------ */
		// visual_path << "models/obj/" << pack << "/visual" << visual_frame << ".obj";
		// mesh_id visual_mid = scenes[i].load_obj_file_as_aggregate(visual_path.str());
		// object_id visual_oid = scenes[i].geometry.add_object(visual_mid);
		// Object& visual = scenes[i].geometry.object(visual_oid);
		// visual.mat.diffuse = Red;

		// for (uint32_t j = 0; j < bridge_parts ; ++j) {
		// 	std::stringstream bridge_path;
		// 	bridge_path << "models/obj/" << pack << "/bridge" << j << i+1 << ".obj";
		// 	mesh_id bridge_mid = scenes[i].load_obj_file_as_aggregate(bridge_path.str());
		// 	object_id bridge_oid = scenes[i].geometry.add_object(bridge_mid);
		// 	Object& bridge = scenes[i].geometry.object(bridge_oid);
		// 	bridge.mat.diffuse = Green;
		// }

		// mesh_id teapot_mesh_id = scenes[i].load_obj_file_as_aggregate("models/obj/teapot2.obj");
		// mesh_id teapot_mesh_id = scenes[i].load_obj_file_as_aggregate("models/obj/teapot-low_res.obj");
		// object_id teapot_obj_id = scenes[i].geometry.add_object(teapot_mesh_id);
		// Object& teapot_obj = scenes[i].geometry.object(teapot_obj_id);
		// teapot_obj.geom.setPos(makeVector(-1.f,0.f,0.f));
		// teapot_obj.geom.setScale(makeVector(3.f,3.f,3.f));
		// teapot_obj.mat.diffuse = Green;
		// teapot_obj.mat.shininess = 1.f;
		// teapot_obj.mat.reflectiveness = 0.3f;

		/* ------------------*/

                // scenes[i].set_accelerator_type(KDTREE_ACCELERATOR);
                scenes[i].set_accelerator_type(BVH_ACCELERATOR);
		scenes[i].create_aggregate_mesh();
		scenes[i].create_aggregate_accelerator();
		Mesh& scene_mesh = scenes[i].get_aggregate_mesh();
                if (scenes[i].transfer_aggregate_mesh_to_device() 
                    || scenes[i].transfer_aggregate_accelerator_to_device())
                        std::cerr << "Failed to transfer scene info to device"<< std::endl;


		/*---------------------- Print scene data ----------------------*/
		std::cerr << "Scene " << i << " stats: " << std::endl;
		std::cerr << "\tTriangle count: " << scene_mesh.triangleCount() << std::endl;
		std::cerr << "\tVertex count: " << scene_mesh.vertexCount() << std::endl;
		std::cerr << std::endl;
	}


	/*---------------------- Set initial Camera paramaters -----------------------*/
	camera.set(makeVector(0,3,-30), makeVector(0,0,1), makeVector(0,1,0), M_PI/4.,
		   window_size[0] / (float)window_size[1]);

	/*---------------------------- Set tile size ------------------------------*/
	best_tile_size = clinfo.max_compute_units * clinfo.max_work_item_sizes[0];
	best_tile_size *= 64;
	best_tile_size = std::min(pixel_count, best_tile_size);

	/*---------------------- Initialize ray bundles -----------------------------*/
	int32_t ray_bundle_size = best_tile_size * 4;

	if (ray_bundle_1.initialize(ray_bundle_size)) {
		std::cerr << "Error initializing ray bundle 1" << std::endl;
		std::cerr.flush();
		exit(1);
	}

	if (ray_bundle_2.initialize(ray_bundle_size)) {
		std::cerr << "Error initializing ray bundle 2" << std::endl;
		std::cerr.flush();
		exit(1);
	}
	std::cout << "Initialized ray bundles succesfully" << std::endl;

	/*---------------------- Initialize hit bundle -----------------------------*/
	int32_t hit_bundle_size = ray_bundle_size;

	if (hit_bundle.initialize(hit_bundle_size)) {
		std::cerr << "Error initializing hit bundle" << std::endl;
		std::cerr.flush();
		exit(1);
	}
	std::cout << "Initialized hit bundle succesfully" << std::endl;

	/*----------------------- Initialize cubemap ---------------------------*/
	if (cubemap.initialize("textures/cubemap/Path/posx.jpg",
                               "textures/cubemap/Path/negx.jpg",
                               "textures/cubemap/Path/posy.jpg",
                               "textures/cubemap/Path/negy.jpg",
                               "textures/cubemap/Path/posz.jpg",
                               "textures/cubemap/Path/negz.jpg")) {  
		std::cerr << "Failed to initialize cubemap." << std::endl;
		exit(1);
	}
	std::cerr << "Initialized cubemap succesfully." << std::endl;

	/*------------------------ Initialize FrameBuffer ---------------------------*/
	if (framebuffer.initialize(window_size)) {
		std::cerr << "Error initializing framebuffer." << std::endl;
		exit(1);
	}
	std::cout << "Initialized framebuffer succesfully." << std::endl;

	/* ------------------ Initialize ray tracer kernel ----------------------*/
	if (tracer.initialize()){
		std::cerr << "Failed to initialize tracer." << std::endl;
		return 0;
	}
	std::cerr << "Initialized tracer succesfully." << std::endl;


	/* ------------------ Initialize Primary Ray Generator ----------------------*/
	if (prim_ray_gen.initialize()) {
		std::cerr << "Error initializing primary ray generator." << std::endl;
		exit(1);
	}
	std::cout << "Initialized primary ray generator succesfully." << std::endl;


	/* ------------------ Initialize Secondary Ray Generator ----------------------*/
	if (sec_ray_gen.initialize()) {
		std::cerr << "Error initializing secondary ray generator." << std::endl;
		exit(1);
	}
	sec_ray_gen.set_max_rays(ray_bundle_1.count());
	std::cout << "Initialized secondary ray generator succesfully." << std::endl;

	/*------------------------ Initialize RayShader ---------------------------*/
	if (ray_shader.initialize()) {
		std::cerr << "Error initializing ray shader." << std::endl;
		exit(1);
	}
	std::cout << "Initialized ray shader succesfully." << std::endl;

	/*----------------------- Enable timing in all clases -------------------*/
	framebuffer.timing(true);
	prim_ray_gen.timing(true);
	sec_ray_gen.timing(true);
	tracer.timing(true);
	ray_shader.timing(true);

	/*------------------------- Count mem usage -----------------------------------*/
	int32_t total_cl_mem = 0;
	total_cl_mem += pixel_count * 4; /* 4bpp texture */
	// for (uint32_t i = 0; i < frames; ++i)  
	// 	total_cl_mem += scene_info[i].size();
	total_cl_mem += ray_bundle_1.mem().size() + ray_bundle_2.mem().size();
	total_cl_mem += hit_bundle.mem().size();
	total_cl_mem += cubemap.positive_x_mem().size() * 6;
	total_cl_mem += framebuffer.image_mem().size();

	std::cout << "\nMemory stats: " << std::endl;
	std::cout << "\tTotal opencl mem usage: " 
		  << total_cl_mem/1e6 << " MB." << std::endl;
	// for (uint32_t i = 0; i < frames; ++i)  
	// 	std::cout << "\tScene " << i << " mem usage: " << scene_info[i].size()/1e6 << " MB." << std::endl;

	std::cout << "\tFramebuffer+Tex mem usage: " 
		  << (framebuffer.image_mem().size() + pixel_count * 4)/1e6
		  << " MB."<< std::endl;
	std::cout << "\tCubemap mem usage: " 
		  << (cubemap.positive_x_mem().size()*6)/1e6 
		  << " MB."<< std::endl;
	std::cout << "\tRay mem usage: " 
		  << (ray_bundle_1.mem().size()*2)/1e6
		  << " MB."<< std::endl;
	std::cout << "\tRay hit info mem usage: " 
		  << hit_bundle.mem().size()/1e6
		  << " MB."<< std::endl;

        /* !! ---------------------- Test area ---------------- */
	std::cerr << std::endl;
	std::cerr << "Misc info: " << std::endl;

	std::cerr << "Tile size: " << best_tile_size << std::endl;
	std::cerr << "Tiles: " << pixel_count / (float)best_tile_size << std::endl;
	std::cerr << "color_cl size: "
		  << sizeof(color_cl)
		  << std::endl;
	std::cerr << "directional_light_cl size: "
		  << sizeof(directional_light_cl)
		  << std::endl;

	std::cerr << "ray_cl size: "
		  << sizeof(ray_cl)
		  << std::endl;
	std::cerr << "sample_cl size: "
		  << sizeof(sample_cl)
		  << std::endl;
	std::cerr << "sample_trace_info_cl size: "
		  << sizeof(sample_trace_info_cl)
		  << std::endl;

	/*------------------------ Set GLUT and misc functions -----------------------*/
	rt_time.snap_time();
	seq_time.snap_time();

	glutKeyboardFunc(gl_key);
	glutMotionFunc(gl_mouse);
	glutDisplayFunc(gl_loop);
	glutIdleFunc(gl_loop);
	glutMainLoop();	

	clinfo.release_resources();

	return 0;
}
Exemplo n.º 20
0
Arquivo: main.cpp Projeto: ba50/nBody
//----------------------------------------------------------------------
int main(int argc, char** argv)
{
	
	int i, j, k;
	double r_ij;

	FILE *XYZ_file, *p_file;

	std::ifstream IN_file;

	std::string buffer;
	std::string IN_filename = "in";
	std::string OUT_filename ="out";
	std::string XYZ_filename = "xyz";

	parameters param;
	state stat;
	Vector sumaP;

	/* Load data */

	IN_file.open(IN_filename);

	IN_file >> param.n;
	std::getline(IN_file, buffer);

	IN_file >> param.m;
	std::getline(IN_file, buffer);

	IN_file >> param.e;
	std::getline(IN_file, buffer);

	IN_file >> param.R;
	std::getline(IN_file, buffer);

	IN_file >> param.f;
	std::getline(IN_file, buffer);

	IN_file >> param.L;
	std::getline(IN_file, buffer);

	IN_file >> param.a;
	std::getline(IN_file, buffer);

	IN_file >> stat.T;
	std::getline(IN_file, buffer);

	IN_file >> param.tau;
	std::getline(IN_file, buffer);

	IN_file >> param.So;
	std::getline(IN_file, buffer);

	IN_file >> param.Sd;
	std::getline(IN_file, buffer);

	IN_file >> param.Sout;
	std::getline(IN_file, buffer);

	IN_file >> param.Sxyz;
	std::getline(IN_file, buffer);

	IN_file.close();

	param.L = param.L * param.a*(param.n - 1);

	/* Okreslanie stanu poczatkowego ukladu */

	srand(time_t(NULL));

	param.N = (int) pow(param.n, 3);

	stat.r = new Vector[param.N];
	stat.p = new Vector[param.N];
	stat.F_p = new Vector[param.N];
	stat.F_s = new Vector[param.N];
printf("init \n");
	for (i = 0; i < param.n; i++){
		for (j = 0; j < param.n; j++){
			for (k = 0; k < param.n; k++){
				stat.r[i + j*param.n + k*param.n*param.n].x = (i - (param.n - 1) / 2.f)*param.a + (j - (param.n - 1) / 2) * param.a / 2.f + (k - (param.n - 1) / 2)*param.a / 2.f;
				stat.r[i + j*param.n + k*param.n*param.n].y = (j - (param.n - 1) / 2)*param.a*sqrt(3.f) / 2 + (k - (param.n - 1) / 2)*param.a*sqrt(3.f) / 6;
				stat.r[i + j*param.n + k*param.n*param.n].z = (k - (param.n - 1) / 2)*param.a * sqrt(2.f / 3.f);
			}
		}
	}
	
/*	XYZ_file = fopen( XYZ_filename.c_str(), "w");

	fprintf(XYZ_file, "%d\n", param.N);
	fprintf(XYZ_file, "STEP:\t%d\n", param.N);
	for (i = 0; i < param.N; i++){
		fprintf(XYZ_file, "Ar\t%f\t%f\t%f\n", stat.r[i].x, stat.r[i].y, stat.r[i].z);
	}
	fprintf(XYZ_file, "\n", param.N);
*/
	printf("p \n");
	for (i = 0; i < param.N; i++){
		stat.r[i].r = sqrt(pow(stat.r[i].x, 2) + pow(stat.r[i].y, 2) + pow(stat.r[i].z, 2));
		
		stat.p[i].x = znak()*sqrt(2*param.m*(-K_B*stat.T*log(r0_1()) / 2));
		stat.p[i].y = znak()*sqrt(2*param.m*(-K_B*stat.T*log(r0_1()) / 2));
		stat.p[i].z = znak()*sqrt(2*param.m*(-K_B*stat.T*log(r0_1()) / 2));

		stat.p[i].r = sqrt(pow(stat.p[i].x, 2) + pow(stat.p[i].y, 2) + pow(stat.p[i].z, 2));
	}

	sumaP.x = 0;
	sumaP.y = 0;
	sumaP.z = 0;
	
	printf("sum p \n");
	for (i = 0; i < param.N; i++){
		sumaP.x += stat.p[i].x;
		sumaP.y += stat.p[i].y;
		sumaP.z += stat.p[i].z;
		
		stat.F_s[i].x = 0;
		stat.F_s[i].y = 0;
		stat.F_s[i].z = 0;

		stat.F_p[i].x = 0;
		stat.F_p[i].y = 0;
		stat.F_p[i].z = 0;
	}

	p_file = fopen( "p", "w");
/*
	for (i = 0; i < param.N; i++){
		stat.p[i].x -= sumaP.x / (double) param.N;
		stat.p[i].y -= sumaP.y / (double) param.N;
		stat.p[i].z -= sumaP.z / (double) param.N;
		fprintf(p_file, "%f\t%f\t%f\n", stat.p[i].x, stat.p[i].y, stat.p[i].z);
	}
*/
	fclose(p_file);
	
	
	/* Initial state */

		stat.V_p = 0;
		stat.V_s = 0;
		printf("main \n");
		for (i = 0; i < param.N; i++){
/*
			if (stat.r[i].r >= param.L){

				stat.V_s += param.f*pow(stat.r[i].r - param.L, 2) / 2;

				stat.F_s[i].x += param.f*(param.L - stat.r[i].r)* stat.r[i].x / stat.r[i].r;
				stat.F_s[i].y += param.f*(param.L - stat.r[i].r)* stat.r[i].y / stat.r[i].r;
				stat.F_s[i].z += param.f*(param.L - stat.r[i].r)* stat.r[i].z / stat.r[i].r;
			}
*/
			for (j = i; j < param.N; j++){
				
				if (i != j){
					r_ij = sqrt(pow(stat.r[i].x - stat.r[j].x, 2) + pow(stat.r[i].y - stat.r[j].y, 2) + pow(stat.r[i].z - stat.r[j].z, 2));

					stat.V_p += param.e*(pow(param.R / r_ij, 12) - 2 * pow(param.R / r_ij, 6));

					stat.F_p[i].x += 12 * param.e*(pow(param.R / r_ij, 12) - pow(param.R / r_ij, 6))*(stat.r[i].x - stat.r[j].x) / pow(r_ij, 2);
					stat.F_p[j].x -= stat.F_p[i].x;

					stat.F_p[i].y += 12 * param.e*(pow(param.R / r_ij, 12) - pow(param.R / r_ij, 6))*(stat.r[i].y - stat.r[j].y) / pow(r_ij, 2);
					stat.F_p[j].y -= stat.F_p[i].y;

					stat.F_p[i].z += 12 * param.e*(pow(param.R / r_ij, 12) - pow(param.R / r_ij, 6))*(stat.r[i].z - stat.r[j].z) / pow(r_ij, 2);
					stat.F_p[j].z -= stat.F_p[i].z;
				}
		
			}
			printf("%d/%d\r",i,param.N);
		}
	printf("\n");
	//--------------------------------------------------------------------
    printf("Hello, OpenCL\n");
    //Setup our GLUT window and OpenGL related things
    //glut callback functions are setup here too
    init_gl(argc, argv);

    //initialize our CL object, this sets up the context
    example = new CL();
    
    //load and build our CL program from the file
    #include "part2.cl" //std::string kernel_source is defined in this file
    example->loadProgram(kernel_source);

    //initialize our particle system with positions, velocities and color
    int num = NUM_PARTICLES;
    std::vector<Vec4> pos(num);
    std::vector<Vec4> color(num);
    std::vector<Vec4> F_p(num);
    std::vector<Vec4> F_s(num);
    std::vector<Vec4> Mom(num);

    //fill our vectors with initial data
    for(int i = 0; i < num; i++)
    {
    	
        pos[i].x = stat.r[i].x;
        pos[i].y = stat.r[i].y;
        pos[i].z = stat.r[i].z;
        pos[i].w = 1.0f;
        
        F_p[i].x = stat.F_p[i].x;
        F_p[i].y = stat.F_p[i].y;
        F_p[i].z = stat.F_p[i].z;
        F_p[i].w = 1.0f;
        
        F_s[i].x = stat.F_s[i].x;
        F_s[i].y = stat.F_s[i].y;
        F_s[i].z = stat.F_s[i].z;
        F_s[i].w = 1.0f;
        
        Mom[i].x = stat.p[i].x;
        Mom[i].y = stat.p[i].y;
        Mom[i].z = stat.p[i].z;
        Mom[i].w = 1.0f;
        
        color[i] = Vec4(1.0f, 0.0f,0.0f, 1.0f);
    }
    
    

    //our load data function sends our initial values to the GPU
    example->loadData(pos, color,  F_p, F_s, Mom);
    //initialize the kernel
    example->popCorn();
    
    //this starts the GLUT program, from here on out everything we want
    //to do needs to be done in glut callback functions
    glutMainLoop();

}
Exemplo n.º 21
0
void init_stuff()
{
	int i;
	int seed;

	chdir(DATA_DIR);
	
#ifndef WINDOWS
	setlocale(LC_NUMERIC,"en_US");
#endif
	init_translatables();

	//create_error_mutex();
	init_globals();
	init_crc_tables();
	init_zip_archives();
	cache_system_init(MAX_CACHE_SYSTEM);
	init_texture_cache();

	init_vars();
	
	read_config();

	file_check_datadir();

#ifdef LOAD_XML
	//Well, the current version of the map editor doesn't support having a datadir - will add that later ;-)
	load_translatables();
#endif

#ifdef LINUX
#ifdef GTK2
	init_filters();
#else
	file_selector = create_fileselection();
#endif
#endif	//LINUX

	init_gl();

	window_resize();
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LESS);
//	glDepthFunc(GL_LEQUAL);
    glEnable(GL_TEXTURE_2D);
	glShadeModel(GL_SMOOTH);
	glFrontFace(GL_CCW);
	glCullFace(GL_BACK);
	glEnable(GL_NORMALIZE);
	glClearColor( 0.0, 0.0, 0.0, 0.0 );
	glClearStencil(0);

	seed = time (NULL);
  	srand (seed);

	init_texture_cache();
	init_particles ();
	init_e3d_cache();
	init_2d_obj_cache();

	for(i=0; i<256; i++)
        tile_list[i]=0;

	for (i = 0; i < MAX_LIGHTS; i++)
		lights_list[i] = NULL;

	new_map(256,256);
	load_all_tiles();

	//lights setup
	build_global_light_table();
	build_sun_pos_table();
	reset_material();
	init_lights();
	//disable_local_lights();
	//clear_error_log();

	// Setup the new eye candy system
#ifdef	EYE_CANDY
	ec_init();
#endif	//EYE_CANDY

	init_gl_extensions();

	if(have_multitexture)
#ifdef	NEW_TEXTURES
		ground_detail_text = load_texture_cached("./textures/ground_detail.bmp", tt_mesh);
#else	/* NEW_TEXTURES */
		ground_detail_text = load_texture_cache ("./textures/ground_detail.bmp",255);
#endif	/* NEW_TEXTURES */

	//load the fonts texture
	init_fonts();
#ifdef	NEW_TEXTURES
	icons_text=load_texture_cached("./textures/gamebuttons.bmp", tt_gui);
	buttons_text=load_texture_cached("./textures/buttons.bmp", tt_gui);
#else	/* NEW_TEXTURES */
	icons_text=load_texture_cache("./textures/gamebuttons.bmp",0);
	buttons_text=load_texture_cache("./textures/buttons.bmp",0);
#endif	/* NEW_TEXTURES */
	//get the application home dir

	have_multitexture=0;//debug only

#ifndef LINUX
	GetCurrentDirectory(sizeof(exec_path),exec_path);
#else
	exec_path[0]='.';exec_path[1]='/';exec_path[2]=0;
#endif
	init_browser();

    if(SDL_InitSubSystem(SDL_INIT_TIMER)<0)
    { 
        char str[120];
        snprintf(str, sizeof(str), "Couldn't initialize the timer: %s\n", SDL_GetError());
        log_error(__FILE__, __LINE__, str);
        SDL_Quit();
	    exit(1);
    }

	SDL_SetTimer (1000/(18*4), my_timer);

	SDL_EnableUNICODE(1);

    //we might want to do this later.

	// creating windows
	display_browser();
	toggle_window(browser_win);

	display_o3dow();
	toggle_window(o3dow_win);

	display_replace_window();
	toggle_window(replace_window_win);

	display_edit_window();
	toggle_window(edit_window_win);

	create_particles_window ();
}
Exemplo n.º 22
0
/**
 * main
 *
 * TODO: Write function block once this is cleaned up.
 */
int main(int argc, char** argv)
{
  /*
   * Local Variables.
   */
  SDL_Event transient_event;
  SCREEN *screen;
  MATCH_STATE *match_state;
  Uint32 frame_start_time;
  Uint32 frame_time_taken_ms;
  Uint32 physics_time_delta;
  Uint32 last_physics_update;
  Uint32 ai_time_delta;
  Uint32 last_ai_update;
  Uint32 ms_per_frame;
  int rc;
  StrMap *config_table;
  Uint32 last_animation_update = 0;
  Uint32 animation_ms_per_frame;
  int max_fps;
  FONT *font;
  char disc_graphic_file[MAX_CONFIG_VALUE_LEN + 1];
  char grass_tile_file[MAX_CONFIG_VALUE_LEN + 1];
  char o_xml_file[MAX_CONFIG_VALUE_LEN + 1];
  char d_xml_file[MAX_CONFIG_VALUE_LEN + 1];
  int ii;
  SDL_Color white = {0xFF, 0xFF, 0xFF, 0x00};

  /*
   * Begin logging.
   */
  DT_INIT_LOG;

  /*
   * TODO: Move loading and retrieving constants using defaults from the config
   * file to a different folder, code file. Simple api.
   */
  load_config_to_str_map("config.txt", &config_table);
  if (!get_config_value_int(config_table,
                            cv_animation_ms_per_frame,
                            (int *)&animation_ms_per_frame))
  {
    game_exit("Programmer error: animation ms per frame not handled in cfg.");
  }
  if (!get_config_value_int(config_table, cv_max_fps, &max_fps))
  {
    game_exit("Programmer error: max fps not handled in cfg.");
  }
  ms_per_frame = (int) MILLISECONDS_PER_SECOND / max_fps;
  if (!get_config_value_str(config_table, cv_disc_graphic, (char *)disc_graphic_file))
  {
    game_exit("Programmer error: disc graphic not handled in cfg.");
  }
  if (!get_config_value_str(config_table, cv_grass_tile_filename, (char *)grass_tile_file))
  {
    game_exit("Programmer error: grass tile graphic not handled in cfg.");
  }
  if (!get_config_value_str(config_table, cv_o_xml_file, (char *)o_xml_file))
  {
    game_exit("Programmer error: O XML file not handled in cfg.");
  }
  if (!get_config_value_str(config_table, cv_d_xml_file, (char *)d_xml_file))
  {
    game_exit("Programmer error: D XML file not handled in cfg.");
  }
  DT_DEBUG_LOG("Config file loaded\n");

  /*
   * Create the screen object and use it to initialise the window system.
   */
  screen = create_screen();
  rc = init_window_system(screen, SCREEN_WIDTH, SCREEN_HEIGHT, BPP);
  if (INIT_OK != rc)
  {
    game_exit("Window system could not be initialised.");
  }
  DT_DEBUG_LOG("Graphics subsystem created and initialized\n");

  /*
   * Initialise Audio subsystem
   */
  rc = init_audio_subsystem(config_table);
  if (INIT_AUDIO_SYSTEM_OK != rc)
  {
    /*
     * Don't exit just because we can't output audio. The audio code will
     * handle this case.
     */
    DT_DEBUG_LOG("Audio subsystem could not be initialised\n");
  }
  else
  {
    DT_DEBUG_LOG("Audio subsystem created and initialized\n");
  }

  /*
   * Initialise the opengl components of the screen.
   */
  rc = init_gl(screen);
  if (GL_INIT_OK != rc)
  {
    game_exit("Could not do opengl initialisation.");
  }
  DT_DEBUG_LOG("OpenGL setup complete\n");

  /*
   * TODO: Proper font management system where more than one font can be loaded
   *
   * Create the font object that is going to be used to write text throughout
   * the game.
   */
  rc = create_font("..\\..\\resources\\Fonts\\LucidaSansRegular.ttf",
                   &font,
                   30,
                   TTF_STYLE_NORMAL,
                   white);
  if (BUILD_FONT_OK != rc)
  {
    game_exit("Could not load up LucidaSansRegular font.");
  }
  DT_DEBUG_LOG("Lucida sans regular font loaded\n");

  /*
   * TODO: Constants to move from here.
   *
   * Create a new match state object before starting the game loop.
   */
  match_state = create_match_state(15,
                                   60 * 60,
                                   disc_graphic_file,
                                   grass_tile_file,
                                   o_xml_file,
                                   d_xml_file,
                                   create_o_automaton_states,
                                   create_automaton_events);
  if (NULL == match_state)
  {
    game_exit("Failed to create match state.");
  }
  init_pitch(match_state->pitch);
  DT_DEBUG_LOG("Match state created and initialized\n");

  /*
   * Scale the pitch by an arbitrary amount to account for the otherwise small
   * scaling.
   */
  scale_camera(match_state->camera_handler, 10.0f);

  /*
   * Load the animation data.
   */
  rc = load_animation_data(match_state->animation_handler);
  if (LOAD_ANIMATION_DATA_OK != rc)
  {
    game_exit("Failed to load animation data.");
  }
  DT_DEBUG_LOG("Animation data loaded\n");

  /*
   * Initialise the timings
   */
  last_physics_update = SDL_GetTicks();
  last_ai_update = SDL_GetTicks();

  /*
   * Initialise and start a new match.
   */
  start_match(match_state);

  // @@@DAT testing
  throw_multi_player_ai_event_by_name(match_state->teams,
                                      match_state->players_per_team,
                                      match_state->teams[0]->players[0]->automaton,
                                      AUTOMATON_EVENT_PULL_THROWN);

  /*
   * Game loop
   */
  while(true)
  {
    /*
     * Frame time is tracked so that we can determine how long to wait before
     * displaying the next frame. i.e. to fix the FPS.
     */
    frame_start_time = SDL_GetTicks();

    /*
     * Look at disc
     */
    look_at_location(match_state->camera_handler,
                     match_state->disc->position.x,
                     match_state->disc->position.y,
                     screen);

    /*
     * While there are events to process, do so.
     */
    while(SDL_PollEvent(&transient_event))
    {
      /*
       * First check whether it is an SDL_QUIT event. If so then exit with
       * message.
       */
      if (transient_event.type == SDL_QUIT)
      {
        destroy_match_state(match_state);
        game_exit("User requested exit via SDL_QUIT event.");
      }
      else if ((transient_event.type == SDL_KEYDOWN) ||
               (transient_event.type == SDL_KEYUP))
      {
        /*
         * The event was the user either depressing or releasing a key so call
         * to the keyboard event handler to deal with the event.
         */
        handle_keyboard_event(&(transient_event.key),
                              transient_event.type,
                              match_state,
                              screen);
      }
      else if ((transient_event.type == SDL_MOUSEBUTTONDOWN) ||
               (transient_event.type == SDL_MOUSEBUTTONUP))
      {
        /*
         * The event was the user either depressing or releasing a mouse button
         * so pass to the mouse button event handler to deal with it. This
         * includes the mouse wheel moving.
         */
        handle_mousebutton_event(&(transient_event.button), match_state);
      }
    }

    /*
     * Perform an update on all the ai objects.
     */
    ai_time_delta = SDL_GetTicks() - last_ai_update;
    process_all_player_ai(match_state->teams,
                          match_state->players_per_team,
                          ai_time_delta);
    last_ai_update = SDL_GetTicks();

    /*
     * Process the automaton timed event queue to see if any events need to be
     * popped.
     */
    pop_all_timed_events(match_state->automaton_handler->timed_event_queue,
                         SDL_GetTicks(),
                         match_state);

    /*
     * Do physics processing. This updates the positions of all moving entities
     * in the game.
     *
     * WARNING - If this takes longer than the amount of time allocated per
     * frame then there might be 'interesting' problems in the frame refresh.
     */
    physics_time_delta = SDL_GetTicks() - last_physics_update;
    calculate_positions(match_state,
                        physics_time_delta);
    last_physics_update = SDL_GetTicks();

    /*
     * Having moved all of the objects to their new positions we need to
     * detect collisions and verify the new locations.
     *
     * At the end of this function the positions of all objects will have been
     * updated.
     */
    detect_and_handle_collisions(match_state->teams,
                                 match_state->players_per_team,
                                 match_state->disc);

    /*
     * Update the camera object.
     */
    update_camera_position(match_state);

    /*
     * TODO: Is this management of animations sufficient?
     *
     * Update the animation frame counters.
     */
    if (SDL_GetTicks() - last_animation_update >= animation_ms_per_frame)
    {
      last_animation_update = SDL_GetTicks();
      for (ii = 0; ii < match_state->players_per_team; ii++)
      {
        increment_animation_frame_counter(match_state->teams[0]->players[ii],
                                          match_state->animation_handler);
        increment_animation_frame_counter(match_state->teams[1]->players[ii],
                                          match_state->animation_handler);
      }
    }

    /*
     * If the frame has taken less than the maximum allowed amount of time to
     * render then delay the screen update.
     */
    frame_time_taken_ms = SDL_GetTicks() - frame_start_time;
    if (frame_time_taken_ms < ms_per_frame)
    {
      SDL_Delay(ms_per_frame - frame_time_taken_ms);
    }

    /*
     * Redraw the screen.
     */
    redraw_screen(screen, match_state, font);
  }

  return(0);
}
Exemplo n.º 23
0
int
main(int argc, char **argv)
{
	struct sigaction sigint;
	struct display display = { 0 };
	struct window  window  = { 0 };
	int i, ret = 0;

	window.display = &display;
	display.window = &window;
	window.window_size.width  = 250;
	window.window_size.height = 250;
	window.buffer_size = 32;
	window.frame_sync = 1;

	for (i = 1; i < argc; i++) {
		if (strcmp("-f", argv[i]) == 0)
			window.fullscreen = 1;
		else if (strcmp("-o", argv[i]) == 0)
			window.opaque = 1;
		else if (strcmp("-s", argv[i]) == 0)
			window.buffer_size = 16;
		else if (strcmp("-b", argv[i]) == 0)
			window.frame_sync = 0;
		else if (strcmp("-h", argv[i]) == 0)
			usage(EXIT_SUCCESS);
		else
			usage(EXIT_FAILURE);
	}

	display.display = wl_display_connect(NULL);
	assert(display.display);

	display.registry = wl_display_get_registry(display.display);
	wl_registry_add_listener(display.registry,
				 &registry_listener, &display);

	wl_display_dispatch(display.display);

	init_egl(&display, &window);
	create_surface(&window);
	init_gl(&window);

	display.cursor_surface =
		wl_compositor_create_surface(display.compositor);

	sigint.sa_handler = signal_int;
	sigemptyset(&sigint.sa_mask);
	sigint.sa_flags = SA_RESETHAND;
	sigaction(SIGINT, &sigint, NULL);

	/* The mainloop here is a little subtle.  Redrawing will cause
	 * EGL to read events so we can just call
	 * wl_display_dispatch_pending() to handle any events that got
	 * queued up as a side effect. */
	while (running && ret != -1) {
		wl_display_dispatch_pending(display.display);
		redraw(&window, NULL, 0);
	}

	fprintf(stderr, "simple-egl exiting\n");

	destroy_surface(&window);
	fini_egl(&display);

	wl_surface_destroy(display.cursor_surface);
	if (display.cursor_theme)
		wl_cursor_theme_destroy(display.cursor_theme);

	if (display.shell)
		xdg_shell_destroy(display.shell);

	if (display.compositor)
		wl_compositor_destroy(display.compositor);

	wl_registry_destroy(display.registry);
	wl_display_flush(display.display);
	wl_display_disconnect(display.display);

	return 0;
}
Exemplo n.º 24
0
/* Main plugin stuff */
const VisPluginInfo *get_plugin_info (void)
{
	static VisActorPlugin actor = {
		.requisition = lv_nebulus_requisition,
		.palette = lv_nebulus_palette,
		.render = lv_nebulus_render,
		.vidoptions.depth = VISUAL_VIDEO_DEPTH_GL
	};

	static VisPluginInfo info = {
		.type = VISUAL_PLUGIN_TYPE_ACTOR,

		.plugname = "nebulus",
		.name = "Nebulus",
		.author = N_("Original by: Pascal Brochart <*****@*****.**> and many others, Port and maintaince by: Dennis Smit <*****@*****.**>"),
		.version = "1.0",
		.about = N_("Libvisual nebulus plugin"),
		.help = N_("This plugin shows multiple visual effect using openGL"),
		.license = VISUAL_PLUGIN_LICENSE_GPL,

		.init = lv_nebulus_init,
		.cleanup = lv_nebulus_cleanup,
		.events = lv_nebulus_events,

		.plugin = VISUAL_OBJECT (&actor)
	};

	VISUAL_VIDEO_ATTR_OPTIONS_GL_ENTRY(actor.vidoptions, VISUAL_GL_ATTRIBUTE_RED_SIZE, 5);
	VISUAL_VIDEO_ATTR_OPTIONS_GL_ENTRY(actor.vidoptions, VISUAL_GL_ATTRIBUTE_GREEN_SIZE, 5);
	VISUAL_VIDEO_ATTR_OPTIONS_GL_ENTRY(actor.vidoptions, VISUAL_GL_ATTRIBUTE_BLUE_SIZE, 5);
	VISUAL_VIDEO_ATTR_OPTIONS_GL_ENTRY(actor.vidoptions, VISUAL_GL_ATTRIBUTE_DEPTH_SIZE, 16);
	VISUAL_VIDEO_ATTR_OPTIONS_GL_ENTRY(actor.vidoptions, VISUAL_GL_ATTRIBUTE_DOUBLEBUFFER, 1);
	VISUAL_VIDEO_ATTR_OPTIONS_GL_ENTRY(actor.vidoptions, VISUAL_GL_ATTRIBUTE_RGBA, 1);

	return &info;
}

static int lv_nebulus_init (VisPluginData *plugin)
{
	NebulusPrivate *priv;

#if ENABLE_NLS
	bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
#endif

	visual_return_val_if_fail (plugin != NULL, -1);

	priv = visual_mem_new0 (NebulusPrivate, 1);
	visual_object_set_private (VISUAL_OBJECT (plugin), priv);

	glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxtexsize);
	if (maxtexsize < 256) {
		visual_log (VISUAL_LOG_CRITICAL, _("Nebulus: max texture size is lower than 256"));
		return -1;
	}

	if (tunnel_first)
		precalculate_tunnel();

	priv->pcmbuf = visual_buffer_new_allocate (1024 * sizeof (float));

	visual_video_init (&child_image);
	visual_video_init (&energy_image);
	visual_video_init (&tentacle_image);
	visual_video_init (&tunnel_image);
	visual_video_init (&twist_image);
	visual_video_init (&background_image);

	init_gl();

	return 0;
}
Exemplo n.º 25
0
struct rtb_window *
rtb_window_open_under(struct rutabaga *r, intptr_t parent,
		int w, int h, const char *title)
{
	struct rtb_style_data stdata;
	struct rtb_window *self;

	assert(r);
	assert(h > 0);
	assert(w > 0);
	assert(!r->win);

	self = window_impl_open(r, w, h, title, parent);
	if (!self)
		goto err_window_impl;

	init_gl();

	if (RTB_SUBCLASS(RTB_SURFACE(self), rtb_surface_init, &super))
		goto err_surface_init;

	self->w = w;
	self->h = h;

	self->surface = RTB_SURFACE(self);

	stdata = rtb_style_get_defaults();
	self->style_list = stdata.style;
	self->style_fonts = calloc(stdata.nfonts, sizeof(*self->style_fonts));

	if (shaders_init(self))
		goto err_shaders;

	if (ibos_init(self))
		goto err_ibos;

	if (rtb_font_manager_init(&self->font_manager,
				self->dpi.x, self->dpi.y))
		goto err_font;

	rtb_elem_set_layout(RTB_ELEMENT(self), rtb_layout_vpack_top);

	self->on_event   = win_event;
	self->mark_dirty = mark_dirty;
	self->attached   = attached;

	self->flags = RTB_ELEM_CLICK_FOCUS;

	/* for core profiles */
	glGenVertexArrays(1, &self->vao);
	glBindVertexArray(self->vao);

	self->rtb = r;
	r->win = self;

	self->mouse.current_cursor = RTB_MOUSE_CURSOR_DEFAULT;

	return self;

err_font:
	ibos_fini(self);
err_ibos:
	shaders_fini(self);
err_shaders:
err_surface_init:
	window_impl_close(self);
err_window_impl:
	return NULL;
}
Exemplo n.º 26
0
void * glclient_thread(void * arg)
{
  server_thread_args_t * a = (server_thread_args_t *)arg;
  static graphics_context_t gc;

  static struct js_event joy;
  int joy_fd;
  static char button[32];

  glclient_context_t *glcc = a->user_context_ptr;

  joy_fd = open(glcc->joy_dev, O_RDONLY);
  if (joy_fd == -1)
  {
    printf("Error: Joystick device open\n");
  }
  if (joy_fd != -1)
  {
    fcntl(joy_fd, F_SETFL, O_NONBLOCK);
  }

  gls_init(a);

  gls_cmd_get_context();
  gc.screen_width = glsc_global.screen_width;
  gc.screen_height = glsc_global.screen_height;
  printf("width:%d height:%d\n",glsc_global.screen_width,glsc_global.screen_height);
  init_gl(&gc);

  float aspect = (float)gc.screen_width / (float)gc.screen_height;

  mat_perspective(proj_mat, aspect, 0.1f, 1024.0f, 60.0f);
  glUniform4fv(gc.uloc_light, 1, light_pos);

  srand(0x12345678);
  int j;
  for (j = 0; j < 1024; j++)
  {
    obj[j].z = randf() * 8.0f - 10.0f;
    obj[j].x = (randf() * 2.0f - 1.0f) * obj[j].z;
    obj[j].y = (randf() * 1.0f - 0.5f) * obj[j].z;
    obj[j].dx = randf() * 0.0f - 0.0f;
    obj[j].dy = randf() * 0.0f - 0.0f;
    obj[j].dz = randf() * 0.0f - 0.0f;
    obj[j].rx = randf() * 6.28;
    obj[j].ry = randf() * 6.28;
    obj[j].rz = randf() * 6.28;
    obj[j].drx = randf() * 0.1f - 0.05f;
    obj[j].dry = randf() * 0.1f - 0.05f;
    obj[j].drz = randf() * 0.1f - 0.05f;
  }

  float x = 1.57f;
  float y = 0.0f;
  float z = -2.0f;
  int k = 1;

  int i;
  for (i = 0; i < 432000; i++)
  {
    struct timeval times, timee;
    gettimeofday(&times, NULL);

    if (joy_fd != -1)
    {
      while (read(joy_fd, &joy, sizeof(struct js_event)) == sizeof(struct js_event))
      {
        if ((joy.type & JS_EVENT_BUTTON) == JS_EVENT_BUTTON)
        {
          button[joy.number] = joy.value;
        }
      }

      if (button[4] > 0)
      {
        y += 0.01f;
      }
      if (button[6] > 0)
      {
        y += -0.01f;
      }
      if (button[5] > 0)
      {
        x += 0.01f * aspect;
      }
      if (button[7] > 0)
      {
        x += -0.01f * aspect;
      }
      if (button[12] > 0)
      {
        z += -0.01f;
      }
      if (button[13] > 0)
      {
        k++;
        k = (k > 45) ? 45 : k;
      }
      if (button[14] > 0)
      {
        z += 0.01f;
      }
      if (button[15] > 0)
      {
        k--;
        k = (k < 1) ? 1 : k;
      }
    }

    glUseProgram(gc.program);
    glBindBuffer(GL_ARRAY_BUFFER, gc.vbo_pos);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, gc.vbo_ind);
    glEnableVertexAttribArray(gc.vloc_pos);
    glEnableVertexAttribArray(gc.vloc_nor);
    glEnableVertexAttribArray(gc.vloc_tex);

    glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    for (j = 0; j < k; j++)
    {
      obj[j].rx += obj[j].drx;
      obj[j].ry += obj[j].dry;
      obj[j].rz += obj[j].drz;

      if (j == 0)
      {
        obj[j].x = 0.0f;
        obj[j].y = 0.0f;
        obj[j].z = z;
        obj[j].rx = -y;
        obj[j].ry = x;
        obj[j].rz = 0.0f;
      }

      mat_identity(model_mat);
      mat_translate(model_mat, obj[j].x, obj[j].y, obj[j].z);
      mat_rotate_x(model_mat, obj[j].rx);
      mat_rotate_y(model_mat, obj[j].ry);
      mat_rotate_z(model_mat, obj[j].rz);

      mat_copy(nor_mat, model_mat);
      mat_invert(nor_mat);
      mat_transpose(nor_mat);
      glUniformMatrix4fv(gc.uloc_nor, 1, GL_FALSE, nor_mat);
      mat_copy(obj[j].nor_mat, nor_mat);

      mat_copy(modelproj_mat, proj_mat);
      mat_mul(modelproj_mat, model_mat);
      glUniformMatrix4fv(gc.uloc_model, 1, GL_FALSE, modelproj_mat);
      mat_copy(obj[j].modelproj_mat, modelproj_mat);

      glDrawElements(GL_TRIANGLES, sizeof(ind_model) / sizeof(GLushort), GL_UNSIGNED_SHORT, 0);
    }
    glDisableVertexAttribArray(gc.vloc_tex);
    glDisableVertexAttribArray(gc.vloc_nor);
    glDisableVertexAttribArray(gc.vloc_pos);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    gls_cmd_flip(i);
    gettimeofday(&timee, NULL);
    //printf("%d:%f ms ", i, get_diff_time(times, timee) * 1000.0f);
  }
  glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  gls_cmd_flip(i);
  release_gl(&gc);
  gls_free();
  if (joy_fd != -1)
  {
    close(joy_fd);
  }
  pthread_exit(NULL);
}