Пример #1
0
int main(int argc, char * arg[])
{

    //Controls the game loop
    bool run=true;

    // init everyting - SDL, if it is nonzero we have a problem
    if(SDL_Init(SDL_INIT_EVERYTHING) != 0)
    {
        std::cout << "ERROR SDL_Init " <<SDL_GetError()<< std::endl;

        return -1;
	}

	//Request opengl 4.1 context, Core Context
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK,SDL_GL_CONTEXT_PROFILE_CORE);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);

    //Create a window
    SDL_Window * window = SDL_CreateWindow(
                                           "SDL",             // window title
                                           SDL_WINDOWPOS_CENTERED,     // x position, centered
                                           SDL_WINDOWPOS_CENTERED,     // y position, centered
                                           640,                        // width, in pixels
                                           480,                        // height, in pixels
                                           SDL_WINDOW_OPENGL           // flags
                                           );

    // Create an OpenGL context associated with the window.
    SDL_GLContext glcontext = SDL_GL_CreateContext(window);

    //Call our InitOpenGL Function
    initOpenGL();
    //Set our viewport
    setViewport(640,480);

    initScene();
    //Value to hold the event generated by SDL
    SDL_Event event;
    //Game Loop
    while(run)
    {
        //While we still have events in the queue
        while (SDL_PollEvent(&event)) {
            //Get event type
            if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) {
                //set our boolean which controls the loop to false
                run = false;
            }
            if (event.type==SDL_KEYDOWN){
                  switch( event.key.keysym.sym )
                  {
                    case SDLK_LEFT:
                      break;
                      case SDLK_RIGHT:
                      break;
                      case SDLK_UP:
                      break;
                      case SDLK_DOWN:
                      break;
                    default:
                      break;
                  }
            }
        }
        //init Scene
        update();
        //render
        render();
        //Call swap so that our GL back buffer is displayed
        SDL_GL_SwapWindow(window);

    }

    // clean up, reverse order!!!
    cleanUp();
    SDL_GL_DeleteContext(glcontext);
    SDL_DestroyWindow(window);
    SDL_Quit();

    return 0;
}
Пример #2
0
//Program entry point
int main(int argc, char *argv[])
{
	UNUSED(argc);
	UNUSED(argv);

	//paths required by platform code
	platform::app_code.app_dll_path = "App.dll";
	platform::app_state.record_file = "input.smi";

	//Load the application dll
	platform_load_app_code(&platform::app_code);

	//initialize sdl
	if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
	{
		std::cerr << ERROR_LINE << "SDL Error: Unable to initialize SDL" << std::endl;
	}
	else
	{
		std::cout << "SDL initialized"<<std::endl;
	}

	//SDL version
	{
		SDL_version ver;
		SDL_VERSION(&ver);
		std::cout << "SDL version " << (int)ver.major << "." << (int)ver.minor << "." << (int)ver.patch << std::endl;
		SDL_GetVersion(&ver);
		std::cout << "Linked version " << (int)ver.major << "." << (int)ver.minor << "." << (int)ver.patch << std::endl;
	}

	//init time
	platform_update_time(platform::app_time);

	//call app config to get settings
	platform::app_code.config(&platform::services.config);

	//Set Opengl attributes
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, PLATFORM_GL_VERSION_MAJOR);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, PLATFORM_GL_VERSION_MINOR);

	//Set buffer attributes
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, PLATFORM_GL_DOUBLEBUFFER);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, PLATFORM_GL_DEPTHBUFFER);


	//Create a window
	platform_create_window();

	if (!platform::services.config.sdl_window)
	{
		std::cerr << ERROR_LINE << "Error: Unable to create window" << std::endl;
		return -1;
	}
	else
	{
		platform::services.config.quit = false;
		std::cout << "SDL window " << platform::services.config.width << "x" << platform::services.config.height << " opened" << std::endl;
	}

	//set OpenGL context
	auto sdl_context = SDL_GL_CreateContext(platform::services.config.sdl_window);

	// Initialise GLEW
	glewExperimental = GL_TRUE;
	GLenum glewError = glewInit();

	if (glewError != GLEW_OK)
	{
		std::cerr << ERROR_LINE << "GLEW Error: Unable to initialise glew";
		return -1;
	}
	else
	{
		std::cout<<"GLEW "<<glewGetString(GLEW_VERSION)<<" Initialised";
	}

	//Allocate memory for the app
	auto base_address = Gigabytes(1);
	platform::services.memory = {};
	platform::services.memory.permanent_memory_size = Megabytes(8);
	platform::services.memory.permanent_memory = platform::os::get_memory(base_address,platform::services.memory.permanent_memory_size);

	if (!platform::services.memory.permanent_memory)
	{
		std::cerr << "\nUnable to allocate enough memory";
		return -1;
	}

	//link memory to app state
	platform::app_state.memory = &platform::services.memory;

	//call the application startup
	platform::app_code.startup(&platform::services);

	//run application
	#ifdef __EMSCRIPTEN__
	emscripten_set_main_loop(platform_update, 0, true);
	#else
	//run as long as quit is not set to true
	while(!platform::services.config.quit)
	{
		platform_update();
	}
	#endif

	//free resources
	SDL_GL_DeleteContext(sdl_context);
	SDL_DestroyWindow(platform::services.config.sdl_window);

	//exit
	return 0;
}
Пример #3
0
FPlatformOpenGLContext* PlatformCreateOpenGLContext(FPlatformOpenGLDevice* Device, void* InWindowHandle)
{
	Device->SharedContext->Context = SDL_GL_CreateContext((SDL_Window*)InWindowHandle);
	return Device->SharedContext;
}
Пример #4
0
int main(int argc, char *argv[])
{
    SDL_Window *window;
    SDL_GLContext context;

    // Slightly different SDL initialization
    if ( SDL_Init(SDL_INIT_VIDEO) != 0 ) {
        printf("Unable to initialize SDL: %s\n", SDL_GetError());
        return 1;
    }

    SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); // *new*

    window = SDL_CreateWindow("sdl_fog_density", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_OPENGL);
    if ( !window ) {
        printf("Unable to create window: %s\n", SDL_GetError());
        return 1;
    }

    context = SDL_GL_CreateContext(window);

    // Set the OpenGL state after creating the context with SDL_SetVideoMode

    glClearColor( 0, 0, 0, 0 );

    glEnable( GL_TEXTURE_2D ); // Needed when we're using the fixed-function pipeline.

    glViewport( 0, 0, 640, 480 );

    glMatrixMode( GL_PROJECTION );
    glPushMatrix(); // just for testing
    glLoadIdentity();

    glOrtho( 0, 640, 480, 0, -1000, 1000 );

    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();

    // Load the OpenGL texture

    GLuint texture; // Texture object handle
    SDL_Surface *surface; // Gives us the information to make the texture

    if ( (surface = IMG_Load("screenshot.png")) ) {

        // Check that the image's width is a power of 2
        if ( (surface->w & (surface->w - 1)) != 0 ) {
            printf("warning: image.bmp's width is not a power of 2\n");
        }

        // Also check if the height is a power of 2
        if ( (surface->h & (surface->h - 1)) != 0 ) {
            printf("warning: image.bmp's height is not a power of 2\n");
        }

        // Have OpenGL generate a texture object handle for us
        glGenTextures( 1, &texture );

        // Bind the texture object
        glBindTexture( GL_TEXTURE_2D, texture );

        // Set the texture's stretching properties
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

        //SDL_LockSurface(surface);

        // Add some greyness
        memset(surface->pixels, 0x66, surface->w*surface->h);

        // Edit the texture object's image data using the information SDL_Surface gives us
        glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, surface->w, surface->h, 0,
                      GL_RGBA, GL_UNSIGNED_BYTE, surface->pixels );

        //SDL_UnlockSurface(surface);
    }
    else {
        printf("SDL could not load image.bmp: %s\n", SDL_GetError());
        SDL_Quit();
        return 1;
    }

    // Free the SDL_Surface only if it was successfully created
    if ( surface ) {
        SDL_FreeSurface( surface );
    }

    // Clear the screen before drawing
    glClear( GL_COLOR_BUFFER_BIT );

    // Bind the texture to which subsequent calls refer to
    glBindTexture( GL_TEXTURE_2D, texture );

    glEnable(GL_FOG);
    GLfloat fogColor[] = { 1.0, 0.5, 0.5, 0.05 };
    glFogfv(GL_FOG_COLOR, fogColor);
    glFogf(GL_FOG_DENSITY, 0.2);
    glFogi(GL_FOG_MODE, GL_EXP2);

    assert(glIsEnabled(GL_FOG));

    glBegin( GL_QUADS );
        glTexCoord2i( 0, 0 ); glVertex3f( 10, 10, 10 );
        glTexCoord2i( 1, 0 ); glVertex3f( 300, 10, 10 );
        glTexCoord2i( 1, 1 ); glVertex3f( 300, 128, 10 );
        glTexCoord2i( 0, 1 ); glVertex3f( 10, 128, 10 );

        glTexCoord2f( 0, 0.5 ); glVertex3f( 410, 10, 5 );
        glTexCoord2f( 1, 0.5 ); glVertex3f( 600, 10, 6 );
        glTexCoord2f( 1, 1   ); glVertex3f( 630, 200, 7 );
        glTexCoord2f( 0.5, 1 ); glVertex3f( 310, 250, 8 );
    glEnd();

    glBegin( GL_TRIANGLE_STRIP );
        glTexCoord2i( 0, 0 ); glVertex3f( 100, 300, 1 );
        glTexCoord2i( 1, 0 ); glVertex3f( 300, 300, 1 );
        glTexCoord2i( 1, 1 ); glVertex3f( 300, 400, 1 );
        glTexCoord2i( 0, 1 ); glVertex3f( 500, 410, 1 );
    glEnd();

    glDisable(GL_TEXTURE_2D);

    glColor3ub(90, 255, 255);
    glBegin( GL_QUADS );
        glVertex3f( 10, 410, 5 );
        glVertex3f( 300, 410, 50 );
        glVertex3f( 300, 480, 100 );
        glVertex3f( 10, 470, 5 );
    glEnd();

    glBegin( GL_QUADS );
        glColor3f(1.0, 0, 1.0);   glVertex3f( 410, 410, 10 );
        glColor3f(0, 1.0, 0);     glVertex3f( 600, 410, 10 );
        glColor3f(0, 0, 1.0);     glVertex3f( 600, 480, 10 );
        glColor3f(1.0, 1.0, 1.0); glVertex3f( 410, 470, 10 );
    glEnd();

    SDL_GL_SwapWindow(window);

#if !defined(__EMSCRIPTEN__)
    // Wait for 3 seconds to give us a chance to see the image
    SDL_Delay(30000);
#endif

    // Now we can delete the OpenGL texture and close down SDL
    glDeleteTextures( 1, &texture );

    SDL_Quit();

    return 0;
}
Пример #5
0
bool OpenGLSdlGraphicsManager::setupMode(uint width, uint height) {
	// In case we request a fullscreen mode we will use the mode the user
	// has chosen last time or the biggest mode available.
	if (_wantsFullScreen) {
		if (_desiredFullscreenWidth && _desiredFullscreenHeight) {
			// In case only a distinct set of modes is available we check
			// whether the requested mode is actually available.
			if (!_fullscreenVideoModes.empty()) {
				VideoModeArray::const_iterator i = Common::find(_fullscreenVideoModes.begin(),
				                                                _fullscreenVideoModes.end(),
				                                                VideoMode(_desiredFullscreenWidth, _desiredFullscreenHeight));
				// It's not available fall back to default.
				if (i == _fullscreenVideoModes.end()) {
					_desiredFullscreenWidth = 0;
					_desiredFullscreenHeight = 0;
				}
			}
		}

		// In case no desired mode has been set we default to the biggest mode
		// available or the requested mode in case we don't know any
		// any fullscreen modes.
		if (!_desiredFullscreenWidth || !_desiredFullscreenHeight) {
			if (!_fullscreenVideoModes.empty()) {
				VideoModeArray::const_iterator i = _fullscreenVideoModes.end();
				--i;

				_desiredFullscreenWidth  = i->width;
				_desiredFullscreenHeight = i->height;
			} else {
				_desiredFullscreenWidth  = width;
				_desiredFullscreenHeight = height;
			}
		}

		// Remember our choice.
		ConfMan.setInt("last_fullscreen_mode_width", _desiredFullscreenWidth, Common::ConfigManager::kApplicationDomain);
		ConfMan.setInt("last_fullscreen_mode_height", _desiredFullscreenHeight, Common::ConfigManager::kApplicationDomain);

		// Use our choice.
		width  = _desiredFullscreenWidth;
		height = _desiredFullscreenHeight;
	}

	// This is pretty confusing since RGBA8888 talks about the memory
	// layout here. This is a different logical layout depending on
	// whether we run on little endian or big endian. However, we can
	// only safely assume that RGBA8888 in memory layout is supported.
	// Thus, we chose this one.
	const Graphics::PixelFormat rgba8888 =
#ifdef SCUMM_LITTLE_ENDIAN
	                                       Graphics::PixelFormat(4, 8, 8, 8, 8, 0, 8, 16, 24);
#else
	                                       Graphics::PixelFormat(4, 8, 8, 8, 8, 24, 16, 8, 0);
#endif

#if SDL_VERSION_ATLEAST(2, 0, 0)
	if (_glContext) {
		notifyContextDestroy();

		SDL_GL_DeleteContext(_glContext);
		_glContext = nullptr;
	}

	_window->destroyWindow();

	uint32 flags = SDL_WINDOW_OPENGL;
	if (_wantsFullScreen) {
		flags |= SDL_WINDOW_FULLSCREEN;
	} else {
		flags |= SDL_WINDOW_RESIZABLE;
	}

	// Request a OpenGL (ES) context we can use.
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, _glContextProfileMask);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, _glContextMajor);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, _glContextMinor);

	if (!_window->createWindow(width, height, flags)) {
		// We treat fullscreen requests as a "hint" for now. This means in
		// case it is not available we simply ignore it.
		if (_wantsFullScreen) {
			_window->createWindow(width, height, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
		}

		if (!_window->getSDLWindow()) {
			return false;
		}
	}

	_glContext = SDL_GL_CreateContext(_window->getSDLWindow());
	if (!_glContext) {
		return false;
	}

	notifyContextCreate(rgba8888, rgba8888);
	int actualWidth, actualHeight;
	getWindowDimensions(&actualWidth, &actualHeight);
	setActualScreenSize(actualWidth, actualHeight);
	_eventSource->resetKeyboardEmulation(actualWidth - 1, actualHeight - 1);
	return true;
#else
	// WORKAROUND: Working around infamous SDL bugs when switching
	// resolutions too fast. This might cause the event system to supply
	// incorrect mouse position events otherwise.
	// Reference: http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=665779
	const uint32 curTime = SDL_GetTicks();
	if (_hwScreen && (curTime < _lastVideoModeLoad || curTime - _lastVideoModeLoad < 100)) {
		for (int i = 10; i > 0; --i) {
			SDL_PumpEvents();
			SDL_Delay(10);
		}
	}

	uint32 flags = SDL_OPENGL;
	if (_wantsFullScreen) {
		flags |= SDL_FULLSCREEN;
	} else {
		flags |= SDL_RESIZABLE;
	}

	if (_hwScreen) {
		// When a video mode has been setup already we notify the manager that
		// the context is about to be destroyed.
		// We do this because on Windows SDL_SetVideoMode can destroy and
		// recreate the OpenGL context.
		notifyContextDestroy();
	}

	_hwScreen = SDL_SetVideoMode(width, height, 32, flags);

	if (!_hwScreen) {
		// We treat fullscreen requests as a "hint" for now. This means in
		// case it is not available we simply ignore it.
		if (_wantsFullScreen) {
			_hwScreen = SDL_SetVideoMode(width, height, 32, SDL_OPENGL | SDL_RESIZABLE);
		}
	}

	// Part of the WORKAROUND mentioned above.
	_lastVideoModeLoad = SDL_GetTicks();

	if (_hwScreen) {
		notifyContextCreate(rgba8888, rgba8888);
		setActualScreenSize(_hwScreen->w, _hwScreen->h);
		_eventSource->resetKeyboardEmulation(_hwScreen->w - 1, _hwScreen->h - 1);
	}

	// Ignore resize events (from SDL) for a few frames, if this isn't
	// caused by a notification from SDL. This avoids bad resizes to a
	// (former) resolution for which we haven't processed an event yet.
	if (!_gotResize)
		_ignoreResizeEvents = 10;

	return _hwScreen != nullptr;
#endif
}
Пример #6
0
int main(int argc, char **argv)
{

if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        fprintf(stderr, "Error: Unable to init SDL: %s\n", SDL_GetError());
        exit(1);
    }
	SDL_Window* screen;
	SDL_GLContext glcontext;
    screen = SDL_CreateWindow("Window Name", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
                               600, 600,SDL_WINDOW_OPENGL);

    glcontext = SDL_GL_CreateContext(screen);
    SDL_ShowCursor(false);
    GLenum err = glewInit();

    if (err != GLEW_OK) fprintf(stderr, "Error: %s", glewGetErrorString(err));

    if (!screen) {
        fprintf(stderr, "Unable to start video: %s\n", SDL_GetError());
    }
    
    setupGL();
    light=glm::vec3(0.0,-100.0,20.0);
    //setup geometry
    geoms.push_back(new CCubeVAO(1000,10,1000,glm::vec3(0,-50,0)));
    geoms.push_back(new CCubeVAO(50,50,10,glm::vec3(-100,0,0)));
    geoms.push_back(new CCubeVAO(10,10,10,glm::vec3(100,70,-100)));
    geoms.push_back(new CCubeVAO(100,10,500,glm::vec3(200,50,-100)));
    geoms.push_back(new ImageVAO(tex));
    yaw=0;
    pit=0;

	bool quit=false;
	long long count=0;

	while(!quit){
	
	input(screen,quit);
	
	render(screen,count++);
	
	
	
	}



//cleanup
glUseProgram(0);

for(int x=0;x<geoms.size();x++)
delete geoms.at(x);


glDeleteProgram(program);
glDeleteTextures(1,&tex);
SDL_GL_DeleteContext(glcontext);



}
Пример #7
0
int main(int argc, char* argv[]) {

	if(SDL_Init(SDL_INIT_EVERYTHING) < 0)
	{
		std::cout << "Could not init SDL 2" << std::endl;
		return 0;
	}

	SDL_Window *mainWindow = SDL_CreateWindow("Game",
                                              SDL_WINDOWPOS_CENTERED,
                                              SDL_WINDOWPOS_CENTERED,
                                              WINDOW_WIDTH,
                                              WINDOW_HEIGHT,
                                              SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);

	if(!mainWindow)
	{
		std::cout << "Could not create a window" << std::endl;
		return 0;
	}	

	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);

	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);

	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GLContext mainContext = SDL_GL_CreateContext(mainWindow);
	SDL_GL_SetSwapInterval(1);
	int value = 0;
	SDL_GL_GetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, &value);
	std::cout << "SDL_GL_CONTEXT_MAJOR_VERSION: " << value << std::endl;
	SDL_GL_GetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, &value);
	std::cout << "SDL_GL_CONTEXT_MINOR_VERSION: " << value << std::endl;

	struct stat statBuffer = {};
	bool loop = true;

	GameState gameState = {};

	gameState.memory.mainMemorySz = MEGABYTES(128);
	gameState.memory.mainMemory   = mmap(0,
                                               gameState.memory.mainMemorySz,
                                               PROT_READ | PROT_WRITE,
                                               MAP_ANONYMOUS | MAP_PRIVATE,
                                               -1, 0);


	gameState.memory.transientMemorySz = GIGABYTES(2);
	gameState.memory.transientMemory   = mmap(0,
                                                    gameState.memory.transientMemorySz,
                                                    PROT_READ | PROT_WRITE,
                                                    MAP_ANONYMOUS | MAP_PRIVATE,
                                                    -1, 0);

	int currentTime = SDL_GetTicks();
	while(loop)
	{	
		int lastTime = currentTime;
		currentTime  = SDL_GetTicks();

		int elapsedTime = currentTime - lastTime;

		// NOTE(Brett): Check for the libgame.so and load the newest verion of the functions
		stat("libgame.so", &statBuffer);
		if(LastLibBuildTime == 0 || (statBuffer.st_mtime > LastLibBuildTime))
		{
			if(LibHandle)
				dlclose(LibHandle); 

			LibHandle                   = dlopen("libgame.so", RTLD_GLOBAL);
			GameUpdateAndRender         = (update_method)dlsym(LibHandle, "UpdateAndRender");
			GameSetup                   = (setup_method)dlsym(LibHandle, "Setup");
			LastLibBuildTime            = (int)statBuffer.st_mtime;
			gameState.initialized = false;
			
			GameSetup(&gameState);
		}

		SDL_Event event;
		while(SDL_PollEvent(&event))
		{
			if(event.type == SDL_QUIT)
				loop = false;

			if(event.type == SDL_KEYDOWN)
			{
				switch(event.key.keysym.sym)
				{
					case SDLK_ESCAPE:
						loop = false;
						break;
					default:
						break;
				}

			}
		}
		
		GameUpdateAndRender(&gameState);
		SDL_GL_SwapWindow(mainWindow);
	}

	return 0;
}
Пример #8
0
/*
===============
GLimp_SetMode
===============
*/
static rserr_t GLimp_SetMode(int mode, qboolean fullscreen, qboolean noborder)
{
	const char *glstring;
	int perChannelColorBits;
	int colorBits, depthBits, stencilBits;
	int samples;
	int i = 0;
	SDL_Surface *icon = NULL;
	Uint32 flags = SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL;
	SDL_DisplayMode desktopMode;
	int display = 0;
	int x = 0, y = 0;

	Com_Printf( "Initializing OpenGL display\n");

	if ( r_allowResize->integer )
		flags |= SDL_WINDOW_RESIZABLE;

	/*icon = SDL_CreateRGBSurfaceFrom(
			(void *)CLIENT_WINDOW_ICON.pixel_data,
			CLIENT_WINDOW_ICON.width,
			CLIENT_WINDOW_ICON.height,
			CLIENT_WINDOW_ICON.bytes_per_pixel * 8,
			CLIENT_WINDOW_ICON.bytes_per_pixel * CLIENT_WINDOW_ICON.width,
#ifdef Q3_LITTLE_ENDIAN
			0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000
#else
			0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF
#endif
			);*/

	// If a window exists, note its display index
	if( screen != NULL )
		display = SDL_GetWindowDisplayIndex( screen );

	if( SDL_GetDesktopDisplayMode( display, &desktopMode ) == 0 )
	{
		displayAspect = (float)desktopMode.w / (float)desktopMode.h;

		Com_Printf( "Display aspect: %.3f\n", displayAspect );
	}
	else
	{
		Com_Memset( &desktopMode, 0, sizeof( SDL_DisplayMode ) );

		Com_Printf( "Cannot determine display aspect, assuming 1.333\n" );
	}

	Com_Printf( "...setting mode %d:", mode );

	if (mode == -2)
	{
		// use desktop video resolution
		if( desktopMode.h > 0 )
		{
			glConfig.vidWidth = desktopMode.w;
			glConfig.vidHeight = desktopMode.h;
		}
		else
		{
			glConfig.vidWidth = 640;
			glConfig.vidHeight = 480;
			Com_Printf( "Cannot determine display resolution, assuming 640x480\n" );
		}

		//glConfig.windowAspect = (float)glConfig.vidWidth / (float)glConfig.vidHeight;
	}
	else if ( !R_GetModeInfo( &glConfig.vidWidth, &glConfig.vidHeight, /*&glConfig.windowAspect,*/ mode ) )
	{
		Com_Printf( " invalid mode\n" );
		return RSERR_INVALID_MODE;
	}
	Com_Printf( " %d %d\n", glConfig.vidWidth, glConfig.vidHeight);

	// Center window
	if( r_centerWindow->integer && !fullscreen )
	{
		x = ( desktopMode.w / 2 ) - ( glConfig.vidWidth / 2 );
		y = ( desktopMode.h / 2 ) - ( glConfig.vidHeight / 2 );
	}

	// Destroy existing state if it exists
	if( opengl_context != NULL )
	{
		SDL_GL_DeleteContext( opengl_context );
		opengl_context = NULL;
	}

	if( screen != NULL )
	{
		SDL_GetWindowPosition( screen, &x, &y );
		ri.Printf( PRINT_DEVELOPER, "Existing window at %dx%d before being destroyed\n", x, y );
		SDL_DestroyWindow( screen );
		screen = NULL;
	}

	if( fullscreen )
	{
		flags |= SDL_WINDOW_FULLSCREEN;
		glConfig.isFullscreen = qtrue;
	}
	else
	{
		if( noborder )
			flags |= SDL_WINDOW_BORDERLESS;

		glConfig.isFullscreen = qfalse;
	}

	colorBits = r_colorbits->value;
	if ((!colorBits) || (colorBits >= 32))
		colorBits = 24;

	if (!r_depthbits->value)
		depthBits = 24;
	else
		depthBits = r_depthbits->value;

	stencilBits = r_stencilbits->value;
	//samples = r_ext_multisample->value;

	for (i = 0; i < 16; i++)
	{
		int testColorBits, testDepthBits, testStencilBits;

		// 0 - default
		// 1 - minus colorBits
		// 2 - minus depthBits
		// 3 - minus stencil
		if ((i % 4) == 0 && i)
		{
			// one pass, reduce
			switch (i / 4)
			{
				case 2 :
					if (colorBits == 24)
						colorBits = 16;
					break;
				case 1 :
					if (depthBits == 24)
						depthBits = 16;
					else if (depthBits == 16)
						depthBits = 8;
				case 3 :
					if (stencilBits == 24)
						stencilBits = 16;
					else if (stencilBits == 16)
						stencilBits = 8;
			}
		}

		testColorBits = colorBits;
		testDepthBits = depthBits;
		testStencilBits = stencilBits;

		if ((i % 4) == 3)
		{ // reduce colorBits
			if (testColorBits == 24)
				testColorBits = 16;
		}

		if ((i % 4) == 2)
		{ // reduce depthBits
			if (testDepthBits == 24)
				testDepthBits = 16;
			else if (testDepthBits == 16)
				testDepthBits = 8;
		}

		if ((i % 4) == 1)
		{ // reduce stencilBits
			if (testStencilBits == 24)
				testStencilBits = 16;
			else if (testStencilBits == 16)
				testStencilBits = 8;
			else
				testStencilBits = 0;
		}

		if (testColorBits == 24)
			perChannelColorBits = 8;
		else
			perChannelColorBits = 4;

#ifdef __sgi /* Fix for SGIs grabbing too many bits of color */
		if (perChannelColorBits == 4)
			perChannelColorBits = 0; /* Use minimum size for 16-bit color */

		/* Need alpha or else SGIs choose 36+ bit RGB mode */
		SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 1);
#endif

		SDL_GL_SetAttribute( SDL_GL_RED_SIZE, perChannelColorBits );
		SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, perChannelColorBits );
		SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, perChannelColorBits );
		SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, testDepthBits );
		SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, testStencilBits );

		/*SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, samples ? 1 : 0 );
		SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, samples );*/

		if(r_stereo->integer)
		{
			glConfig.stereoEnabled = qtrue;
			SDL_GL_SetAttribute(SDL_GL_STEREO, 1);
		}
		else
		{
			glConfig.stereoEnabled = qfalse;
			SDL_GL_SetAttribute(SDL_GL_STEREO, 0);
		}

		SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

		// If not allowing software GL, demand accelerated
		if( !r_allowSoftwareGL->integer )
			SDL_GL_SetAttribute( SDL_GL_ACCELERATED_VISUAL, 1 );

		if( ( screen = SDL_CreateWindow( CLIENT_WINDOW_TITLE, x, y,
				glConfig.vidWidth, glConfig.vidHeight, flags ) ) == 0 )
		{
			ri.Printf( PRINT_DEVELOPER, "SDL_CreateWindow failed: %s\n", SDL_GetError( ) );
			continue;
		}

		if( fullscreen )
		{
			SDL_DisplayMode mode;

			switch( testColorBits )
			{
				case 16: mode.format = SDL_PIXELFORMAT_RGB565; break;
				case 24: mode.format = SDL_PIXELFORMAT_RGB24;  break;
				default: ri.Printf( PRINT_DEVELOPER, "testColorBits is %d, can't fullscreen\n", testColorBits ); continue;
			}

			mode.w = glConfig.vidWidth;
			mode.h = glConfig.vidHeight;
			mode.refresh_rate = glConfig.displayFrequency = ri.Cvar_VariableIntegerValue( "r_displayRefresh" );
			mode.driverdata = NULL;

			if( SDL_SetWindowDisplayMode( screen, &mode ) < 0 )
			{
				ri.Printf( PRINT_DEVELOPER, "SDL_SetWindowDisplayMode failed: %s\n", SDL_GetError( ) );
				continue;
			}
		}

		SDL_SetWindowTitle( screen, CLIENT_WINDOW_TITLE );
		SDL_SetWindowIcon( screen, icon );

        if( ( opengl_context = (QGLContext)SDL_GL_CreateContext( screen ) ) == NULL )
		{
			Com_Printf( "SDL_GL_CreateContext failed: %s\n", SDL_GetError( ) );
			continue;
		}

		if( SDL_GL_MakeCurrent( screen, opengl_context ) < 0 )
		{
			Com_Printf( "SDL_GL_MakeCurrent failed: %s\n", SDL_GetError( ) );
			continue;
		}

		SDL_GL_SetSwapInterval( r_swapInterval->integer );

		glConfig.colorBits = testColorBits;
		glConfig.depthBits = testDepthBits;
		glConfig.stencilBits = testStencilBits;

		Com_Printf( "Using %d color bits, %d depth, %d stencil display.\n",
				glConfig.colorBits, glConfig.depthBits, glConfig.stencilBits );
		break;
	}

	/*SDL_FreeSurface( icon );*/

	GLimp_DetectAvailableModes();

	glstring = (char *) qglGetString (GL_RENDERER);
	Com_Printf( "GL_RENDERER: %s\n", glstring );

	return RSERR_OK;
#if 0
	const char*   glstring;
	int sdlcolorbits;
	int colorbits, depthbits, stencilbits;
	int tcolorbits, tdepthbits, tstencilbits;
	int samples;
	int i = 0;
	Uint32 flags = SDL_WINDOW_OPENGL;

	Com_Printf( "Initializing OpenGL display\n");

	if ( r_allowResize->integer )
		flags |= SDL_WINDOW_RESIZABLE;

	if( videoInfo == NULL )
	{
		static SDL_DisplayMode sVideoInfo;
		static SDL_PixelFormat sPixelFormat;

		if (SDL_GetCurrentDisplayMode( 0, &sVideoInfo ) < 0)
		  Com_Error(ERR_FATAL, "SDL_GetCurrentDisplayMode failed : %s\n", SDL_GetError());

		// Take a copy of the videoInfo
		sPixelFormat.format = sVideoInfo.format;
		sPixelFormat.palette = NULL; // Should already be the case
		//Com_Memcpy( &sVideoInfo, videoInfo, sizeof( SDL_DisplayMode ) );
		sVideoInfo.format = sPixelFormat.format;
		videoInfo = &sVideoInfo;

		if( videoInfo->h > 0 )
		{
			glConfig.displayWidth = videoInfo->w;
			glConfig.displayHeight = videoInfo->h;

			// Guess the display aspect ratio through the desktop resolution
			// by assuming (relatively safely) that it is set at or close to
			// the display's native aspect ratio
			glConfig.displayAspect = (float)videoInfo->w / (float)videoInfo->h;

			Com_Printf( "Estimated display aspect: %.3f\n", glConfig.displayAspect );
		}
		else
		{
			glConfig.displayWidth = 480;
			glConfig.displayHeight = 640;
			glConfig.displayAspect = 1.333f;

			Com_Printf(
					"Cannot estimate display resolution/aspect, assuming 640x480/1.333\n" );
		}
	}

	Com_Printf( "...setting mode %d:", mode );

	if (mode == -2)
	{
		// use desktop video resolution
		if( videoInfo->h > 0 )
		{
			glConfig.vidWidth = videoInfo->w;
			glConfig.vidHeight = videoInfo->h;
		}
		else
		{
			glConfig.vidWidth = 640;
			glConfig.vidHeight = 480;
			Com_Printf(
					"Cannot determine display resolution, assuming 640x480\n" );
		}

		glConfig.displayAspect = (float)glConfig.vidWidth / (float)glConfig.vidHeight;
	}
	else if ( !R_GetModeInfo( &glConfig.vidWidth, &glConfig.vidHeight, /*&glConfig.displayAspect,*/ mode ) )
	{
		Com_Printf( " invalid mode\n" );
		return RSERR_INVALID_MODE;
	}
	Com_Printf( " %d %d\n", glConfig.vidWidth, glConfig.vidHeight);

	if (fullscreen)
	{
		flags |= SDL_WINDOW_FULLSCREEN;
		glConfig.isFullscreen = qtrue;
	}
	else
	{
		if (noborder)
			flags |= SDL_WINDOW_BORDERLESS;

		glConfig.isFullscreen = qfalse;
	}

	colorbits = r_colorbits->value;
	if ((!colorbits) || (colorbits >= 32))
		colorbits = 24;

	if (!r_depthbits->value)
		depthbits = 24;
	else
		depthbits = r_depthbits->value;
	stencilbits = r_stencilbits->value;
	//samples = r_ext_multisample->value;

	for (i = 0; i < 16; i++)
	{
		// 0 - default
		// 1 - minus colorbits
		// 2 - minus depthbits
		// 3 - minus stencil
		if ((i % 4) == 0 && i)
		{
			// one pass, reduce
			switch (i / 4)
			{
				case 2 :
					if (colorbits == 24)
						colorbits = 16;
					break;
				case 1 :
					if (depthbits == 24)
						depthbits = 16;
					else if (depthbits == 16)
						depthbits = 8;
				case 3 :
					if (stencilbits == 24)
						stencilbits = 16;
					else if (stencilbits == 16)
						stencilbits = 8;
			}
		}

		tcolorbits = colorbits;
		tdepthbits = depthbits;
		tstencilbits = stencilbits;

		if ((i % 4) == 3)
		{ // reduce colorbits
			if (tcolorbits == 24)
				tcolorbits = 16;
		}

		if ((i % 4) == 2)
		{ // reduce depthbits
			if (tdepthbits == 24)
				tdepthbits = 16;
			else if (tdepthbits == 16)
				tdepthbits = 8;
		}

		if ((i % 4) == 1)
		{ // reduce stencilbits
			if (tstencilbits == 24)
				tstencilbits = 16;
			else if (tstencilbits == 16)
				tstencilbits = 8;
			else
				tstencilbits = 0;
		}

		sdlcolorbits = 4;
		if (tcolorbits == 24)
			sdlcolorbits = 8;

#ifdef __sgi /* Fix for SGIs grabbing too many bits of color */
		if (sdlcolorbits == 4)
			sdlcolorbits = 0; /* Use minimum size for 16-bit color */

		/* Need alpha or else SGIs choose 36+ bit RGB mode */
		SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 1);
#endif

		SDL_GL_SetAttribute( SDL_GL_RED_SIZE, sdlcolorbits );
		SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, sdlcolorbits );
		SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, sdlcolorbits );
		SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, tdepthbits );
		SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, tstencilbits );

		SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, samples ? 1 : 0 );
		SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, samples );

		/*if(r_stereoEnabled->integer)
		{
			glConfig.stereoEnabled = qtrue;
			SDL_GL_SetAttribute(SDL_GL_STEREO, 1);
		}
		else
		{*/
			glConfig.stereoEnabled = qfalse;
			SDL_GL_SetAttribute(SDL_GL_STEREO, 0);
		//}

		SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

#if 0 // See http://bugzilla.icculus.org/show_bug.cgi?id=3526
		// If not allowing software GL, demand accelerated
		if( !r_allowSoftwareGL->integer )
		{
			if( SDL_GL_SetAttribute( SDL_GL_ACCELERATED_VISUAL, 1 ) < 0 )
			{
				Com_Printf( "Unable to guarantee accelerated "
						"visual with libSDL < 1.2.10\n" );
			}
		}
#endif

		if( SDL_GL_SetSwapInterval(r_swapInterval->integer ) < 0 )
			Com_Printf( "SDL_GL_SetSwapInterval not supported\n" );

#ifdef USE_ICON
		{
			SDL_Surface *icon = SDL_CreateRGBSurfaceFrom(
					(void *)CLIENT_WINDOW_ICON.pixel_data,
					CLIENT_WINDOW_ICON.width,
					CLIENT_WINDOW_ICON.height,
					CLIENT_WINDOW_ICON.bytes_per_pixel * 8,
					CLIENT_WINDOW_ICON.bytes_per_pixel * CLIENT_WINDOW_ICON.width,
#ifdef Q3_LITTLE_ENDIAN
					0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000
#else
					0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF
#endif
					);

			SDL_WM_SetIcon( icon, NULL );
			SDL_FreeSurface( icon );
		}
#endif

		SDL_ShowCursor(0);

		if (!(window = SDL_CreateWindow(CLIENT_WINDOW_TITLE, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, glConfig.vidWidth, glConfig.vidHeight, flags)))
		{
			Com_Printf( "SDL_CreateWindow failed: %s\n", SDL_GetError( ) );
			continue;
		}

		opengl_context = SDL_GL_CreateContext(window);

		Com_Printf( "Using %d/%d/%d Color bits, %d depth, %d stencil display.\n",
				sdlcolorbits, sdlcolorbits, sdlcolorbits, tdepthbits, tstencilbits);

		glConfig.colorBits = tcolorbits;
		glConfig.depthBits = tdepthbits;
		glConfig.stencilBits = tstencilbits;
		break;
	}

	GLimp_DetectAvailableModes();

	if (!window)
	{
		Com_Printf( "Couldn't get a visual\n" );
		return RSERR_INVALID_MODE;
	}

	screen = window;

	// FIXME: Defines needed here
	glstring = (char *) qglGetString (GL_RENDERER);
	Com_Printf( "GL_RENDERER: %s\n", glstring );

	return RSERR_OK;
#endif
}
Пример #9
0
int main(int argc, char **argv){
	/* vertices for a triangle */
	/* Why does triangle[] = { vec4_new(...) } result in a segfault when returning
	 * from _mm_load_ps?
	 */
	/* Just want a sort of 3D object, but not a closed object otherwise it's hard
	 * to tell what's going on w/ flat shading */
	vec4_t object[18];
	//+Z face
	object[0] = vec4_new(-1, -1, 1, 1);
	object[1] = vec4_new(1, -1, 1, 1);
	object[2] = vec4_new(1, 1, 1, 1);
	object[3] = vec4_new(1, 1, 1, 1);
	object[4] = vec4_new(-1, 1, 1, 1);
	object[5] = vec4_new(-1, -1, 1, 1);
	//+X face
	object[6] = vec4_new(1, -1, 1, 1);
	object[7] = vec4_new(1, -1, -1, 1);
	object[8] = vec4_new(1, 1, -1, 1);
	object[9] = vec4_new(1, 1, -1, 1);
	object[10] = vec4_new(1, 1, 1, 1);
	object[11] = vec4_new(1, -1, 1, 1);
	//-X face
	object[12] = vec4_new(-1, -1, 1, 1);
	object[13] = vec4_new(-1, -1, -1, 1);
	object[14] = vec4_new(-1, 1, -1, 1);
	object[15] = vec4_new(-1, 1, -1, 1);
	object[16] = vec4_new(-1, 1, 1, 1);
	object[17] = vec4_new(-1, -1, 1, 1);

	if (SDL_Init(SDL_INIT_EVERYTHING) != 0){
		fprintf(stderr, "SDL Init error: %s\n", SDL_GetError());
		return 1;
	}

	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
#ifdef DEBUG
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
#endif

	SDL_Window *win = SDL_CreateWindow("SSE GL Test", SDL_WINDOWPOS_CENTERED,
		SDL_WINDOWPOS_CENTERED, WIN_WIDTH, WIN_HEIGHT, SDL_WINDOW_OPENGL);
	SDL_GLContext context = SDL_GL_CreateContext(win);

	if (check_GL_error("Opened win + context")){
		SDL_GL_DeleteContext(context);
		SDL_DestroyWindow(win);
		return 1;
	}

	glewExperimental = GL_TRUE;
	GLenum err = glewInit();
	if (err != GLEW_OK){
		fprintf(stderr, "GLEW init error %d\n", err);
		SDL_GL_DeleteContext(context);
		SDL_DestroyWindow(win);
		return 1;
	}
	check_GL_error("Post GLEW init");
#ifdef DEBUG
	glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
	glDebugMessageCallbackARB(gl_debug_callback, NULL);
	glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE,
		0, NULL, GL_TRUE);
#endif
	glClearColor(0, 0, 0, 1);
	glClearDepth(1);
	glEnable(GL_DEPTH_TEST);

	//Model's vao and vbo
	GLuint model[2];
	glGenVertexArrays(1, model);
	glBindVertexArray(model[0]);
	glGenBuffers(1, model + 1);
	glBindBuffer(GL_ARRAY_BUFFER, model[1]);
	glBufferData(GL_ARRAY_BUFFER, 4 * 6 * 3 * sizeof(GLfloat), object, GL_STATIC_DRAW);
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
	if (check_GL_error("Setup buffers")){
		return 1;
	}

	GLint vshader = make_shader(vert_shader_src, GL_VERTEX_SHADER);
	GLint fshader = make_shader(frag_shader_src, GL_FRAGMENT_SHADER);
	if (vshader == -1 || fshader == -1){
		return 1;
	}
	GLint program = make_program(vshader, fshader);
	if (program == -1){
		return 1;
	}
	glDeleteShader(vshader);
	glDeleteShader(fshader);

	mat4_t model_mat = mat4_mult(mat4_rotate(45, vec4_new(1, 1, 0, 0)), mat4_scale(2, 2, 2));
	model_mat = mat4_mult(mat4_translate(vec4_new(0, 2, -5, 1)), model_mat);
	mat4_t view_mat = mat4_look_at(vec4_new(0, 0, 5, 0), vec4_new(0, 0, 0, 0), vec4_new(0, 1, 0, 0));
	mat4_t proj_mat = mat4_perspective(75, ((float)WIN_WIDTH) / WIN_HEIGHT, 1, 100);
	glUseProgram(program);
	GLuint model_unif = glGetUniformLocation(program, "model");
	GLuint view_unif = glGetUniformLocation(program, "view");
	GLuint proj_unif = glGetUniformLocation(program, "proj");
	glUniformMatrix4fv(model_unif, 1, GL_FALSE, (GLfloat*)&model_mat);
	glUniformMatrix4fv(view_unif, 1, GL_FALSE, (GLfloat*)&view_mat);
	glUniformMatrix4fv(proj_unif, 1, GL_FALSE, (GLfloat*)&proj_mat);

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glDrawArrays(GL_TRIANGLES, 0, 18);
	SDL_GL_SwapWindow(win);
	check_GL_error("Post Draw");

	SDL_Event e;
	int quit = 0;
	while (!quit){
		while (SDL_PollEvent(&e)){
			if (e.type == SDL_QUIT || e.type == SDL_KEYDOWN){
				quit = 1;
			}
		}
	}

	glDeleteProgram(program);
	glDeleteVertexArrays(1, model);
	glDeleteBuffers(1, model + 1);
	SDL_GL_DeleteContext(context);
	SDL_DestroyWindow(win);

	return 0;
}
Пример #10
0
Window::Window() {
    SDL_Init(SDL_INIT_VIDEO);
    displayWindow = SDL_CreateWindow("My Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_OPENGL);
    SDL_GLContext context = SDL_GL_CreateContext(displayWindow);
    SDL_GL_MakeCurrent(displayWindow, context);
}
Пример #11
0
BBSDLContext *bbSDLGraphicsCreateGraphics( int width,int height,int depth,int hz,int flags ) {

	int mode;
	char * appTitle = bbStringToUTF8String( bbAppTitle );
	
	int windowFlags = 0;

	if ((flags & FLAGS_DX) == 0) {
		windowFlags = SDL_WINDOW_OPENGL;
	}
	
	if (flags & FLAGS_BORDERLESS) windowFlags |= SDL_WINDOW_BORDERLESS;
	
	if( depth ){
		windowFlags |= SDL_WINDOW_FULLSCREEN;
		mode=MODE_DISPLAY;
	} else {
		if (flags & FLAGS_FULLSCREEN) {
			windowFlags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
		}
		mode=MODE_WINDOW;
	}

	if ((flags & FLAGS_DX) == 0) {
		if (flags & FLAGS_BACKBUFFER) SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
		if (flags & FLAGS_ALPHABUFFER) SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 1);
		if (flags & FLAGS_DEPTHBUFFER) SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
		if (flags & FLAGS_STENCILBUFFER) SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
	}
#ifdef __ANDROID__
	SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
	SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6);
	SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
#endif

#ifdef __RASPBERRYPI__
	int rpi_mode;
	int rpi_group;
	
	if (depth && (flags & FLAGS_RPI_TV_FULLSCREEN)) {
		bmx_tvservice_get_closest_mode(width, height, hz, &rpi_mode, &rpi_group);
		bmx_tvservice_setmode(rpi_mode, rpi_group, width, height);
	}
	SDL_VideoInit(NULL);
#endif
	SDL_Window *window = SDL_CreateWindow(appTitle, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
		width, height, windowFlags);
		
	if (window == NULL) {
printf("error... %s\n", SDL_GetError());fflush(stdout);
		return NULL;
	}

	SDL_GLContext context = 0;
	
	if ((flags & FLAGS_DX) == 0) {
		SDL_GL_SetSwapInterval(-1);
	
		context = SDL_GL_CreateContext(window);
	}

	BBSDLContext *bbcontext=(BBSDLContext*)malloc( sizeof(BBSDLContext) );
	memset( bbcontext,0,sizeof(BBSDLContext) );
	bbcontext->mode=mode;	
	bbcontext->width=width;	
	bbcontext->height=height;
#ifdef __RASPBERRYPI__
	bbcontext->depth=16;
#else
	bbcontext->depth=24;	
#endif
	bbcontext->hertz=hz;
	bbcontext->flags=flags;
	bbcontext->sync=-1;	
	bbcontext->window=window;
	bbcontext->context=context;
	SDL_GetWindowWMInfo(window, &bbcontext->info);
	return bbcontext;

}
Пример #12
0
int main(int argc, const char * argv[]) {
    
    // Window size
    int SCREEN_WIDTH = 800;
    int SCREEN_HEIGHT = 600;
    
    SDL_Window *mainwindow; /* Our window handle */
    SDL_GLContext maincontext; /* Our opengl context handle */
    
    SDL_Init(SDL_INIT_VIDEO);
    
    mainwindow = SDL_CreateWindow(PROGRAM_NAME, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                                  SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);
    
    /* Create our opengl context and attach it to our window */
    maincontext = SDL_GL_CreateContext(mainwindow);
    
    /* This makes our buffer swap syncronized with the monitor's vertical refresh */
    SDL_GL_SetSwapInterval(1);
    
    player.setColor(0, 1, 0);
    myGrid.size = 9;
    myGrid.LinesX = 10;
    myGrid.LinesY = 10;
    myGrid.placeTypes();
    myGrid.printTypes();
    
    SDL_Event event;
    bool running = true;
    // Initialize camera
    changeSize(SCREEN_WIDTH, SCREEN_HEIGHT);
    while (running) {
        Uint32 start = SDL_GetTicks();
        //std::cout << "Start: " << start << std::endl;
        while (SDL_PollEvent(&event)) {
            
            switch (event.type) {
                    
                // Capture any window event
                // https://wiki.libsdl.org/SDL_WindowEvent
                case SDL_WINDOWEVENT:
                    switch (event.window.event) {
                        case SDL_WINDOWEVENT_RESIZED:
                            int w = event.window.data1;
                            int h = event.window.data2;
                            changeSize(w, h);
                            break;
                    }
                    break;
                    
                // Handle keyboar events
                case SDL_KEYDOWN:
                    switch (event.key.keysym.sym) {
                        case SDLK_UP:
                            std::cout << "Up key pressed" << std::endl;
                            player.move(1, 0, 0);
                            std::cout << "Player pos X " << player.posX << std::endl;
                            break;
                        case SDLK_DOWN:
                            std::cout << "Down key pressed" << std::endl;
                            player.move(-1, 0, 0);
                            std::cout << "Player pos X " << player.posX << std::endl;
                            break;
                        case SDLK_LEFT:
                            std::cout << "Left key pressed" << std::endl;
                            player.move(0, 1, 0);
                            std::cout << "Player pos Y " << player.posY << std::endl;
                            break;
                        case SDLK_RIGHT:
                            std::cout << "Right key pressed" << std::endl;
                            player.move(0, -1, 0);
                            std::cout << "Player pos Y " << player.posY << std::endl;
                            break;
                    }
                    break;
                    
                case SDL_QUIT:
                    running = false;
                    break;
            }
        }
        
        renderScene(mainwindow);
        
        // Insure that screen update happen no more then 60 fps
        //std::cout << "End: " << SDL_GetTicks() << std::endl;
        if (1000/60>(SDL_GetTicks() - start)) {
            SDL_Delay(1000/60 - (SDL_GetTicks() - start));
        }
    }
    
    /* Delete our opengl context, destroy our window, and shutdown SDL */
    SDL_GL_DeleteContext(maincontext);
    SDL_DestroyWindow(mainwindow);
    SDL_Quit();
    
    return 0;
}
Пример #13
0
/* Run Program */
int main (int argc, char** argv) {
	
	//Read input argument
	int steps=1000;
	double h = 0.1;
	if (argc == 1){
		printf("USAGE: NumberOfSteps StepSize/Tolerance\nExited.\n");
		return 0;
	} 
	if (argc > 1) steps = atoi(argv[1]);	
	if (argc > 2) h = atof(argv[2]);	
	printf("Input arguments: %i %f \n", steps, h);
	
	//Check if SDL Initialization is successful
	if (SDL_Init(SDL_INIT_VIDEO) != 0) {
		return -1;
	}

	//Create Window
	SDL_Window *win = SDL_CreateWindow("Exercise 5, Lorenz Equations",50,50,800,600,SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);
	if (!win) {
		fprintf(stderr, "Could not create window: %s\n", SDL_GetError());
	}
	
	//Initialize OpenGL
	SDL_GLContext context = SDL_GL_CreateContext(win);
	if (!context) {
		fprintf(stderr, "Could not create OpenGL context: %s\n", SDL_GetError());
	}
	glViewport(0,0,(GLsizei)800,(GLsizei)600);
	glClearColor(1.0f,1.0f,1.0f,1.0f);
	glClear(GL_COLOR_BUFFER_BIT);
	SDL_GL_SwapWindow(win);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glEnable(GL_DEPTH_TEST);
	glFrustum(-100,100,-100,100,0.01,100);
	glEnable(GL_POLYGON_OFFSET_FILL);
	glPolygonOffset(1,1);
	glEnable(GL_LIGHTING);
	glShadeModel(GL_SMOOTH);
	GLfloat lightcol[] = {0.9,0.9,0.9,1.0};
	GLfloat lightamb[] = {0.5,0.5,0.5,1.0};
	GLfloat lightpos[] = {20.0,20.0,30.0,1.0};
	glLightfv(GL_LIGHT0,GL_AMBIENT,lightamb);
	glLightfv(GL_LIGHT0,GL_DIFFUSE,lightcol);
	glEnable(GL_LIGHT0);
	glEnable(GL_COLOR_MATERIAL);
	glColorMaterial(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE);
	glEnable(GL_RESCALE_NORMAL);
	

	//Init all vectors
	double t0 = 0;
	double* t = malloc(sizeof(double)*steps);
	double* xValues = malloc(sizeof(double)*steps);
	double* yValues = malloc(sizeof(double)*steps);
	double* zValues = malloc(sizeof(double)*steps);
	double* xValues_it = malloc(sizeof(double)*steps);
	double* yValues_it = malloc(sizeof(double)*steps);
	double* zValues_it = malloc(sizeof(double)*steps);
	double xmin = -4;
	double xmax = 4;
	double ymin = -4;
	double ymax = 4;
	double xsteps = 21;
	double ysteps = 21;
	struct Matrix* X = new_Matrix(xsteps,ysteps);
	struct Matrix* Y = new_Matrix(xsteps,ysteps);
	struct Matrix* Z = new_Matrix(xsteps,ysteps);	
	meshgrid(xmin,xmax,ymin,ymax,xsteps,ysteps,X,Y);
	paraboloid(X,Y,Z);
	struct Vector* vec0 = new_Vector(DIM);
	vec0->values[0] = 1;
	vec0->values[1] = 1;
	vec0->values[2] = 2;
	vec0->values[3] = 1-0.25;
	vec0->values[4] = -1-0.25;
	vec0->values[5] = -1;
	struct Vector** vec = malloc(sizeof(struct Vector*)*steps);	
	for (int j=1; j < steps; j++) {
		vec[j] = new_Vector(DIM);
	}
	
	//find geodesic iteratively
	struct Vector** vec_it = malloc(sizeof(struct Vector*)*steps);
	vec_it[0] = vec0;	
	for (int j=1; j < steps; j++) {
		vec_it[j] = new_Vector(DIM);
		geodesic_step(vec_it[j-1],h,vec_it[j]);		
	}
	for (int j=0; j < steps; j++) {
		xValues_it[j] = vec_it[j]->values[0];
		yValues_it[j] = vec_it[j]->values[1];
		zValues_it[j] = vec_it[j]->values[2];
	}

	//solve ODE
	//adaptive_rk3(geodesic_rhs,t0,vec0,h,t,vec,steps);
	euler(geodesic_rhs,t0,vec0,h,t,vec,steps);

	for (int j=0; j < steps; j++) {
		xValues[j] = vec[j]->values[0];
		yValues[j] = vec[j]->values[1];
		zValues[j] = vec[j]->values[2];
	}
	
	SDL_GL_SwapWindow(win);

	/* Look Around Loop	*/
	bool loop = true;
	bool wireframe = false;
	bool overlay = true;
	double xMouse = 0;
	double yMouse = 0;
	double xpos = 0;
	double ypos = 0;
	double zpos = 0;
	bool mouseDown = false;
	double mouseZoom = 0.1;
	SDL_Event event;
	while (loop) {
		while (SDL_PollEvent(&event)) {
			if (event.type == SDL_QUIT) {
				loop = false;
			}
			if (event.type== SDL_MOUSEBUTTONDOWN) {
				mouseDown = true;
			}
			if (event.type == SDL_MOUSEBUTTONUP) {
				mouseDown = false;
			}
			if (event.type == SDL_MOUSEMOTION) {
				if(mouseDown){
					xMouse += 0.5*event.motion.xrel;
					yMouse += 0.5*event.motion.yrel;
				}
			}
			if (event.type== SDL_KEYDOWN) {
				if(event.key.keysym.scancode == SDL_SCANCODE_W)
					ypos += 0.1;
				if(event.key.keysym.scancode == SDL_SCANCODE_S)
					ypos -= 0.1;
				if(event.key.keysym.scancode == SDL_SCANCODE_A)
					xpos -= 0.1;
				if(event.key.keysym.scancode == SDL_SCANCODE_D)
					xpos += 0.1;
				if(event.key.keysym.scancode == SDL_SCANCODE_Q)
					zpos += 0.1;
				if(event.key.keysym.scancode == SDL_SCANCODE_E)
					zpos -= 0.1;
				if(event.key.keysym.scancode == SDL_SCANCODE_TAB)
					wireframe = !wireframe;
				if(event.key.keysym.scancode == SDL_SCANCODE_O)
					overlay = !overlay;
			}
			if (event.type== SDL_MOUSEWHEEL) {
				if (event.wheel.y < 0)
					mouseZoom /= 1.2;
				else
					mouseZoom *= 1.2;
			}
		}
		
		//Draw current frame buffer
		SDL_GL_SwapWindow(win);	

		//Prepare next frame buffer
		glClearColor( 1.0f, 1.0f, 1.0f, 1.0f );
        glClear( GL_COLOR_BUFFER_BIT);
        glEnable(GL_DEPTH_TEST);
		glClear(GL_DEPTH_BUFFER_BIT);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
		
		glTranslated(xpos, ypos, zpos);
		glScaled(mouseZoom,mouseZoom,mouseZoom);
		glRotated(-90, 1.0, 0.0, 0.0);
		glRotated(-yMouse, 1.0, 0.0, 0.0);
		glRotated(-xMouse, 0.0, 0.0, 1.0);


		plotAxis3D(-10,10,-10,10,-5,30,0,0,0);
		glColor4f(0.2,0.4,0.5,1.0);
		glLightfv(GL_LIGHT0,GL_POSITION,lightpos);
		if (wireframe) {
			glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
			surf(X,Y,Z);
		} else {
			glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
			surf(X,Y,Z);
			if (overlay) {
				glColor4f(0.2,0.2,0.2,1.0);
				glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
				surf(X,Y,Z);
			}
		}
		
		glColor4f(0.85,0.85,0.10,1.0);
		plotArray3D(xValues,yValues,zValues,steps);
		glColor4f(0.9,0.2,0.4,1.0);
		plotArray3D(xValues_it,yValues_it,zValues_it,steps);
		glColor4f(0.0,0.0,0.0,1.0);
	}


	//Clean Up Memory					
	free(t);
	for (int j=1; j < steps; j++) {
		delete_Vector(vec[j]);
	}
	free(vec);
	free(xValues);
	free(yValues);
	free(zValues);
	delete_Vector(vec0);
	delete_Matrix(X);
	delete_Matrix(Y);
	delete_Matrix(Z);

	SDL_GL_DeleteContext(context);
	SDL_DestroyWindow(win);
	SDL_Quit();
	return 0;
}
Пример #14
0
bool Application::Init(int w, int h) {
  if (SDL_Init(SDL_INIT_VIDEO) < 0) {
    return EmitSDLError("error initialize SDL");
    return false;
  }
#ifdef __APPLE__
  SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
#else
  SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
#endif
  SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
  SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);

  window_ = SDL_CreateWindow(nullptr, SDL_WINDOWPOS_UNDEFINED,
                             SDL_WINDOWPOS_UNDEFINED, w, h, SDL_WINDOW_OPENGL);
  gl_context_ = SDL_GL_CreateContext(window_);
  if (gl_context_ == nullptr) {
    return EmitSDLError("error creating GL context");
  }

  // Enable vsync
  SDL_GL_SetSwapInterval(1);

  if (TTF_Init() != 0) {
    return EmitSDLError("error initialize font system");
  }

  std::string resource_folder_name = std::string(kResourceFolderName) + "/";
  std::string font_file_name = resource_folder_name + kFontFileName;
  font_ = TTF_OpenFont(font_file_name.c_str(), 14);
  if (font_ == nullptr) {
    std::string message;
    message += "error read font ";
    message += kFontFileName;
    message += "at size " + std::to_string(14);
    return EmitSDLError(message.c_str());
  }
  std::string demo_file_name = resource_folder_name + kDemoFileName;
  world_ = ParseWorld((CreateJsonObject(demo_file_name.c_str())));
  world_->Start(World::EngineType::kLiquidFun);

  // We have two camera setup: the first one for viewing the board and the
  // second one for background. The second camera does not move.
  cameras_.resize(2);
  cameras_[0] =
      make_unique<Camera>(Vector3f(0, -50, 650), Vector3f(0, 50, 0),
                          Vector3f(0, 1, 0), M_PI / 2.0, 1.0, 10.0, 500000.0);

  cameras_[1] =
      make_unique<Camera>(Vector3f(0, 0, 800), Vector3f(0, 0, 0),
                          Vector3f(0, 1, 0), M_PI / 2.0, 1.0, 10.0, 500000.0);

  poly_drawer_ = make_unique<NodeGroupDrawer<NodeBuldgedDrawer>>(
      LoadMesh3DGLProgram(), cameras_[0].get(), Vector2f(w, h));
  path_drawer_ = make_unique<NodeGroupDrawer<NodePathDrawer>>(
      LoadSimpleGLProgram(), cameras_[0].get(), Vector2f(w, h));
  particle_drawer_ = make_unique<NodeGroupDrawer<SphereDrawer>>(
      LoadSphereGLProgram(), cameras_[0].get(), Vector2f(w, h));
  // Add Node to each group drawer.
  for (size_t i = 0; i < world_->GetNumNodes(); ++i) {
    auto& collision_shapes = world_->GetNodeByIndex(i)->collision_shapes;
    if (collision_shapes.size() == 1 &&
        collision_shapes[0]->shape_type == Shape2DType::kDisk) {
      particle_drawer_->AddNode(world_->GetNodeByIndex(i));
    } else {
      poly_drawer_->AddNode(world_->GetNodeByIndex(i));
    }
    path_drawer_->AddNode(world_->GetNodeByIndex(i));
  }

  text_drawer_ = make_unique<TextDrawer>(font_);
  // Use the fixed camera for background drawing.
  canvas_drawer_ = make_unique<CanvasDrawer>(LoadBackgroundGLProgram(),
                                             cameras_[1].get(), Vector2f(w, h));
  return true;
}
Пример #15
0
int
engine_init(void)
{
	if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_AUDIO)) {
		DBG_LOG("Failed to initialize SDL: %s", SDL_GetError());
		return -1;
	}

	SDL_LogSetAllPriority(SDL_LOG_PRIORITY_WARN);

	fullscreen = false;

	/* require OpenGL 3.2 */
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
	// SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

	main_win = SDL_CreateWindow(RPG_WINDOW_TITLE,
		SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
		RPG_OUT_WIDTH, RPG_OUT_HEIGHT, SDL_WINDOW_RESIZABLE | SDL_WINDOW_OPENGL);
	if (!main_win) {
		DBG_LOG("Failed to create window: %s", SDL_GetError());
		goto failure;
	}

	main_ctx = SDL_GL_CreateContext(main_win);
	if (!main_ctx) {
		DBG_LOG("Failed to initialize GL context: %s", SDL_GetError());
		goto failure;
	}

	SDL_GL_MakeCurrent(main_win, main_ctx);

	/* now that context is created we can initialize GL */
	int res = gl3wInit();
	if (res != GL3W_OK) {
		DBG_LOG("Error opening GL library (%d)", res);
		goto failure;
	}

	if (!gl3wIsSupported(3, 2)) {
		DBG_LOG("Error OpenGL 3.2 or later required");
		goto failure;
	}

	/* register published key events */
	engine_key_state.left = keystate_register("left");
	engine_key_state.right = keystate_register("right");
	engine_key_state.up = keystate_register("up");
	engine_key_state.down = keystate_register("down");
	engine_key_state.button_a = keystate_register("a");
	engine_key_state.button_b = keystate_register("b");
	engine_key_state.button_x = keystate_register("x");
	engine_key_state.button_y = keystate_register("y");
	engine_key_state.start = keystate_register("start");
	engine_key_state.select = keystate_register("select");

	return 0;
failure:
	engine_fini();
	return -1;
}
Пример #16
0
int
main(int argc, char *argv[])
{
    /* Platform */
    int width, height;
    const char *font_path;
    gui_size font_height;
    SDL_Window *win;
    SDL_GLContext glContext;
    NVGcontext *vg = NULL;
    unsigned int started;
    unsigned int dt;

    /* GUI */
    struct gui_input in;
    struct gui_font font;
    struct demo_gui gui;

    if (argc < 2) {
        fprintf(stdout,"Missing TTF Font file argument: gui <path>\n");
        exit(EXIT_FAILURE);
    }
    font_path = argv[1];
    font_height = 10;

    /* SDL */
    SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_EVENTS);
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    win = SDL_CreateWindow("Demo",
        SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
        WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_OPENGL|SDL_WINDOW_SHOWN);
    glContext = SDL_GL_CreateContext(win);
    SDL_GetWindowSize(win, &width, &height);

    /* OpenGL */
    glewExperimental = 1;
    if (glewInit() != GLEW_OK)
        die("[GLEW] failed setup\n");
    glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);

    /* nanovg */
    vg = nvgCreateGLES2(NVG_ANTIALIAS|NVG_DEBUG);
    if (!vg) die("[NVG]: failed to init\n");
    nvgCreateFont(vg, "fixed", font_path);
    nvgFontFace(vg, "fixed");
    nvgFontSize(vg, font_height);
    nvgTextAlign(vg, NVG_ALIGN_LEFT|NVG_ALIGN_MIDDLE);

    /* GUI */
    memset(&in, 0, sizeof in);
    memset(&gui, 0, sizeof gui);
    gui.memory = malloc(MAX_MEMORY);
    font.userdata.ptr = vg;
    nvgTextMetrics(vg, NULL, NULL, &font.height);
    font.width = font_get_width;
    init_demo(&gui, &font);

    while (gui.running) {
        /* Input */
        SDL_Event evt;
        started = SDL_GetTicks();
        gui_input_begin(&in);
        while (SDL_PollEvent(&evt)) {
            if (evt.type == SDL_WINDOWEVENT) resize(&evt);
            else if (evt.type == SDL_QUIT) goto cleanup;
            else if (evt.type == SDL_KEYUP) key(&in, &evt, gui_false);
            else if (evt.type == SDL_KEYDOWN) key(&in, &evt, gui_true);
            else if (evt.type == SDL_MOUSEBUTTONDOWN) btn(&in, &evt, gui_true);
            else if (evt.type == SDL_MOUSEBUTTONUP) btn(&in, &evt, gui_false);
            else if (evt.type == SDL_MOUSEMOTION) motion(&in, &evt);
            else if (evt.type == SDL_TEXTINPUT) text(&in, &evt);
            else if (evt.type == SDL_MOUSEWHEEL) gui_input_scroll(&in, evt.wheel.y);
        }
        gui_input_end(&in);

        /* GUI */
        SDL_GetWindowSize(win, &width, &height);
        run_demo(&gui, &in);

        /* Draw */
        glClearColor(0.4f, 0.4f, 0.4f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
        draw(vg, &gui.queue, width, height);
        SDL_GL_SwapWindow(win);

        /* Timing */
        dt = SDL_GetTicks() - started;
        if (dt < DTIME)
            SDL_Delay(DTIME - dt);
    }

cleanup:
    /* Cleanup */
    free(gui.memory);
    nvgDeleteGLES2(vg);
    SDL_GL_DeleteContext(glContext);
    SDL_DestroyWindow(win);
    SDL_Quit();
    return 0;
}
Пример #17
0
SDL_Surface *
SDL_SetVideoMode(int width, int height, int bpp, Uint32 flags)
{
    SDL_DisplayMode desktop_mode;
    SDL_DisplayMode mode;
    int window_x = SDL_WINDOWPOS_UNDEFINED;
    int window_y = SDL_WINDOWPOS_UNDEFINED;
    Uint32 window_flags;
    Uint32 desktop_format;
    Uint32 desired_format;
    Uint32 surface_flags;

    if (!SDL_GetVideoDevice()) {
        if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE) < 0) {
            return NULL;
        }
    }
    
    SDL_GetDesktopDisplayMode(&desktop_mode);

    if (width == 0) {
        width = desktop_mode.w;
    }
    if (height == 0) {
        height = desktop_mode.h;
    }

    /* See if we can simply resize the existing window and surface */
    if (SDL_ResizeVideoMode(width, height, bpp, flags) == 0) {
        return SDL_PublicSurface;
    }

    /* Destroy existing window */
    SDL_PublicSurface = NULL;
    if (SDL_ShadowSurface) {
        SDL_FreeSurface(SDL_ShadowSurface);
        SDL_ShadowSurface = NULL;
    }
    if (SDL_VideoSurface) {
        SDL_DelPaletteWatch(SDL_VideoSurface->format->palette,
                            SDL_VideoPaletteChanged, NULL);
        SDL_FreeSurface(SDL_VideoSurface);
        SDL_VideoSurface = NULL;
    }
    if (SDL_VideoContext) {
        /* SDL_GL_MakeCurrent(0, NULL); *//* Doesn't do anything */
        SDL_GL_DeleteContext(SDL_VideoContext);
        SDL_VideoContext = NULL;
    }
    if (SDL_VideoWindow) {
        SDL_GetWindowPosition(SDL_VideoWindow, &window_x, &window_y);
        SDL_DestroyWindow(SDL_VideoWindow);
    }

    /* Set up the event filter */
    if (!SDL_GetEventFilter(NULL, NULL)) {
        SDL_SetEventFilter(SDL_CompatEventFilter, NULL);
    }

    /* Create a new window */
    window_flags = SDL_WINDOW_SHOWN;
    if (flags & SDL_FULLSCREEN) {
        window_flags |= SDL_WINDOW_FULLSCREEN;
    }
    if (flags & SDL_OPENGL) {
        window_flags |= SDL_WINDOW_OPENGL;
    }
    if (flags & SDL_RESIZABLE) {
        window_flags |= SDL_WINDOW_RESIZABLE;
    }
    if (flags & SDL_NOFRAME) {
        window_flags |= SDL_WINDOW_BORDERLESS;
    }
    GetEnvironmentWindowPosition(width, height, &window_x, &window_y);
    SDL_SetFullscreenDisplayMode(NULL);
    SDL_VideoWindow =
        SDL_CreateWindow(wm_title, window_x, window_y, width, height,
                         window_flags);
    if (!SDL_VideoWindow) {
        return NULL;
    }
    SDL_SetWindowIcon(SDL_VideoWindow, SDL_VideoIcon);

    window_flags = SDL_GetWindowFlags(SDL_VideoWindow);
    surface_flags = 0;
    if (window_flags & SDL_WINDOW_FULLSCREEN) {
        surface_flags |= SDL_FULLSCREEN;
    }
    if (window_flags & SDL_WINDOW_OPENGL) {
        surface_flags |= SDL_OPENGL;
    }
    if (window_flags & SDL_WINDOW_RESIZABLE) {
        surface_flags |= SDL_RESIZABLE;
    }
    if (window_flags & SDL_WINDOW_BORDERLESS) {
        surface_flags |= SDL_NOFRAME;
    }

    /* Set up the desired display mode */
    desktop_format = desktop_mode.format;
    if (desktop_format && ((flags & SDL_ANYFORMAT)
                           || (bpp == SDL_BITSPERPIXEL(desktop_format)))) {
        desired_format = desktop_format;
    } else {
        switch (bpp) {
        case 0:
            if (desktop_format) {
                desired_format = desktop_format;
            } else {
                desired_format = SDL_PIXELFORMAT_RGB888;
            }
            bpp = SDL_BITSPERPIXEL(desired_format);
            break;
        case 8:
            desired_format = SDL_PIXELFORMAT_INDEX8;
            break;
        case 15:
            desired_format = SDL_PIXELFORMAT_RGB555;
            break;
        case 16:
            desired_format = SDL_PIXELFORMAT_RGB565;
            break;
        case 24:
            desired_format = SDL_PIXELFORMAT_RGB24;
            break;
        case 32:
            desired_format = SDL_PIXELFORMAT_RGB888;
            break;
        default:
            SDL_SetError("Unsupported bpp in SDL_SetVideoMode()");
            return NULL;
        }
    }
    mode.format = desired_format;
    mode.w = width;
    mode.h = height;
    mode.refresh_rate = 0;

    /* Set the desired display mode */
    if (flags & SDL_FULLSCREEN) {
        if (SDL_SetFullscreenDisplayMode(&mode) < 0) {
            return NULL;
        }
    }

    /* If we're in OpenGL mode, just create a stub surface and we're done! */
    if (flags & SDL_OPENGL) {
        SDL_VideoContext = SDL_GL_CreateContext(SDL_VideoWindow);
        if (!SDL_VideoContext) {
            return NULL;
        }
        if (SDL_GL_MakeCurrent(SDL_VideoWindow, SDL_VideoContext) < 0) {
            return NULL;
        }
        SDL_VideoSurface =
            SDL_CreateRGBSurfaceFrom(NULL, width, height, bpp, 0, 0, 0, 0, 0);
        if (!SDL_VideoSurface) {
            return NULL;
        }
        SDL_VideoSurface->flags |= surface_flags;
        SDL_PublicSurface = SDL_VideoSurface;
        return SDL_PublicSurface;
    }

    /* Create a renderer for the window */
    if (SDL_CreateRenderer
        (SDL_VideoWindow, -1,
         SDL_RENDERER_SINGLEBUFFER | SDL_RENDERER_PRESENTDISCARD) < 0) {
        return NULL;
    }
    SDL_GetRendererInfo(&SDL_VideoRendererInfo);

    /* Create a texture for the screen surface */
    SDL_VideoTexture =
        SDL_CreateTexture(desired_format, SDL_TEXTUREACCESS_STREAMING, width,
                          height);

    if (!SDL_VideoTexture) {
        SDL_VideoTexture =
            SDL_CreateTexture(desktop_format,
                              SDL_TEXTUREACCESS_STREAMING, width, height);
    }
    if (!SDL_VideoTexture) {
        return NULL;
    }

    /* Create the screen surface */
    SDL_VideoSurface = CreateVideoSurface(SDL_VideoTexture);
    if (!SDL_VideoSurface) {
        return NULL;
    }
    SDL_VideoSurface->flags |= surface_flags;

    /* Set a default screen palette */
    if (SDL_VideoSurface->format->palette) {
        SDL_VideoSurface->flags |= SDL_HWPALETTE;
        SDL_DitherColors(SDL_VideoSurface->format->palette->colors,
                         SDL_VideoSurface->format->BitsPerPixel);
        SDL_AddPaletteWatch(SDL_VideoSurface->format->palette,
                            SDL_VideoPaletteChanged, SDL_VideoSurface);
        SDL_SetPaletteColors(SDL_VideoSurface->format->palette,
                             SDL_VideoSurface->format->palette->colors, 0,
                             SDL_VideoSurface->format->palette->ncolors);
    }

    /* Create a shadow surface if necessary */
    if ((bpp != SDL_VideoSurface->format->BitsPerPixel)
        && !(flags & SDL_ANYFORMAT)) {
        SDL_ShadowSurface =
            SDL_CreateRGBSurface(0, width, height, bpp, 0, 0, 0, 0);
        if (!SDL_ShadowSurface) {
            return NULL;
        }
        SDL_ShadowSurface->flags |= surface_flags;

        /* 8-bit SDL_ShadowSurface surfaces report that they have exclusive palette */
        if (SDL_ShadowSurface->format->palette) {
            SDL_ShadowSurface->flags |= SDL_HWPALETTE;
            if (SDL_VideoSurface->format->palette) {
                SDL_SetSurfacePalette(SDL_ShadowSurface,
                                      SDL_VideoSurface->format->palette);
            } else {
                SDL_DitherColors(SDL_ShadowSurface->format->palette->colors,
                                 SDL_ShadowSurface->format->BitsPerPixel);
            }
            SDL_AddPaletteWatch(SDL_ShadowSurface->format->palette,
                                SDL_VideoPaletteChanged, SDL_ShadowSurface);
        }
    }
    SDL_PublicSurface =
        (SDL_ShadowSurface ? SDL_ShadowSurface : SDL_VideoSurface);

    SDL_VideoFlags = flags;

    ClearVideoSurface();

    SetupScreenSaver(flags);

    /* We're finally done! */
    return SDL_PublicSurface;
}
Пример #18
0
int main(int argc, char* argv[]) {
    char* b3dFilePath;

    /* camera variables */
    float angleX = 0.f, angleY = 0.f;
    float positionX = 0.f, positionY = 0.f, positionZ = 0.f;

    /* camera movement variables */
    float forwardX = 0.f, forwardY = 0.f, forwardZ = 1.f;
    float rightX = 1.f, rightY = 0.f, rightZ = 0.f;

    /* memory to store only the rotation transform of the view matrix */
    float viewRotation[16];

    if (argc < 2) b3dFilePath = "test1/test1.b3d";
    else b3dFilePath = argv[1];

    b3dTest = loadB3DFile(b3dFilePath);
/*
    printf("textures:\n");
    printf("directory: %s\n", getDirectoryFromFile(b3dTest));
    printf("texture count: %d\n", getNumberOfTexturesFromBRUSChunk(getBRUSChunkFromBB3DChunk(getBB3DChunkFromFile(b3dTest))));
*/
    SDL_Init(SDL_INIT_VIDEO);

    glWindow = SDL_CreateWindow("B3D Lightmap Viewer", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
        SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_OPENGL);

    glContext = SDL_GL_CreateContext(glWindow);

    glActiveTextureARB = SDL_GL_GetProcAddress("glActiveTextureARB");
    glClientActiveTextureARB = SDL_GL_GetProcAddress("glClientActiveTextureARB");

    keyPress = SDL_GetKeyboardState(NULL);

    /* multitexture setup */

    /* commentary: possible support for more than 2 texture layers? if necessary. */

    textures = loadTextures(b3dTest);

    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

    glActiveTextureARB(GL_TEXTURE0_ARB);
    glEnable(GL_TEXTURE_2D);

    glActiveTextureARB(GL_TEXTURE1_ARB);
    glEnable(GL_TEXTURE_2D);

    /* OpenGL initial setup */

    glClearColor(0.f, 0.f, 0.5f, 1.f);

    glEnable(GL_DEPTH_TEST);

    glMatrixMode(GL_PROJECTION);
    gluPerspective(70.0, 1.333, 10, 10000);

    glMatrixMode(GL_MODELVIEW);

    /* main loop */

    while (!quit) {
        int differentialX = 0, differentialY = 0;
        int mouseStates = 0;

        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) quit = 1;
        }

        if (keyPress[SDL_SCANCODE_ESCAPE]) quit = 1;

        mouseStates = SDL_GetRelativeMouseState(&differentialX, &differentialY);

        /* change camera orientation when mouse dragged */
        if (mouseStates & SDL_BUTTON(SDL_BUTTON_LEFT)) {
            angleX -= MOUSE_VERTICAL_SENSITIVITY * differentialY;
            angleY -= MOUSE_HORIZONTAL_SENSITIVITY * differentialX;
        }

        /* use existing base vectors in view rotation matrix for movement */
        forwardX = viewRotation[2];
        forwardY = viewRotation[6];
        forwardZ = viewRotation[10];

        rightX = viewRotation[0];
        rightY = viewRotation[4];
        rightZ = viewRotation[8];

        /* move camera forward when W pressed */
        if (keyPress[SDL_SCANCODE_W]) {
            positionX -= CAMERA_SPEED * forwardX;
            positionY -= CAMERA_SPEED * forwardY;
            positionZ -= CAMERA_SPEED * forwardZ;
        }

        /* move camera left when A pressed */
        if (keyPress[SDL_SCANCODE_A]) {
            positionX -= CAMERA_SPEED * rightX;
            positionY -= CAMERA_SPEED * rightY;
            positionZ -= CAMERA_SPEED * rightZ;
        }

        /* move camera backward when S pressed */
        if (keyPress[SDL_SCANCODE_S]) {
            positionX += CAMERA_SPEED * forwardX;
            positionY += CAMERA_SPEED * forwardY;
            positionZ += CAMERA_SPEED * forwardZ;
        }

        /* move camera right when D pressed */
        if (keyPress[SDL_SCANCODE_D]) {
            positionX += CAMERA_SPEED * rightX;
            positionY += CAMERA_SPEED * rightY;
            positionZ += CAMERA_SPEED * rightZ;
        }

        /* reset camera position and orientation when R pressed */
        if (keyPress[SDL_SCANCODE_R]) {
            positionX = 0.f;
            positionY = 0.f;
            positionZ = 0.f;
            angleX = 0.f;
            angleY = 0.f;
        }

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        /* construct the view matrix */
        glLoadIdentity();
        glRotatef(-angleX, 1.f, 0.f, 0.f);
        glRotatef(-angleY, 0.f, 1.f, 0.f);
        glGetFloatv(GL_MODELVIEW_MATRIX, viewRotation);
        glTranslatef(-positionX, -positionY, -positionZ);
        glScalef(1.f, 1.f, -1.f);

        drawB3D(b3dTest);

        SDL_GL_SwapWindow(glWindow);
        SDL_Delay(16);
    }

    /* commentary: still need to clear the loaded data from memory */

    SDL_DestroyWindow(glWindow);
    SDL_Quit();

    return 0;
}
Пример #19
0
static bool
_cg_winsys_display_setup(cg_display_t *display, cg_error_t **error)
{
    cg_display_sdl2_t *sdl_display;
    const char *(*get_string_func)(GLenum name);
    const char *gl_version;

    c_return_val_if_fail(display->winsys == NULL, false);

    sdl_display = c_slice_new0(cg_display_sdl2_t);
    display->winsys = sdl_display;

    set_gl_attribs_from_framebuffer_config(&display->onscreen_template->config);

    if (display->renderer->driver == CG_DRIVER_GLES2) {
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK,
                            SDL_GL_CONTEXT_PROFILE_ES);
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
    } else if (display->renderer->driver == CG_DRIVER_GL3) {
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK,
                            SDL_GL_CONTEXT_PROFILE_CORE);
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS,
                            SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);
    }

    /* Create a dummy 1x1 window that never gets display so that we can
     * create a GL context */
    sdl_display->dummy_window =
        SDL_CreateWindow("",
                         0,
                         0, /* x/y */
                         1,
                         1, /* w/h */
                         SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN);
    if (sdl_display->dummy_window == NULL) {
        _cg_set_error(error,
                      CG_WINSYS_ERROR,
                      CG_WINSYS_ERROR_INIT,
                      "SDL_CreateWindow failed: %s",
                      SDL_GetError());
        goto error;
    }

    sdl_display->context = SDL_GL_CreateContext(sdl_display->dummy_window);

    if (sdl_display->context == NULL) {
        _cg_set_error(error,
                      CG_WINSYS_ERROR,
                      CG_WINSYS_ERROR_INIT,
                      "SDL_GL_CreateContext failed: %s",
                      SDL_GetError());
        goto error;
    }

    /* SDL doesn't seem to provide a way to select between GL and GLES
     * and instead it will just pick one itself. We can at least try to
     * verify that it picked the one we were expecting by looking at the
     * GL version string */
    get_string_func = SDL_GL_GetProcAddress("glGetString");
    gl_version = get_string_func(GL_VERSION);

    switch (display->renderer->driver) {
    case CG_DRIVER_GL:
    case CG_DRIVER_GL3:
        /* The first character of the version string will be a digit if
         * it's normal GL */
        if (!c_ascii_isdigit(gl_version[0])) {
            _cg_set_error(error,
                          CG_WINSYS_ERROR,
                          CG_WINSYS_ERROR_INIT,
                          "The GL driver was requested but SDL is using GLES");
            goto error;
        }

        if (display->renderer->driver == CG_DRIVER_GL3 && gl_version[0] < '3') {
            _cg_set_error(error,
                          CG_WINSYS_ERROR,
                          CG_WINSYS_ERROR_INIT,
                          "The GL3 driver was requested but SDL is using "
                          "GL %c",
                          gl_version[0]);
            goto error;
        }
        break;

    case CG_DRIVER_GLES2:
        if (!c_str_has_prefix(gl_version, "OpenGL ES 2") &&
            !c_str_has_prefix(gl_version, "OpenGL ES 3")) {
            _cg_set_error(error,
                          CG_WINSYS_ERROR,
                          CG_WINSYS_ERROR_INIT,
                          "The GLES2 driver was requested but SDL is "
                          "not using GLES2 or GLES3");
            goto error;
        }
        break;

    default:
        c_assert_not_reached();
    }

    return true;

error:
    _cg_winsys_display_destroy(display);
    return false;
}
Пример #20
0
int main(int argc, char *argv[]) {
	int done;
	SDL_Event event;
	int width, height;
	struct sth_stash* stash = 0;
	FILE* fp = 0;
	int datasize;
	unsigned char* data;
	float sx,sy,dx,dy,lh;
	int droidRegular, droidItalic, droidBold, droidJapanese, dejavu;
	SDL_Surface* surface;
	GLuint texture;

	if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
	{
		fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError());
		return -1;
	}


	// Init OpenGL
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
    SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);

#ifdef STH_OPENGL3
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
#endif



	width = 800;
	height = 600;	

    SDL_Window* window = SDL_CreateWindow("FontStash Demo", 100, 100, width, height, SDL_WINDOW_OPENGL);

	if (!window)
	{
		fprintf(stderr, "Could not initialise SDL opengl\n");
		return -1;
	}

    SDL_GLContext context = SDL_GL_CreateContext(window);
	
	stash = sth_create(512,512);
	if (!stash)
	{
		fprintf(stderr, "Could not create stash.\n");
		return -1;
	}

	// Load the first truetype font from memory (just because we can).
	fp = fopen("DroidSerif-Regular.ttf", "rb");
	if (!fp) goto error_add_font;
	fseek(fp, 0, SEEK_END);
	datasize = (int)ftell(fp);
	fseek(fp, 0, SEEK_SET);
	data = (unsigned char*)malloc(datasize);
	if (data == NULL) goto error_add_font;
	fread(data, 1, datasize, fp);
	fclose(fp);
	fp = 0;
	
	if (!(droidRegular = sth_add_font_from_memory(stash, data)))
		goto error_add_font;

	// Load the remaining truetype fonts directly.
	if (!(droidItalic = sth_add_font(stash,"DroidSerif-Italic.ttf")))
		goto error_add_font;
	if (!(droidBold = sth_add_font(stash,"DroidSerif-Bold.ttf")))
		goto error_add_font;
	if (!(droidJapanese = sth_add_font(stash,"DroidSansJapanese.ttf")))
		goto error_add_font;

	// Load a bitmap font
	surface = IMG_Load("dejavu-sans_0.png");
	if (surface == NULL)
	{
		fprintf(stderr, "%s.\n", IMG_GetError());
		return -1;
	}
	glGenTextures(1, &texture);
	glBindTexture(GL_TEXTURE_2D, texture);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	if (SDL_MUSTLOCK(surface)) SDL_LockSurface(surface);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA8, surface->w, surface->h, 0, GL_ALPHA, GL_UNSIGNED_BYTE, surface->pixels);
	if (SDL_MUSTLOCK(surface)) SDL_UnlockSurface(surface);
	SDL_FreeSurface(surface);
	dejavu = sth_add_bitmap_font(stash, 17, -4, 2);
	sth_add_glyph_for_char(stash, dejavu, texture, "T", 18, 14, 363, 331, 10, 11, 0,  3, 10);
	sth_add_glyph_for_char(stash, dejavu, texture, "h", 18, 14, 225, 382,  8, 11, 1,  3, 10);
	sth_add_glyph_for_char(stash, dejavu, texture, "i", 18, 14, 478, 377,  2, 11, 1,  3,  4);
	sth_add_glyph_for_char(stash, dejavu, texture, "s", 18, 14, 199, 455,  7,  8, 1,  6,  9);
	sth_add_glyph_for_char(stash, dejavu, texture, " ", 18, 14,  66, 185,  1,  1, 0, 14,  5);
	sth_add_glyph_for_char(stash, dejavu, texture, "a", 18, 14,  18, 459,  8,  8, 1,  6, 10);
	sth_add_glyph_for_char(stash, dejavu, texture, "b", 18, 14, 198, 383,  8, 11, 1,  3, 10);
	sth_add_glyph_for_char(stash, dejavu, texture, "t", 18, 14, 436, 377,  5, 11, 1,  3,  6);
	sth_add_glyph_for_char(stash, dejavu, texture, "m", 18, 14, 494, 429, 12,  8, 2,  6, 16);
	sth_add_glyph_for_char(stash, dejavu, texture, "p", 18, 14, 436, 353,  8, 11, 1,  6, 10);
	sth_add_glyph_for_char(stash, dejavu, texture, "f", 18, 14, 442, 377,  5, 11, 1,  3,  7);
	sth_add_glyph_for_char(stash, dejavu, texture, "o", 18, 14, 483, 438,  8,  8, 1,  6, 10);
	sth_add_glyph_for_char(stash, dejavu, texture, "n", 18, 14,   0, 459,  8,  8, 1,  6, 10);
	sth_add_glyph_for_char(stash, dejavu, texture, ".", 18, 14, 285, 476,  2,  3, 1, 11,  6);
	
	done = 0;
	while (!done)
	{
		while (SDL_PollEvent(&event))
		{
			switch (event.type)
			{
				case SDL_MOUSEMOTION:
					break;
				case SDL_MOUSEBUTTONDOWN:
					break;
				case SDL_KEYDOWN:
					if (event.key.keysym.sym == SDLK_ESCAPE)
						done = 1;
					break;
				case SDL_QUIT:
					done = 1;
					break;
				default:
					break;
			}
		}
		
		// Update and render
		glViewport(0, 0, width, height);
		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

		glClearColor(0.3f, 0.3f, 0.32f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

#ifdef STH_OPENGL3
        std::cout << "OpenGL3" << std::endl;
        glm::mat4 proj = glm::ortho(0.0f, (GLfloat) width, 0.0f, (GLfloat) height, -1.0f, 1.0f);

        sth_projection_matrix(stash, glm::value_ptr(proj));
        sth_color(stash, 1.0f, 0.0f, 0.0f, 1.0f);
#else
        std::cout << "Immediate OpenGL" << std::endl;
		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		glOrtho(0,width,0,height,-1,1);

		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();

		glColor4ub(255,255,255,255);
#endif

		sx = 100; sy = 250;
		
		sth_begin_draw(stash);
		
		dx = sx; dy = sy;
		sth_draw_text(stash, droidRegular, 24.0f, dx, dy, "The quick ", &dx);
		sth_draw_text(stash, droidItalic, 48.0f, dx, dy, "brown ", &dx);
		sth_draw_text(stash, droidRegular, 24.0f, dx, dy, "fox ", &dx);
		sth_vmetrics(stash, droidItalic, 24, NULL, NULL, &lh);
		dx = sx;
		dy -= lh*1.2f;
		sth_draw_text(stash, droidItalic, 24.0f, dx, dy, "jumps over ", &dx);
		sth_draw_text(stash, droidBold, 24.0f, dx, dy, "the lazy ", &dx);
		sth_draw_text(stash, droidRegular, 24.0f, dx, dy, "dog.", &dx);
		dx = sx;
		dy -= lh*1.2f;
		sth_draw_text(stash, droidRegular, 12.0f, dx, dy, "Now is the time for all good men to come to the aid of the party.", &dx);
		sth_vmetrics(stash, droidItalic, 12, NULL, NULL, &lh);
		dx = sx;
		dy -= lh*1.2f*2;
		sth_draw_text(stash, droidItalic, 18.0f, dx, dy, "Ég get etið gler án þess að meiða mig.", &dx);
		sth_vmetrics(stash, droidItalic, 18, NULL, NULL, &lh);
		dx = sx;
		dy -= lh*1.2f;
		sth_draw_text(stash, droidJapanese, 18.0f, dx, dy, "私はガラスを食べられます。それは私を傷つけません。", &dx);
		dx = sx;
		dy -= lh*1.2f*2;
		sth_draw_text(stash, dejavu, 18.0f, dx, dy, "This is a bitmap font.", &dx);

		sth_end_draw(stash);
		
        SDL_GL_SwapWindow(window);
	}
	
	sth_delete(stash);
	free(data);
    SDL_GL_DeleteContext(context);
	SDL_Quit();
	return 0;

error_add_font:
	fprintf(stderr, "Could not add font.\n");
	return -1;
}
Пример #21
0
bool
GLAppSDL::initialize(int argc, char* argv[])
{
    if (!AppBaseSDL::initialize(argc, argv))
        return false;

    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, profile);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, majorVersion);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, minorVersion);
#if defined(DEBUG)
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
#endif

    if (profile == SDL_GL_CONTEXT_PROFILE_ES) {
#if 0
        int numVideoDrivers = SDL_GetNumVideoDrivers();
        int i;
        const char** drivers;

        drivers = (const char**)SDL_malloc(sizeof(const char*) * numVideoDrivers);
        for (i = 0; i < numVideoDrivers; i++) {
            drivers[i] = SDL_GetVideoDriver(i);
        }
#endif

        // Only the indicated platforms pay attention to these hints
        // but they could be set on any platform.
#if __WINDOWS__ || __LINUX__
        SDL_SetHint(SDL_HINT_OPENGL_ES_DRIVER, "1");
#endif

#if __WINDOWS__
        // If using ANGLE copied from Chrome should set to "d3dcompiler_46.dll"
        // Should set value via compiler -D definition from gyp file.
        SDL_SetHint(SDL_HINT_VIDEO_WIN_D3DCOMPILER, "none");
#endif
    }

#if __MACOSX__
    SDL_SetHint(SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK, "1");
#endif
    
    pswMainWindow = SDL_CreateWindow(
                        szName,
                        SDL_WINDOWPOS_UNDEFINED,
                        SDL_WINDOWPOS_UNDEFINED,
                        w_width, w_height,
                        SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE
                    );

    if (pswMainWindow == NULL) {
        (void)SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, szName, SDL_GetError(), NULL);
        return false;
    }

#if __WINDOWS__
    // Set the applications own icon in place of the Windows default set by SDL.
    // Needs to be done here to avoid change being visible.
    setWindowsIcon(pswMainWindow);
#endif

    sgcGLContext = SDL_GL_CreateContext(pswMainWindow);
    // Work around bug in SDL. It returns a 2.x context when 3.x is requested.
    // It does though internally record an error.
    const char* error = SDL_GetError();
    if (sgcGLContext == NULL
        || (error[0] != '\0'
            && majorVersion >= 3
            && (profile == SDL_GL_CONTEXT_PROFILE_CORE
                || profile == SDL_GL_CONTEXT_PROFILE_COMPATIBILITY))
        ) {
        (void)SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, szName, SDL_GetError(), NULL);
        return false;
    }

#if __WINDOWS__
    if (profile != SDL_GL_CONTEXT_PROFILE_ES)
    {
        // No choice but to use GLEW for GL on Windows; there is no .lib with static
        // bindings. For ES we use one of the hardware vendor SDKs all of which have
        // static bindings.
        // TODO: Figure out how to support {GLX,WGL}_EXT_create_context_es2_profile
        //       were there are no static bindings. Need a GLEW equivalent for ES and
        //       different compile options. Perhaps can borrow function loading stuff
        //       from SDL's testgles2.c.

        // So one build of this library can be linked in to applications using GLEW and
        // applications not using GLEW, do not call any GLEW functions directly.
        // Call via queried function pointers.
        void* glewdll = SDL_LoadObject("glew32.dll");
        if (glewdll == NULL) {
            std::string sName(szName);

            (void)SDL_ShowSimpleMessageBox(
                SDL_MESSAGEBOX_ERROR,
                szName,
                SDL_GetError(),
                NULL);
            return false;
        }
        
        typedef GLenum(GLEWAPIENTRY PFNGLEWINIT)(void);
        typedef const GLubyte * GLEWAPIENTRY PFNGLEWGETERRORSTRING(GLenum error);
        PFNGLEWINIT* pGlewInit;
        PFNGLEWGETERRORSTRING* pGlewGetErrorString;
        bool error = true;
#define STR(s) #s
#if defined(_M_IX86)
        /* Win32 GLEW uses __stdcall. */
  #define DNAMESTR(x,n) STR(_##x##@##n)
#else
        /* x64 uses __cdecl. */
  #define DNAMESTR(x,n) STR(x)
#endif
        pGlewInit = (PFNGLEWINIT*)SDL_LoadFunction(glewdll, DNAMESTR(glewInit,0));
        if (pGlewInit != NULL) {
            pGlewGetErrorString = (PFNGLEWGETERRORSTRING*)SDL_LoadFunction(
                    glewdll, DNAMESTR(glewGetErrorString,4));
            if (pGlewGetErrorString != NULL) {
                error = false;
            }
        }

        if (error) {
            std::string sName(szName);

            (void)SDL_ShowSimpleMessageBox(
                SDL_MESSAGEBOX_ERROR,
                szName,
                SDL_GetError(),
                NULL);
            return false;
        }

        int iResult = pGlewInit();
        if (iResult != GLEW_OK) {
            std::string sName(szName);

            (void)SDL_ShowSimpleMessageBox(
                          SDL_MESSAGEBOX_ERROR,
                          szName,
                          (const char*)pGlewGetErrorString(iResult),
                          NULL);
            return false;
        }
    }
Пример #22
0
// SDL wants main() to have this exact signature
extern "C" int main(int argc, char* argv[])
{
    // Initialize SDL
    if (SDL_Init(SDL_INIT_VIDEO))
    {
        fprintf(stderr, "SDL_Init: %s\n", SDL_GetError());
        return 1;
    }

    // Plain 32-bit RGBA8 pixel format
    SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);

    // Don't need built-in depth buffer, we use our own.
    //SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);

    // Select OpenGL version
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);

#ifdef _DEBUG
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
#endif

    // Create the window
	SDL_Window* window = SDL_CreateWindow("OpenGL", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_OPENGL);
    if (!window)
    {
        fprintf(stderr, "SDL_CreateWindow: %s\n", SDL_GetError());
        return 1;
    }

    // Create the OpenGL context
    SDL_GLContext context = SDL_GL_CreateContext(window);
    if (!context)
    {
        fprintf(stderr, "SDL_GL_CreateContext: %s\n", SDL_GetError());
        return 1;
    }

    // Initialize OpenGL (must be called before calling any OpenGL functions)
    OpenGL_Init();	

	// DEBUG: print OpenGL version
	const GLubyte* version = glGetString(GL_VERSION);
	fprintf(stdout, "OpenGL Version: %s\n", version);	

	//======================== VAO ===============================
	// Hook up the vertex and index buffers to a "vertex array object" (VAO)
	// VAOs are the closest thing OpenGL has to a "mesh" object.
	// VAOs are used to feed data from buffers to thgle inputs of a vertex shader.
	//============================================================	

	//===================== VBO/EBO ===============================
	Skybox skyBox = Skybox();
	skyBox.load();

	TerrainMesh terrainMesh = TerrainMesh(64, 64, 0.0);
	terrainMesh.load();

	
	//============================================================

	//===================== TEXTURES =============================
	
	//============================================================

	//======================= SHADERS ============================
	// init terrain shader
	ShaderSet terrainShaderSet;
	terrainShaderSet.SetVersion("330");

	// set uniforms (use preambles here or define them in the shader file, but NOT both)
	terrainShaderSet.SetPreamble(
		"uniform mat4 iModelViewProjection;\n"
		"uniform mat4 iModel;\n"
		"uniform mat4 iView;\n"
		"uniform vec3 iLightPosition_worldspace;\n"
		"uniform sampler2DArray iTextureArray;\n"
	);
	GLuint* terrainShaderId = terrainShaderSet.AddProgramFromExts({ "a3.vert", "a3.frag" });


	// init skybox shader
	ShaderSet skyboxShaderSet;
	skyboxShaderSet.SetVersion("330");

	// set uniforms (use preambles here or define them in the shader file, but NOT both)
	skyboxShaderSet.SetPreamble(
		"uniform mat4 iProjection;\n"
		"uniform mat4 iView;\n"
		"uniform samplerCube iSkyBoxCubeTexture;\n"
	);
	GLuint* skyboxShaderId = skyboxShaderSet.AddProgramFromExts({ "skybox.vert", "skybox.frag" });
	//============================================================

	//======================== LIGHTS ============================
	glm::vec3 light = glm::vec3(4, 40, 4);
	//============================================================

	//================== BEZIER CURVES ===========================
	glm::vec3 xzLength = glm::vec3(32.0, 0.0, 32.0);
	glm::vec3 yPull = glm::vec3(0.0, 20.0, 0.0);
	glm::vec3 xPull = glm::vec3(20.0, 0.0, 0.0);

	CubicBezierCurve bezierCurve1 = CubicBezierCurve(light, xzLength, yPull, yPull);
	CubicBezierCurve bezierCurve2 = CubicBezierCurve(bezierCurve1.p3, xzLength, -yPull, -yPull);
	CubicBezierCurve bezierCurve3 = CubicBezierCurve(bezierCurve2.p3, -xzLength, xPull, xPull);
	CubicBezierCurve bezierCurve4 = CubicBezierCurve(bezierCurve3.p3, -xzLength, -xPull, -xPull);
	
	BezierPath bezierPath = BezierPath(std::vector<CubicBezierCurve>{ bezierCurve1, bezierCurve2, bezierCurve3, bezierCurve4 });
	//============================================================
	
    // Begin main loop
	double lastTime = 0;
	InputHandler inputHandler = InputHandler(window);
	Camera camera = Camera(4, 40, 4);
	float bezierTime = 0.0;
	const float bezierSpeed = 0.001;
    while (1)
    {			
		//================= UPDATE USER INPUT ========================
		double currentTime = SDL_GetTicks() / 1000.0;		
		float deltaTime = float(currentTime - lastTime);
		
		if (inputHandler.updateInput(deltaTime) == -1)
		{
			goto quit;
		}
		camera.update(inputHandler.getInputData(), deltaTime);

		lastTime = currentTime;
		//============================================================

		//================= COMPUTE MATRICES =========================
		// move camera position along bezier curve		
		glm::vec3 bezPos = bezierPath.getPointAt(bezierTime);
		bezierTime += bezierSpeed;
		bezierTime = (bezierTime > 1.0) ? 0.0 : bezierTime;
		camera.position = bezPos;

		// Projection matrix
		glm::mat4 Projection = glm::perspective(
			camera.FoV,
			camera.aspectRatio,
			camera.nearClip,
			camera.farClip
		);

		// Or, for an ortho camera :
		//glm::mat4 Projection = glm::ortho(-10.0f,10.0f,-10.0f,10.0f,0.0f,100.0f); // In world coordinates

		// Camera matrix
		glm::mat4 View = glm::lookAt(
			camera.position,
			camera.position + camera.direction,
			camera.up
		);

		// Model matrix : an identity matrix (model will be at the origin)
		glm::mat4 Model = glm::mat4(1.0f);
		// Our ModelViewProjection : multiplication of our 3 matrices
		glm::mat4 ModelViewProjection = Projection * View * Model; // Remember, matrix multiplication is the other way around
		//glm::mat4 ModelViewProjection = MVP;
		//============================================================		

		//================== UPDATE SHADERS ==========================
		// Set the color to clear with
		//glClearColor(100.0f / 255.0f, 149.0f / 255.0f, 237.0f / 255.0f, 1.0f);
		glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

		// Clear the screen
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		//===================== Z-BUFFER =============================
		// Enable depth test
		glEnable(GL_DEPTH_TEST);
		// Accept fragment if it closer to the camera than the former one
		glDepthFunc(GL_LESS);


		// TERRAIN ======================================================
		// Recompile/relink any programs that changed (must be called)
		terrainShaderSet.UpdatePrograms();

		// set OpenGL's shader program (must be called in loop)
		glUseProgram(*terrainShaderId);

		// get uniform handles
		GLuint iModelViewProjectionLoc = glGetUniformLocation(*terrainShaderId, "iModelViewProjection");
		GLuint iModelLoc = glGetUniformLocation(*terrainShaderId, "iModel");
		GLuint iViewLoc = glGetUniformLocation(*terrainShaderId, "iView");
		GLuint iLightPosition_worldspaceLoc = glGetUniformLocation(*terrainShaderId, "iLightPosition_worldspace");

		// send matrix uniforms to shader
		if (iModelViewProjectionLoc != -1)
		{
			glUniformMatrix4fv(iModelViewProjectionLoc, 1, GL_FALSE, &ModelViewProjection[0][0]);
		}

		if (iModelLoc != -1)
		{
			glUniformMatrix4fv(iModelLoc, 1, GL_FALSE, &Model[0][0]);
		}
		if (iViewLoc != -1)
		{
			glUniformMatrix4fv(iViewLoc, 1, GL_FALSE, &View[0][0]);
		}						

		// pass light position uniform to shader
		if (iLightPosition_worldspaceLoc != -1) 
		{
			glUniform3f(iLightPosition_worldspaceLoc, light.x, light.y, light.z);
		}				

		terrainMesh.generateTextureUniform(terrainShaderId, "iTextureArray");

		terrainMesh.attachToVAO(0, 1, 2, 3);

		terrainMesh.draw();



		// SKYBOX ========================================================
		// Recompile/relink any programs that changed (must be called)
		skyboxShaderSet.UpdatePrograms();

		// set OpenGL's shader program (must be called in loop)
		glUseProgram(*skyboxShaderId);

		// get skybox shader uniform handles
		GLuint iSkyBoxViewLoc = glGetUniformLocation(*skyboxShaderId, "iView");
		GLuint iSkyBoxProjectionLoc = glGetUniformLocation(*skyboxShaderId, "iProjection");
		if (iSkyBoxViewLoc != -1)
		{
			// remove the translation component of the view matrix
			// to make sure the skybox's origin is always at the camera
			glm::mat4 newView = glm::mat4(glm::mat3(View));
			glUniformMatrix4fv(iSkyBoxViewLoc, 1, GL_FALSE, &newView[0][0]);
		}
		if (iSkyBoxProjectionLoc != -1)
		{
			glUniformMatrix4fv(iSkyBoxProjectionLoc, 1, GL_FALSE, &Projection[0][0]);
		}

		// generate uniforms for object textures		
		skyBox.generateTextureUniform(skyboxShaderId, "iSkyBoxCubeTexture");

		skyBox.attachToVAO(4);

		skyBox.draw();


		// draw wireframe of mesh
		//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);		
		

		// check for errors
		GLenum err2;
		while ((err2 = glGetError()) != GL_NO_ERROR) {
			std::cerr << "OpenGL error: " << err2 << std::endl;
		}

		// disable the depth buffer
		glDisable(GL_DEPTH_TEST);

        // SDL docs: "On Mac OS X make sure you bind 0 to the draw framebuffer before swapping the window, otherwise nothing will happen."
        glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
        
        // Display the frame of rendering to the window
        SDL_GL_SwapWindow(window);		
    }

quit:
    SDL_Quit();
    return 0;
}
Пример #23
0
int main(void) {
    /* SDL variables. */
    SDL_Event event;
    SDL_Window *window;
    SDL_GLContext gl_context;
    const unsigned int WINDOW_WIDTH = 500, WINDOW_HEIGHT = WINDOW_WIDTH;
    double dt, initial_time;

    /* OpenGL variables. */
    GLint
        attribute_coord2d,
        ibo_size,
        width_location,
        height_location,
        time_location,
        periods_x_location,
        periods_y_location,
        pi2_location,
        program
    ;
    GLuint ibo, vbo;
    const char *attribute_name = "coord2d";
    const float
        periods_x = 10.0,
        periods_y = 10.0,
        pi2 = 2.0 * acos(-1.0)
    ;

    /* SDL init. */
    SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO);
    window = SDL_CreateWindow(__FILE__, 0, 0,
            WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_OPENGL);
    gl_context = SDL_GL_CreateContext(window);
    glewInit();

    /* OpenGL init. */
    {
        program = common_get_shader_program(vertex_shader_source, fragment_shader_source);
        attribute_coord2d = glGetAttribLocation(program, attribute_name);
        if (attribute_coord2d == -1) {
            fprintf(stderr, "error: attribute_coord2d: %s\n", attribute_name);
            return EXIT_FAILURE;
        }
        height_location = glGetUniformLocation(program, "height");
        periods_x_location = glGetUniformLocation(program, "periods_x");
        periods_y_location = glGetUniformLocation(program, "periods_y");
        pi2_location = glGetUniformLocation(program, "pi2");
        time_location = glGetUniformLocation(program, "time");
        width_location = glGetUniformLocation(program, "width");

        glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
        glUseProgram(program);
        glViewport(0, 0, WIDTH, HEIGHT);

        glGenBuffers(1, &vbo);
        glBindBuffer(GL_ARRAY_BUFFER, vbo);
        glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

        glGenBuffers(1, &ibo);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indexes), indexes, GL_STATIC_DRAW);
        glGetBufferParameteriv(GL_ELEMENT_ARRAY_BUFFER, GL_BUFFER_SIZE, &ibo_size);

        glUniform1f(pi2_location, pi2);
        glUniform1f(width_location, WIDTH);
        glUniform1f(height_location, HEIGHT);
        glUniform1f(periods_x_location, periods_x);
        glUniform1f(periods_y_location, periods_y);
    }

    initial_time = common_get_secs();
    common_fps_init();
    while (1) {
        dt = common_get_secs() - initial_time;

        /* OpenGL draw. */
        glClear(GL_COLOR_BUFFER_BIT);
        glEnableVertexAttribArray(attribute_coord2d);
        glBindBuffer(GL_ARRAY_BUFFER, vbo);
        glVertexAttribPointer(attribute_coord2d, 2, GL_FLOAT, GL_FALSE, 0, 0);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
        glUniform1f(time_location, dt);
        glDrawElements(GL_TRIANGLES, ibo_size / sizeof(indexes[0]), GL_UNSIGNED_INT, 0);
        glDisableVertexAttribArray(attribute_coord2d);

        common_fps_update_and_print();
        SDL_GL_SwapWindow(window);
        if (SDL_PollEvent(&event) && event.type == SDL_QUIT)
            break;
    }

    /* OpenGL cleanup. */
    glDeleteBuffers(1, &ibo);
    glDeleteBuffers(1, &vbo);
    glDeleteProgram(program);

    /* SDL cleanup. */
    SDL_GL_DeleteContext(gl_context);
    SDL_DestroyWindow(window);
    SDL_Quit();

    return EXIT_SUCCESS;
}
Пример #24
0
/*
===================
GLimp_Init
===================
*/
bool GLimp_Init( glimpParms_t parms )
{
	common->Printf( "Initializing OpenGL subsystem\n" );
	
	GLimp_PreInit(); // DG: make sure SDL is initialized
	
	// DG: make window resizable
	Uint32 flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE;
	// DG end
	
	if( parms.fullScreen )
		flags |= SDL_WINDOW_FULLSCREEN;
		
	int colorbits = 24;
	int depthbits = 24;
	int stencilbits = 8;
	
	for( int i = 0; i < 16; i++ )
	{
		// 0 - default
		// 1 - minus colorbits
		// 2 - minus depthbits
		// 3 - minus stencil
		if( ( i % 4 ) == 0 && i )
		{
			// one pass, reduce
			switch( i / 4 )
			{
				case 2 :
					if( colorbits == 24 )
						colorbits = 16;
					break;
				case 1 :
					if( depthbits == 24 )
						depthbits = 16;
					else if( depthbits == 16 )
						depthbits = 8;
				case 3 :
					if( stencilbits == 24 )
						stencilbits = 16;
					else if( stencilbits == 16 )
						stencilbits = 8;
			}
		}
		
		int tcolorbits = colorbits;
		int tdepthbits = depthbits;
		int tstencilbits = stencilbits;
		
		if( ( i % 4 ) == 3 )
		{
			// reduce colorbits
			if( tcolorbits == 24 )
				tcolorbits = 16;
		}
		
		if( ( i % 4 ) == 2 )
		{
			// reduce depthbits
			if( tdepthbits == 24 )
				tdepthbits = 16;
			else if( tdepthbits == 16 )
				tdepthbits = 8;
		}
		
		if( ( i % 4 ) == 1 )
		{
			// reduce stencilbits
			if( tstencilbits == 24 )
				tstencilbits = 16;
			else if( tstencilbits == 16 )
				tstencilbits = 8;
			else
				tstencilbits = 0;
		}
		
		int channelcolorbits = 4;
		if( tcolorbits == 24 )
			channelcolorbits = 8;
			
		SDL_GL_SetAttribute( SDL_GL_RED_SIZE, channelcolorbits );
		SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, channelcolorbits );
		SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, channelcolorbits );
		SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
		SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, tdepthbits );
		SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, tstencilbits );
		
		if( r_waylandcompat.GetBool() )
			SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 0 );
		else
			SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, channelcolorbits );
			
		SDL_GL_SetAttribute( SDL_GL_STEREO, parms.stereo ? 1 : 0 );
		
		SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, parms.multiSamples ? 1 : 0 );
		SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, parms.multiSamples );
		
#if SDL_VERSION_ATLEAST(2, 0, 0)
		
		// RB begin
		if( r_useOpenGL32.GetInteger() > 0 )
		{
			glConfig.driverType = GLDRV_OPENGL32_COMPATIBILITY_PROFILE;
			
			SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 );
			SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 2 );
		}
		if( r_debugContext.GetBool() )
		{
			SDL_GL_SetAttribute( SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG );
		}
		
		if( r_useOpenGL32.GetInteger() > 1 )
		{
			glConfig.driverType = GLDRV_OPENGL32_CORE_PROFILE;
			
			SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE );
		}
		// RB end
		
		// DG: set display num for fullscreen
		int windowPos = SDL_WINDOWPOS_UNDEFINED;
		if( parms.fullScreen > 0 )
		{
			if( parms.fullScreen > SDL_GetNumVideoDisplays() )
			{
				common->Warning( "Couldn't set display to num %i because we only have %i displays",
								 parms.fullScreen, SDL_GetNumVideoDisplays() );
			}
			else
			{
				// -1 because SDL starts counting displays at 0, while parms.fullScreen starts at 1
				windowPos = SDL_WINDOWPOS_UNDEFINED_DISPLAY( ( parms.fullScreen - 1 ) );
			}
		}
		// TODO: if parms.fullScreen == -1 there should be a borderless window spanning multiple displays
		/*
		 * NOTE that this implicitly handles parms.fullScreen == -2 (from r_fullscreen -2) meaning
		 * "do fullscreen, but I don't care on what monitor", at least on my box it's the monitor with
		 * the mouse cursor.
		 */
		
		
		window = SDL_CreateWindow( GAME_NAME,
								   windowPos,
								   windowPos,
								   parms.width, parms.height, flags );
		// DG end
		
		context = SDL_GL_CreateContext( window );
		
		if( !window )
		{
			common->DPrintf( "Couldn't set GL mode %d/%d/%d: %s",
							 channelcolorbits, tdepthbits, tstencilbits, SDL_GetError() );
			continue;
		}
		
		if( SDL_GL_SetSwapInterval( r_swapInterval.GetInteger() ) < 0 )
			common->Warning( "SDL_GL_SWAP_CONTROL not supported" );
			
		// RB begin
		SDL_GetWindowSize( window, &glConfig.nativeScreenWidth, &glConfig.nativeScreenHeight );
		// RB end
		
		glConfig.isFullscreen = ( SDL_GetWindowFlags( window ) & SDL_WINDOW_FULLSCREEN ) == SDL_WINDOW_FULLSCREEN;
#else
		glConfig.driverType = GLDRV_OPENGL3X;
		
		SDL_WM_SetCaption( GAME_NAME, GAME_NAME );
		
		if( SDL_GL_SetAttribute( SDL_GL_SWAP_CONTROL, r_swapInterval.GetInteger() ) < 0 )
			common->Warning( "SDL_GL_SWAP_CONTROL not supported" );
		
		window = SDL_SetVideoMode( parms.width, parms.height, colorbits, flags );
		if( !window )
		{
			common->DPrintf( "Couldn't set GL mode %d/%d/%d: %s",
							 channelcolorbits, tdepthbits, tstencilbits, SDL_GetError() );
			continue;
		}
		
		glConfig.nativeScreenWidth = window->w;
		glConfig.nativeScreenHeight = window->h;
		
		glConfig.isFullscreen = ( window->flags & SDL_FULLSCREEN ) == SDL_FULLSCREEN;
#endif
		
		common->Printf( "Using %d color bits, %d depth, %d stencil display\n",
						channelcolorbits, tdepthbits, tstencilbits );
						
		glConfig.colorBits = tcolorbits;
		glConfig.depthBits = tdepthbits;
		glConfig.stencilBits = tstencilbits;
		
		// RB begin
		glConfig.displayFrequency = 60;
		glConfig.isStereoPixelFormat = parms.stereo;
		glConfig.multisamples = parms.multiSamples;
		
		glConfig.pixelAspect = 1.0f;	// FIXME: some monitor modes may be distorted
		// should side-by-side stereo modes be consider aspect 0.5?
		
		// RB end
		
		break;
	}
	
	if( !window )
	{
		common->Printf( "No usable GL mode found: %s", SDL_GetError() );
		return false;
	}
	
#ifdef __APPLE__
	glewExperimental = GL_TRUE;
#endif
	
	GLenum glewResult = glewInit();
	if( GLEW_OK != glewResult )
	{
		// glewInit failed, something is seriously wrong
		common->Printf( "^3GLimp_Init() - GLEW could not load OpenGL subsystem: %s", glewGetErrorString( glewResult ) );
	}
	else
	{
		common->Printf( "Using GLEW %s\n", glewGetString( GLEW_VERSION ) );
	}
	
	// DG: disable cursor, we have two cursors in menu (because mouse isn't grabbed in menu)
	SDL_ShowCursor( SDL_DISABLE );
	// DG end
	
	return true;
}
Пример #25
0
//"		outColor = mix(texture(texKitten, vec2(Texcoord.x + sin(Texcoord.y * 60.0 + time * 2.0) / 30.0, 1.0 - Texcoord.y)) * vec4(0.0, 0.0, 1.0, 1.0), texture(texPuppy, vec2(Texcoord)), factor);"
//"	if (Texcoord.x < 1.0 && Texcoord.y < 1.0 || Texcoord.x > 1.0 && Texcoord.y > 1.0)"
//"	if((Texcoord.x - 1.0) * (Texcoord.x - 1.0) + (Texcoord.y - 1.0) * (Texcoord.y - 1.0) < 1.0)"
//"	float factor = (sin(time * 3.0) + 1.0) / 2.0;"
//"	if (Texcoord.y < 0.5)"
//"		outColor = mix(texture(texKitten, Texcoord), texture(texPuppy, Texcoord), factor);"
//"	else"
//"		outColor = mix(texture(texKitten, vec2(Texcoord.x, 1.0 - Texcoord.y)), texture(texPuppy, vec2(Texcoord.x, 1.0 - Texcoord.y)), factor);"
int main(int argc, char *argv[])
{
	// Timer for blending the two textures
	//auto t_start = std::chrono::high_resolution_clock::now();

	// Initialize SDL
	SDL_Init(SDL_INIT_VIDEO);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
	SDL_Window* window = SDL_CreateWindow("OpenGL tutorial", 100, 100, 800, 600, SDL_WINDOW_OPENGL);
	SDL_GLContext context = SDL_GL_CreateContext(window);

	// Initialize GLEW
	glewExperimental = GL_TRUE;
	glewInit();

	// Create Vertex Array Object
	GLuint vao;
	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);

	// Create a Vertex Buffer Object and copy the vertex data to it
	GLuint vbo;
	glGenBuffers(1, &vbo); // Generate 1 buffer

	GLfloat vertices[] = {
	//  Position      Color             Texcoords
		-1.0f,  1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // Top-left
		1.0f,  1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, // Top-right
		1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, // Bottom-right
		-1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f  // Bottom-left
	};

	glBindBuffer(GL_ARRAY_BUFFER, vbo);
	glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

	// Create an element array
	GLuint ebo;
	glGenBuffers(1, &ebo); // Generate 1 buffer

	GLuint elements[] = {
		0, 1, 2,
		2, 3, 0
	};

	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW);

	// Create and compile the vertex shader
	GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
	glShaderSource(vertexShader, 1, &vertexSource, NULL);
	glCompileShader(vertexShader);

	// Create and compile the fragment shader
	GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
	glShaderSource(fragmentShader, 1, &fragmentSource, NULL);
	glCompileShader(fragmentShader);

	// Link the vertex and fragment shader into a shader program
	GLuint shaderProgram = glCreateProgram();
	glAttachShader(shaderProgram, vertexShader);
	glAttachShader(shaderProgram, fragmentShader);
	glBindFragDataLocation(shaderProgram, 0, "outColor");
	glLinkProgram(shaderProgram);
	glUseProgram(shaderProgram);

	// Specify the layout of the vertex data
	// The first number (2, 3, 2 in the attribs below) tell how many floats are needed for each attribute
	// N * sizeof(float) this tells the vertex shader how many bytes are incoming per vertex
	// The 0 and/or (void*)(N * sizeof(float)) tells how many bytes should be skipped before each attribute
	GLint posAttrib = glGetAttribLocation(shaderProgram, "position");
	glEnableVertexAttribArray(posAttrib);
	glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 7 * sizeof(GLfloat), 0);

	GLint colAttrib = glGetAttribLocation(shaderProgram, "color");
	glEnableVertexAttribArray(colAttrib);
	glVertexAttribPointer(colAttrib, 3, GL_FLOAT, GL_FALSE, 7 * sizeof(GLfloat), (void*)(2 * sizeof(GLfloat)));

	GLint texAttrib = glGetAttribLocation(shaderProgram, "texcoord");
	glEnableVertexAttribArray(texAttrib);
	glVertexAttribPointer(texAttrib, 2, GL_FLOAT, GL_FALSE, 7 * sizeof(GLfloat), (void*)(5 * sizeof(GLfloat)));

	// Get alpha uniform from fragment shader
	//GLint uniTime = glGetUniformLocation(shaderProgram, "time");

	// Create texture and load image with SOIL
	GLuint textures[2];
	glGenTextures(2, textures);

	int width, height;
	unsigned char* image;

	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, textures[0]);
		image = SOIL_load_image("sample.png", &width, &height, 0, SOIL_LOAD_RGB);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
		SOIL_free_image_data(image);
	glUniform1i(glGetUniformLocation(shaderProgram, "texKitten"), 0);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);

	glActiveTexture(GL_TEXTURE1);
	glBindTexture(GL_TEXTURE_2D, textures[1]);
		image = SOIL_load_image("sample2.png", &width, &height, 0, SOIL_LOAD_RGB);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
		SOIL_free_image_data(image);
	glUniform1i(glGetUniformLocation(shaderProgram, "texPuppy"), 1);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);

	SDL_Event windowEvent;

	// Error checking
	GLint status, status2;
	glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &status);
	glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &status2);
	char buffer1[512], buffer2[512];
	glGetShaderInfoLog(vertexShader, 512, NULL, buffer1);
	glGetShaderInfoLog(fragmentShader, 512, NULL, buffer2);
	std::cout
		<< "GL_Error: " << glGetError()
		<< "\n Vertex shader status: " << status
		<< "\n Vertex shader log: " << buffer1
		<< "\n Fragment shader status: " << status2
		<< "\n Fragment shader log: " << buffer2
		<< std::endl;



	while (true)
	{
		if (SDL_PollEvent(&windowEvent))
		{
			if (windowEvent.type == SDL_QUIT)
			{
				break;
			}
		}
		// Clear screen to black
		glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT);

		// Set the time uniform
		//auto t_now = std::chrono::high_resolution_clock::now();
		//float time = std::chrono::duration_cast<std::chrono::duration<float>>(t_now - t_start).count();
		//glUniform1f(uniTime, time);

		// Draw a rectangle from two triangles using 6 vertices
		glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

		// Swap buffers
		SDL_GL_SwapWindow(window);
	}
	glDeleteTextures(2, textures);

	glDeleteProgram(shaderProgram);
	glDeleteShader(fragmentShader);
	glDeleteShader(vertexShader);

	glDeleteBuffers(1, &vbo);
	glDeleteBuffers(1, &ebo);

	glDeleteVertexArrays(1, &vao);

	SDL_GL_DeleteContext(context);
	SDL_Quit();
	return 0;
}
Пример #26
0
string SDLInit(const char *title, int2 &screensize, bool fullscreen)
{
    //SDL_SetMainReady();
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER /* | SDL_INIT_AUDIO*/) < 0)
    {
        return SDLError("Unable to initialize SDL");
    }

    SDL_SetEventFilter(SDLHandleAppEvents, nullptr);

    DebugLog(-1, "SDL initialized...");

    SDL_LogSetAllPriority(SDL_LOG_PRIORITY_WARN);

    // on demand now
    //extern bool sfxr_init();
    //if (!sfxr_init())
    //   return SDLError("Unable to initialize audio");

    #ifdef PLATFORM_MOBILE
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
    #else
    //certain older Intel HD GPUs and also Nvidia Quadro 1000M don't support 3.1 ? the 1000M is supposed to support 4.2
    //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
    #ifndef WIN32
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);
    #endif
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
    #endif

    //SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);      // set this if we're in 2D mode for speed on mobile?
    SDL_GL_SetAttribute(SDL_GL_RETAINED_BACKING, 1);    // because we redraw the screen each frame

    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

    DebugLog(-1, "SDL about to figure out display mode...");

    #ifdef PLATFORM_MOBILE
    landscape = screensize.x() >= screensize.y();
    int modes = SDL_GetNumDisplayModes(0);
    screensize = int2(0);
    for (int i = 0; i < modes; i++)
    {
        SDL_DisplayMode mode;
        SDL_GetDisplayMode(0, i, &mode);
        //printf("mode: %d %d\n", mode.w, mode.h);
        if (landscape ? mode.w > screensize.x() : mode.h > screensize.y())
        {
            screensize = int2(mode.w, mode.h);
        }
    }

    DebugLog(-1, inttoa(screensize.x()));
    DebugLog(-1, inttoa(screensize.y()));
    DebugLog(-1, "SDL about to create window...");

    _sdl_window = SDL_CreateWindow(title,
                                    0, 0,
                                    screensize.x(), screensize.y(),
                                    SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_BORDERLESS);

    DebugLog(-1, _sdl_window ? "SDL window passed..." : "SDL window FAILED...");

    if (landscape) SDL_SetHint("SDL_HINT_ORIENTATIONS", "LandscapeLeft LandscapeRight");

    int ax = 0, ay = 0;
    SDL_GetWindowSize(_sdl_window, &ax, &ay);
    int2 actualscreensize(ax, ay);
    //screenscalefactor = screensize.x / actualscreensize.x;  // should be 2 on retina
    #ifdef __IOS__
        assert(actualscreensize == screensize);
        screensize = actualscreensize;
    #else
        screensize = actualscreensize;  // __ANDROID__
        DebugLog(-1, inttoa(screensize.x()));
        DebugLog(-1, inttoa(screensize.y()));
    #endif
    #else
    _sdl_window = SDL_CreateWindow(title,
                                    SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                                    screensize.x(), screensize.y(),
                                    SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE |
                                        (fullscreen ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0));
    #endif

    if (!_sdl_window)
        return SDLError("Unable to create window");

    DebugLog(-1, "SDL window opened...");


    _sdl_context = SDL_GL_CreateContext(_sdl_window);
    DebugLog(-1, _sdl_context ? "SDL context passed..." : "SDL context FAILED...");
    if (!_sdl_context) return SDLError("Unable to create OpenGL context");

    DebugLog(-1, "SDL OpenGL context created...");

    /*
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
    */

    #ifndef __IOS__
        SDL_GL_SetSwapInterval(1);  // vsync on
    #endif

    SDL_JoystickEventState(SDL_ENABLE);
    SDL_JoystickUpdate();
    for(int i = 0; i < SDL_NumJoysticks(); i++)
    {
        SDL_Joystick *joy = SDL_JoystickOpen(i);
        if (joy)
        {
            DebugLog(-1, "Detected joystick: %s (%d axes, %d buttons, %d balls, %d hats)\n",
                         SDL_JoystickName(joy), SDL_JoystickNumAxes(joy), SDL_JoystickNumButtons(joy),
                         SDL_JoystickNumBalls(joy), SDL_JoystickNumHats(joy));
        };
    };

    starttime = SDL_GetTicks();
    lastmillis = starttime - 16;    // ensure first frame doesn't get a crazy delta

    return "";
}
Пример #27
0
int main(int argc, char **argv)
{

	//Initializes console Position
	HWND hWnd = GetConsoleWindow();
	MoveWindow(hWnd, 1350, 0, 500, 1000, TRUE);
	std::cout << "GameArtsEngine" << std::endl;


	//Initializes SDL and gets everything set up 
	SDL_Init(SDL_INIT_VIDEO);
	SDL_Window *window = SDL_CreateWindow("GameArtsEngine", 40, 40, windowWidth, windowHeight, SDL_WINDOW_OPENGL);
	SDL_GLContext glcontext = SDL_GL_CreateContext(window);

	//Initializes our Glew
	glewInit();

	//Initializes our Engine
	iGAEngine->initGL(windowWidth, windowHeight);

	aiString list;
	Assimp::Importer imp;
	imp.GetExtensionList(list);
	std::cout << list.C_Str() << std::endl;




										/**************************************ALL THE ONE TIME SCENE SETUP GOES HERE*******************************************/

	
	//Creates a basic Light for our scene --> will eventually be moved to the Engine itself
	mainLight = new Light(LIGHT_POINT);
	mainLight->setDiffuse(2, 2, 2, 1);
	mainLight->setExponent(10);
	mainLight->setPosition(-5,25,5);

	
	//Load Textures
	defaultTexture = iGAEngine->loadTexture("Assets/Textures/ModelgridTexture.jpg");

	//Load Models->Primitives ------------------------ENABLE IF YOU NEED PRIMITIVES---------------------------------
	teapodModel = new meshLoader("Assets/Models/Primitives/teapod.dae");
	cylinderModel = new meshLoader("Assets/Models/Primitives/cylinder.dae");
	sphereModel = new meshLoader("Assets/Models/Primitives/sphere.dae");
	cubeModel = new meshLoader("Assets/Models/Primitives/cube.dae");
	

	//Load Models->GameModels

	//-----------------------------------------------------------------------------------------SHADERSETUP--------------------------------------------
	
	if (GLEW_ARB_vertex_shader && GLEW_ARB_fragment_shader){

		cout << endl << "SHADER LOG: -------------------------------------------------------- BEGIN" << endl;
		
		// Simple Normal Shader without SpecMap
		normalShader = new Shader("normal.vert", "normal.frag");
		normalShader->useShader();
		normalShader->setAttribute1i("diffuseMap0", 0);
		normalShader->setAttribute1i("normalMap1", 1);
		normalShader->setAttribute1f("SpecularPower", 2.0f);
		normalShader->setAttribute4f("Specular", 0.5, 0.5, 0.5, 1.0);
		normalShader->setAttribute4f("Ambient", 0.3, 0.3, 0.3, 1.0);
		normalShader->setAttribute4f("Diffuse", 1, 1, 1, 1.0);
		normalShader->setAttribute3f("fvLightPosition", 50.3f, 18.9f, 27.2f);

		// Normal Shader with SpecMap
		normalSpecShader = new Shader("normalSpec.vert", "normalSpec.frag");
		normalSpecShader->useShader();
		normalSpecShader->setAttribute1i("diffuseMap0", 0);
		normalSpecShader->setAttribute1i("normalMap1", 1);
		normalSpecShader->setAttribute1i("specularMap2", 2);
		normalSpecShader->setAttribute1f("SpecularPower", 2.0f);
		normalSpecShader->setAttribute4f("Specular", 0.5, 0.5, 0.5, 1.0);
		normalSpecShader->setAttribute4f("Ambient", 0.3, 0.3, 0.3, 1.0);
		normalSpecShader->setAttribute4f("Diffuse", 1, 1, 1, 1.0);
		normalSpecShader->setAttribute3f("fvLightPosition", 50.3f, 18.9f, 27.2f);

		// Simple LambertShader with DiffuseMap
		diffuseShader = new Shader("lambertDiffuse.vert", "lambertDiffuse.frag");
		diffuseShader->useShader();
		diffuseShader->setAttribute4f("Ambient", 0.3, 0.3, 0.3, 1.0);
		diffuseShader->setAttribute4f("Diffuse", 1, 1, 1, 1.0);
		diffuseShader->setAttribute3f("fvLightPosition", 50.3f, 18.9f, 27.2f);


		lambertShader_static = new Shader("lambert_static.vert", "lambert_static.frag");
		lambertShader_static->useShader();
		lambertShader_static->setAttribute4f("Ambient", 0.3, 0.3, 0.3, 1.0);
		lambertShader_static->setAttribute4f("Diffuse", 1, 1, 1, 1.0);
		lambertShader_static->setAttribute3f("fvLightPosition", 50.3f, 18.9f, 27.2f);
		
		cout << endl << "SHADER LOG: ---------------------------------------------------------- END" << endl;

	}
	else{
		cout << endl << "GLSL not supported" << endl;
	}

	//-----------------------------------------------------------------------------------------SHADERSETUP--------------------------------------------




										/**************************************ALL THE ONE TIME SCENE SETUP GOES HERE*******************************************/

	
	// Main Engine Loop
	bool isRunning = true;
	SDL_Event  event;

	while (isRunning )
	{
		//Gets states of the Mouse and stroes them in the struct
		SDL_GetMouseState(&mouseState.x, &mouseState.y);
		mouseState.LeftButtonDown = SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(1);
		mouseState.MiddleButtonDown = SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(2);
		mouseState.RightButtonDown = SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(3);

		drawMainScene(window); // calls stuff that needs to update every frame
		
		//Event loop
		while (SDL_PollEvent(&event)){

			if (event.type == SDL_QUIT)
				isRunning = false;
		}


		if (viewportNavigation())
			isRunning = false;
	}

	delete teapodModel;
	delete lambertShader_static;
	delete diffuseShader;
	delete normalShader;
	delete normalSpecShader;

	GAEngine::Unitialize();


	SDL_Quit();

	return 1;

}
Пример #28
0
bool COpenGL::init()
{
	CVideoEngine::init();
	const GLint oglfilter = m_VidConfig.m_opengl_filter;


#if SDL_VERSION_ATLEAST(2, 0, 0)    

    Uint32 flags = SDL_WINDOW_OPENGL;

    if(m_VidConfig.Fullscreen)
        flags |= SDL_WINDOW_FULLSCREEN;
    else
        flags |= (SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);


    window = SDL_CreateWindow("Commander Genius",
                              SDL_WINDOWPOS_CENTERED,
                              SDL_WINDOWPOS_CENTERED,
                              m_VidConfig.m_DisplayRect.w,
                              m_VidConfig.m_DisplayRect.h,
                              flags);

    glcontext = SDL_GL_CreateContext(window);
    
	// Set clear colour
	glClearColor(0,0,0,0);
	
	// Set projection
	glMatrixMode( GL_PROJECTION );
	glLoadIdentity();
    
#if defined(TARGET_OS_IPHONE) || defined(TARGET_IPHONE_SIMULATOR)	// TODO: dont check for iphone but for opengles
#define glOrtho glOrthof
#endif
	glOrtho( 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f );
    
	// Now Initialize modelview matrix
	glMatrixMode( GL_MODELVIEW );
	glLoadIdentity();

    // Setup the view port for the first time
#if defined(TARGET_OS_IPHONE) || defined(TARGET_IPHONE_SIMULATOR)
	glViewport(0, 0, 480, 320);
#else
    setUpViewPort(mAspectCorrectionRect);
#endif

    /*Using the standard OpenGL API for specifying a 2D texture
     image: glTexImage2D, glSubTexImage2D, glCopyTexImage2D,
     and glCopySubTexImage2D.  The target for these commands is
     GL_TEXTURE_RECTANGLE_ARB though.
     
     This is similar to how the texture cube map functionality uses the 2D
     texture image specification API though with its own texture target.
     
     The texture target GL_TEXTURE_RECTANGLE_ARB should also
     be used for glGetTexImage, glGetTexLevelParameteriv, and
     glGetTexLevelParameterfv.*/
    
	// Enable Texture loading for the blit screen
	glEnable(m_texparam);
    
    createTexture(m_texture, oglfilter, m_GamePOTScaleDim.w, m_GamePOTScaleDim.h);
	
	if(m_VidConfig.m_ScaleXFilter <= 1)
	{	// In that case we can do a texture based rendering
		createTexture(m_texFX, oglfilter, m_GamePOTScaleDim.w, m_GamePOTScaleDim.h, true);
	}
#else // not SDL 2.0
	// Setup the view port for the first time
    setUpViewPort(mAspectCorrectionRect);

	// Set clear colour
	glClearColor(0,0,0,0);
	
	// Set projection
	glMatrixMode( GL_PROJECTION );
	glLoadIdentity();

	#if defined(TARGET_OS_IPHONE) || defined(TARGET_IPHONE_SIMULATOR)	// TODO: dont check for iphone but for opengles
	#define glOrtho glOrthof
	#endif
	glOrtho( 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f );

	// Now Initialize modelview matrix
	glMatrixMode( GL_MODELVIEW );
	glLoadIdentity();
    /*Using the standard OpenGL API for specifying a 2D texture
    image: glTexImage2D, glSubTexImage2D, glCopyTexImage2D,
    and glCopySubTexImage2D.  The target for these commands is
    GL_TEXTURE_RECTANGLE_ARB though.

    This is similar to how the texture cube map functionality uses the 2D
    texture image specification API though with its own texture target.

    The texture target GL_TEXTURE_RECTANGLE_ARB should also
    be used for glGetTexImage, glGetTexLevelParameteriv, and
    glGetTexLevelParameterfv.*/

	// Enable Texture loading for the blit screen
	glEnable(m_texparam);
	
	createTexture(m_texture, oglfilter, m_GamePOTScaleDim.w, m_GamePOTScaleDim.h);
	
    //if(m_VidConfig.m_ScaleXFilter <= 1)
	{ // In that case we can do a texture based rendering
	  createTexture(m_texFX, oglfilter, m_GamePOTScaleDim.w, m_GamePOTScaleDim.h, true);
	} 
    /*else
	{
	  createTexture(m_texFX, oglfilter, m_GamePOTScaleDim.w, m_GamePOTScaleDim.h, true);
    }*/
#endif
	
	// If there were any errors
	int error;
	error = glGetError();
	if( error != GL_NO_ERROR)
	{
		gLogging.ftextOut("OpenGL Init(): %d<br>",error);
#if SDL_VERSION_ATLEAST(2, 0, 0)
        SDL_DestroyWindow(window);
        SDL_GL_DeleteContext(glcontext);
#endif
		return false;
	}

    gLogging.ftextOut("OpenGL Init(): Interface successfully opened!<br>");


    GLfloat light_ambient[] = { 1.0, 1.0, 1.0, 1.0 };
    GLfloat light_diffuse[] = { 1.0, 1.0, 1.0, 1.0 };
    GLfloat light_specular[] = { 1.0, 1.0, 1.0, 1.0 };
    GLfloat light_position[] = { 0.0, 0.0, 1.0, 0.0 };

    glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
    glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
    glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
    glLightfv(GL_LIGHT0, GL_POSITION, light_position);

    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
	
	return true;
}
Пример #29
0
int main(int, char**)
{
    // Setup SDL
	if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
	{
        printf("Error: %s\n", SDL_GetError());
        return -1;
	}

    // Setup window
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
	SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
	SDL_DisplayMode current;
	SDL_GetCurrentDisplayMode(0, &current);
	SDL_Window *window = SDL_CreateWindow("ImGui SDL2+OpenGL3 example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, SDL_WINDOW_OPENGL|SDL_WINDOW_RESIZABLE);
	SDL_GLContext glcontext = SDL_GL_CreateContext(window);
    gl3wInit();

    // Setup ImGui binding
    ImGui_ImplSdlGL3_Init(window);

    // Load Fonts
    // (there is a default font, this is only if you want to change it. see extra_fonts/README.txt for more details)
    //ImGuiIO& io = ImGui::GetIO();
    //io.Fonts->AddFontDefault();
    //io.Fonts->AddFontFromFileTTF("../../extra_fonts/Cousine-Regular.ttf", 15.0f);
    //io.Fonts->AddFontFromFileTTF("../../extra_fonts/DroidSans.ttf", 16.0f);
    //io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyClean.ttf", 13.0f);
    //io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyTiny.ttf", 10.0f);
    //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());

    bool show_test_window = true;
    bool show_another_window = false;
    ImVec4 clear_color = ImColor(114, 144, 154);

    // Main loop
	bool done = false;
    while (!done)
    {
        SDL_Event event;
        while (SDL_PollEvent(&event))
        {
            ImGui_ImplSdlGL3_ProcessEvent(&event);
            if (event.type == SDL_QUIT)
                done = true;
        }
        ImGui_ImplSdlGL3_NewFrame();

        // 1. Show a simple window
        // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
        {
            static float f = 0.0f;
            ImGui::Text("Hello, world!");
            ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
            ImGui::ColorEdit3("clear color", (float*)&clear_color);
            if (ImGui::Button("Test Window")) show_test_window ^= 1;
            if (ImGui::Button("Another Window")) show_another_window ^= 1;
            ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
        }

        // 2. Show another simple window, this time using an explicit Begin/End pair
        if (show_another_window)
        {
            ImGui::SetNextWindowSize(ImVec2(200,100), ImGuiSetCond_FirstUseEver);
            ImGui::Begin("Another Window", &show_another_window);
            ImGui::Text("Hello");
            ImGui::End();
        }

        // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
        if (show_test_window)
        {
            ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver);
            ImGui::ShowTestWindow(&show_test_window);
        }

        // Rendering
        glViewport(0, 0, (int)ImGui::GetIO().DisplaySize.x, (int)ImGui::GetIO().DisplaySize.y);
        glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w);
        glClear(GL_COLOR_BUFFER_BIT);
        ImGui::Render();
        SDL_GL_SwapWindow(window);
    }

    // Cleanup
    ImGui_ImplSdlGL3_Shutdown();
    SDL_GL_DeleteContext(glcontext);  
	SDL_DestroyWindow(window);
	SDL_Quit();

    return 0;
}
Пример #30
0
void App::init()
{
	SDL_Init(SDL_INIT_EVERYTHING);
	window = SDL_CreateWindow("Try hard!", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, screen_width, screen_height, SDL_WINDOW_OPENGL);

	SDL_GLContext glContext = SDL_GL_CreateContext(window);
	if (glContext == nullptr)
		std::cout << "SDLFEL";

	GLenum error = glewInit();
	if (error != GLEW_OK)
		std::cout << "GlewFel!";

	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	glClearColor(0.7f, 0.7f, 1.0f, 1.0);
	glEnable(GL_DEPTH_TEST);

	initShader();
	initGaussTex();
	
	importer = new OBJimporter();

	importer->loadObj("models/sphere1.obj");
	models = importer->CreateTriangleData();
	models[0]->createBBox("sphere.txt");
	models[0]->addTranslation(vec3(5, 2, -5));
	models[0]->initNormalTexture("normalMap.png");
	delete importer;

	importer = new OBJimporter();

	std::vector<Model*> xxx;
	importer->loadObj("models/skyBox.obj");
	xxx = importer->CreateTriangleData();
	xxx[0]->createBBox("box.txt");
	xxx[0]->addTranslation(vec3(0, 19, 0));
	xxx[0]->Scale(vec3(40,40,40));
	models.push_back(xxx[0]);

	delete importer;
	importer = new OBJimporter();

	std::vector<Model*> temp;
	importer->loadObj("models/box.obj");
	temp = importer->CreateTriangleData();
	temp[0]->createBBox("box.txt");
	
	Model* box2;
	box2 = new Model(*temp[0]);
	Model* box3;
	box3 = new Model(*temp[0]);
	
	temp[0]->addTranslation(vec3(3,0,3));
	box2->addTranslation(vec3(-18, 10, -18));
	box3->addTranslation(vec3(10, 3, -3));
	models.push_back(temp[0]);
	models.push_back(box2);
	models.push_back(box3);
		
	Model* boxTemplate;
	/*for (int i = 0; i < 2000; i++) {
		boxTemplate = new Model(*models[0]);
		boxTemplate->addTranslation(vec3(i % 40 - 20, 5, (int)(i/40)-20));
		models.push_back(boxTemplate);
	}

	for (int i = 0; i < 2000; i++) {
		boxTemplate = new Model(*temp[0]);
		boxTemplate->addTranslation(vec3(i % 40 - 20, 3, (int)(i / 40) - 20));
		models.push_back(boxTemplate);
	}*/

	unsigned char* Pheightmap = nullptr;
	Model* hm = importer->getGround("height_map2.bmp", Pheightmap);
	this->terrain = hm;
	_player.setHM(Pheightmap);
	delete importer;
	createScreenQuad();

	quadTree = new QuadTree(vec3(-25, 0, 25), 50);
	quadTree->buildTree(models);
}