Пример #1
0
/**
 * 
 * @return 
 */
static bool initDrivers()
{
    listOfSDLDrivers.clear();
    int nbDriver=SDL_GetNumRenderDrivers();
   
    for(int i=0;i<nbDriver;i++)
    {
        SDL_RendererInfo info;
        SDL_GetRenderDriverInfo(i,&info);
        sdlDriverInfo sdlInfo;
        sdlInfo.index=i;
        if(info.name)
            sdlInfo.driverName=std::string(info.name);
        else
            sdlInfo.driverName=std::string("Invalid driver");
        sdlInfo.flags=info.flags;
        listOfSDLDrivers.push_back(sdlInfo);
        printf("[SDK]Found driver [%d] %s, with flags=%x\n",i,sdlInfo.driverName.c_str(),info.flags);
        if(info.flags & SDL_RENDERER_SOFTWARE) // by default we peek the software one
            sdlSoftwareDriverIndex=i;
    }
    sdlDriverIndex=sdlSoftwareDriverIndex;
    SDL_LogSetOutputFunction(SDL_Logger,NULL);
    return true;
}
Пример #2
0
int available_render_driver(const std::string& driver)
{
  int num_drivers = SDL_GetNumRenderDrivers();
  int render_driver = -1;

  if( num_drivers < 0 )
  {
    NOM_LOG_ERR( NOM_LOG_CATEGORY_RENDER, SDL_GetError() );
    return num_drivers;
  }

  for( auto i = 0; i < num_drivers; ++i )
  {
    SDL_RendererInfo info;
    if( SDL_GetRenderDriverInfo( i, &info ) == 0 )
    {
      if( ! strcmp( info.name, driver.c_str() ) )
      {
        // Success!
        render_driver = i;
        break;
      }
    }
    else
    {
      NOM_LOG_ERR( NOM_LOG_CATEGORY_RENDER, SDL_GetError() );
      render_driver = -1;
    }
  }

  return render_driver;
}
Пример #3
0
void logGraphicsDriverInfo(std::ostream& out)
{
  const int nVideoDrivers = SDL_GetNumVideoDrivers();
  out << "Found " << nVideoDrivers << " video drivers" << std::endl;

  const std::string currentVideoDriver(SDL_GetCurrentVideoDriver());
  for (int i = 0; i < nVideoDrivers; i++) {
    const std::string videoDriver(SDL_GetVideoDriver(i));
    out << "Video Driver #" << i << ": " << videoDriver;
    if (currentVideoDriver == videoDriver)
      out << " (Current)";
    out << std::endl;
  }

  const int nRenderDrivers = SDL_GetNumRenderDrivers();
  out << "Found " << nRenderDrivers << " render drivers" << std::endl;

  SDL_RendererInfo info;
  for (int i = 0 ; i < nRenderDrivers ; ++i) {
    SDL_GetRenderDriverInfo(i, &info);
    out << "Render Driver #" << i << ": " << info.name;

    bool isSoftware      = info.flags & SDL_RENDERER_SOFTWARE;
    bool isHardware      = info.flags & SDL_RENDERER_ACCELERATED;
    bool isVSyncEnabled  = info.flags & SDL_RENDERER_PRESENTVSYNC;
    bool isTargetTexture = info.flags & SDL_RENDERER_TARGETTEXTURE;

    out << "\t [";
    if (isSoftware) out << "SW";
    if (isHardware) out << "HW";
    if (isVSyncEnabled) out << ", VSync";
    if (isTargetTexture) out << ", TT";
    out << "]" << std::endl;
  }
}
Пример #4
0
bool Graphics::videoInfo()
{
    logger->log("SDL video info");
#ifdef USE_SDL2
    logger->log("Using video driver: %s", SDL_GetCurrentVideoDriver());

    if (mRenderer)
    {
        SDL_RendererInfo info;
        SDL_GetRendererInfo(mRenderer, &info);
        dumpRendererInfo("Current SDL renderer name: %s", info);

        const int num = SDL_GetNumRenderDrivers();
        logger->log("Known renderers");
        for (int f = 0; f < num; f ++)
        {
            if (!SDL_GetRenderDriverInfo(f, &info))
                dumpRendererInfo("renderer name: %s", info);
        }
    }
#else
    char videoDriverName[65];
    if (SDL_VideoDriverName(videoDriverName, 64))
        logger->log("Using video driver: %s", videoDriverName);
    else
        logger->log1("Using video driver: unknown");
    mDoubleBuffer = ((mWindow->flags & SDL_DOUBLEBUF) == SDL_DOUBLEBUF);
    logger->log("Double buffer mode: %s", mDoubleBuffer ? "yes" : "no");

    ImageHelper::dumpSurfaceFormat(mWindow);

    const SDL_VideoInfo *const vi = SDL_GetVideoInfo();
    if (!vi)
        return false;

    logger->log("Possible to create hardware surfaces: %s",
            ((vi->hw_available) ? "yes" : "no"));
    logger->log("Window manager available: %s",
            ((vi->wm_available) ? "yes" : "no"));
    logger->log("Accelerated hardware to hardware blits: %s",
            ((vi->blit_hw) ? "yes" : "no"));
    logger->log("Accelerated hardware to hardware colorkey blits: %s",
            ((vi->blit_hw_CC) ? "yes" : "no"));
    logger->log("Accelerated hardware to hardware alpha blits: %s",
            ((vi->blit_hw_A) ? "yes" : "no"));
    logger->log("Accelerated software to hardware blits: %s",
            ((vi->blit_sw) ? "yes" : "no"));
    logger->log("Accelerated software to hardware colorkey blits: %s",
            ((vi->blit_sw_CC) ? "yes" : "no"));
    logger->log("Accelerated software to hardware alpha blits: %s",
            ((vi->blit_sw_A) ? "yes" : "no"));
    logger->log("Accelerated color fills: %s",
            ((vi->blit_fill) ? "yes" : "no"));
#endif

    return true;
}
Пример #5
0
/*
 * meh_window_has_accelerated returns if any accelerated renderer
 * support hardware acceleration.
 */
gboolean meh_window_has_accelerated(void) {
	for (int i = 0; i < SDL_GetNumRenderDrivers(); i++) {
		SDL_RendererInfo info;
		SDL_GetRenderDriverInfo(i, &info);
		if (info.flags & SDL_RENDERER_ACCELERATED) {
			return TRUE;
		}
	}
	return FALSE;
}
Пример #6
0
void renderer::init_sdl2() {
	if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_EVENTS) != 0) {
        SDL2_PrintErrorAndDie();
	}

	window_ = SDL_CreateWindow("Grounded",               //    window title
			SDL_WINDOWPOS_UNDEFINED,           //    initial x position
			SDL_WINDOWPOS_UNDEFINED,           //    initial y position
			WINDOW_WIDTH,                               //    width, in pixels
			WINDOW_HEIGHT,                               //    height, in pixels
			SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL //    flags - see below
			);
	if (window_ == NULL) {
        SDL2_PrintErrorAndDie();
	}

    int numdrivers = SDL_GetNumRenderDrivers ();
    std::cout << "Render driver count: " << numdrivers << std::endl;
    for (int i=0; i<numdrivers; i++) {
        SDL_RendererInfo drinfo;
        SDL_GetRenderDriverInfo (i, &drinfo);
        std::cout << "Driver name ("<<i<<"): " << drinfo.name << std::endl;
        if (drinfo.flags & SDL_RENDERER_SOFTWARE) std::cout << " the renderer is a software fallback" << std::endl;
        if (drinfo.flags & SDL_RENDERER_ACCELERATED) std::cout << " the renderer uses hardware acceleration" << std::endl;
        if (drinfo.flags & SDL_RENDERER_PRESENTVSYNC) std::cout << " present is synchronized with the refresh rate" << std::endl;
        if (drinfo.flags & SDL_RENDERER_TARGETTEXTURE) std::cout << " the renderer supports rendering to texture" << std::endl;
    }

    renderer_ = SDL_CreateRenderer(window_, -1, 0);
    if (!renderer_) {
        SDL2_PrintErrorAndDie();
    }
    
    SDL_Surface* tmp;
    tmp = SDL_LoadBMP("../common/img/tiles.bmp");
    if (!tmp)
        SDL2_PrintErrorAndDie();
    
    if (0 != SDL_SetColorKey(tmp, 
        SDL_TRUE, 
        SDL_MapRGB(tmp->format, 255, 0, 255))) {
        SDL2_PrintErrorAndDie();
    }
        
    
    tiles_ = SDL_CreateTextureFromSurface(renderer_, tmp);
    if (!tiles_)
        SDL2_PrintErrorAndDie();
    
    SDL_FreeSurface(tmp);
}
Пример #7
0
CAMLprim value
caml_SDL_GetRenderDrivers(value unit)
{
    CAMLparam0();
    CAMLlocal2(ret, dinf);
    unsigned int i, n;
    SDL_RendererInfo info;
    n = SDL_GetNumRenderDrivers();
    ret = caml_alloc(n, 0);
    for (i = 0; i < n; i++) {
        int r = SDL_GetRenderDriverInfo(i, &info);
        if (r) caml_failwith("Sdlrender.get_render_drivers");
        Store_field(ret, i, Val_SDL_RendererInfo(&info));
    }
    CAMLreturn(ret);
}
Пример #8
0
static void osd_sdl_info(void)
{
#if SDL_VERSION_ATLEAST(1,3,0)
	int i, cur, num = SDL_GetNumVideoDrivers();

	mame_printf_verbose("Available videodrivers: ");
	for (i=0;i<num;i++)
	{
		const char *name = SDL_GetVideoDriver(i);
		mame_printf_verbose("%s ", name);
	}
	mame_printf_verbose("\n");
	mame_printf_verbose("Current Videodriver: %s\n", SDL_GetCurrentVideoDriver());
	num = SDL_GetNumVideoDisplays();
	cur = SDL_GetCurrentVideoDisplay();
	for (i=0;i<num;i++)
	{
		SDL_DisplayMode mode;
		int j;

		SDL_SelectVideoDisplay(i);
		mame_printf_verbose("\tDisplay #%d\n", i);
		if (SDL_GetDesktopDisplayMode(&mode));
			mame_printf_verbose("\t\tDesktop Mode:         %dx%d-%d@%d\n", mode.w, mode.h, SDL_BITSPERPIXEL(mode.format), mode.refresh_rate);
		if (SDL_GetCurrentDisplayMode(&mode));
			mame_printf_verbose("\t\tCurrent Display Mode: %dx%d-%d@%d\n", mode.w, mode.h, SDL_BITSPERPIXEL(mode.format), mode.refresh_rate);
		mame_printf_verbose("\t\tRenderdrivers:\n");
		for (j=0; j<SDL_GetNumRenderDrivers(); j++)
		{
			SDL_RendererInfo info;
			SDL_GetRenderDriverInfo(j, &info);
			mame_printf_verbose("\t\t\t%10s (%dx%d)\n", info.name, info.max_texture_width, info.max_texture_height);
		}
	}
	SDL_SelectVideoDisplay(cur);

	mame_printf_verbose("Available audio drivers: \n");
	num = SDL_GetNumAudioDrivers();
	for (i=0;i<num;i++)
	{
		mame_printf_verbose("\t%-20s\n", SDL_GetAudioDriver(i));
	}
#endif
}
Пример #9
0
void SDLFrontend::initRenderer ()
{
	info(LOG_CLIENT, "init sdl renderer");
	const int renderers = SDL_GetNumRenderDrivers();
	SDL_RendererInfo ri;
	for (int i = 0; i < renderers; i++) {
		SDL_GetRenderDriverInfo(i, &ri);
		info(LOG_CLIENT, String::format("available renderer %s", ri.name));
	}

#if defined(SDL_VIDEO_OPENGL_ES2)
	const std::string rendererStr = "opengles2";
#elif defined(SDL_VIDEO_OPENGL_ES)
	const std::string rendererStr = "opengles";
#elif defined(SDL_VIDEO_OPENGL)
	const std::string rendererStr = "opengl";
#else
#error "No supported renderer found"
#endif

	const ConfigVarPtr& renderer = Config.getConfigVar("renderer", rendererStr, true);
	const std::string& rendererValue = renderer->getValue();
	info(LOG_CLIENT, "try renderer: " + rendererValue);
	SDL_SetHint(SDL_HINT_RENDER_DRIVER, rendererValue.c_str());
	_renderer = SDL_CreateRenderer(_window, -1, 0);
	SDL_GetRendererInfo(_renderer, &ri);

	SDL_RenderSetLogicalSize(_renderer, getWidth(), getHeight());

	_softwareRenderer = (ri.flags & SDL_RENDERER_SOFTWARE);

	info(LOG_CLIENT, String::format("actual renderer %s", ri.name));
	if (strcmp(ri.name, "opengles2")) {
		// disable shaders as they are currently built for glesv2
		ConfigManager::get().getConfigVar("shader")->setValue("false");
		info(LOG_CLIENT, "disable shaders for the current renderer");
	}
	info(LOG_CLIENT, String::format("max texture resolution: %i:%i", ri.max_texture_width, ri.max_texture_height));
	SDL_SetRenderDrawBlendMode(_renderer, SDL_BLENDMODE_BLEND);
	SDL_SetRenderDrawColor(_renderer, 0, 0, 0, 255);
}
Пример #10
0
void BRPrintRendererInfo () {
  SDL_RendererInfo renInfo;
  int drivers, n;

  drivers = SDL_GetNumRenderDrivers ();
  if (!drivers)
    printf ("W: No SDL render drivers available!\n");
  else {
    for (n = 0; n < drivers; n++) {
      if (SDL_GetRenderDriverInfo (n, &renInfo) == 0) {
        printf ("I: Available SDL render driver #%i: '%s', max. texture: %ix%i, flags:%s%s%s%s.\n",
                n, renInfo.name, renInfo.max_texture_width, renInfo.max_texture_height,
                renInfo.flags & SDL_RENDERER_SOFTWARE ? " SOFTWARE" : "",
                renInfo.flags & SDL_RENDERER_ACCELERATED ? " ACCELERATED" : "",
                renInfo.flags & SDL_RENDERER_PRESENTVSYNC ? " PRESENTVSYNC" : "",
                renInfo.flags & SDL_RENDERER_TARGETTEXTURE ? " TARGETTEXTURE" : "");
      }
      else
        printf ("W: Unable to get info on render driver #%i.\n", n);
    }
  }
}
Пример #11
0
int initWindow(SDL_Window **window, SDL_Renderer **renderer, int argc, char *argv[]) {
    if(SDL_Init(SDL_INIT_EVERYTHING) == -1) {
        fprintf(stderr, "SDL Init failed: %s\n", SDL_GetError());
        return 1;
    }

    int flags=IMG_INIT_JPG|IMG_INIT_PNG;
    if(IMG_Init(flags) != flags) {
        fprintf(stderr, "IMG_Init failed: %s\n", IMG_GetError());
        return 1;
    }

    if(Mix_OpenAudio( MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, 2, 1024 ) == -1) {
        fprintf(stderr, "Audio Init failed: %s\n", Mix_GetError());
        return 1;
    }
    int mixFlags = MIX_INIT_OGG;
    if(Mix_Init(mixFlags) != mixFlags) {
        fprintf(stderr, "Audio Init2 failed: %s\n", Mix_GetError());
        return 1;
    }

    if(TTF_Init()==-1) {
        printf("TTF_Init: %s\n", TTF_GetError());
        return 1;
    }

    WIDTH = 800;
    HEIGHT = 600;

    int useSoftwareAccel = 0;
    int useFullscreen = 0;
    int optionIndex = 0;
    int c;
    struct option longOptions[] = {
        {"software", no_argument, &useSoftwareAccel, 1},
        {"hardware", no_argument, &useSoftwareAccel, 0},
        {"fullscreen", no_argument, &useFullscreen, 1},
        {"level", required_argument, 0, 'l'}
    };

    while((c = getopt_long(argc, argv, "l", longOptions, &optionIndex)) != -1) {
        switch(c) {
        case 'l':
            FIRSTLEVEL = optarg;
            break;
        }
    }

    if(useFullscreen) {
        SDL_DisplayMode displayInfo;
        SDL_GetCurrentDisplayMode(0, &displayInfo);
        WINDOW_WIDTH = displayInfo.w;
        WINDOW_HEIGHT = displayInfo.h;
    } else {
        WINDOW_WIDTH = WIDTH;
        WINDOW_HEIGHT = HEIGHT;
    }
    WIDTH_OFFSET = (WINDOW_WIDTH - WIDTH)/2;
    HEIGHT_OFFSET = (WINDOW_HEIGHT - HEIGHT)/2;

    for(int i=0; i<SDL_GetNumRenderDrivers(); i++) {
        SDL_RendererInfo info;
        SDL_GetRenderDriverInfo(i, &info);
        printf("Video Driver %d (%s): flags(%d) %s,%s,%s,%s - %d\n", i, info.name, info.flags,
               (info.flags & SDL_RENDERER_SOFTWARE) ? "Software" : "",
               (info.flags & SDL_RENDERER_ACCELERATED) ? "Hardware Accelerated" : "",
               (info.flags & SDL_RENDERER_PRESENTVSYNC) ? "VSync" : "",
               (info.flags & SDL_RENDERER_TARGETTEXTURE) ? "TextureRender" : "",
               info.num_texture_formats
              );
        /*for(int texN=0; texN<info.num_texture_formats; texN++) {
        	printf("%d ", info.texture_formats[texN]);
        }
        printf("\n");*/
    }

    *window = SDL_CreateWindow("Terracer", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WINDOW_WIDTH, WINDOW_HEIGHT, (useFullscreen ? SDL_WINDOW_BORDERLESS : 0));
    //  -1 for first rendering driver that fits the flags
    if(useSoftwareAccel || (*renderer = SDL_CreateRenderer(*window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC)) == NULL) {
        fprintf(stderr, "Loading hardware acceleration failed. Using software fallback...\n");
        if((*renderer = SDL_CreateRenderer(*window, -1, SDL_RENDERER_SOFTWARE)) == NULL) {
            fprintf(stderr, "Loading software fallback renderer failed! Error: %s\n", SDL_GetError());
            return 1;
        }
    }

    SDL_RenderSetLogicalSize(*renderer, WIDTH, HEIGHT);

    return 0;
}
Пример #12
0
static void *sdl2_gfx_init(const video_info_t *video, const input_driver_t **input, void **input_data)
{
   int i;
   unsigned flags;
   settings_t *settings = config_get_ptr();

#ifdef HAVE_X11
   XInitThreads();
#endif

   if (SDL_WasInit(0) == 0)
   {
      if (SDL_Init(SDL_INIT_VIDEO) < 0)
         return NULL;
   }
   else if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0)
      return NULL;

   sdl2_video_t *vid = (sdl2_video_t*)calloc(1, sizeof(*vid));
   if (!vid)
      return NULL;

   RARCH_LOG("[SDL]: Available renderers (change with $SDL_RENDER_DRIVER):\n");
   for (i = 0; i < SDL_GetNumRenderDrivers(); ++i)
   {
      SDL_RendererInfo renderer;
      if (SDL_GetRenderDriverInfo(i, &renderer) == 0)
         RARCH_LOG("\t%s\n", renderer.name);
   }

   RARCH_LOG("[SDL]: Available displays:\n");
   for(i = 0; i < SDL_GetNumVideoDisplays(); ++i)
   {
      SDL_DisplayMode mode;

      if (SDL_GetCurrentDisplayMode(i, &mode) < 0)
         RARCH_LOG("\tDisplay #%i mode: unknown.\n", i);
      else
         RARCH_LOG("\tDisplay #%i mode: %ix%i@%ihz.\n", i, mode.w, mode.h,
                   mode.refresh_rate);
   }

//   void *sdl_input = NULL;

   if (!video->fullscreen)
      RARCH_LOG("[SDL]: Creating window @ %ux%u\n", video->width, video->height);


   if (video->fullscreen)
      flags = settings->video.windowed_fullscreen ? SDL_WINDOW_FULLSCREEN_DESKTOP : SDL_WINDOW_FULLSCREEN;
   else
      flags = SDL_WINDOW_RESIZABLE;

   vid->window = SDL_CreateWindow("", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                                  video->width, video->height, flags);

   if (!vid->window)
   {
      RARCH_ERR("[SDL]: Failed to init SDL window: %s\n", SDL_GetError());
      goto error;
   }

   vid->video = *video;
   vid->video.smooth  = settings->video.smooth;
   vid->should_resize = true;

   sdl_tex_zero(&vid->frame);
   sdl_tex_zero(&vid->menu);

   if (video->fullscreen)
      SDL_ShowCursor(SDL_DISABLE);

   sdl2_init_renderer(vid);
   sdl2_init_font(vid, settings->video.font_path, settings->video.font_size);

   sdl2_gfx_set_handles(vid);

   *input = NULL;
   *input_data = NULL;

   return vid;

error:
   sdl2_gfx_free(vid);
   return NULL;
}
Пример #13
0
/*GLOBAL FUNCTIONS*/
void NLF_screen_init()
{
	int flags;
	int aux;
	char *str;
	int sdlRet;
	NLF_bool saydone;

	/*INITIALIZING SDL_IMAGE*/
	flags = IMG_INIT_JPG | IMG_INIT_PNG | IMG_INIT_TIF;
	if((IMG_Init(flags) & flags) != flags)
	{
		flags = IMG_INIT_TIF;
		if((IMG_Init(flags) & flags) != flags)
		{
			printf("\tCan't initialize SDL_image\nSDL_IMAGE ERROR: %s\n", IMG_GetError());
			printf("\ttraing for TIF format... ");
			flags = IMG_INIT_TIF;
			if((IMG_Init(flags) & flags) != flags)
			{
				printf("fail\n\tSDL_IMAGE ERROR: %s\n", IMG_GetError());
				tifFlag = NLF_True;
			}else{
				printf("done\n");
				tifFlag = NLF_False;
			}

			printf("\ttraing for PNG format... \n");
			flags = IMG_INIT_PNG;
			if((IMG_Init(flags) & flags) != flags)
			{
				printf("fail\n\tSDL_IMAGE ERROR: %s\n", IMG_GetError());
				pngFlag = NLF_True;
			}else{
				printf("done\n");
				pngFlag = NLF_False;
			}

			printf("\ttraing for JPG format... \n");
			flags = IMG_INIT_JPG;
			if((IMG_Init(flags) & flags) != flags)
			{
				printf("fail\n\tSDL_IMAGE ERROR: %s\n", IMG_GetError());
				jpgFlag = NLF_True;
			}else{
				printf("done\n");
				jpgFlag = NLF_False;
			}

			if(jpgFlag == NLF_False && pngFlag == NLF_False && tifFlag == NLF_False)
			{
				printf("\tScreen module initialization has failed.\n");
				str = SDL_GetError();
				printf("\tSDL_ERROR: %s\n", str);
				printf("\tAborting\n");
				NLF_error_make_file_crash_report(NLF_ErrorSDLImageInitializer, "Screen module initialization has failed", "SDL Error: ", str, NULL);
				exit(NLF_ErrorSDLImageInitializer);
			}
		}
	}else{
		jpgFlag = NLF_True;
		pngFlag = NLF_True;
		tifFlag = NLF_True;
	}
	/************************/

	/*SETTING GLOBALS VARIABLES*/
	///GETTING DISPLAY INFORMATIONS
	aux = SDL_GetNumVideoDisplays();
	if(aux < 0)
	{
		//error case
		printf("Fail trying to get video display number.\n");
		str = SDL_GetError();
		printf("\tSDL_ERROR: %s\n", str);
		printf("\tAborting\n");
		NLF_error_make_file_crash_report(NLF_ErrorSDLProblem, "Fail trying to get video display number", "SDL Error: ", str, NULL);
		exit(aux);
	}else{
		displayInUse = 0;
		printf("\n\t%d Displays avaliable, piking the number %d as pattern\n", aux, displayInUse + 1);
	}

	displayInfoUnknown = NLF_False;
	for(aux = 0; aux < 3; aux++)
	{
		saydone = NLF_False;
		if(aux == 0)
			sdlRet = SDL_GetCurrentDisplayMode(displayInUse, &videoMode);
		else if(aux == 1)
			sdlRet = SDL_GetDisplayMode(displayInUse, displayInUse, &videoMode);
		else if(aux == 2)
			sdlRet = SDL_GetWindowDisplayMode(displayInUse, &videoMode);

		if(sdlRet != 0)
		{
			if(aux == 2)
			{
				//totally unsuccessful case
				printf("\tSorry, impossible to get display #%d mode:\n\tSDL_ERROR: %s\n", displayInUse + 1, SDL_GetError());
				printf("\tstandard 800x600 will be set\n");
				displayInfoUnknown = NLF_True;
			}else{
				printf("\tSorry, could not get display #%d mode:\n\tSDL_ERROR: %s\n", displayInUse + 1, SDL_GetError());
				printf("\ttrying another way...\n");
				saydone = NLF_True;
			}
		}else{
			printf("\tcurrent display(%d) mode detected %dx%dpx @ %dhz. \n", displayInUse + 1, videoMode.w, videoMode.h, videoMode.refresh_rate);
			if(videoMode.w == 0 || videoMode.h == 0 || videoMode.refresh_rate == 0)
			{
				printf("\tSorry, could not get all display #%d mode information\n", displayInUse + 1);
				printf("\ttrying another way...\n");
				saydone = NLF_True;
			}else{
				printf("\tdone\n");
				aux = 3;
			}
		}
	}
	///****************************

	/*SETTING SOME GLOBAL VARIABLES*/
	camera.x = 0;
	camera.y = 0;
	if(displayInfoUnknown == NLF_False)
	{
		camera.w = 800;
		camera.h = 600;
	}else{
		camera.w = videoMode.w;
		camera.h = videoMode.h;
	}

	screens = NULL;
	currentFPS = 0;
	//there's just no need to the FPS be greater then the display refresh rate
	(videoMode.refresh_rate >= 60 || videoMode.refresh_rate == 0) ? (idealFPS = 60): (idealFPS = videoMode.refresh_rate);
	/*******************************/

	///CREATING WINDOW SET
	window = SDL_CreateWindow("NorthLionFramework Game", 0, 0, camera.w, camera.h, SDL_WINDOW_BORDERLESS | SDL_WINDOW_MAXIMIZED);
	if(window == NULL)
	{
		printf("\tCould not craete the window\n");
		str = SDL_GetError();
		printf("\tSDL_ERROR: %s\n", str);
		printf("\tAborting\n");
		NLF_error_make_file_crash_report(NLF_ErrorSDLProblem, "Could not craete the window", "SDL Error: ", str, NULL);
		exit(NLF_ErrorSDLProblem); //I don't know what to do else but quiting... you know, we need a window .-.
	}

	//this loop will try to initialize the render the best way possible
	for(aux = 0; aux < 4 && window_rederer == NULL; aux++)
	{
		switch(aux)
		{
			case 0:
				flags = SDL_RENDERER_SOFTWARE | SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_TARGETTEXTURE;
				break;
			case 1:
				flags = SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_TARGETTEXTURE;
				break;
			case 2:
				flags = SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC;
				break;
			case 3:
				flags = SDL_RENDERER_ACCELERATED;
				break;
		}
		if(aux > 0)
			printf("\ttrying flags(%d)... ", flags);

		window_rederer = SDL_CreateRenderer(window, -1, flags);
		if(window_rederer == NULL)
		{
			if(aux > 0)
				printf("fail\n");
			if(aux != 3)
			{
				printf("\tCould not create render with all flags(%d)\n", flags);
				printf("\tSDL_ERROR: %s\n", SDL_GetError());
			}else{
				printf("\tIt was impossible to create the render.\n");
				str = SDL_GetError();
				printf("\tSDL_ERROR: %s\n", str);
				printf("\tAborting\n");
				NLF_error_make_file_crash_report(NLF_ErrorSDLProblem, "It was impossible to create the render", "SDL Error: ", str, NULL);
				exit(NLF_ErrorSDLProblem); //I don't know what to do else but quiting... you know, we also need a renderer .-.
			}
		}else{
			if(aux > 0)
				printf("done\n");
		}
	}
	if(aux > 0)
	///*******************

	///GETTING VIDEO CARD INFORMATION
	aux = 0;
	if(SDL_GetRendererInfo(window_rederer, &rendererInfo) < 0)
	{
		printf("\tCould not get information about the renderer.\n");
		printf("\tSDL_ERROR: %s\n", SDL_GetError());
		rendererInfoUnknown = NLF_True;
	}else{
		aux = 1;
		rendererInfoUnknown = NLF_False;
	}

	if(SDL_GetRenderDriverInfo(displayInUse, &rendererDriverInfo) < 0)
	{
		printf("\tCould not get information about the renderer driver.\n");
		printf("\tSDL_ERROR: %s\n", SDL_GetError());
		rendererDriverInfoUnkown = NLF_True;
	}else{
		aux = 1;
		rendererDriverInfoUnkown = NLF_False;
	}
	///******************************
	/***************************/
}
Пример #14
0
void window_init(void) {
	// SDL base stuff
	if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
		error(1, SDL_GetError());
	}
	
	if ((windowMain = SDL_CreateWindow("Engine", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, windowWidth, windowHeight, FLAGS)) == NULL) {
		error(1, SDL_GetError());
	}
	SDL_SetWindowMinimumSize(windowMain, 100, 100);
	
	// Renderer stuff
	windowMainGLContext = SDL_GL_CreateContext(windowMain); // yes, it's openGL stuff
	
	int oglId = -1;
	int rdnum = SDL_GetNumRenderDrivers();
	for (int i=0;i<rdnum;i++) {
		SDL_RendererInfo info;
		if (SDL_GetRenderDriverInfo(i, &info)) {
			continue;
		}
		if (!strcmp(info.name, "opengl")) {
			oglId = i;
		}
	}
	if (oglId == -1) {
		error(-1, "Cannot find the OpenGL renderer driver.");
	}
	
	if ((windowMainRenderer = SDL_CreateRenderer(windowMain, oglId, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC)) < 0) {
		error(1, SDL_GetError());
	}
	
	// OpenGL stuff
	
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, true);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
	if (SDL_GL_SetSwapInterval(17) < 0) {
		log_write(loggingLevel_warn, "Unable to setup VSync ! %s", SDL_GetError());
	}
	
	glShadeModel(GL_SMOOTH);
	
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
	
	//glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
	glClearColor(1.0f, 1.0f, 1.0f, 0.0f);
	glClearDepth(1.0f);
	
	glEnable(GL_TEXTURE_2D);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(fov, (float)windowWidth/(float)windowHeight, 1.0f, 100.0f);
	
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glViewport(0, 0, windowWidth, windowHeight);
	
	if (glGetError() != GL_NO_ERROR) {
		error(glGetError(), "OpenGL error.");
	}
	
	log_write(loggingLevel_debug, "GL version: %s", glGetString(GL_VERSION));
	log_write(loggingLevel_debug, "GL vendor: %s", glGetString(GL_VENDOR));
	log_write(loggingLevel_debug, "GL renderer: %s", glGetString(GL_RENDERER));
	log_write(loggingLevel_debug, "Video driver: %s", SDL_GetCurrentVideoDriver());
	
	// nothing else to do
}
Пример #15
0
int graphics_SetMode(int width, int height, int fullscreen,
int resizable, const char* title, const char* renderer, char** error) {
    graphics_calculateUnitToPixels(width, height);

#if defined(ANDROID)
    if (!fullscreen) {
        // do not use windowed on Android
        *error = strdup("Windowed mode is not supported on Android");
        return 0;
    }
#endif

    char errormsg[512];

    // initialize SDL video if not done yet
    if (!graphics_InitVideoSubsystem(error)) {
        return 0;
    }

    // think about the renderer we want
#ifndef WINDOWS
#ifdef ANDROID
    char preferredrenderer[20] = "opengles";
#else
    char preferredrenderer[20] = "opengl";
#endif
#else
    char preferredrenderer[20] = "direct3d";
#endif
    int softwarerendering = 0;
    if (renderer) {
        if (strcasecmp(renderer, "software") == 0) {
#ifdef ANDROID
            // we don't want software rendering on Android
#else
            softwarerendering = 1;
            strcpy(preferredrenderer, "software");
#endif
        } else {
            if (strcasecmp(renderer, "opengl") == 0) {
#ifdef ANDROID
                // opengles is the opengl we want for android :-)
                strcpy(preferredrenderer, "opengles");
#else
                // regular opengl on desktop platforms
                strcpy(preferredrenderer, "opengl");
#endif
            }
#ifdef WINDOWS
            // only windows knows direct3d obviously
            if (strcasecmp(renderer,"direct3d") == 0) {
                strcpy(preferredrenderer, "direct3d");
            }
#endif
        }
    }

    // get renderer index
    int rendererindex = -1;
    if (strlen(preferredrenderer) > 0 && !softwarerendering) {
        int count = SDL_GetNumRenderDrivers();
        if (count > 0) {
            int r = 0;
            while (r < count) {
                SDL_RendererInfo info;
                SDL_GetRenderDriverInfo(r, &info);
                if (strcasecmp(info.name, preferredrenderer) == 0) {
                    rendererindex = r;
                    break;
                }
                r++;
            }
        }
    }

    //  see if anything changes at all
    unsigned int oldw = 0;
    unsigned int oldh = 0;
    graphics_GetWindowDimensions(&oldw,&oldh);
    if (mainwindow && mainrenderer &&
    width == (int)oldw && height == (int)oldh) {
        SDL_RendererInfo info;
        SDL_GetRendererInfo(mainrenderer, &info);
        if (strcasecmp(preferredrenderer, info.name) == 0) {
            //  same renderer and resolution
            if (strcmp(SDL_GetWindowTitle(mainwindow), title) != 0) {
                SDL_SetWindowTitle(mainwindow, title);
            }
            //  toggle fullscreen if desired
            if (graphics_IsFullscreen() != fullscreen) {
                graphics_ToggleFullscreen();
            }
            return 1;
        }
    }

    //  Check if we support the video mode for fullscreen -
    //   This is done to avoid SDL allowing impossible modes and
    //   giving us a fake resized/padded/whatever output we don't want.
    if (fullscreen) {
        //  check all video modes in the list SDL returns for us
        int count = graphics_GetNumberOfVideoModes();
        int i = 0;
        int supportedmode = 0;
        while (i < count) {
            int w,h;
            graphics_GetVideoMode(i, &w, &h);
            if (w == width && h == height) {
                supportedmode = 1;
                break;
            }
            i++;
        }
        if (!supportedmode) {
            //  check for desktop video mode aswell
            int w,h;
            graphics_GetDesktopVideoMode(&w,&h);
            if (w == 0 || h == 0 || width != w || height != h) {
                *error = strdup("Video mode is not supported");
                return 0;
            }
        }
    }

    // notify texture manager of device shutdown
    texturemanager_deviceLost();

    // destroy old window/renderer if we got one
    graphics_Close(1);

    // create window
    if (fullscreen) {
        mainwindow = SDL_CreateWindow(title, 0, 0, width, height,
        SDL_WINDOW_FULLSCREEN);
        mainwindowfullscreen = 1;
    } else {
        mainwindow = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED,
        SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_MINIMIZED);
        mainwindowfullscreen = 0;
    }

    if (!mainwindow) {
        snprintf(errormsg, sizeof(errormsg),
        "Failed to open SDL window: %s", SDL_GetError());
        errormsg[sizeof(errormsg)-1] = 0;
        *error = strdup(errormsg);
        return 0;
    }

    // see if we actually ended up with the resolution we wanted:
    int actualwidth, actualheight;
    SDL_GetWindowSize(mainwindow, &actualwidth, &actualheight);
    if (actualwidth != width || actualheight != height) {
        if (fullscreen) {  // we failed to get the requested resolution:
            SDL_DestroyWindow(mainwindow);
            snprintf(errormsg, sizeof(errormsg), "Failed to open "
            "SDL window: ended up with other resolution than requested");
            *error = strdup(errormsg);
            return 0;
        }
    }

    // Create renderer
    if (!softwarerendering) {
        mainrenderer = SDL_CreateRenderer(mainwindow, rendererindex,
        SDL_RENDERER_ACCELERATED|SDL_RENDERER_PRESENTVSYNC);
        if (!mainrenderer) {
            softwarerendering = 1;
            strcpy(preferredrenderer, "software");
        }
    }
    if (softwarerendering) {
        mainrenderer = SDL_CreateRenderer(mainwindow, -1,
        SDL_RENDERER_SOFTWARE);
    }
    if (!mainrenderer) {
        // we failed to create the renderer
        if (mainwindow) {
            // destroy window aswell in case it is open
            SDL_DestroyWindow(mainwindow);
            mainwindow = NULL;
        }
        if (softwarerendering) {
            snprintf(errormsg, sizeof(errormsg),
            "Failed to create SDL renderer (backend software): %s",
            SDL_GetError());
        } else {
            SDL_RendererInfo info;
            SDL_GetRenderDriverInfo(rendererindex, &info);
            snprintf(errormsg, sizeof(errormsg),
            "Failed to create SDL renderer (backend %s): %s",
            info.name, SDL_GetError());
        }
        errormsg[sizeof(errormsg)-1] = 0;
        *error = strdup(errormsg);
        return 0;
    } else {
        SDL_RendererInfo info;
        SDL_GetRendererInfo(mainrenderer, &info);
    }

    // notify texture manager that device is back
    texturemanager_deviceRestored();

    // Transfer textures back to SDL
    /*if (!graphicstexturelist_TransferTexturesToHW()) {
        SDL_RendererInfo info;
        SDL_GetRendererInfo(mainrenderer, &info);
        snprintf(errormsg, sizeof(errormsg),
        "Failed to create SDL renderer (backend %s): "
        "Cannot recreate textures", info.name);
        *error = strdup(errormsg);
        SDL_DestroyRenderer(mainrenderer);
        SDL_DestroyWindow(mainwindow);
        return 0;
    }*/

    // Re-focus window if previously focussed
    if (!inbackground) {
        SDL_RaiseWindow(mainwindow);
    }

    graphicsactive = 1;
    return 1;
}
Пример #16
0
bool initGL() {
	#ifdef DEBUG_DRIVERS /************ DEBUG DRIVERS ********************************/
	// Identify video drivers (this is for debug)
    OUTSTREAM << "\nSDL found the following video drivers:\n";
    int numdrivers = SDL_GetNumVideoDrivers();
    const char* drivername;
    for (int i = 0; i < numdrivers; ++i) {
        drivername = SDL_GetVideoDriver(i);
        if (SDL_VideoInit(drivername) == 0) {
            SDL_VideoQuit();
            OUTSTREAM << "\t\t   Driver " << drivername << " works.\n";
        }
        else {
            OUTSTREAM << "\t<!>\tDriver " << drivername << " DOES NOT WORK!\n";
        }
    }
    // Identify render drivers (this is for debug)
    OUTSTREAM << "SDL found the following render drivers: ";
    numdrivers = SDL_GetNumRenderDrivers();
    for (int i = 0; i < numdrivers; ++i) {
        SDL_RendererInfo info;
        SDL_GetRenderDriverInfo(i, &info);
        OUTSTREAM << info.name << ((i < numdrivers - 1)? ", " : "\n");
    }
    #endif /************************** DEBUG DRIVERS ********************************/

    // Initialize SDL overall.
    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        OUTSTREAM << "<!>    SDL did not initialize! SDL Error: " << SDL_GetError() << std::endl;
        return false;
    }

    // SDL_GL_CONTEXT_CORE gives us only the newer version, deprecated functions are disabled
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);

    // Specify OpenGL version
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, GLVERSION_MAJOR);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, GLVERSION_MINOR);

    // Turn on double buffering with a 24bit Z buffer.
    // You may need to change this to 16 or 32 for your system
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

    // Create the SDL window
    pWindow = SDL_CreateWindow("OpenGL Window",	// name of window
                    SDL_WINDOWPOS_CENTERED,		// x position of window
                    SDL_WINDOWPOS_CENTERED,		// y position of window
                    RESOLUTION_X, RESOLUTION_Y,	// x and y width of window
                    SCREENOPTIONS);    			// options (fullscreen, etc)

    // If the window couldn't be created for whatever reason
    if (pWindow == NULL) {
        OUTSTREAM << "<!>    SDL window was not created! SDL Error: " << SDL_GetError() << std::endl;
        return false;
	}
	else {
		OUTSTREAM << "SDL window created.\n";
	}

    //Create context
    context = SDL_GL_CreateContext(pWindow);    //context is the place where openGL can draw
    if(context == NULL) {
        OUTSTREAM << "<!>    OpenGL context was not created! SDL Error: " << SDL_GetError() << std::endl;
        return false;
	}
	else {
		OUTSTREAM << "GL context created.\n";
	}

	checkGlError(__LINE__);

    //Initialize GLEW (openGL Extensions Wrangler)
    glewExperimental = GL_TRUE;     // Sometimes things wont work without this line
    GLenum glewError = glewInit();  // GL enumerator error is thrown here when using openGL versions 3.2+ It's fine.
                                    // see https://www.opengl.org/wiki/OpenGL_Loading_Library
    if(glewError != GLEW_OK) {
        OUTSTREAM << "<!>    Could not initialize GLEW! " << glewGetErrorString(glewError) << std::endl;
        return false;
	}
	else {
		OUTSTREAM << "GLEW initialized.\n";
	}

	checkGlError(__LINE__);


    #ifdef USE_VSYNC /************ USE VSYNC ********************************/
	if (SDL_GL_SetSwapInterval(1) < 0) {
		OUTSTREAM << "<!>    Warning: Unable to set VSync! SDL Error: " << SDL_GetError() << std::endl;
		// Do not return. This is not an essential functionality.
	}
	else {
		OUTSTREAM << "VSync enabled.\n";
	}
	#endif /********************** USE VSYNC ********************************/
    
    // set openGL clear color
    glClearColor(CLEARCOLOR);

    #ifdef USE_DEPTHBUFFER
    // enable the occlusion of objects hidden behind other objects (using the depth buffer)
    glEnable(GL_DEPTH_TEST);				
    // set the test for that occlusion to: "draw if distance of new fragment is less than or equal to old fragment"
    glDepthFunc(GL_LEQUAL);
    #endif

    #ifdef USE_BACKFACE_CULLING
    // enable the culling of back faces (back faces will not be drawn)
    glEnable(GL_CULL_FACE);
    #endif

    #ifdef USE_TRANSPARENCY
    // enable transparency
    glEnable (GL_BLEND);
    // set transparency function (this is standard transparency)
    glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    #endif

	checkGlError(__LINE__);
    checkSDLError(__LINE__);

    return true;
}
Пример #17
0
/*
 * initialize sdl video
 * args:
 *   width - video width
 *   height - video height
 *   flags - window flags:
 *              0- none
 *              1- fullscreen
 *              2- maximized
 *
 * asserts:
 *   none
 *
 * returns: error code
 */
static int video_init(int width, int height, int flags)
{
	int w = width;
	int h = height;
	int32_t my_flags = SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE;

	switch(flags)
	{
		case 2:
		  my_flags |= SDL_WINDOW_MAXIMIZED;
		  break;
		case 1:
		  my_flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
		  break;
		case 0:
		default:
		  break;
	}

	if(verbosity > 0)
		printf("RENDER: Initializing SDL2 render\n");

    if (sdl_window == NULL) /*init SDL*/
    {
        if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) < 0)
        {
            fprintf(stderr, "RENDER: Couldn't initialize SDL2: %s\n", SDL_GetError());
            return -1;
        }

        SDL_SetHint("SDL_HINT_RENDER_SCALE_QUALITY", "1");

		sdl_window = SDL_CreateWindow(
			"Guvcview Video",                  // window title
			SDL_WINDOWPOS_UNDEFINED,           // initial x position
			SDL_WINDOWPOS_UNDEFINED,           // initial y position
			w,                               // width, in pixels
			h,                               // height, in pixels
			my_flags
		);

		if(sdl_window == NULL)
		{
			fprintf(stderr, "RENDER: (SDL2) Couldn't open window: %s\n", SDL_GetError());
			render_sdl2_clean();
            return -2;
		}

		int display_index = SDL_GetWindowDisplayIndex(sdl_window);

		int err = SDL_GetDesktopDisplayMode(display_index, &display_mode);
		if(!err)
		{
			if(verbosity > 0)
				printf("RENDER: video display %i ->  %dx%dpx @ %dhz\n",
					display_index,
					display_mode.w,
					display_mode.h,
					display_mode.refresh_rate);
		}
		else
			fprintf(stderr, "RENDER: Couldn't determine display mode for video display %i\n", display_index);

		if(w > display_mode.w)
			w = display_mode.w;
		if(h > display_mode.h)
			h = display_mode.h;

		if(verbosity > 0)
			printf("RENDER: setting window size to %ix%i\n", w, h);

		SDL_SetWindowSize(sdl_window, w, h);
    }

    if(verbosity > 2)
    {
		/* Allocate a renderer info struct*/
        SDL_RendererInfo *rend_info = (SDL_RendererInfo *) malloc(sizeof(SDL_RendererInfo));
        if (!rend_info)
        {
                fprintf(stderr, "RENDER: Couldn't allocate memory for the renderer info data structure\n");
                render_sdl2_clean();
                return -5;
        }
        /* Print the list of the available renderers*/
        printf("\nRENDER: Available SDL2 rendering drivers:\n");
        int i = 0;
        for (i = 0; i < SDL_GetNumRenderDrivers(); i++)
        {
            if (SDL_GetRenderDriverInfo(i, rend_info) < 0)
            {
                fprintf(stderr, " Couldn't get SDL2 render driver information: %s\n", SDL_GetError());
            }
            else
            {
                printf(" %2d: %s\n", i, rend_info->name);
                printf("    SDL_RENDERER_TARGETTEXTURE [%c]\n", (rend_info->flags & SDL_RENDERER_TARGETTEXTURE) ? 'X' : ' ');
                printf("    SDL_RENDERER_SOFTWARE      [%c]\n", (rend_info->flags & SDL_RENDERER_SOFTWARE) ? 'X' : ' ');
                printf("    SDL_RENDERER_ACCELERATED   [%c]\n", (rend_info->flags & SDL_RENDERER_ACCELERATED) ? 'X' : ' ');
                printf("    SDL_RENDERER_PRESENTVSYNC  [%c]\n", (rend_info->flags & SDL_RENDERER_PRESENTVSYNC) ? 'X' : ' ');
            }
        }

        free(rend_info);
	}

    main_renderer = SDL_CreateRenderer(sdl_window, -1,
		SDL_RENDERER_TARGETTEXTURE |
		SDL_RENDERER_PRESENTVSYNC  |
		SDL_RENDERER_ACCELERATED);

	if(main_renderer == NULL)
	{
		fprintf(stderr, "RENDER: (SDL2) Couldn't get a accelerated renderer: %s\n", SDL_GetError());
		fprintf(stderr, "RENDER: (SDL2) trying with a software renderer\n");

		main_renderer = SDL_CreateRenderer(sdl_window, -1,
		SDL_RENDERER_TARGETTEXTURE |
		SDL_RENDERER_SOFTWARE);


		if(main_renderer == NULL)
		{
			fprintf(stderr, "RENDER: (SDL2) Couldn't get a software renderer: %s\n", SDL_GetError());
			fprintf(stderr, "RENDER: (SDL2) giving up...\n");
			render_sdl2_clean();
			return -3;
		}
	}

	if(verbosity > 2)
    {
		/* Allocate a renderer info struct*/
        SDL_RendererInfo *rend_info = (SDL_RendererInfo *) malloc(sizeof(SDL_RendererInfo));
        if (!rend_info)
        {
                fprintf(stderr, "RENDER: Couldn't allocate memory for the renderer info data structure\n");
                render_sdl2_clean();
                return -5;
        }

		/* Print the name of the current rendering driver */
		if (SDL_GetRendererInfo(main_renderer, rend_info) < 0)
		{
			fprintf(stderr, "Couldn't get SDL2 rendering driver information: %s\n", SDL_GetError());
		}
		printf("RENDER: rendering driver in use: %s\n", rend_info->name);
		printf("    SDL_RENDERER_TARGETTEXTURE [%c]\n", (rend_info->flags & SDL_RENDERER_TARGETTEXTURE) ? 'X' : ' ');
		printf("    SDL_RENDERER_SOFTWARE      [%c]\n", (rend_info->flags & SDL_RENDERER_SOFTWARE) ? 'X' : ' ');
		printf("    SDL_RENDERER_ACCELERATED   [%c]\n", (rend_info->flags & SDL_RENDERER_ACCELERATED) ? 'X' : ' ');
		printf("    SDL_RENDERER_PRESENTVSYNC  [%c]\n", (rend_info->flags & SDL_RENDERER_PRESENTVSYNC) ? 'X' : ' ');

		free(rend_info);
	}

	SDL_RenderSetLogicalSize(main_renderer, width, height);
	SDL_SetRenderDrawBlendMode(main_renderer, SDL_BLENDMODE_NONE);

    rending_texture = SDL_CreateTexture(main_renderer,
#ifdef USE_PLANAR_YUV
		SDL_PIXELFORMAT_IYUV,  /*yuv420p*/
#else
		SDL_PIXELFORMAT_YUY2,  /*yuv422*/
#endif
		SDL_TEXTUREACCESS_STREAMING,
		width,
		height);

	if(rending_texture == NULL)
	{
		fprintf(stderr, "RENDER: (SDL2) Couldn't get a texture for rending: %s\n", SDL_GetError());
		render_sdl2_clean();
		return -4;
	}

    return 0;
}
Пример #18
0
void SDLWindow::initializeOpenGL() {
    // Set Attributes
    SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 2);
    SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 2);
    SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 2);
    SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 2);
    SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 0);
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
    SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0);
    SDL_GL_SetAttribute(SDL_GL_ACCUM_RED_SIZE, 0);
    SDL_GL_SetAttribute(SDL_GL_ACCUM_GREEN_SIZE, 0);
    SDL_GL_SetAttribute(SDL_GL_ACCUM_BLUE_SIZE, 0);
    SDL_GL_SetAttribute(SDL_GL_ACCUM_ALPHA_SIZE, 0);
    SDL_GL_SetAttribute(SDL_GL_STEREO, 0);
#if not defined(__linux__)
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 32);
#endif // not defined(__linux__)
    SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1);
    SDL_GL_SetAttribute(SDL_GL_RETAINED_BACKING, 0);
#if defined(CONTEXT_MAJOR_VERSION) && defined(CONTEXT_MINOR_VERSION)
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, CONTEXT_MAJOR_VERSION);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, CONTEXT_MINOR_VERSION);
#endif // defined(CONTEXT_MAJOR_VERSION) && defined(CONTEXT_MINOR_VERSION)
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_EGL, 0);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG | SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG | SDL_GL_CONTEXT_ROBUST_ACCESS_FLAG | SDL_GL_CONTEXT_RESET_ISOLATION_FLAG);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
    SDL_GL_SetAttribute(SDL_GL_SHARE_WITH_CURRENT_CONTEXT, 0);
    SDL_GL_SetAttribute(SDL_GL_FRAMEBUFFER_SRGB_CAPABLE, 0);

    // Create Window
    m_sdlWindow = SDL_CreateWindow(m_title.c_str(), m_xOrigin, m_yOrigin, m_xSize, m_ySize, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI);
    if (m_sdlWindow == NULL) {
        printf("SDL_CreateWindow Error: %s\n", SDL_GetError());
        assert(m_sdlWindow != NULL);
    }

#if defined(CONTEXT_MAJOR_VERSION) && defined(CONTEXT_MINOR_VERSION)
    // Create Context
    m_sdlContext = SDL_GL_CreateContext(m_sdlWindow);
    if (m_sdlContext == NULL) {
        printf("SDL_GL_CreateContext Error: %s\n", SDL_GetError());
        assert(m_sdlContext != NULL);
    } else {
        std::cout << "OpenGL context: " << CONTEXT_MAJOR_VERSION << "." << CONTEXT_MINOR_VERSION << std::endl;
    }
#else
    // Create Context
    const int major[] = { 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 2 };
    const int minor[] = { 5, 4, 3, 2, 1, 0, 3, 2, 1, 0, 0 };
    int index = 0;
    for (index = 0; index < 11; ++index) {
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, major[index]);
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, minor[index]);
        m_sdlGlContext = SDL_GL_CreateContext(m_sdlWindow);
        if (m_sdlGlContext != NULL) {
            break;
        }
    }
    if (m_sdlGlContext == NULL) {
        printf("SDL_GL_CreateContext Error: %s\n", SDL_GetError());
        assert(m_sdlGlContext != NULL);
    } else {
        std::cout << "OpenGL context: " << major[index] << "." << minor[index] << std::endl;
    }
#endif // defined(CONTEXT_MAJOR_VERSION) && defined(CONTEXT_MINOR_VERSION)

    // Set Context to Current
    SDL_GL_MakeCurrent(m_sdlWindow, m_sdlGlContext);

    // Log relevant information
    std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl;
    std::cout << "OpenGL GLEXT version: " << GL_GLEXT_VERSION << std::endl;
    std::cout << "OpenGL GLSL version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl;
    std::cout << "OpenGL Renderer: " << glGetString(GL_RENDERER) << std::endl;
    std::cout << "OpenGL Vendor: " << glGetString(GL_VENDOR) << std::endl;

    GLint extensionsCount;
    glGetIntegerv(GL_NUM_EXTENSIONS, &extensionsCount);
    std::cout << "OpenGL Extensions: " << extensionsCount << std::endl;

#if not defined(__APPLE__) && not defined(__linux__)
    // TODO Fix this for unsupported platforms
    for (GLint i = 0; i < extensionsCount; ++i) {
        std::cout << glGetStringi(GL_EXTENSIONS, i) << std::endl;
    }
#endif // defined(__APPLE__) && not defined(__linux__)

    int videoDrivers = SDL_GetNumVideoDrivers();
    std::cout << "Video Drivers: " << videoDrivers << std::endl;

    const std::string currentVideoDriver(SDL_GetCurrentVideoDriver());
    for (int i = 0; i < videoDrivers; ++i) {
        const std::string videoDriver(SDL_GetVideoDriver(i));
        std::cout << "Video Driver " << i << ": " << videoDriver;
        if (currentVideoDriver == videoDriver) {
            std::cout << " [Current]";
        }
        std::cout << std::endl;
    }

    int renderDrivers = SDL_GetNumRenderDrivers();
    std::cout << "Render Drivers: " << renderDrivers << std::endl;

    SDL_RendererInfo info;
    for (int i = 0; i < renderDrivers; ++i) {
        SDL_GetRenderDriverInfo(i, &info);
        std::cout << "Render Driver " << i << ": " << info.name;

        bool isSoftware = info.flags & SDL_RENDERER_SOFTWARE;
        bool isHardware = info.flags & SDL_RENDERER_ACCELERATED;
        bool isVSyncEnabled = info.flags & SDL_RENDERER_PRESENTVSYNC;
        bool isTargetTexture = info.flags & SDL_RENDERER_TARGETTEXTURE;

        std::cout << " [";
        if (isSoftware)
            std::cout << "SW";
        if (isHardware)
            std::cout << "HW";
        if (isVSyncEnabled)
            std::cout << ", VS";
        if (isTargetTexture)
            std::cout << ", TT";
        std::cout << "]" << std::endl;
    }
}
Пример #19
0
bool Graphics::InitVideo()
{
	if (drawtarget == screen) drawtarget = NULL;
	if (screen) delete screen;
	
	uint32_t window_flags = SDL_WINDOW_SHOWN | SDL_WINDOW_BORDERLESS;
	if (is_fullscreen) window_flags |= SDL_WINDOW_FULLSCREEN;
	
	if (window)
	{
		stat("second call to Graphics::InitVideo()");
		abort();
	}
	
	stat("SDL_CreateWindow: %dx%d @ %dbpp", Graphics::SCREEN_WIDTH*SCALE, Graphics::SCREEN_HEIGHT*SCALE, screen_bpp);
	window = SDL_CreateWindow("NXEngine", 
		SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
		Graphics::SCREEN_WIDTH*SCALE, Graphics::SCREEN_HEIGHT*SCALE,
		window_flags);

	if (!window)
	{
		staterr("Graphics::InitVideo: error setting video mode (SDL_CreateWindow: %s)", SDL_GetError());
		return 1;
	}

	int drv_index = -1;
#if 0
	{
		int drivers = SDL_GetNumRenderDrivers();
		SDL_RendererInfo info;
		for (int i = 0; i < drivers; ++i)
		{
			if (SDL_GetRenderDriverInfo(i, &info))
			{
				staterr("Graphics::InitVideo: SDL_GetRenderDriverInfo() failed: %s", SDL_GetError());
			}

			if (strcmp("opengl", info.name) == 0)
			{
				drv_index = i;
				break;
			}
		}
	}
#endif
	
	renderer = SDL_CreateRenderer(window, drv_index, /*SDL_RENDERER_SOFTWARE | */SDL_RENDERER_ACCELERATED | SDL_RENDERER_TARGETTEXTURE);
	if (!renderer)
	{
		staterr("Graphics::InitVideo: error setting video mode (SDL_CreateRenderer: %s)", SDL_GetError());
		return 1;
	}

	SDL_RendererInfo info;
	if (SDL_GetRendererInfo(renderer, &info))
	{
		staterr("Graphics::InitVideo: SDL_GetRendererInfo failed: %s", SDL_GetError());
		return 1;
	}

	if (!(info.flags & SDL_RENDERER_TARGETTEXTURE))
	{
		staterr("Graphics::InitVideo: SDL_RENDERER_TARGETTEXTURE is not supported");
		return 1;
	}

	
	SDL_ShowCursor(is_fullscreen == false);

	screen = NXSurface::createScreen(Graphics::SCREEN_WIDTH*SCALE, Graphics::SCREEN_HEIGHT*SCALE, 
		info.texture_formats[0]);
    
    if (!screen)
    {
        staterr("Graphics::InitVideo: no screen has been created");
        return 1;
    }

	if (!drawtarget) drawtarget = screen;
	return 0;
}
Пример #20
0
SDL_bool
SDLTest_CommonInit(SDLTest_CommonState * state)
{
    int i, j, m, n, w, h;
    SDL_DisplayMode fullscreen_mode;

    if (state->flags & SDL_INIT_VIDEO) {
        if (state->verbose & VERBOSE_VIDEO) {
            n = SDL_GetNumVideoDrivers();
            if (n == 0) {
                fprintf(stderr, "No built-in video drivers\n");
            } else {
                fprintf(stderr, "Built-in video drivers:");
                for (i = 0; i < n; ++i) {
                    if (i > 0) {
                        fprintf(stderr, ",");
                    }
                    fprintf(stderr, " %s", SDL_GetVideoDriver(i));
                }
                fprintf(stderr, "\n");
            }
        }
        if (SDL_VideoInit(state->videodriver) < 0) {
            fprintf(stderr, "Couldn't initialize video driver: %s\n",
                    SDL_GetError());
            return SDL_FALSE;
        }
        if (state->verbose & VERBOSE_VIDEO) {
            fprintf(stderr, "Video driver: %s\n",
                    SDL_GetCurrentVideoDriver());
        }

        /* Upload GL settings */
        SDL_GL_SetAttribute(SDL_GL_RED_SIZE, state->gl_red_size);
        SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, state->gl_green_size);
        SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, state->gl_blue_size);
        SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, state->gl_alpha_size);
        SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, state->gl_double_buffer);
        SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, state->gl_buffer_size);
        SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, state->gl_depth_size);
        SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, state->gl_stencil_size);
        SDL_GL_SetAttribute(SDL_GL_ACCUM_RED_SIZE, state->gl_accum_red_size);
        SDL_GL_SetAttribute(SDL_GL_ACCUM_GREEN_SIZE, state->gl_accum_green_size);
        SDL_GL_SetAttribute(SDL_GL_ACCUM_BLUE_SIZE, state->gl_accum_blue_size);
        SDL_GL_SetAttribute(SDL_GL_ACCUM_ALPHA_SIZE, state->gl_accum_alpha_size);
        SDL_GL_SetAttribute(SDL_GL_STEREO, state->gl_stereo);
        SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, state->gl_multisamplebuffers);
        SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, state->gl_multisamplesamples);
        if (state->gl_accelerated >= 0) {
            SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL,
                                state->gl_accelerated);
        }
        SDL_GL_SetAttribute(SDL_GL_RETAINED_BACKING, state->gl_retained_backing);
        if (state->gl_major_version) {
            SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, state->gl_major_version);
            SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, state->gl_minor_version);
        }
        if (state->gl_debug) {
            SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
        }

        if (state->verbose & VERBOSE_MODES) {
            SDL_Rect bounds;
            SDL_DisplayMode mode;
            int bpp;
            Uint32 Rmask, Gmask, Bmask, Amask;

            n = SDL_GetNumVideoDisplays();
            fprintf(stderr, "Number of displays: %d\n", n);
            for (i = 0; i < n; ++i) {
                fprintf(stderr, "Display %d: %s\n", i, SDL_GetDisplayName(i));

                SDL_zero(bounds);
                SDL_GetDisplayBounds(i, &bounds);
                fprintf(stderr, "Bounds: %dx%d at %d,%d\n", bounds.w, bounds.h, bounds.x, bounds.y);

                SDL_GetDesktopDisplayMode(i, &mode);
                SDL_PixelFormatEnumToMasks(mode.format, &bpp, &Rmask, &Gmask,
                                           &Bmask, &Amask);
                fprintf(stderr,
                        "  Current mode: %dx%d@%dHz, %d bits-per-pixel (%s)\n",
                        mode.w, mode.h, mode.refresh_rate, bpp,
                        SDL_GetPixelFormatName(mode.format));
                if (Rmask || Gmask || Bmask) {
                    fprintf(stderr, "      Red Mask   = 0x%.8x\n", Rmask);
                    fprintf(stderr, "      Green Mask = 0x%.8x\n", Gmask);
                    fprintf(stderr, "      Blue Mask  = 0x%.8x\n", Bmask);
                    if (Amask)
                        fprintf(stderr, "      Alpha Mask = 0x%.8x\n", Amask);
                }

                /* Print available fullscreen video modes */
                m = SDL_GetNumDisplayModes(i);
                if (m == 0) {
                    fprintf(stderr, "No available fullscreen video modes\n");
                } else {
                    fprintf(stderr, "  Fullscreen video modes:\n");
                    for (j = 0; j < m; ++j) {
                        SDL_GetDisplayMode(i, j, &mode);
                        SDL_PixelFormatEnumToMasks(mode.format, &bpp, &Rmask,
                                                   &Gmask, &Bmask, &Amask);
                        fprintf(stderr,
                                "    Mode %d: %dx%d@%dHz, %d bits-per-pixel (%s)\n",
                                j, mode.w, mode.h, mode.refresh_rate, bpp,
                                SDL_GetPixelFormatName(mode.format));
                        if (Rmask || Gmask || Bmask) {
                            fprintf(stderr, "        Red Mask   = 0x%.8x\n",
                                    Rmask);
                            fprintf(stderr, "        Green Mask = 0x%.8x\n",
                                    Gmask);
                            fprintf(stderr, "        Blue Mask  = 0x%.8x\n",
                                    Bmask);
                            if (Amask)
                                fprintf(stderr,
                                        "        Alpha Mask = 0x%.8x\n",
                                        Amask);
                        }
                    }
                }
            }
        }

        if (state->verbose & VERBOSE_RENDER) {
            SDL_RendererInfo info;

            n = SDL_GetNumRenderDrivers();
            if (n == 0) {
                fprintf(stderr, "No built-in render drivers\n");
            } else {
                fprintf(stderr, "Built-in render drivers:\n");
                for (i = 0; i < n; ++i) {
                    SDL_GetRenderDriverInfo(i, &info);
                    SDLTest_PrintRenderer(&info);
                }
            }
        }

        SDL_zero(fullscreen_mode);
        switch (state->depth) {
        case 8:
            fullscreen_mode.format = SDL_PIXELFORMAT_INDEX8;
            break;
        case 15:
            fullscreen_mode.format = SDL_PIXELFORMAT_RGB555;
            break;
        case 16:
            fullscreen_mode.format = SDL_PIXELFORMAT_RGB565;
            break;
        case 24:
            fullscreen_mode.format = SDL_PIXELFORMAT_RGB24;
            break;
        default:
            fullscreen_mode.format = SDL_PIXELFORMAT_RGB888;
            break;
        }
        fullscreen_mode.refresh_rate = state->refresh_rate;

        state->windows =
            (SDL_Window **) SDL_malloc(state->num_windows *
                                        sizeof(*state->windows));
        state->renderers =
            (SDL_Renderer **) SDL_malloc(state->num_windows *
                                        sizeof(*state->renderers));
        if (!state->windows || !state->renderers) {
            fprintf(stderr, "Out of memory!\n");
            return SDL_FALSE;
        }
        for (i = 0; i < state->num_windows; ++i) {
            char title[1024];

            if (state->num_windows > 1) {
                SDL_snprintf(title, SDL_arraysize(title), "%s %d",
                             state->window_title, i + 1);
            } else {
                SDL_strlcpy(title, state->window_title, SDL_arraysize(title));
            }
            state->windows[i] =
                SDL_CreateWindow(title, state->window_x, state->window_y,
                                 state->window_w, state->window_h,
                                 state->window_flags);
            if (!state->windows[i]) {
                fprintf(stderr, "Couldn't create window: %s\n",
                        SDL_GetError());
                return SDL_FALSE;
            }
            if (state->window_minW || state->window_minH) {
                SDL_SetWindowMinimumSize(state->windows[i], state->window_minW, state->window_minH);
            }
            if (state->window_maxW || state->window_maxH) {
                SDL_SetWindowMaximumSize(state->windows[i], state->window_maxW, state->window_maxH);
            }
            SDL_GetWindowSize(state->windows[i], &w, &h);
            if (!(state->window_flags & SDL_WINDOW_RESIZABLE) &&
                (w != state->window_w || h != state->window_h)) {
                printf("Window requested size %dx%d, got %dx%d\n", state->window_w, state->window_h, w, h);
                state->window_w = w;
                state->window_h = h;
            }
            if (SDL_SetWindowDisplayMode(state->windows[i], &fullscreen_mode) < 0) {
                fprintf(stderr, "Can't set up fullscreen display mode: %s\n",
                        SDL_GetError());
                return SDL_FALSE;
            }

            if (state->window_icon) {
                SDL_Surface *icon = SDLTest_LoadIcon(state->window_icon);
                if (icon) {
                    SDL_SetWindowIcon(state->windows[i], icon);
                    SDL_FreeSurface(icon);
                }
            }

            SDL_ShowWindow(state->windows[i]);

            state->renderers[i] = NULL;

            if (!state->skip_renderer
                && (state->renderdriver
                    || !(state->window_flags & SDL_WINDOW_OPENGL))) {
                m = -1;
                if (state->renderdriver) {
                    SDL_RendererInfo info;
                    n = SDL_GetNumRenderDrivers();
                    for (j = 0; j < n; ++j) {
                        SDL_GetRenderDriverInfo(j, &info);
                        if (SDL_strcasecmp(info.name, state->renderdriver) ==
                            0) {
                            m = j;
                            break;
                        }
                    }
                    if (m == n) {
                        fprintf(stderr,
                                "Couldn't find render driver named %s",
                                state->renderdriver);
                        return SDL_FALSE;
                    }
                }
                state->renderers[i] = SDL_CreateRenderer(state->windows[i],
                                            m, state->render_flags);
                if (!state->renderers[i]) {
                    fprintf(stderr, "Couldn't create renderer: %s\n",
                            SDL_GetError());
                    return SDL_FALSE;
                }
                if (state->logical_w && state->logical_h) {
                    SDL_RenderSetLogicalSize(state->renderers[i], state->logical_w, state->logical_h);
                } else if (state->scale) {
                    SDL_RenderSetScale(state->renderers[i], state->scale, state->scale);
                }
                if (state->verbose & VERBOSE_RENDER) {
                    SDL_RendererInfo info;

                    fprintf(stderr, "Current renderer:\n");
                    SDL_GetRendererInfo(state->renderers[i], &info);
                    SDLTest_PrintRenderer(&info);
                }
            }
        }
    }

    if (state->flags & SDL_INIT_AUDIO) {
        if (state->verbose & VERBOSE_AUDIO) {
            n = SDL_GetNumAudioDrivers();
            if (n == 0) {
                fprintf(stderr, "No built-in audio drivers\n");
            } else {
                fprintf(stderr, "Built-in audio drivers:");
                for (i = 0; i < n; ++i) {
                    if (i > 0) {
                        fprintf(stderr, ",");
                    }
                    fprintf(stderr, " %s", SDL_GetAudioDriver(i));
                }
                fprintf(stderr, "\n");
            }
        }
        if (SDL_AudioInit(state->audiodriver) < 0) {
            fprintf(stderr, "Couldn't initialize audio driver: %s\n",
                    SDL_GetError());
            return SDL_FALSE;
        }
        if (state->verbose & VERBOSE_VIDEO) {
            fprintf(stderr, "Audio driver: %s\n",
                    SDL_GetCurrentAudioDriver());
        }

        if (SDL_OpenAudio(&state->audiospec, NULL) < 0) {
            fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError());
            return SDL_FALSE;
        }
    }

    return SDL_TRUE;
}
Пример #21
0
SDL_bool
CommonInit(CommonState * state)
{
    int i, j, m, n;
    SDL_DisplayMode fullscreen_mode;

    if (state->flags & SDL_INIT_VIDEO) {
        if (state->verbose & VERBOSE_VIDEO) {
            n = SDL_GetNumVideoDrivers();
            if (n == 0) {
                fprintf(stderr, "No built-in video drivers\n");
            } else {
                fprintf(stderr, "Built-in video drivers:");
                for (i = 0; i < n; ++i) {
                    if (i > 0) {
                        fprintf(stderr, ",");
                    }
                    fprintf(stderr, " %s", SDL_GetVideoDriver(i));
                }
                fprintf(stderr, "\n");
            }
        }
        if (SDL_VideoInit(state->videodriver, 0) < 0) {
            fprintf(stderr, "Couldn't initialize video driver: %s\n",
                    SDL_GetError());
            return SDL_FALSE;
        }
        if (state->verbose & VERBOSE_VIDEO) {
            fprintf(stderr, "Video driver: %s\n",
                    SDL_GetCurrentVideoDriver());
        }

        if (state->verbose & VERBOSE_MODES) {
            SDL_DisplayMode mode;
            int bpp;
            Uint32 Rmask, Gmask, Bmask, Amask;

            n = SDL_GetNumVideoDisplays();
            fprintf(stderr, "Number of displays: %d\n", n);
            for (i = 0; i < n; ++i) {
                fprintf(stderr, "Display %d:\n", i);
                SDL_SelectVideoDisplay(i);

                SDL_GetDesktopDisplayMode(&mode);
                SDL_PixelFormatEnumToMasks(mode.format, &bpp, &Rmask, &Gmask,
                                           &Bmask, &Amask);
                fprintf(stderr,
                        "  Current mode: %dx%d@%dHz, %d bits-per-pixel\n",
                        mode.w, mode.h, mode.refresh_rate, bpp);
                if (Rmask || Gmask || Bmask) {
                    fprintf(stderr, "      Red Mask = 0x%.8x\n", Rmask);
                    fprintf(stderr, "      Green Mask = 0x%.8x\n", Gmask);
                    fprintf(stderr, "      Blue Mask = 0x%.8x\n", Bmask);
                    if (Amask)
                        fprintf(stderr, "      Alpha Mask = 0x%.8x\n", Amask);
                }

                /* Print available fullscreen video modes */
                m = SDL_GetNumDisplayModes();
                if (m == 0) {
                    fprintf(stderr, "No available fullscreen video modes\n");
                } else {
                    fprintf(stderr, "  Fullscreen video modes:\n");
                    for (j = 0; j < m; ++j) {
                        SDL_GetDisplayMode(j, &mode);
                        SDL_PixelFormatEnumToMasks(mode.format, &bpp, &Rmask,
                                                   &Gmask, &Bmask, &Amask);
                        fprintf(stderr,
                                "    Mode %d: %dx%d@%dHz, %d bits-per-pixel\n",
                                j, mode.w, mode.h, mode.refresh_rate, bpp);
                        if (Rmask || Gmask || Bmask) {
                            fprintf(stderr, "        Red Mask = 0x%.8x\n",
                                    Rmask);
                            fprintf(stderr, "        Green Mask = 0x%.8x\n",
                                    Gmask);
                            fprintf(stderr, "        Blue Mask = 0x%.8x\n",
                                    Bmask);
                            if (Amask)
                                fprintf(stderr,
                                        "        Alpha Mask = 0x%.8x\n",
                                        Amask);
                        }
                    }
                }
            }
        }

        SDL_SelectVideoDisplay(state->display);
        if (state->verbose & VERBOSE_RENDER) {
            SDL_RendererInfo info;

            n = SDL_GetNumRenderDrivers();
            if (n == 0) {
                fprintf(stderr, "No built-in render drivers\n");
            } else {
                fprintf(stderr, "Built-in render drivers:\n");
                for (i = 0; i < n; ++i) {
                    SDL_GetRenderDriverInfo(i, &info);
                    PrintRenderer(&info);
                }
            }
        }

        switch (state->depth) {
        case 8:
            fullscreen_mode.format = SDL_PIXELFORMAT_INDEX8;
            break;
        case 15:
            fullscreen_mode.format = SDL_PIXELFORMAT_RGB555;
            break;
        case 16:
            fullscreen_mode.format = SDL_PIXELFORMAT_RGB565;
            break;
        default:
            fullscreen_mode.format = SDL_PIXELFORMAT_RGB888;
            break;
        }
        fullscreen_mode.w = state->window_w;
        fullscreen_mode.h = state->window_h;
        fullscreen_mode.refresh_rate = state->refresh_rate;
        SDL_SetFullscreenDisplayMode(&fullscreen_mode);

        state->windows =
            (SDL_WindowID *) SDL_malloc(state->num_windows *
                                        sizeof(*state->windows));
        if (!state->windows) {
            fprintf(stderr, "Out of memory!\n");
            return SDL_FALSE;
        }
        for (i = 0; i < state->num_windows; ++i) {
            char title[1024];

            if (state->num_windows > 1) {
                SDL_snprintf(title, SDL_arraysize(title), "%s %d",
                             state->window_title, i + 1);
            } else {
                SDL_strlcpy(title, state->window_title, SDL_arraysize(title));
            }
            state->windows[i] =
                SDL_CreateWindow(title, state->window_x, state->window_y,
                                 state->window_w, state->window_h,
                                 state->window_flags);
            if (!state->windows[i]) {
                fprintf(stderr, "Couldn't create window: %s\n",
                        SDL_GetError());
                return SDL_FALSE;
            }

            if (!state->skip_renderer
                && (state->renderdriver
                    || !(state->window_flags & SDL_WINDOW_OPENGL))) {
                m = -1;
                if (state->renderdriver) {
                    SDL_RendererInfo info;
                    n = SDL_GetNumRenderDrivers();
                    for (j = 0; j < n; ++j) {
                        SDL_GetRenderDriverInfo(j, &info);
                        if (SDL_strcasecmp(info.name, state->renderdriver) ==
                            0) {
                            m = j;
                            break;
                        }
                    }
                    if (m == n) {
                        fprintf(stderr,
                                "Couldn't find render driver named %s",
                                state->renderdriver);
                        return SDL_FALSE;
                    }
                }
                if (SDL_CreateRenderer
                    (state->windows[i], m, state->render_flags) < 0) {
                    fprintf(stderr, "Couldn't create renderer: %s\n",
                            SDL_GetError());
                    return SDL_FALSE;
                }
                if (state->verbose & VERBOSE_RENDER) {
                    SDL_RendererInfo info;

                    fprintf(stderr, "Current renderer:\n");
                    SDL_GetRendererInfo(&info);
                    PrintRenderer(&info);
                }
            }
        }
        SDL_SelectRenderer(state->windows[0]);
    }

    if (state->flags & SDL_INIT_AUDIO) {
        if (state->verbose & VERBOSE_AUDIO) {
            n = SDL_GetNumAudioDrivers();
            if (n == 0) {
                fprintf(stderr, "No built-in audio drivers\n");
            } else {
                fprintf(stderr, "Built-in audio drivers:");
                for (i = 0; i < n; ++i) {
                    if (i > 0) {
                        fprintf(stderr, ",");
                    }
                    fprintf(stderr, " %s", SDL_GetAudioDriver(i));
                }
                fprintf(stderr, "\n");
            }
        }
        if (SDL_AudioInit(state->audiodriver) < 0) {
            fprintf(stderr, "Couldn't initialize audio driver: %s\n",
                    SDL_GetError());
            return SDL_FALSE;
        }
        if (state->verbose & VERBOSE_VIDEO) {
            fprintf(stderr, "Audio driver: %s\n",
                    SDL_GetCurrentAudioDriver());
        }

        if (SDL_OpenAudio(&state->audiospec, NULL) < 0) {
            fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError());
            return SDL_FALSE;
        }
    }

    return SDL_TRUE;
}
Пример #22
0
    //------------------------------------------------------------------------
    bool platform_support::init(unsigned width, unsigned height, unsigned flags)
    {
        ERROR_PRINT("platform_support::init %d,%d\n", width, height);
        m_window_flags = flags;
        int wflags = 0;

        if(m_specific->m_texture) SDL_DestroyTexture(m_specific->m_texture);
        if(m_specific->m_renderer) SDL_DestroyRenderer(m_specific->m_renderer);
        if(m_specific->m_surface) SDL_FreeSurface(m_specific->m_surface);
        //if(m_specific->m_mwindow) SDL_DestroyWindow(m_specific->m_mwindow);
        m_specific->m_texture = 0;
        m_specific->m_renderer = 0;
        m_specific->m_surface = 0;
        //m_specific->m_mwindow = 0;

        if(m_window_flags & window_resize)
        {
            wflags |= SDL_WINDOW_RESIZABLE;
        }
        if(m_window_flags & window_fullscreen)
        {
            wflags |= SDL_WINDOW_FULLSCREEN;
#ifdef __ANDROID__DISABLED
            width = Android_ScreenWidth;
            height = Android_ScreenHeight;
#endif

#ifdef __ANDROID__
            if (m_window_flags & window_keep_aspect_ratio)
            {
               width = (double)Android_ScreenWidth/Android_ScreenHeight*height;
               width_factor = (double)width/Android_ScreenWidth;
               hight_factor = (double)height/Android_ScreenHeight;
            }
#endif
        }
        DEBUG_PRINT("platform_support::init %d,%d,%d", width, height, wflags);

        int numRendDrv = SDL_GetNumRenderDrivers();
        DEBUG_PRINT("num rend drv %d\n", numRendDrv);

        for (int i = 0; i < numRendDrv; i++)
        {
           SDL_RendererInfo info;
           SDL_GetRenderDriverInfo(i, &info);
           DEBUG_PRINT("index %i, %s, flags %x, texture formats %x\n", i, info.name, info.flags,
                 info.texture_formats[0]);
        }

        if (!m_specific->m_mwindow)
        {
           m_specific->m_mwindow = SDL_CreateWindow(m_caption,
                 SDL_WINDOWPOS_UNDEFINED,
                 SDL_WINDOWPOS_UNDEFINED,
                 width, height,
                 wflags);
        }

        if (m_specific->m_mwindow == 0) 
        {
            ERROR_PRINT( 
                    "Unable to create %dx%d %d bpp window: %s\n", 
                    width, 
                    height, 
                    m_bpp, 
                    SDL_GetError());
            return false;
        }

        m_specific->m_surface = SDL_CreateRGBSurface(0, width, height,
              m_bpp,
              m_specific->m_rmask, 
              m_specific->m_gmask, 
              m_specific->m_bmask, 
              m_specific->m_amask);
        DEBUG_PRINT("surface at %p", m_specific->m_surface);

        if(m_specific->m_surface == 0) 
        {
            ERROR_PRINT( 
                    "Unable to create image buffer %dx%d %d bpp: %s\n", 
                    width, 
                    height, 
                    m_bpp, 
                    SDL_GetError());
            return false;
        }

        m_specific->m_renderer = SDL_CreateRenderer(m_specific->m_mwindow,
              -1, 0);
        if(m_specific->m_renderer == 0) 
        {
            ERROR_PRINT( 
                    "Unable to create renderer: %s\n", 
                    SDL_GetError());
            return false;
        }

        {
           SDL_RendererInfo info;
           SDL_GetRendererInfo(m_specific->m_renderer, &info);
           DEBUG_PRINT("Current, %s, flags %x, texture formats %x, %x\n", info.name, info.flags,
                 SDL_PIXELFORMAT_ARGB8888, info.texture_formats[0]);
        }

        m_specific->m_texture = SDL_CreateTexture(
              m_specific->m_renderer,
              m_specific->m_pformat,
              SDL_TEXTUREACCESS_STREAMING, width, height);
        if(m_specific->m_renderer == 0) 
        {
            ERROR_PRINT( 
                    "Unable to create texture: %s\n", 
                    SDL_GetError());
            return false;
        }

        void* pixels;
        int pitch;
        if (SDL_LockTexture(m_specific->m_texture, NULL, &pixels, &pitch) < 0)
        {
           SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
                 "Couldn't lock texture: %s\n",
                 SDL_GetError());
        }

        m_rbuf_window.attach((unsigned char*)pixels, 
                             width, height, 
                             m_flip_y ? -pitch : pitch);


        if (!m_specific->m_initialized)
        {
            m_initial_width = width;
            m_initial_height = height;
            on_init();
            m_specific->m_initialized = true;
        }
        on_resize(m_rbuf_window.width(), m_rbuf_window.height());
        m_specific->m_update_flag = true;
        return true;
    }
Пример #23
0
void sdl_init(int width, int height, bool fullscreen) {
  sdlCurrentFrame = sdlNextFrame = 0;
  int drv_index = -1, it = 0;
  char rendername[256] = { 0 };
  if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS)) {
    fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError());
    exit(1);
  }

  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);
  SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1);

  fullscreen_flags = fullscreen?SDL_WINDOW_FULLSCREEN_DESKTOP:0;
  window = SDL_CreateWindow("Moonlight", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, SDL_WINDOW_OPENGL | fullscreen_flags);
  if(!window) {
    fprintf(stderr, "SDL: could not create window - exiting\n");
    exit(1);
  }

  SDL_GLContext ctx = SDL_GL_CreateContext(window);
  SDL_GL_MakeCurrent(window, ctx);

  glGetStringAPI = (glGetString_Func)SDL_GL_GetProcAddress("glGetString");

  for(it = 0; it < SDL_GetNumRenderDrivers(); it++) {
      SDL_RendererInfo info;
      SDL_GetRenderDriverInfo(it,&info);

      strcat(rendername, info.name);
      strcat(rendername, " ");

      if(strcmp("opengles2", info.name) == 0)
          drv_index = it;
  }
  fprintf(stdout, "Available Renderers: %s\n", rendername);
  fprintf(stdout, "Vendor     : %s\n", glGetStringAPI(GL_VENDOR));
  fprintf(stdout, "Renderer   : %s\n", glGetStringAPI(GL_RENDERER));
  fprintf(stdout, "Version    : %s\n", glGetStringAPI(GL_VERSION));
  fprintf(stdout, "Extensions : %s\n", glGetStringAPI(GL_EXTENSIONS));

  SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear");

  SDL_SetRelativeMouseMode(SDL_TRUE);
  renderer = SDL_CreateRenderer(window, drv_index, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
  if (!renderer) {
    printf("SDL_CreateRenderer failed: %s\n", SDL_GetError());
    exit(1);
  }

  SDL_ShowCursor(SDL_DISABLE);

  bmp = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_YV12, SDL_TEXTUREACCESS_STREAMING, width, height);
  if (!bmp) {
    fprintf(stderr, "SDL: could not create texture - exiting\n");
    exit(1);
  }

  mutex = SDL_CreateMutex();
  if (!mutex) {
    fprintf(stderr, "Couldn't create mutex\n");
    exit(1);
  }
}