/**
 * initSound(): Initialize sound.
 * @return 1 on success; -1 if sound was already initialized; 0 on error.
 */
int Audio_SDL::initSound(void)
{
	int i;
	int videoLines;
	
	if (m_soundInitialized)
		return -1;
	
	// Make sure sound is ended first.
	endSound();
	
	switch (m_soundRate)
	{
		case 11025:
			m_segLength = (CPU_Mode ? 220 : 184);
			break;
		case 22050:
			m_segLength = (CPU_Mode ? 441 : 368);
			break;
		case 44100:
			m_segLength = (CPU_Mode ? 882 : 735);
			break;
	}
	
	videoLines = (CPU_Mode ? 312 : 262);
	for (i = 0; i < videoLines; i++)
	{
		Sound_Extrapol[i][0] = ((m_segLength * i) / videoLines);
		Sound_Extrapol[i][1] = (((m_segLength * (i + 1)) / videoLines) - Sound_Extrapol[i][0]);
	}
	for (i = 0; i < m_segLength; i++)
		Sound_Interpol[i] = ((videoLines * i) / m_segLength);
	
	// Clear the segment buffers.
	memset(Seg_L, 0, m_segLength << 2);
	memset(Seg_R, 0, m_segLength << 2);
	
	// Attempt to initialize SDL audio.
	if (SDL_InitSubSystem(SDL_INIT_AUDIO) == -1)
		return 0;
	
	// Allocate the segment buffer.
	pMsndOut = static_cast<unsigned char*>(malloc(m_segLength << 2));
	
	// Set up the SDL audio specification.
	SDL_AudioSpec spec;
	spec.freq = m_soundRate;
	spec.format = AUDIO_S16SYS;
	spec.channels = !m_stereo ? 1 : 2; // TODO: Initializing 1 channel seems to double-free if it's later changed...
	spec.samples = 1024;
	spec.callback = AudioCallback;
	audiobuf = static_cast<unsigned char*>(malloc((spec.samples * spec.channels * 2 * 4) * sizeof(short)));
	
	// "user" parameter for the callback function is a pointer to this object.
	spec.userdata = this;
	
	memset(audiobuf, 0, (spec.samples * spec.channels * 2 * 4) * sizeof(short));
	if (SDL_OpenAudio(&spec, 0) != 0)
		return 0;
	SDL_PauseAudio(0);
	
	// Sound is initialized.
	m_soundInitialized = true;
	return 1;
}
static int Init()
{
	nInitedSubsytems = SDL_WasInit(SDL_INIT_VIDEO);

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

	nGamesWidth = nVidImageWidth;
	nGamesHeight = nVidImageHeight;

	nRotateGame = 0;

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

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

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

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

	nSize = 2;
	bVidScanlines = 0;

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

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

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

	// Initialize the buffer surfaces
	BlitFXInit();

	// Init opengl
	init_gl();

	return 0;
}
Beispiel #3
0
int main(int argc, char * * argv)
{
  const SDL_VideoInfo *videoInfo;
  Uint32 videoFlags = 0;
   
  /* Initialize SDL */
  printf("(II) Initializing SDL video subsystem...\n");
  if(SDL_InitSubSystem(SDL_INIT_VIDEO) == -1)
  {
    printf("(EE) Error initializing SDL video subsystem: %s\n", SDL_GetError());
    return -1;
  }
   
  /* Video Info */
  printf("(II) Getting video info...\n");
  if(!(videoInfo = SDL_GetVideoInfo()))
  {
    printf("(EE) Video query failed: %s\n", SDL_GetError());
    SDL_QuitSubSystem(SDL_INIT_VIDEO);
    return -1;
  }
   
  /* Setting the video mode */
  videoFlags |= SDL_OPENGL | SDL_GL_DOUBLEBUFFER | SDL_HWPALETTE;
  
  if(videoInfo->hw_available)
    videoFlags |= SDL_HWSURFACE;
  else
    videoFlags |= SDL_SWSURFACE;
  
  if(videoInfo->blit_hw)
    videoFlags |= SDL_HWACCEL;
  
  //videoFlags |= SDL_FULLSCREEN;

  SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  //SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 16);
//   SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32);
//   SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
//   SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
//   SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
//   SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
  //SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
   
  printf("(II) Setting video mode %dx%d...\n", screen_width, screen_height);
  if(!(sdl_Screen = SDL_SetVideoMode(screen_width, screen_height, 0, videoFlags)))
  {
    printf("(EE) Error setting videomode %dx%d: %s\n", screen_width, screen_height, SDL_GetError());
    SDL_QuitSubSystem(SDL_INIT_VIDEO);
    return -1;
  }
   
  char caption[500];
  sprintf(caption, "z64, LLE video plugin by Ziggy");
  SDL_WM_SetCaption(caption, caption);



  static char pixels[256*256*4];
  ilInit();
  glewInit();

  ilLoadImage("tex1.png");
  glBindTexture(GL_TEXTURE_2D, 1);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 256, 256, 0, GL_RGBA, GL_UNSIGNED_BYTE,
               ilGetData());
  glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
                   GL_LINEAR );
  glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
                   GL_LINEAR );
  ilLoadImage("tex2.png");
  glBindTexture(GL_TEXTURE_2D, 2);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 256, 256, 0, GL_RGBA, GL_UNSIGNED_BYTE,
               ilGetData());
  glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
                   GL_LINEAR );
  glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
                   GL_LINEAR );

  glDisable(GL_DEPTH_TEST);
  glDisable(GL_BLEND);

  glViewport(0, 0, screen_width, screen_height);

  glLoadIdentity();
  glScalef(2, 2, 1);
  glTranslatef(-0.5, -0.5, 0);

  rglShader_t * shader = rglCreateShader(
    "void main()                                                    \n"
    "{                                                              \n"
    "  gl_Position = ftransform();                                  \n"
    "  gl_FrontColor = gl_Color;                                    \n"
    "  gl_TexCoord[0] = gl_MultiTexCoord0;                          \n"
    "}                                                              \n"
    ,
    "uniform sampler2D texture0;       \n"
    "uniform sampler2D texture1;       \n"
    "                                  \n"
    "void main()                       \n"
    "{                                 \n"
    "  gl_FragColor = gl_Color * (texture2D(texture0, vec2(gl_TexCoord[0])) + texture2D(texture1, vec2(gl_TexCoord[0]))); \n"
    "}                                 \n"
  );
  rglUseShader(shader);

  int location;
  location = glGetUniformLocationARB(shader->prog, "texture0");
  glUniform1iARB(location, 0);
  location = glGetUniformLocationARB(shader->prog, "texture1");
  glUniform1iARB(location, 1);
  
  //glEnable(GL_TEXTURE_2D);

  glActiveTextureARB(GL_TEXTURE0_ARB);
  glBindTexture(GL_TEXTURE_2D, 1);
  glActiveTextureARB(GL_TEXTURE1_ARB);
  glBindTexture(GL_TEXTURE_2D, 2);
  

  glColor4ub(255,255,255,255);
  glEnable(GL_TEXTURE_2D);
  glBegin(GL_QUADS);
  
  glTexCoord2f(0, 0);
  glVertex2f  (0, 0);
  
  glTexCoord2f(0, 1);
  glVertex2f  (0, 1);
  
  glTexCoord2f(1, 1);
  glVertex2f  (1, 1);
  
  glTexCoord2f(1, 0);
  glVertex2f  (1, 0);
  
  glEnd();

  SDL_GL_SwapBuffers();

  getchar();

  return 0;
}
Beispiel #4
0
qboolean SNDDMA_Init (dma_t *dma)
{
	SDL_AudioSpec desired, obtained;
	int		tmp, val;
	char	drivername[128];

	if (SDL_InitSubSystem(SDL_INIT_AUDIO) < 0)
	{
		Con_Printf("Couldn't init SDL audio: %s\n", SDL_GetError());
		return false;
	}

	/* Set up the desired format */
	desired.freq = tmp = snd_mixspeed.value;
	desired.format = (loadas8bit.value) ? AUDIO_U8 : AUDIO_S16SYS;
	desired.channels = 2; /* = desired_channels; */
	if (desired.freq <= 11025)
		desired.samples = 256;
	else if (desired.freq <= 22050)
		desired.samples = 512;
	else if (desired.freq <= 44100)
		desired.samples = 1024;
	else if (desired.freq <= 56000)
		desired.samples = 2048; /* for 48 kHz */
	else
		desired.samples = 4096; /* for 96 kHz */
	desired.callback = paint_audio;
	desired.userdata = NULL;

	/* Open the audio device */
	if (SDL_OpenAudio(&desired, &obtained) == -1)
	{
		Con_Printf("Couldn't open SDL audio: %s\n", SDL_GetError());
		SDL_QuitSubSystem(SDL_INIT_AUDIO);
		return false;
	}

	/* Make sure we can support the audio format */
	switch (obtained.format)
	{
	case AUDIO_S8:		/* maybe needed by AHI */
	case AUDIO_U8:
	case AUDIO_S16SYS:
		/* Supported */
		break;
	default:
		Con_Printf ("Unsupported audio format received (%u)\n", obtained.format);
		SDL_CloseAudio();
		SDL_QuitSubSystem(SDL_INIT_AUDIO);
		return false;
	}

	memset ((void *) dma, 0, sizeof(dma_t));
	shm = dma;

	/* Fill the audio DMA information block */
	shm->samplebits = (obtained.format & 0xFF); /* first byte of format is bits */
	shm->signed8 = (obtained.format == AUDIO_S8);
	if (obtained.freq != tmp)
		Con_Printf ("Warning: Rate set (%d) didn't match requested rate (%d)!\n", obtained.freq, tmp);
	shm->speed = obtained.freq;
	shm->channels = obtained.channels;
	tmp = (obtained.samples * obtained.channels) * 10;
	if (tmp & (tmp - 1))
	{	/* make it a power of two */
		val = 1;
		while (val < tmp)
			val <<= 1;

		tmp = val;
	}
	shm->samples = tmp;
	shm->samplepos = 0;
	shm->submission_chunk = 1;

	Con_Printf ("SDL audio spec  : %d Hz, %d samples, %d channels\n",
			obtained.freq, obtained.samples, obtained.channels);
	{
		const char *driver = SDL_GetCurrentAudioDriver();
		const char *device = SDL_GetAudioDeviceName(0, SDL_FALSE);
		q_snprintf(drivername, sizeof(drivername), "%s - %s",
			driver != NULL ? driver : "(UNKNOWN)",
			device != NULL ? device : "(UNKNOWN)");
	}
	buffersize = shm->samples * (shm->samplebits / 8);
	Con_Printf ("SDL audio driver: %s, %d bytes buffer\n", drivername, buffersize);

	shm->buffer = (unsigned char *) calloc (1, buffersize);
	if (!shm->buffer)
	{
		SDL_CloseAudio();
		SDL_QuitSubSystem(SDL_INIT_AUDIO);
		shm = NULL;
		Con_Printf ("Failed allocating memory for SDL audio\n");
		return false;
	}

	SDL_PauseAudio(0);

	return true;
}
Beispiel #5
0
	bool Graphics::Initialize(int width, int height, unsigned int bpp, bool fullScreen)
	{ 
		Log("****Initializing Graphics****");
		Log("Initializing Screen...");
		if(SDL_InitSubSystem(SDL_INIT_VIDEO) == -1)
		{
			Error("Unable to initialize Screen");
			return false;
		}

		m_width = width;
		m_height = height;
		m_fullScreen = fullScreen;
		m_bitsPerPixel = bpp;

		unsigned int flags = SDL_HWSURFACE | SDL_OPENGL;

		if(fullScreen)
		{
			flags |= SDL_FULLSCREEN;
		}

		m_buffer = SDL_SetVideoMode(m_width, m_height, m_bitsPerPixel, flags);

		if(!m_buffer)
		{
			if(fullScreen)
			{
				Warning("Unable to set up full screen");

				flags = SDL_HWSURFACE;

				m_buffer = 
					SDL_SetVideoMode(m_width, m_height, m_bitsPerPixel, flags);

				if(!m_buffer)
				{
					Error("Unable to set up screen buffer");
					return false;
				}
			}
			else
			{
				Error("Unable to set up screen buffer");
				return false;
			}
		} 
		Log("width:" + ToString(m_width) + " height:" + ToString(m_height) + 
			" bpp:" + ToString(m_bitsPerPixel) + " fullscreen:" + (m_fullScreen ? "true" : "false"));

		Log("Initializing GL Extensions...");

		GLenum glewInitCode = glewInit();
		if(glewInitCode != GLEW_OK) 
		{
			std::string error = "Unable to initialize GL Extensions";
			switch(glewInitCode)
			{
			case 1:
				error += " no GL ver"; 
				break;
			case 2:
				error += " OGL ver < 1.1";
				break;
			case 3:
				error += " GLX ver < 1.2";
				break;
			default:
				error += " unknown error";
			}

			Error(error);
		}

		Log("GL Extensions Initialized");
		Log(" ");

		return true;
	}
Beispiel #6
0
/*
 * This thread will read the buttons in an interrupt like fashion, and
 * also initializes SDL_INIT_VIDEO and the surfaces
 *
 * it must be done in the same thread (at least on windows) because events only
 * work in the thread which called SDL_Init(SubSystem) with SDL_INIT_VIDEO
 *
 * This is an SDL thread and relies on preemptive behavoir of the host
 **/
static int sdl_event_thread(void * param)
{
    SDL_InitSubSystem(SDL_INIT_VIDEO);

    SDL_Surface *picture_surface;
    int width, height;

    /* Try and load the background image. If it fails go without */
    if (background) {
        picture_surface = SDL_LoadBMP("UI256.bmp");
        if (picture_surface == NULL) {
            background = false;
            DEBUGF("warn: %s\n", SDL_GetError());
        }
    }
    
    /* Set things up */
    if (background)
    {
        width = UI_WIDTH;
        height = UI_HEIGHT;
    } 
    else 
    {
#ifdef HAVE_REMOTE_LCD
        if (showremote)
        {
            width = SIM_LCD_WIDTH > SIM_REMOTE_WIDTH ? SIM_LCD_WIDTH : SIM_REMOTE_WIDTH;
            height = SIM_LCD_HEIGHT + SIM_REMOTE_HEIGHT;
        }
        else
#endif
        {
            width = SIM_LCD_WIDTH;
            height = SIM_LCD_HEIGHT;
        }
    }
   
    
    if ((gui_surface = SDL_SetVideoMode(width * display_zoom, height * display_zoom, 24, SDL_HWSURFACE|SDL_DOUBLEBUF)) == NULL) {
        panicf("%s", SDL_GetError());
    }

    SDL_WM_SetCaption(UI_TITLE, NULL);

    if (background && picture_surface != NULL)
        SDL_BlitSurface(picture_surface, NULL, gui_surface, NULL);

    /* let system_init proceed */
    SDL_SemPost((SDL_sem *)param);

    /*
     * finally enter the button loop */
    while(gui_message_loop());

    /* Order here is relevent to prevent deadlocks and use of destroyed
       sync primitives by kernel threads */
    sim_thread_shutdown();
    sim_kernel_shutdown();

    return 0;
}
Beispiel #7
0
/**
 * @brief The entry point of Naev.
 *
 *    @param[in] argc Number of arguments.
 *    @param[in] argv Array of argc arguments.
 *    @return EXIT_SUCCESS on success.
 */
int main( int argc, char** argv )
{
   char buf[PATH_MAX];

   /* Save the binary path. */
   binary_path = strdup(argv[0]);

   /* Print the version */
   LOG( " "APPNAME" v%s", naev_version(0) );
#ifdef GIT_COMMIT
   DEBUG( " git HEAD at " GIT_COMMIT );
#endif /* GIT_COMMIT */

   /* Initializes SDL for possible warnings. */
   SDL_Init(0);

   /* Initialize the threadpool */
   threadpool_init();

   /* Set up debug signal handlers. */
   debug_sigInit();

   /* Must be initialized before input_init is called. */
   if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) {
      WARN("Unable to initialize SDL Video: %s", SDL_GetError());
      return -1;
   }

   /* Get desktop dimensions. */
#if SDL_VERSION_ATLEAST(1,2,10)
   const SDL_VideoInfo *vidinfo = SDL_GetVideoInfo();
   gl_screen.desktop_w = vidinfo->current_w;
   gl_screen.desktop_h = vidinfo->current_h;
#else /* #elif SDL_VERSION_ATLEAST(1,2,10) */
   gl_screen.desktop_w = 0;
   gl_screen.desktop_h = 0;
#endif /* #elif SDL_VERSION_ATLEAST(1,2,10) */

   /* We'll be parsing XML. */
   LIBXML_TEST_VERSION
   xmlInitParser();

   /* Input must be initialized for config to work. */
   input_init();

   conf_setDefaults(); /* set the default config values */

   /*
    * Attempts to load the data path from datapath.lua
    * At this early point in the load process, the binary path
    * is the only place likely to be checked.
    */
   conf_loadConfigPath();

   /* Parse the user data path override first. */
   conf_parseCLIPath( argc, argv );

   /* Create the home directory if needed. */
   if (nfile_dirMakeExist("%s", nfile_configPath()))
      WARN("Unable to create config directory '%s'", nfile_configPath());

   /* Set the configuration. */
   nsnprintf(buf, PATH_MAX, "%s"CONF_FILE, nfile_configPath());

#if HAS_UNIX
   /* TODO get rid of this cruft ASAP. */
   int oldconfig = 0;
   if (!nfile_fileExists( buf )) {
      char *home, buf2[PATH_MAX];
      home = SDL_getenv( "HOME" );
      if (home != NULL) {
         nsnprintf( buf2, PATH_MAX, "%s/.naev/"CONF_FILE, home );
         if (nfile_fileExists( buf2 ))
            oldconfig = 1;
      }
   }
#endif /* HAS_UNIX */

   conf_loadConfig(buf); /* Lua to parse the configuration file */
   conf_parseCLI( argc, argv ); /* parse CLI arguments */

   /* Enable FPU exceptions. */
#if defined(HAVE_FEENABLEEXCEPT) && defined(DEBUGGING)
   if (conf.fpu_except)
      feenableexcept( FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW );
#endif /* defined(HAVE_FEENABLEEXCEPT) && defined(DEBUGGING) */

   /* Open data. */
   if (ndata_open() != 0)
      ERR("Failed to open ndata.");

   /* Load the start info. */
   if (start_load())
      ERR("Failed to load module start data.");

   /* Load the data basics. */
   LOG(" %s", ndata_name());
   DEBUG();

   /* Display the SDL Version. */
   print_SDLversion();
   DEBUG();

   /* random numbers */
   rng_init();

   /*
    * OpenGL
    */
   if (gl_init()) { /* initializes video output */
      ERR("Initializing video output failed, exiting...");
      SDL_Quit();
      exit(EXIT_FAILURE);
   }
   window_caption();
   gl_fontInit( NULL, NULL, conf.font_size_def ); /* initializes default font to size */
   gl_fontInit( &gl_smallFont, NULL, conf.font_size_small ); /* small font */

   /* Display the load screen. */
   loadscreen_load();
   loadscreen_render( 0., "Initializing subsystems..." );
   time_ms = SDL_GetTicks();


   /*
    * Input
    */
   if ((conf.joystick_ind >= 0) || (conf.joystick_nam != NULL)) {
      if (joystick_init()) WARN("Error initializing joystick input");
      if (conf.joystick_nam != NULL) { /* use the joystick name to find a joystick */
         if (joystick_use(joystick_get(conf.joystick_nam))) {
            WARN("Failure to open any joystick, falling back to default keybinds");
            input_setDefault();
         }
         free(conf.joystick_nam);
      }
      else if (conf.joystick_ind >= 0) /* use a joystick id instead */
         if (joystick_use(conf.joystick_ind)) {
            WARN("Failure to open any joystick, falling back to default keybinds");
            input_setDefault();
         }
   }


   /*
    * OpenAL - Sound
    */
   if (conf.nosound) {
      LOG("Sound is disabled!");
      sound_disabled = 1;
      music_disabled = 1;
   }
   if (sound_init()) WARN("Problem setting up sound!");
   music_choose("load");

   /* FPS stuff. */
   fps_setPos( 15., (double)(gl_screen.h-15-gl_defFont.h) );

   /* Misc graphics init */
   if (nebu_init() != 0) { /* Initializes the nebula */
      /* An error has happened */
      ERR("Unable to initialize the Nebula subsystem!");
      /* Weirdness will occur... */
   }
   gui_init(); /* initializes the GUI graphics */
   toolkit_init(); /* initializes the toolkit */
   map_init(); /* initializes the map. */
   cond_init(); /* Initialize conditional subsystem. */
   cli_init(); /* Initialize console. */

   /* Data loading */
   load_all();

   /* Generate the CSV. */
   if (conf.devcsv)
      dev_csv();

   /* Unload load screen. */
   loadscreen_unload();

   /* Start menu. */
   menu_main();

   /* Force a minimum delay with loading screen */
   if ((SDL_GetTicks() - time_ms) < NAEV_INIT_DELAY)
      SDL_Delay( NAEV_INIT_DELAY - (SDL_GetTicks() - time_ms) );
   fps_init(); /* initializes the time_ms */

#if HAS_UNIX
   /* Tell the player to migrate their configuration files out of ~/.naev */
   /* TODO get rid of this cruft ASAP. */
   if ((oldconfig) && (!conf.datapath)) {
      char path[PATH_MAX], *script, *home;
      uint32_t scriptsize;
      int ret;

      nsnprintf( path, PATH_MAX, "%s/naev-confupdate.sh", ndata_getDirname() );
      home = SDL_getenv("HOME");
      ret = dialogue_YesNo( "Warning", "Your configuration files are in a deprecated location and must be migrated:\n"
            "   \er%s/.naev/\e0\n\n"
            "The update script can likely be found in your Naev data directory:\n"
            "   \er%s\e0\n\n"
            "Would you like to run it automatically?", home, path );

      /* Try to run the script. */
      if (ret) {
         ret = -1;
         /* Running from ndata. */
         if (ndata_getPath() != NULL) {
            script = ndata_read( "naev-confupdate.sh", &scriptsize );
            if (script != NULL)
               ret = system(script);
         }

         /* Running from laid-out files or ndata_read failed. */
         if ((nfile_fileExists(path)) && (ret == -1)) {
            script = nfile_readFile( (int*)&scriptsize, path );
            if (script != NULL)
               ret = system(script);
         }

         /* We couldn't find the script. */
         if (ret == -1) {
            dialogue_alert( "The update script was not found at:\n\er%s\e0\n\n"
                  "Please locate and run it manually.", path );
         }
         /* Restart, as the script succeeded. */
         else if (!ret) {
            dialogue_msg( "Update Completed",
                  "Configuration files were successfully migrated. Naev will now restart." );
            execv(argv[0], argv);
         }
         else { /* I sincerely hope this else is never hit. */
            dialogue_alert( "The update script encountered an error. Please exit Naev and move your config and save files manually:\n\n"
                  "\er%s/%s\e0 =>\n   \eD%s\e0\n\n"
                  "\er%s/%s\e0 =>\n   \eD%s\e0\n\n"
                  "\er%s/%s\e0 =>\n   \eD%snebula/\e0\n\n",
                  home, ".naev/conf.lua", nfile_configPath(),
                  home, ".naev/{saves,screenshots}/", nfile_dataPath(),
                  home, ".naev/gen/*.png", nfile_cachePath() );
         }
      }
      else {
int
main ()
{
	SDL_Rect r;
	SDL_Event ev;

	if (SDL_Init (SDL_INIT_VIDEO) < 0) {
		fprintf (stderr, "SDL_Init error\n");
		exit (1);
	}


	if (SDL_InitSubSystem (SDL_INIT_AUDIO < 0)) {
		printf ("no audio\n");
	} else {
		printf ("audio initialized\n");
		have_audio = 1;
	}

	if ((sur = SDL_SetVideoMode (320, 200, 24, SDL_HWSURFACE | SDL_DOUBLEBUF)) == NULL) {
		fprintf (stderr, "error in SDL_SetVideoMode\n");
		exit (1);
	}

	SDL_EnableUNICODE (1);

	audio_desired.freq = 11025;
	audio_desired.format = AUDIO_U8;
	audio_desired.channels = 1;
	audio_desired.samples = 8192;
	audio_desired.callback = audio_callback;

	if (SDL_OpenAudio (&audio_desired, &audio_obtained) < 0) {
		fprintf (stderr, "error in SDL_OpenAudio\n");
		exit (1);
	}

	test_music ();
	SDL_PauseAudio (0);

	while (1) {
		while (SDL_PollEvent (&ev)) {
			switch (ev.type) {
			case SDL_QUIT:
				exit (0);
				break;
			case SDL_KEYDOWN:
				printf ("got key %d\n", ev.key.keysym.unicode);
				break;

				/* ignore these events */
			case SDL_KEYUP:
			case SDL_ACTIVEEVENT:
			case SDL_MOUSEMOTION:
				break;
			default:
				printf ("got uknown event %d\n", ev.type);
				break;
			}
		}

		r.x = 0; r.y = 0; r.w = 320; r.h = 200;
		SDL_FillRect (sur, &r, 0);

		r.x = 160 + 120 * cos (get_time () * .5 * M_PI);
		r.y = 100;
		r.w = 20;
		r.h = 20;
		SDL_FillRect (sur, &r, 0xff0000);
	
		SDL_Flip (sur);

		usleep (33 * 1000);

	}

	return (0);
}
Beispiel #9
0
void I_InitTimer(void)
{
    // initialize timer
    SDL_InitSubSystem(SDL_INIT_TIMER);
}
Beispiel #10
0
SDLVideo::SDLVideo(int parm)
{
	const SDL_version *SDLVersion = SDL_Linked_Version();

	if(SDLVersion->major != SDL_MAJOR_VERSION
		|| SDLVersion->minor != SDL_MINOR_VERSION)
	{
		I_FatalError("SDL version conflict (%d.%d.%d vs %d.%d.%d dll)\n",
			SDL_MAJOR_VERSION, SDL_MINOR_VERSION, SDL_PATCHLEVEL,
			SDLVersion->major, SDLVersion->minor, SDLVersion->patch);
		return;
	}

	if (SDL_InitSubSystem (SDL_INIT_VIDEO) == -1)
	{
		I_FatalError("Could not initialize SDL video.\n");
		return;
	}

	if(SDLVersion->patch != SDL_PATCHLEVEL)
	{
		Printf_Bold("SDL version warning (%d.%d.%d vs %d.%d.%d dll)\n",
			SDL_MAJOR_VERSION, SDL_MINOR_VERSION, SDL_PATCHLEVEL,
			SDLVersion->major, SDLVersion->minor, SDLVersion->patch);
	}

    // [Russell] - Just for windows, display the icon in the system menu and
    // alt-tab display
    #if WIN32 && !_XBOX
    HICON hIcon = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_ICON1));

    if (hIcon)
    {
        HWND WindowHandle;

        SDL_SysWMinfo wminfo;
        SDL_VERSION(&wminfo.version)
        SDL_GetWMInfo(&wminfo);

        WindowHandle = wminfo.window;

        SendMessage(WindowHandle, WM_SETICON, ICON_SMALL, (LPARAM)hIcon);
        SendMessage(WindowHandle, WM_SETICON, ICON_BIG, (LPARAM)hIcon);
    }
    #endif

    I_SetWindowCaption();

   sdlScreen = NULL;
   infullscreen = false;
   screenw = screenh = screenbits = 0;
   palettechanged = false;

   // Get Video modes
   SDL_PixelFormat fmt;
   fmt.palette = NULL;
   fmt.BitsPerPixel = 8;
   fmt.BytesPerPixel = 1;

   SDL_Rect **sdllist = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_SWSURFACE);

   vidModeIterator = 0;
   vidModeIteratorBits = 8;
   vidModeList.clear();

   if(!sdllist)
   {
	  // no fullscreen modes, but we could still try windowed
	  Printf(PRINT_HIGH, "SDL_ListModes returned NULL. No fullscreen video modes are available.\n");
	  return;
   }
   else if(sdllist == (SDL_Rect **)-1)
   {
      I_FatalError("SDL_ListModes returned -1. Internal error.\n");
      return;
   }
   else
   {
      vidMode_t CustomVidModes[] =
      {
         { 640, 480, 8 }
        ,{ 640, 400, 8 }
        ,{ 320, 240, 8 }
        ,{ 320, 200, 8 }
      };

      // Add in generic video modes reported by SDL
      for(int i = 0; sdllist[i]; ++i)
      {
        vidMode_t vm;

        vm.width = sdllist[i]->w;
        vm.height = sdllist[i]->h;
        vm.bits = 8;

        vidModeList.push_back(vm);
      }

      // Now custom video modes to be added
      for (size_t i = 0; i < STACKARRAY_LENGTH(CustomVidModes); ++i)
        vidModeList.push_back(CustomVidModes[i]);

      // Reverse sort the modes
      std::sort(vidModeList.begin(), vidModeList.end(), std::greater<vidMode_t>());

      // Get rid of any duplicates (SDL some times reports duplicates as well)
      vidModeList.erase(std::unique(vidModeList.begin(), vidModeList.end()), vidModeList.end());
   }
}
Beispiel #11
0
BOOL scrnmng_create(int width, int height) {

    char			s[256];
    const SDL_VideoInfo	*vinfo;
    SDL_Surface		*surface;
    SDL_PixelFormat	*fmt;
    BOOL			r;

    if (SDL_InitSubSystem(SDL_INIT_VIDEO | SDL_INIT_TIMER) < 0) {
        fprintf(stderr, "Error: SDL_Init: %s\n", SDL_GetError());
        return(FAILURE);
    }
    SDL_WM_SetCaption(app_name, app_name);
    vinfo = SDL_GetVideoInfo();
    if (vinfo == NULL) {
        fprintf(stderr, "Error: SDL_GetVideoInfo: %s\n", SDL_GetError());
        return(FAILURE);
    }
    SDL_VideoDriverName(s, sizeof(s));

    surface = SDL_SetVideoMode(width, height, vinfo->vfmt->BitsPerPixel,
                               SDL_HWSURFACE | SDL_ANYFORMAT | SDL_DOUBLEBUF | SDL_FULLSCREEN);
    if (surface == NULL) {
        fprintf(stderr, "Error: SDL_SetVideoMode: %s\n", SDL_GetError());
        return(FAILURE);
    }

    r = FALSE;
    fmt = surface->format;
#if defined(SUPPORT_8BPP)
    if (fmt->BitsPerPixel == 8) {
        r = TRUE;
    }
#endif
#if defined(SUPPORT_16BPP)
    if ((fmt->BitsPerPixel == 16) && (fmt->Rmask == 0xf800) &&
            (fmt->Gmask == 0x07e0) && (fmt->Bmask == 0x001f)) {
        r = TRUE;
    }
#endif
#if defined(SUPPORT_24BPP)
    if (fmt->BitsPerPixel == 24) {
        r = TRUE;
    }
#endif
#if defined(SUPPORT_32BPP)
    if (fmt->BitsPerPixel == 32) {
        r = TRUE;
    }
#endif
#if defined(SCREEN_BPP)
    if (fmt->BitsPerPixel != SCREEN_BPP) {
        r = FALSE;
    }
#endif
    if (r) {
        scrnmng.enable = TRUE;
        scrnmng.width = width;
        scrnmng.height = height;
        scrnmng.bpp = fmt->BitsPerPixel;
        return(SUCCESS);
    }
    else {
        fprintf(stderr, "Error: Bad screen mode");
        return(FAILURE);
    }
}
Beispiel #12
0
qboolean
SNDDMA_Init (void)
{
	SDL_AudioSpec desired, obtained;
	int desired_bits, freq;
	
	if (SDL_WasInit(SDL_INIT_EVERYTHING) == 0) {
		if (SDL_Init(SDL_INIT_AUDIO) < 0) {
			Com_Printf ("Couldn't init SDL audio: %s\n", SDL_GetError ());
			return 0;
		}
	} else if (SDL_WasInit(SDL_INIT_AUDIO) == 0) {
		if (SDL_InitSubSystem(SDL_INIT_AUDIO) < 0) {
			Com_Printf ("Couldn't init SDL audio: %s\n", SDL_GetError ());
			return 0;
		}
	}
	
	snd_inited = 0;
	desired_bits = (Cvar_Get("sndbits", "16", CVAR_ARCHIVE))->value;

	/* Set up the desired format */
	freq = (Cvar_Get("s_khz", "0", CVAR_ARCHIVE))->value;
	if (freq == 44)
		desired.freq = 44100;
	else if (freq == 22)
		desired.freq = 22050;
	else
		desired.freq = 11025;
	
	switch (desired_bits) {
		case 8:
			desired.format = AUDIO_U8;
			break;
		case 16:
			if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
				desired.format = AUDIO_S16MSB;
			else
				desired.format = AUDIO_S16LSB;
			break;
		default:
			Com_Printf ("Unknown number of audio bits: %d\n", desired_bits);
			return 0;
	}
	desired.channels = (Cvar_Get("sndchannels", "2", CVAR_ARCHIVE))->value;
	
	if (desired.freq == 44100)
		desired.samples = 2048;
	else if (desired.freq == 22050)
		desired.samples = 1024;
	else
		desired.samples = 512;
	
	desired.callback = paint_audio;
	
	/* Open the audio device */
	if (SDL_OpenAudio (&desired, &obtained) < 0) {
		Com_Printf ("Couldn't open SDL audio: %s\n", SDL_GetError ());
		return 0;
	}

	/* Make sure we can support the audio format */
	switch (obtained.format) {
		case AUDIO_U8:
			/* Supported */
			break;
		case AUDIO_S16LSB:
		case AUDIO_S16MSB:
			if (((obtained.format == AUDIO_S16LSB) &&
				 (SDL_BYTEORDER == SDL_LIL_ENDIAN)) ||
				((obtained.format == AUDIO_S16MSB) &&
				 (SDL_BYTEORDER == SDL_BIG_ENDIAN))) {
				/* Supported */
				break;
			}
			/* Unsupported, fall through */ ;
		default:
			/* Not supported -- force SDL to do our bidding */
			SDL_CloseAudio ();
			if (SDL_OpenAudio (&desired, NULL) < 0) {
				Com_Printf ("Couldn't open SDL audio: %s\n", SDL_GetError ());
				return 0;
			}
			memcpy (&obtained, &desired, sizeof (desired));
			break;
	}
	SDL_PauseAudio (0);

	/* Fill the audio DMA information block */
	shm = &dma;
	shm->samplebits = (obtained.format & 0xFF);
	shm->speed = obtained.freq;
	shm->channels = obtained.channels;
	shm->samples = obtained.samples * shm->channels;
	shm->samplepos = 0;
	shm->submission_chunk = 1;
	shm->buffer = NULL;

	snd_inited = 1;
	return 1;
}
Beispiel #13
0
EXPORT(bool) InitVideo(int w, int h, std::string sphere_dir)
{

    ScreenWidth  = w;
    ScreenHeight = h;

    static bool firstcall = true;

    // Center the window on the display
    putenv("SDL_VIDEO_CENTERED=1");

    if (firstcall)
    {
        LoadConfiguration(sphere_dir);

        if (!InitScreenBuffer())
            return false;

        // initialize SDL
        // Note: SDL_INIT_EVENTTHREAD is currently not supported on Mac OS X
        if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) == -1)
        {
            fprintf(stderr, "Could not initialize SDL:\n%s\n", SDL_GetError());
            return false;
        }

        SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);

        firstcall  = false;

    }
    else
    {
        // reinitialize the screen buffer, because the new resolution can differ
        if (!InitScreenBuffer())
        {
            SDL_Quit();
            return false;
        }

        // reinitialize the SDL video subsystem
        SDL_QuitSubSystem(SDL_INIT_VIDEO);

        if (SDL_InitSubSystem(SDL_INIT_VIDEO) == -1)
        {
            fprintf(stderr, "Could not initialize video:\n%s\n", SDL_GetError());
            return false;
        }

        // keep the window title as what it was
        SetWindowTitle(WindowTitle.c_str());
    }

    int s_width  = ScreenBufferWidth  * (Config.scale ? 2 : 1);
    int s_height = ScreenBufferHeight * (Config.scale ? 2 : 1);

    dword flags = 0;
    if (Config.fullscreen)  flags |= SDL_FULLSCREEN;
    if (Config.vsync)       flags |= SDL_HWSURFACE | SDL_DOUBLEBUF;
    else                    flags |= SDL_SWSURFACE;

    // set up the video surface
    SDLScreenBuffer = SDL_SetVideoMode(s_width, s_height, 32, flags);

    if (SDLScreenBuffer == NULL)
    {
        fprintf(stderr, "Could not set video mode:\n%s\n", SDL_GetError());
        return false;
    }

    SDL_ShowCursor(false);
    SetClippingRectangle(0, 0, SDLScreenBuffer->w, SDLScreenBuffer->h);

    return true;
}
SCA_Joystick *SCA_Joystick::GetInstance( short int joyindex )
{
#ifndef WITH_SDL
	return NULL;
#else  /* WITH_SDL */
	if (joyindex < 0 || joyindex >= JOYINDEX_MAX) {
		ECHO("Error-invalid joystick index: " << joyindex);
		return NULL;
	}

	if (m_refCount == 0) 
	{
		int i;
		/* The video subsystem is required for joystick input to work. However,
		 * when GHOST is running under SDL, video is initialized elsewhere.
		 * Do this once only. */
#  ifdef WITH_GHOST_SDL
		if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) == -1 ) {
#  else
		if (SDL_InitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_VIDEO) == -1 ) {
#  endif
			ECHO("Error-Initializing-SDL: " << SDL_GetError());
			return NULL;
		}
		
		m_joynum = SDL_NumJoysticks();
		
		for (i=0; i<JOYINDEX_MAX; i++) {
			m_instance[i] = new SCA_Joystick(i);
			m_instance[i]->CreateJoystickDevice();
		}
		m_refCount = 1;
	}
	else
	{
		m_refCount++;
	}
	return m_instance[joyindex];
#endif /* WITH_SDL */
}

void SCA_Joystick::ReleaseInstance()
{
	if (--m_refCount == 0)
	{
#ifdef WITH_SDL
		int i;
		for (i=0; i<JOYINDEX_MAX; i++) {
			if (m_instance[i]) {
				m_instance[i]->DestroyJoystickDevice();
				delete m_instance[i];
			}
			m_instance[i] = NULL;
		}

		/* The video subsystem is required for joystick input to work. However,
		 * when GHOST is running under SDL, video is freed elsewhere.
		 * Do this once only. */
#  ifdef WITH_GHOST_SDL
		SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
#  else
		SDL_QuitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_VIDEO);
#  endif
#endif /* WITH_SDL */
	}
}

void SCA_Joystick::cSetPrecision(int val)
{
	m_prec = val;
}


bool SCA_Joystick::aAxisPairIsPositive(int axis)
{
	return (pAxisTest(axis) > m_prec) ? true:false;
}

bool SCA_Joystick::aAxisPairDirectionIsPositive(int axis, int dir)
{

	int res;

	if (dir==JOYAXIS_UP || dir==JOYAXIS_DOWN)
		res = pGetAxis(axis, 1);
	else /* JOYAXIS_LEFT || JOYAXIS_RIGHT */
		res = pGetAxis(axis, 0);
	
	if (dir==JOYAXIS_DOWN || dir==JOYAXIS_RIGHT)
		return (res > m_prec) ? true : false;
	else /* JOYAXIS_UP || JOYAXIS_LEFT */
		return (res < -m_prec) ? true : false;
}
Beispiel #15
0
void Audio::start_audio()
{
    if (!sound_enabled)
    {
        // Since many GNU/Linux distros are infected with PulseAudio, SDL2 could chose PA as first
	// driver option before ALSA, and PA doesn't obbey our sample number requests, resulting
	// in audio gaps, if we're on a GNU/Linux we force ALSA.
	// Else we accept whatever SDL2 wants to give us or what the user specifies on SDL_AUDIODRIVER
	// enviroment variable.
	std::string platform = SDL_GetPlatform();
	if (platform=="Linux"){

	    if (SDL_InitSubSystem(SDL_INIT_AUDIO)!=0) {

		std::cout << "Error initalizing audio subsystem: " << SDL_GetError() << std::endl;
	    }

	    if (SDL_AudioInit("alsa")!=0) {
		std::cout << "Error initalizing audio using ALSA: " << SDL_GetError() << std::endl;
		return;
	    }

	}
	else {
	    if(SDL_Init(SDL_INIT_AUDIO) == -1) 
	    {
		std::cout << "Error initalizing audio: " << SDL_GetError() << std::endl;
		return;
	    }		
	}

        // SDL Audio Properties
        SDL_AudioSpec desired, obtained;

        desired.freq     = FREQ;
        desired.format   = AUDIO_S16SYS;
        desired.channels = CHANNELS;
        desired.samples  = SAMPLES;
        desired.callback = fill_audio;
        desired.userdata = NULL;
	
	// SDL2 block
	dev = SDL_OpenAudioDevice(NULL, 0, &desired, &obtained, /*SDL_AUDIO_ALLOW_FORMAT_CHANGE*/0);
	if (dev == 0)
	{
            std::cout << "Error opening audio device: " << SDL_GetError() << std::endl;
            return;
        }

        if (desired.samples != obtained.samples) {
            std::cout << "Error initalizing audio: number of samples not supported." << std::endl
                      << "Please compare desired vs obtained. Look at what audio driver SDL2 is using." << std::endl;
	    return;
	}

        bytes_per_sample = CHANNELS * (BITS / 8);

        // Start Audio
        sound_enabled = true;

        // how many fragments in the dsp buffer
        const int DSP_BUFFER_FRAGS = 5;
        int specified_delay_samps = (FREQ * SND_DELAY) / 1000;
        int dsp_buffer_samps = SAMPLES * DSP_BUFFER_FRAGS + specified_delay_samps;
        dsp_buffer_bytes = CHANNELS * dsp_buffer_samps * (BITS / 8);
        dsp_buffer = new uint8_t[dsp_buffer_bytes];

        // Create Buffer For Mixing
        uint16_t buffer_size = (FREQ / config.fps) * CHANNELS;
        mix_buffer = new uint16_t[buffer_size];

        clear_buffers();
        clear_wav();

        SDL_PauseAudioDevice(dev,0);
    }
}
Beispiel #16
0
EXPORT void CALL DllTest ( HWND hParent )
{
    // Defining flags for tests
    BOOL init_audio = FALSE;
    BOOL init_timer = FALSE;
    BOOL open_audio_device = FALSE;
    BOOL format_match = FALSE;
    BOOL freq_match = FALSE;

    // Storage for SDL_Errors.
    char *sdl_error[3];

    // Clear the pointers (Should not be truly necessary unless something horrible goes wrong)
    memset(sdl_error, 0, sizeof(char*[3]));

    // Print out inital message
    printf("[JttL's SDL Audio plugin] Starting Audio Test.\n");

    // Make Sure SDL Audio is disabled so we can restart fresh
    SDL_PauseAudio(1);
    SDL_CloseAudio();

    // Quit the subsystems before attempting to reinitalize them, if either are initalized already
    if(SDL_WasInit(SDL_INIT_AUDIO) != 0) SDL_QuitSubSystem(SDL_INIT_AUDIO);
    if(SDL_WasInit(SDL_INIT_TIMER) != 0) SDL_QuitSubSystem(SDL_INIT_TIMER);

    // Attempt to initialize SDL Audio
    if(SDL_Init(SDL_INIT_AUDIO) < 0 )
    {
        sdl_error[0] = SDL_GetError();
        printf("[JttL's SDL Audio plugin] Error: Couldn't initialize audio subsystem: %s\n", sdl_error[0]);
        init_audio = FALSE;
    }
    else
    {
        printf("[JttL's SDL Audio plugin] Audio subsystem initialized.\n");
        init_audio = TRUE;
    }

    // Attempt to initialize SDL Timer
    if(SDL_InitSubSystem(SDL_INIT_TIMER) < 0 )
    {
        sdl_error[1] = SDL_GetError();
        printf("[JttL's SDL Audio plugin] Error: Couldn't initialize timer subsystem: %s\n", sdl_error[1]);
        init_timer = FALSE;
    }
    else
    {
        printf("[JttL's SDL Audio plugin] Timer subsystem initialized.\n");
        init_timer = TRUE;
    }

    // Close the audio device
    SDL_PauseAudio(1);
    SDL_CloseAudio();

    // Prototype of our callback function
    void my_audio_callback(void *userdata, Uint8 *stream, int len);

    // Open the audio device
    SDL_AudioSpec *desired, *obtained;

    // Allocate a desired SDL_AudioSpec
    desired = malloc(sizeof(SDL_AudioSpec));

    // Allocate space for the obtained SDL_AudioSpec
    obtained = malloc(sizeof(SDL_AudioSpec));

    // 22050Hz - FM Radio quality
    desired->freq=GameFreq;

    // Print out message for frequency
    printf("[JttL's SDL Audio plugin] Requesting frequency: %iHz.\n", desired->freq);

    // 16-bit signed audio
    desired->format=AUDIO_S16SYS;

    // Print out message for format
    printf("[JttL's SDL Audio plugin] Requesting format: %i.\n", desired->format);

    // Enable two hardware channels (for Stereo output)
    desired->channels=2;

    // Large audio buffer reduces risk of dropouts but increases response time
    desired->samples=SecondaryBufferSize;

    // Our callback function
    desired->callback=my_audio_callback;
    desired->userdata=NULL;

    // Open the audio device
    if ( SDL_OpenAudio(desired, obtained) < 0 )
    {
        sdl_error[2] = SDL_GetError();
        fprintf(stderr, "[JttL's SDL Audio plugin] Error: Couldn't open audio device: %s\n", sdl_error[2]);
        open_audio_device = FALSE;
    }
    else 
    {
        open_audio_device = TRUE;
    }

    // Check to see if we have the audio format we requested.
    if(desired->format != obtained->format)
    {
        fprintf(stderr, "[JttL's SDL Audio plugin] Error: Obtained audio format differs from requested.\n");
        format_match = FALSE;
    }
    else
    {
        format_match = TRUE;
    }

    // Check to see if we have the frequency we requested.
    if(desired->freq != obtained->freq)
    {
        fprintf(stderr, "[JttL's SDL Audio plugin] Error: Obtained frequency differs from requested.\n");
        freq_match = FALSE;
    }
    else 
    {
        freq_match = TRUE;
    }

    // Free no longer needed objects used for testing the specifications.
    free(desired);
    free(obtained);

    // Uninitialize SDL audio, as it is no longer needed.
    SDL_PauseAudio(1);
    SDL_CloseAudio();

    // Quit the Audio and Timer subsystems if they are enabled. (They should be, unless something went horribly wrong.)
    if(SDL_WasInit(SDL_INIT_AUDIO) != 0) SDL_QuitSubSystem(SDL_INIT_AUDIO);
    if(SDL_WasInit(SDL_INIT_TIMER) != 0) SDL_QuitSubSystem(SDL_INIT_TIMER);

    char tMsg[1024];

    if((init_audio == TRUE) && ( init_timer == TRUE ) && ( open_audio_device == TRUE ) && (format_match == TRUE) && (freq_match == TRUE)) 
    {
        sprintf(tMsg,"[JttL's SDL Audio plugin] Audio test successful.");
        critical_failure = 0;
    }
    else 
    {
        sprintf(tMsg,"[JttL's SDL Audio plugin] Test Results\n--\n");
        if(init_audio != TRUE)
        {
            sprintf(tMsg, "%sError initalizing SDL Audio:\n - %s\n", tMsg,sdl_error[0]);
        }
        if(init_timer != TRUE)
        {
            sprintf(tMsg, "%sError initalizing SDL Timer:\n - %s\n", tMsg,sdl_error[1]);
        }
        if(open_audio_device != TRUE)
        {
            sprintf(tMsg, "%sError opening audio device:\n - %s\n", tMsg,sdl_error[2]);
        }
        if(format_match != TRUE)
        {
            sprintf(tMsg, "%sUnable to get the requested output audio format.\n", tMsg);
        }
        if(freq_match != TRUE)
        {
            sprintf(tMsg, "%sUnable to get the requested output frequency.\n", tMsg);
        }
        critical_failure = 1;
    }

    display_test(tMsg);
}
Beispiel #17
0
void sdl_osd_interface::init(running_machine &machine)
{
	// call our parent
	osd_common_t::init(machine);

	const char *stemp;

	// Switchres
	switchres_init_osd(machine);
	switchres_modeline_setup(machine);

	// determine if we are benchmarking, and adjust options appropriately
	int bench = options().bench();
	std::string error_string;
	if (bench > 0)
	{
		options().set_value(OPTION_THROTTLE, false, OPTION_PRIORITY_MAXIMUM, error_string);
		options().set_value(OSDOPTION_SOUND, "none", OPTION_PRIORITY_MAXIMUM, error_string);
		options().set_value(OSDOPTION_VIDEO, "none", OPTION_PRIORITY_MAXIMUM, error_string);
		options().set_value(OPTION_SECONDS_TO_RUN, bench, OPTION_PRIORITY_MAXIMUM, error_string);
		assert(error_string.c_str()[0] == 0);
	}

	// Some driver options - must be before audio init!
	stemp = options().audio_driver();
	if (stemp != NULL && strcmp(stemp, OSDOPTVAL_AUTO) != 0)
	{
		osd_printf_verbose("Setting SDL audiodriver '%s' ...\n", stemp);
		osd_setenv(SDLENV_AUDIODRIVER, stemp, 1);
	}

	stemp = options().video_driver();
	if (stemp != NULL && strcmp(stemp, OSDOPTVAL_AUTO) != 0)
	{
		osd_printf_verbose("Setting SDL videodriver '%s' ...\n", stemp);
		osd_setenv(SDLENV_VIDEODRIVER, stemp, 1);
	}

#if (SDLMAME_SDL2)
		stemp = options().render_driver();
		if (stemp != NULL)
		{
			if (strcmp(stemp, OSDOPTVAL_AUTO) != 0)
			{
				osd_printf_verbose("Setting SDL renderdriver '%s' ...\n", stemp);
				//osd_setenv(SDLENV_RENDERDRIVER, stemp, 1);
				SDL_SetHint(SDL_HINT_RENDER_DRIVER, stemp);
			}
			else
			{
#if defined(SDLMAME_WIN32)
				// OpenGL renderer has less issues with mode switching on windows
				osd_printf_verbose("Setting SDL renderdriver '%s' ...\n", "opengl");
				//osd_setenv(SDLENV_RENDERDRIVER, stemp, 1);
				SDL_SetHint(SDL_HINT_RENDER_DRIVER, "opengl");
#endif
			}
		}
#endif

	/* Set the SDL environment variable for drivers wanting to load the
	 * lib at startup.
	 */
#if USE_OPENGL
	/* FIXME: move lib loading code from drawogl.c here */

	stemp = options().gl_lib();
	if (stemp != NULL && strcmp(stemp, OSDOPTVAL_AUTO) != 0)
	{
		osd_setenv("SDL_VIDEO_GL_DRIVER", stemp, 1);
		osd_printf_verbose("Setting SDL_VIDEO_GL_DRIVER = '%s' ...\n", stemp);
	}
#endif

	/* get number of processors */
	stemp = options().numprocessors();

	osd_num_processors = 0;

	if (strcmp(stemp, "auto") != 0)
	{
		osd_num_processors = atoi(stemp);
		if (osd_num_processors < 1)
		{
			osd_printf_warning("numprocessors < 1 doesn't make much sense. Assuming auto ...\n");
			osd_num_processors = 0;
		}
	}

	/* Initialize SDL */

	if (!SDLMAME_INIT_IN_WORKER_THREAD)
	{
#if (SDLMAME_SDL2)
#ifdef SDLMAME_EMSCRIPTEN
		// timer brings in threads which are not supported in Emscripten
		if (SDL_InitSubSystem(SDL_INIT_VIDEO| SDL_INIT_JOYSTICK|SDL_INIT_NOPARACHUTE)) {
#else
		if (SDL_InitSubSystem(SDL_INIT_TIMER| SDL_INIT_VIDEO| SDL_INIT_JOYSTICK|SDL_INIT_NOPARACHUTE)) {
#endif
#else
		if (SDL_Init(SDL_INIT_TIMER|SDL_INIT_VIDEO| SDL_INIT_JOYSTICK|SDL_INIT_NOPARACHUTE)) {
#endif
			osd_printf_error("Could not initialize SDL %s\n", SDL_GetError());
			exit(-1);
		}
		osd_sdl_info();
	}

	defines_verbose();

	osd_common_t::init_subsystems();

	if (options().oslog())
		machine.add_logerror_callback(output_oslog);

	/* now setup watchdog */

	int watchdog_timeout = options().watchdog();

	if (watchdog_timeout != 0)
	{
		m_watchdog = auto_alloc(machine, watchdog);
		m_watchdog->setTimeout(watchdog_timeout);
	}

#if (SDLMAME_SDL2)
#ifdef SDLMAME_EMSCRIPTEN
	SDL_EventState(SDL_TEXTINPUT, SDL_FALSE);
#else
	SDL_EventState(SDL_TEXTINPUT, SDL_TRUE);
#endif
#else
	SDL_EnableUNICODE(SDL_TRUE);
#endif
}
int joy_init()
{
	int i, n;

	if (Joy_inited)
		return 0;

	if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) < 0) {
		mprintf(("Could not initialize joystick\n"));
		return 0;
	}

	// enable event processing of the joystick
	if ( (SDL_JoystickEventState(SDL_ENABLE)) != SDL_ENABLE ) {
		mprintf(("ERROR: Unable to initialize joystick event processing!\n"));
		SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
		return 0;
	}

	n = SDL_NumJoysticks();

	if (n < 1) {
		mprintf(("No joysticks found\n"));
		SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
		return 0;
	}

	joy_get_caps(n);

	Cur_joystick = os_config_read_uint(NULL, "CurrentJoystick", JOYSTICKID1);

	sdljoy = SDL_JoystickOpen(Cur_joystick);

	if (sdljoy == NULL) {
		mprintf(("Unable to init joystick %d\n", Cur_joystick));
		SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
		return 0;
	}

	joy_flush();

	joy_num_sticks = n;

	joy_num_buttons = SDL_JoystickNumButtons(sdljoy);
	joy_num_axes = SDL_JoystickNumAxes(sdljoy);
	joy_num_hats = SDL_JoystickNumHats(sdljoy);

	mprintf(( "\nJoystick INITTED!\n\n" ));
	mprintf(( "Using '%s' as the primary joystick:\n", SDL_JoystickName(SDL_JoystickOpen(Cur_joystick)) ));
	mprintf(( "  Number of axes: %i\n", joy_num_axes ));
	mprintf(( "  Number of buttons: %i\n", joy_num_buttons ));
	mprintf(( "  Number of hats: %i\n", joy_num_hats ));
	mprintf(( "  Number of trackballs: %i\n\n", SDL_JoystickNumBalls(sdljoy) ));

	// Fake a calibration
	if (joy_num_sticks > 0) {
		for (i=0; i<JOY_NUM_AXES; i++) {
			joystick.axis_center[i] = 32768;
			joystick.axis_min[i] = 0;
			joystick.axis_max[i] = 65536;
		}
	}

	// we poll for axis type motion so be sure to ignore that during normal event state polling
	SDL_EventState( SDL_JOYAXISMOTION, SDL_IGNORE );
	SDL_EventState( SDL_JOYBALLMOTION, SDL_IGNORE );

	// we do want to make sure that hat/button presses go through event polling though
	// (should be on by default already, just here as a reminder)
	SDL_EventState( SDL_JOYBUTTONDOWN, SDL_ENABLE );
	SDL_EventState( SDL_JOYBUTTONUP, SDL_ENABLE );
	SDL_EventState( SDL_JOYHATMOTION, SDL_ENABLE );

	Joy_inited = 1;

	return joy_num_sticks;
}
Beispiel #19
0
bool init(int flags) {
	
	if (SDL_InitSubSystem(SDL_INIT_VIDEO) == 0) {
		sub_inited = true;
		
		SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8);
		SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 8);
		SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8);
		if (flags & NEED_ACCUM) {
			SDL_GL_SetAttribute( SDL_GL_ACCUM_RED_SIZE, 16);
			SDL_GL_SetAttribute( SDL_GL_ACCUM_GREEN_SIZE, 16);
			SDL_GL_SetAttribute( SDL_GL_ACCUM_BLUE_SIZE, 16);
		}
		//SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 8);
		//SDL_GL_SetAttribute( SDL_GL_BUFFER_SIZE, 32);
		SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 24);
		if (flags & NEED_STENCIL) {
			SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, 8);
		}
		SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1);
		if (flags & WANT_VSYNC) {
			#ifdef SDL_GL_SWAP_CONTROL
			SDL_GL_SetAttribute( SDL_GL_SWAP_CONTROL, 1);
			#else
			cerr << "Using a version of SDL that doesn't support VSYNC." << endl;
			#endif
		}
		if (flags & WANT_MULTISAMPLE4) {
			SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, 1 );
			SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, 4 );
		}
		if (flags & WANT_MULTISAMPLE8) {
			SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, 1 );
			SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, 8 );
		}
		if (flags & WANT_MULTISAMPLE16) {
			SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, 1 );
			SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, 16 );
		}

		if (fullscreen) {
			surface = SDL_SetVideoMode(screen_x, screen_y, 24, SDL_OPENGL | SDL_FULLSCREEN);
		} else {
			surface = SDL_SetVideoMode(screen_x, screen_y, 24, SDL_OPENGL);
		}

		if (surface) {
			inited = true;
		} else {
			cerr << "Could not create video surface: " << SDL_GetError() << endl;
		}
	} else {
		cerr << "Could not init video: " << SDL_GetError() << endl;
	}

	if (sub_inited && !inited) {
		deinit();
	}

	if (inited) {
		while (!get_init_funcs().empty()) {
			get_init_funcs().back().first(get_init_funcs().back().second);
			get_init_funcs().pop_back();
		}
	}
	
	return inited;

}
Beispiel #20
0
int InitVideo(FCEUGI *gi)
{
	// This is a big TODO.  Stubbing this off into its own function,
	// as the SDL surface routines have changed drastically in SDL2
	// TODO - SDL2
	const char * window_name;
	int error, flags = 0;
	int doublebuf, xstretch, ystretch, xres, yres, show_fps;
	uint32_t  Amask, Rmask, Gmask, Bmask;
	int   bpp;

	FCEUI_printf("Initializing video (SDL2.x) ...");

	// load the relevant configuration variables
	g_config->getOption("SDL.Fullscreen", &s_fullscreen);
	g_config->getOption("SDL.DoubleBuffering", &doublebuf);
#ifdef OPENGL
	g_config->getOption("SDL.OpenGL", &s_useOpenGL);
#endif
	g_config->getOption("SDL.SpecialFilter", &s_sponge);
	g_config->getOption("SDL.XStretch", &xstretch);
	g_config->getOption("SDL.YStretch", &ystretch);
	g_config->getOption("SDL.LastXRes", &xres);
	g_config->getOption("SDL.LastYRes", &yres);
	g_config->getOption("SDL.ClipSides", &s_clipSides);
	g_config->getOption("SDL.NoFrame", &noframe);
	g_config->getOption("SDL.ShowFPS", &show_fps);

	// check the starting, ending, and total scan lines
	FCEUI_GetCurrentVidSystem(&s_srendline, &s_erendline);
	s_tlines = s_erendline - s_srendline + 1;

#if OPENGL
	if( !s_useOpenGL || s_sponge )
	{
		FCEUD_PrintError("SDL2 Does not support non-OpenGL rendering or special filters\n");
		KillVideo();
		return -1;
	}
#endif

	// initialize the SDL video subsystem if it is not already active
	if(!SDL_WasInit(SDL_INIT_VIDEO)) {
		error = SDL_InitSubSystem(SDL_INIT_VIDEO);
		if(error) {
			FCEUD_PrintError(SDL_GetError());
			return -1;
		}
	}
	s_inited = 1;

	// For simplicity, hard-code this to 32bpp for now...
	s_curbpp = 32;

	// If game is running, set window name accordingly
	if( gi )
	{
		window_name = (const char *) gi->name;
	}
	else
	{
		window_name = "FCE Ultra";
	}

	s_exs = 1.0;
	s_eys = 1.0;
	if(s_fullscreen) {
		s_window = SDL_CreateWindow( window_name,
		                             SDL_WINDOWPOS_UNDEFINED,
		                             SDL_WINDOWPOS_UNDEFINED,
		                             0, 0,  // Res not specified in full-screen mode
		                             SDL_WINDOW_FULLSCREEN_DESKTOP);
	} else {
#if defined(_GTK) && defined(SDL_VIDEO_DRIVER_X11)
		if(noGui == 0 && strcmp(SDL_GetCurrentVideoDriver(), "x11") == 0) {
			s_window = SDL_CreateWindowFrom((void*)GDK_WINDOW_XID (gtk_widget_get_window(evbox)));
		}
		else
#endif
			s_window = SDL_CreateWindow( window_name,
				                         SDL_WINDOWPOS_UNDEFINED,
				                         SDL_WINDOWPOS_UNDEFINED,
				                         xres, yres,
				                         0);
	}

	// This stuff all applies regardless of full-screen vs windowed mode.
	s_renderer =  SDL_CreateRenderer(s_window, -1, 0);

	// Set logical rendering size & specify scaling mode.  All rendering is
	// now done to the renderer rather than directly to the screen surface.
	// The renderer takes care of any scaling necessary.
	//
	// NOTE: setting scale quality to "nearest" will result in a blown-up but
	// pixelated while "linear" will tend to blur everything.
	SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "nearest");
	SDL_RenderSetLogicalSize(s_renderer, xres, yres);


	//
	// Create the texture that will ultimately be rendered.
	// s_screen is used to build up an image, then the texture will be updated
	// all at once when it's ready
	s_texture = SDL_CreateTexture(s_renderer,
	                              SDL_PIXELFORMAT_ARGB8888,
	                              SDL_TEXTUREACCESS_STREAMING,
	                              xres, yres);
	//
	// Create a surface to draw pixels onto
	//
	SDL_PixelFormatEnumToMasks(SDL_PIXELFORMAT_ARGB8888, &bpp, &Rmask, &Gmask, &Bmask, &Amask);
	s_screen = SDL_CreateRGBSurface(0, xres, yres, bpp,
	                                Rmask, Gmask, Bmask, Amask);

	if( !s_screen )
	{
		FCEUD_PrintError(SDL_GetError());
		return -1;
	}

	//
	// Setup Icon surface
	//
#ifdef LSB_FIRST
	s_IconSurface = SDL_CreateRGBSurfaceFrom((void *)fceu_playicon.pixel_data,
	                32, 32, 24, 32 * 3,
	                0xFF, 0xFF00, 0xFF0000, 0x00);
#else
	s_IconSurface = SDL_CreateRGBSurfaceFrom((void *)fceu_playicon.pixel_data,
	                32, 32, 24, 32 * 3,
	                0xFF0000, 0xFF00, 0xFF, 0x00);
#endif

	SDL_SetWindowIcon(s_window, s_IconSurface);

	s_paletterefresh = 1;   // Force palette refresh

	// always init blit to high since bpp forced to 32 for now.
	InitBlitToHigh(s_curbpp >> 3,
	               s_screen->format->Rmask,
	               s_screen->format->Gmask,
	               s_screen->format->Bmask,
	               0, //s_eefx,  Hard-code SFX off
	               0, //s_sponge,  Hard-code special filters off.
	               0);

	return 0;
}
Beispiel #21
0
void setup (void) {
	SDL_Surface * image;
	TTF_Font *temp1, *temp2;
	SDL_Color color;
	SDL_Rect rect, rect2;
	int g;
	char buffer_file[8192];
	char *systemdata_path = get_systemdata_path ();
	
	/* Inicializar el Video SDL */
	if (SDL_Init(SDL_INIT_VIDEO) < 0) {
		fprintf (stderr,
			_("Error: Can't initialize the video subsystem\n"
			"The error returned by SDL is:\n"
			"%s\n"), SDL_GetError());
		exit (1);
	}
	sprintf (buffer_file, "%simages/icon.png", systemdata_path);
	image = IMG_Load (buffer_file);
	if (image) {
		SDL_WM_SetIcon (image, NULL);
		SDL_FreeSurface (image);
	}
	SDL_WM_SetCaption (_("Paddle Puffle"), _("Paddle Puffle"));
	
	/* Crear la pantalla de dibujado */
	screen = set_video_mode (0);
	
	if (screen == NULL) {
		fprintf (stderr,
			_("Error: Can't setup 760x480 video mode.\n"
			"The error returned by SDL is:\n"
			"%s\n"), SDL_GetError());
		exit (1);
	}
	
	use_sound = 1;
	if (SDL_InitSubSystem (SDL_INIT_AUDIO) < 0) {
		fprintf (stdout,
			_("Warning: Can't initialize the audio subsystem\n"
			"Continuing...\n"));
		use_sound = 0;
	}
	
	if (use_sound) {
		/* Inicializar el sonido */
		if (Mix_OpenAudio (22050, AUDIO_S16, 2, 4096) < 0) {
			fprintf (stdout,
				_("Warning: Can't initialize the SDL Mixer library\n"));
			use_sound = 0;
		}
	}
	
	for (g = 0; g < NUM_IMAGES; g++) {
		sprintf (buffer_file, "%s%s", systemdata_path, images_names[g]);
		image = IMG_Load (buffer_file);
		
		if (image == NULL) {
			fprintf (stderr,
				_("Failed to load data file:\n"
				"%s\n"
				"The error returned by SDL is:\n"
				"%s\n"), buffer_file, SDL_GetError());
			SDL_Quit ();
			exit (1);
		}
		
		images[g] = image;
		/* TODO: Mostrar la carga de porcentaje */
	}
	
	/* Pre-Dibujar la pantalla gris */
	grey_screen = SDL_CreateRGBSurface (SDL_SWSURFACE | SDL_SRCALPHA, 760, 480, 32, 0, 0, 0, 0);
	SDL_FillRect (grey_screen, NULL,
	              SDL_MapRGB (grey_screen->format, 0, 0, 0)); /* Negro */
	SDL_SetAlpha (grey_screen, SDL_SRCALPHA, 128); /* Alpha al 50 % */
	
	if (use_sound) {
		for (g = 0; g < NUM_SOUNDS; g++) {
			sprintf (buffer_file, "%s%s", systemdata_path, sound_names[g]);
			sounds[g] = Mix_LoadWAV (buffer_file);
			
			if (sounds[g] == NULL) {
				fprintf (stderr,
					_("Failed to load data file:\n"
					"%s\n"
					"The error returned by SDL is:\n"
					"%s\n"), buffer_file, SDL_GetError ());
				SDL_Quit ();
				exit (1);
			}
			Mix_VolumeChunk (sounds[g], MIX_MAX_VOLUME / 2);
		}
		
		/* Cargar la música */
		sprintf (buffer_file, "%s%s", systemdata_path, MUS_CARNIE);
		mus_carnie = Mix_LoadMUS (buffer_file);
		
		if (mus_carnie == NULL) {
			fprintf (stderr,
				_("Failed to load data file:\n"
				"%s\n"
				"The error returned by SDL is:\n"
				"%s\n"), buffer_file, SDL_GetError ());
			SDL_Quit ();
			exit (1);
		}
		
	}
	
	if (TTF_Init () < 0) {
		fprintf (stderr,
			_("Error: Can't initialize the SDL TTF library\n"
			"%s\n"), TTF_GetError ());
		SDL_Quit ();
		exit (1);
	}
	
	/* Tipografias 10, 14, 16, 26 */
	sprintf (buffer_file, "%s%s", systemdata_path, "ccfacefront.ttf");
	ttf_facefront = SDL_RWFromFile (buffer_file, "rb");
	
	if (ttf_facefront == NULL) {
		fprintf (stderr,
			_("Failed to load font file 'CCFaceFront'\n"
			"The error returned by SDL is:\n"
			"%s\n"), TTF_GetError ());
		SDL_Quit ();
		exit (1);
	}
	
	SDL_RWseek (ttf_facefront, 0, RW_SEEK_SET);
	temp1 = TTF_OpenFontRW (ttf_facefront, 0, 10);
	SDL_RWseek (ttf_facefront, 0, RW_SEEK_SET);
	ttf14_normal = TTF_OpenFontRW (ttf_facefront, 0, 14);
	SDL_RWseek (ttf_facefront, 0, RW_SEEK_SET);
	ttf16_normal = TTF_OpenFontRW (ttf_facefront, 0, 16);
	SDL_RWseek (ttf_facefront, 0, RW_SEEK_SET);
	ttf26_normal = TTF_OpenFontRW (ttf_facefront, 0, 26);
	
	if (!temp1 || !ttf14_normal || !ttf16_normal || !ttf26_normal) {
		SDL_Quit ();
		exit (1);
	}
	
	SDL_RWseek (ttf_facefront, 0, RW_SEEK_SET);
	ttf20_normal = TTF_OpenFontRW (ttf_facefront, 0, 20);
	SDL_RWseek (ttf_facefront, 0, RW_SEEK_SET);
	ttf20_outline = TTF_OpenFontRW (ttf_facefront, 0, 20);
	SDL_RWseek (ttf_facefront, 0, RW_SEEK_SET);
	ttf16_outline = TTF_OpenFontRW (ttf_facefront, 1, 16);
	
	if (!ttf20_normal || !ttf20_outline || !ttf16_outline) {
		SDL_Quit ();
		exit (1);
	}
	
	TTF_SetFontStyle (temp1, TTF_STYLE_ITALIC);
	TTF_SetFontStyle (ttf14_normal, TTF_STYLE_ITALIC);
	TTF_SetFontStyle (ttf16_normal, TTF_STYLE_ITALIC);
	TTF_SetFontStyle (ttf26_normal, TTF_STYLE_ITALIC);
	TTF_SetFontStyle (ttf16_outline, TTF_STYLE_ITALIC);
	TTF_SetFontStyle (ttf20_outline, TTF_STYLE_ITALIC);
	TTF_SetFontStyle (ttf20_normal, TTF_STYLE_ITALIC);
	
	TTF_SetFontOutline (ttf16_outline, OUTLINE_TEXT);
	TTF_SetFontOutline (ttf20_outline, OUTLINE_TEXT);
	
	/* Generar textos */
	bind_textdomain_codeset (PACKAGE, "UTF-8");
	color.r = color.g = color.b = 0; /* Negro */
	
	for (g = 0; g < NUM_TEXTS; g++) {
		switch (text_info [g]) {
			case 10: temp2 = temp1; break;
			case 14: temp2 = ttf14_normal; break;
			case 16: temp2 = ttf16_normal; break;
			case 26: temp2 = ttf26_normal; break;
			default: temp2 = ttf16_normal;
		}
		
		texts[g] = draw_text (temp2, _(text_strings[g]), &color);
	}
	
	/* Copiar la palabra "Tickets" en el background */
	/* También copiar el nombre del juego al titulo y al fondo */
	rect.x = 607 + ((135 - texts[TEXT_TICKETS]->w) / 2); rect.y = 38;
	rect.w = texts[TEXT_TICKETS]->w; rect.h = texts[TEXT_TICKETS]->h;
	rect2.x = 191; rect2.y = 96;
	rect2.w = images[IMG_TITLE]->w; rect2.h = images[IMG_TITLE]->h;
	for (g = IMG_BACKGROUND_NORMAL; g <= IMG_BACKGROUND_FAIL_1; g++) {
		SDL_BlitSurface (texts[TEXT_TICKETS], NULL, images[g], &rect);
		SDL_BlitSurface (images[IMG_TITLE], NULL, images[g], &rect2);
	}
	
	/* X = 84.35, Y = 50.85 */
	rect2.x = 84; rect2.y = 51;
	SDL_BlitSurface (images[IMG_TITLE], NULL, images[IMG_TITLE_OPENING], &rect2);
	
	TTF_CloseFont (temp1);
	/* Generador de números aleatorios */
	srand ((unsigned int) getpid ());
}
Beispiel #22
0
/**
 * Attempts to initialize the graphical video display.  Returns 0 on
 * success, -1 on failure.
 */
int
InitVideo(FCEUGI *gi)
{
	// XXX soules - const?  is this necessary?
	const SDL_VideoInfo *vinf;
	int error, flags = 0;
	int doublebuf, xstretch, ystretch, xres, yres, show_fps;

	FCEUI_printf("Initializing video...");

	// load the relevant configuration variables
	g_config->getOption("SDL.Fullscreen", &s_fullscreen);
	g_config->getOption("SDL.DoubleBuffering", &doublebuf);
#ifdef OPENGL
	g_config->getOption("SDL.OpenGL", &s_useOpenGL);
#endif
	g_config->getOption("SDL.SpecialFilter", &s_sponge);
	g_config->getOption("SDL.XStretch", &xstretch);
	g_config->getOption("SDL.YStretch", &ystretch);
	g_config->getOption("SDL.LastXRes", &xres);
	g_config->getOption("SDL.LastYRes", &yres);
	g_config->getOption("SDL.ClipSides", &s_clipSides);
	g_config->getOption("SDL.NoFrame", &noframe);
	g_config->getOption("SDL.ShowFPS", &show_fps);

	// check the starting, ending, and total scan lines
	FCEUI_GetCurrentVidSystem(&s_srendline, &s_erendline);
	s_tlines = s_erendline - s_srendline + 1;

	// check if we should auto-set x/y resolution

	// check for OpenGL and set the global flags
#if OPENGL
	if(s_useOpenGL && !s_sponge) {
		flags = SDL_OPENGL;
	}
#endif

	// initialize the SDL video subsystem if it is not already active
	if(!SDL_WasInit(SDL_INIT_VIDEO)) {
		error = SDL_InitSubSystem(SDL_INIT_VIDEO);
		if(error) {
			FCEUD_PrintError(SDL_GetError());
			return -1;
		}
	}
	s_inited = 1;

	// shows the cursor within the display window
	SDL_ShowCursor(1);

	// determine if we can allocate the display on the video card
	vinf = SDL_GetVideoInfo();
	if(vinf->hw_available) {
		flags |= SDL_HWSURFACE;
	}

	// get the monitor's current resolution if we do not already have it
	if(s_nativeWidth < 0) {
		s_nativeWidth = vinf->current_w;
	}
	if(s_nativeHeight < 0) {
		s_nativeHeight = vinf->current_h;
	}

	// check to see if we are showing FPS
	FCEUI_SetShowFPS(show_fps);

	// check if we are rendering fullscreen
	if(s_fullscreen) {
		int no_cursor;
		g_config->getOption("SDL.NoFullscreenCursor", &no_cursor);
		flags |= SDL_FULLSCREEN;
		SDL_ShowCursor(!no_cursor);
	}
	else {
		SDL_ShowCursor(1);
	}

	if(noframe) {
		flags |= SDL_NOFRAME;
	}

	// gives the SDL exclusive palette control... ensures the requested colors
	flags |= SDL_HWPALETTE;

	// enable double buffering if requested and we have hardware support
#ifdef OPENGL
	if(s_useOpenGL) {
		FCEU_printf("Initializing with OpenGL (Disable with '--opengl 0').\n");
		if(doublebuf) {
			SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
		}
	} else
#endif
		if(doublebuf && (flags & SDL_HWSURFACE)) {
			flags |= SDL_DOUBLEBUF;
		}

	if(s_fullscreen) {
		int desbpp, autoscale;
		g_config->getOption("SDL.BitsPerPixel", &desbpp);
		g_config->getOption("SDL.AutoScale", &autoscale);
		if (autoscale)
		{
			double auto_xscale = GetXScale(xres);
			double auto_yscale = GetYScale(yres);
			double native_ratio = ((double)NWIDTH) / s_tlines;
			double screen_ratio = ((double)xres) / yres;
			int keep_ratio;

			g_config->getOption("SDL.KeepRatio", &keep_ratio);

			// Try to choose resolution
			if (screen_ratio < native_ratio)
			{
				// The screen is narrower than the original. Maximizing width will not clip
				auto_xscale = auto_yscale = GetXScale(xres);
				if (keep_ratio)
					auto_yscale = GetYScale(yres);
			}
			else
			{
				auto_yscale = auto_xscale = GetYScale(yres);
				if (keep_ratio)
					auto_xscale = GetXScale(xres);
			}
			s_exs = auto_xscale;
			s_eys = auto_yscale;
		}
		else
		{
			g_config->getOption("SDL.XScale", &s_exs);
			g_config->getOption("SDL.YScale", &s_eys);
		}
		g_config->getOption("SDL.SpecialFX", &s_eefx);

#ifdef OPENGL
		if(!s_useOpenGL) {
			s_exs = (int)s_exs;
			s_eys = (int)s_eys;
		} else {
			desbpp = 0;
		}

		// -Video Modes Tag-
		if(s_sponge) {
			if(s_sponge == 4 || s_sponge == 5) {
				s_exs = s_eys = 3;
			} else {
				s_exs = s_eys = 2;
			}
			s_eefx = 0;
			if(s_sponge == 1 || s_sponge == 4) {
				desbpp = 32;
			}
		}

		if((s_useOpenGL && !xstretch) || !s_useOpenGL)
#endif
			if(xres < (NWIDTH * s_exs) || s_exs <= 0.01) {
				FCEUD_PrintError("xscale out of bounds.");
				KillVideo();
				return -1;
			}

#ifdef OPENGL
		if((s_useOpenGL && !ystretch) || !s_useOpenGL)
#endif
			if(yres < s_tlines * s_eys || s_eys <= 0.01) {
				FCEUD_PrintError("yscale out of bounds.");
				KillVideo();
				return -1;
			}

#ifdef OPENGL
		s_screen = SDL_SetVideoMode(s_useOpenGL ? s_nativeWidth : xres,
		                            s_useOpenGL ? s_nativeHeight : yres,
		                            desbpp, flags);
#else
		s_screen = SDL_SetVideoMode(xres, yres, desbpp, flags);
#endif

		if(!s_screen) {
			FCEUD_PrintError(SDL_GetError());
			return -1;
		}
	} else {
		int desbpp;
		g_config->getOption("SDL.BitsPerPixel", &desbpp);

		g_config->getOption("SDL.XScale", &s_exs);
		g_config->getOption("SDL.YScale", &s_eys);
		g_config->getOption("SDL.SpecialFX", &s_eefx);

		// -Video Modes Tag-
		if(s_sponge) {
			if(s_sponge >= 4) {
				s_exs = s_eys = 3;
			} else {
				s_exs = s_eys = 2;
			}
			s_eefx = 0;
		}

#ifdef OPENGL
		if(!s_useOpenGL) {
			s_exs = (int)s_exs;
			s_eys = (int)s_eys;
		}
		if(s_exs <= 0.01) {
			FCEUD_PrintError("xscale out of bounds.");
			KillVideo();
			return -1;
		}
		if(s_eys <= 0.01) {
			FCEUD_PrintError("yscale out of bounds.");
			KillVideo();
			return -1;
		}
		if(s_sponge && s_useOpenGL) {
			FCEUD_PrintError("scalers not compatible with openGL mode.");
			KillVideo();
			return -1;
		}
#endif

#if defined(_GTK) && defined(SDL_VIDEO_DRIVER_X11)
		if(noGui == 0)
		{
			while (gtk_events_pending())
				gtk_main_iteration_do(FALSE);

			char SDL_windowhack[128];
			sprintf(SDL_windowhack, "SDL_WINDOWID=%u", (unsigned int)GDK_WINDOW_XID(gtk_widget_get_window(evbox)));
			SDL_putenv(SDL_windowhack);

			// init SDL video
			if (SDL_WasInit(SDL_INIT_VIDEO))
				SDL_QuitSubSystem(SDL_INIT_VIDEO);
			if ( SDL_InitSubSystem(SDL_INIT_VIDEO) < 0 )
			{
				fprintf(stderr, "Couldn't init SDL video: %s\n", SDL_GetError());
				gtk_main_quit();
			}
		}
#endif

		s_screen = SDL_SetVideoMode((int)(NWIDTH * s_exs),
		                            (int)(s_tlines * s_eys),
		                            desbpp, flags);
		if(!s_screen) {
			FCEUD_PrintError(SDL_GetError());
			return -1;
		}

#ifdef _GTK
		if(noGui == 0)
		{
			GtkRequisition req;
			gtk_widget_size_request(GTK_WIDGET(MainWindow), &req);
			gtk_window_resize(GTK_WINDOW(MainWindow), req.width, req.height);
		}
#endif
	}
	s_curbpp = s_screen->format->BitsPerPixel;
	if(!s_screen) {
		FCEUD_PrintError(SDL_GetError());
		KillVideo();
		return -1;
	}

#if 0
	// XXX soules - this would be creating a surface on the video
	//              card, but was commented out for some reason...
	s_BlitBuf = SDL_CreateRGBSurface(SDL_HWSURFACE, 256, 240,
	                                 s_screen->format->BitsPerPixel,
	                                 s_screen->format->Rmask,
	                                 s_screen->format->Gmask,
	                                 s_screen->format->Bmask, 0);
#endif

	FCEU_printf(" Video Mode: %d x %d x %d bpp %s\n",
	            s_screen->w, s_screen->h, s_screen->format->BitsPerPixel,
	            s_fullscreen ? "full screen" : "");

	if(s_curbpp != 8 && s_curbpp != 16 && s_curbpp != 24 && s_curbpp != 32) {
		FCEU_printf("  Sorry, %dbpp modes are not supported by FCE Ultra.  Supported bit depths are 8bpp, 16bpp, and 32bpp.\n", s_curbpp);
		KillVideo();
		return -1;
	}

	// if the game being run has a name, set it as the window name
	if(gi)
	{
		if(gi->name) {
			SDL_WM_SetCaption((const char *)gi->name, (const char *)gi->name);
		} else {
			SDL_WM_SetCaption(FCEU_NAME_AND_VERSION,"FCE Ultra");
		}
	}

	// create the surface for displaying graphical messages
#ifdef LSB_FIRST
	s_IconSurface = SDL_CreateRGBSurfaceFrom((void *)fceu_playicon.pixel_data,
	                32, 32, 24, 32 * 3,
	                0xFF, 0xFF00, 0xFF0000, 0x00);
#else
	s_IconSurface = SDL_CreateRGBSurfaceFrom((void *)fceu_playicon.pixel_data,
	                32, 32, 24, 32 * 3,
	                0xFF0000, 0xFF00, 0xFF, 0x00);
#endif
	SDL_WM_SetIcon(s_IconSurface,0);
	s_paletterefresh = 1;

	// XXX soules - can't SDL do this for us?
	// if using more than 8bpp, initialize the conversion routines
	if(s_curbpp > 8) {
		InitBlitToHigh(s_curbpp >> 3,
		               s_screen->format->Rmask,
		               s_screen->format->Gmask,
		               s_screen->format->Bmask,
		               s_eefx, s_sponge, 0);
#ifdef OPENGL
		if(s_useOpenGL)
		{
			int openGLip;
			g_config->getOption("SDL.OpenGLip", &openGLip);

			if(!InitOpenGL(NOFFSET, 256 - (s_clipSides ? 8 : 0),
			               s_srendline, s_erendline + 1,
			               s_exs, s_eys, s_eefx,
			               openGLip, xstretch, ystretch, s_screen))
			{
				FCEUD_PrintError("Error initializing OpenGL.");
				KillVideo();
				return -1;
			}
		}
#endif
	}
/*
 * This thread will read the buttons in an interrupt like fashion, and
 * also initializes SDL_INIT_VIDEO and the surfaces
 *
 * it must be done in the same thread (at least on windows) because events only
 * work in the thread which called SDL_Init(SubSystem) with SDL_INIT_VIDEO
 *
 * This is an SDL thread and relies on preemptive behavoir of the host
 **/
static int sdl_event_thread(void * param)
{
    SDL_InitSubSystem(SDL_INIT_VIDEO);

#if (CONFIG_PLATFORM & PLATFORM_MAEMO)
    SDL_sem *wait_for_maemo_startup;
#endif
    SDL_Surface *picture_surface = NULL;
    int width, height;
    int depth;
    Uint32 flags;

    /* Try and load the background image. If it fails go without */
    if (background) {
        picture_surface = SDL_LoadBMP("UI256.bmp");
        if (picture_surface == NULL) {
            background = false;
            DEBUGF("warn: %s\n", SDL_GetError());
        }
    }
    
    /* Set things up */
    if (background)
    {
        width = UI_WIDTH;
        height = UI_HEIGHT;
    } 
    else 
    {
#ifdef HAVE_REMOTE_LCD
        if (showremote)
        {
            width = SIM_LCD_WIDTH > SIM_REMOTE_WIDTH ? SIM_LCD_WIDTH : SIM_REMOTE_WIDTH;
            height = SIM_LCD_HEIGHT + SIM_REMOTE_HEIGHT;
        }
        else
#endif
        {
            width = SIM_LCD_WIDTH;
            height = SIM_LCD_HEIGHT;
        }
    }

    depth = LCD_DEPTH;
    if (depth < 8)
        depth = 16;

    flags = SDL_HWSURFACE|SDL_DOUBLEBUF;
#if (CONFIG_PLATFORM & (PLATFORM_MAEMO|PLATFORM_PANDORA))
    /* Fullscreen mode for maemo app */
    flags |= SDL_FULLSCREEN;
#endif

    if ((gui_surface = SDL_SetVideoMode(width * display_zoom, height * display_zoom, depth, flags)) == NULL) {
        panicf("%s", SDL_GetError());
    }

#if (CONFIG_PLATFORM & (PLATFORM_MAEMO|PLATFORM_PANDORA))
    /* SDL touch screen fix: Work around a SDL assumption that returns
       relative mouse coordinates when you get to the screen edges
       using the touchscreen and a disabled mouse cursor.
     */
    uint8_t hiddenCursorData = 0;
    SDL_Cursor *hiddenCursor = SDL_CreateCursor(&hiddenCursorData, &hiddenCursorData, 8, 1, 0, 0);

    SDL_ShowCursor(SDL_ENABLE);
    SDL_SetCursor(hiddenCursor);
#endif

    SDL_WM_SetCaption(UI_TITLE, NULL);

    if (background && picture_surface != NULL)
        SDL_BlitSurface(picture_surface, NULL, gui_surface, NULL);

    /* let system_init proceed */
    SDL_SemPost((SDL_sem *)param);

#if (CONFIG_PLATFORM & PLATFORM_MAEMO)
    /* Start maemo thread: Listen to display on/off events and battery monitoring */
    wait_for_maemo_startup = SDL_CreateSemaphore(0); /* 0-count so it blocks */
    SDL_Thread *maemo_thread = SDL_CreateThread(maemo_thread_func, wait_for_maemo_startup);
#endif

    /*
     * finally enter the button loop */
    gui_message_loop();

#if (CONFIG_PLATFORM & PLATFORM_MAEMO)
    /* Ensure maemo thread is up and running */
    SDL_SemWait(wait_for_maemo_startup);
    SDL_DestroySemaphore(wait_for_maemo_startup);

#if (CONFIG_PLATFORM & PLATFORM_MAEMO5)
    pcm_shutdown_gstreamer();
#endif

    g_main_loop_quit (maemo_main_loop);
    g_main_loop_unref(maemo_main_loop);
    SDL_WaitThread(maemo_thread, NULL);
#endif

#if (CONFIG_PLATFORM & (PLATFORM_MAEMO|PLATFORM_PANDORA))
    SDL_FreeCursor(hiddenCursor);
#endif

    if(picture_surface)
        SDL_FreeSurface(picture_surface);

    /* Order here is relevent to prevent deadlocks and use of destroyed
       sync primitives by kernel threads */
#ifdef HAVE_SDL_THREADS
    sim_thread_shutdown(); /* not needed for native threads */
#endif
    return 0;
}
int
main(int argc, char **argv)
{
    int rc;
    RTR3InitExe(argc, &argv, 0);

    for (int i = 1; i < argc; i++)
    {
#ifdef VBOX_OPENGL
        if (strcmp(argv[i], "-gl") == 0)
        {
            gfOpenGL = 1;
            continue;
        }
#endif
        if (strcmp(argv[i], "-loop") == 0 && ++i < argc)
        {
            guLoop = atoi(argv[i]);
            continue;
        }
        RTPrintf("Unrecognized option '%s'\n", argv[i]);
        return -1;
    }

#ifdef RT_OS_WINDOWS
    /* Default to DirectX if nothing else set. "windib" would be possible.  */
    if (!RTEnvExist("SDL_VIDEODRIVER"))
    {
        _putenv("SDL_VIDEODRIVER=directx");
    }
#endif

#ifdef RT_OS_WINDOWS
    _putenv("SDL_VIDEO_WINDOW_POS=0,0");
#else
    RTEnvSet("SDL_VIDEO_WINDOW_POS", "0,0");
#endif

    rc = SDL_InitSubSystem(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_NOPARACHUTE);
    if (rc != 0)
    {
        RTPrintf("Error: SDL_InitSubSystem failed with message '%s'\n", SDL_GetError());
        return -1;
    }

    /* output what SDL is capable of */
    const SDL_VideoInfo *videoInfo = SDL_GetVideoInfo();

    if (!videoInfo)
    {
        RTPrintf("No SDL video info available!\n");
        return -1;
    }

    RTPrintf("SDL capabilities:\n");
    RTPrintf("  Hardware surface support:                    %s\n", videoInfo->hw_available ? "yes" : "no");
    RTPrintf("  Window manager available:                    %s\n", videoInfo->wm_available ? "yes" : "no");
    RTPrintf("  Screen to screen blits accelerated:          %s\n", videoInfo->blit_hw ? "yes" : "no");
    RTPrintf("  Screen to screen colorkey blits accelerated: %s\n", videoInfo->blit_hw_CC ? "yes" : "no");
    RTPrintf("  Screen to screen alpha blits accelerated:    %s\n", videoInfo->blit_hw_A ? "yes" : "no");
    RTPrintf("  Memory to screen blits accelerated:          %s\n", videoInfo->blit_sw ? "yes" : "no");
    RTPrintf("  Memory to screen colorkey blits accelerated: %s\n", videoInfo->blit_sw_CC ? "yes" : "no");
    RTPrintf("  Memory to screen alpha blits accelerated:    %s\n", videoInfo->blit_sw_A ? "yes" : "no");
    RTPrintf("  Color fills accelerated:                     %s\n", videoInfo->blit_fill ? "yes" : "no");
    RTPrintf("  Video memory in kilobytes:                   %d\n", videoInfo->video_mem);
    RTPrintf("  Optimal bpp mode:                            %d\n", videoInfo->vfmt->BitsPerPixel);
    char buf[256];
    RTPrintf("Video driver SDL_VIDEODRIVER / active:         %s/%s\n", RTEnvGet("SDL_VIDEODRIVER"),
                                                                       SDL_VideoDriverName(buf, sizeof(buf)));

    RTPrintf("\n"
             "Starting tests. Any key pressed inside the SDL window will abort this\n"
             "program at the end of the current test. Iterations = %u\n", guLoop);

#ifdef VBOX_OPENGL
    RTPrintf("\n========== "ESC_BOLD"OpenGL is %s"ESC_NORM" ==========\n",
             gfOpenGL ? "ON" : "OFF");
#endif
    bench( 640,  480, 16);  bench( 640,  480, 24);  bench( 640,  480, 32);
    bench(1024,  768, 16);  bench(1024,  768, 24);  bench(1024,  768, 32);
    bench(1280, 1024, 16);  bench(1280, 1024, 24);  bench(1280, 1024, 32);

    RTPrintf("\nSuccess!\n");
    return 0;
}
Beispiel #25
0
bool VideoDriver_SDL::CreateMainSurface(uint w, uint h)
{
	SDL_Surface *newscreen, *icon;
	char caption[50];
	int bpp = BlitterFactory::GetCurrentBlitter()->GetScreenDepth();
	bool want_hwpalette;

	GetAvailableVideoMode(&w, &h);

	DEBUG(driver, 1, "SDL: using mode %ux%ux%d", w, h, bpp);

	if (bpp == 0) usererror("Can't use a blitter that blits 0 bpp for normal visuals");

	char icon_path[MAX_PATH];
	if (FioFindFullPath(icon_path, lastof(icon_path), BASESET_DIR, "openttd.32.bmp") != NULL) {
		/* Give the application an icon */
		icon = SDL_CALL SDL_LoadBMP(icon_path);
		if (icon != NULL) {
			/* Get the colourkey, which will be magenta */
			uint32 rgbmap = SDL_CALL SDL_MapRGB(icon->format, 255, 0, 255);

			SDL_CALL SDL_SetColorKey(icon, SDL_SRCCOLORKEY, rgbmap);
			SDL_CALL SDL_WM_SetIcon(icon, NULL);
			SDL_CALL SDL_FreeSurface(icon);
		}
	}

	if (_use_hwpalette == 2) {
		/* Default is to autodetect when to use SDL_HWPALETTE.
		 * In this case, SDL_HWPALETTE is only used for 8bpp
		 * blitters in fullscreen.
		 *
		 * When using an 8bpp blitter on a 8bpp system in
		 * windowed mode with SDL_HWPALETTE, OpenTTD will claim
		 * the system palette, making all other applications
		 * get the wrong colours. In this case, we're better of
		 * trying to approximate the colors we need using system
		 * colors, using a shadow surface (see below).
		 *
		 * On a 32bpp system, SDL_HWPALETTE is ignored, so it
		 * doesn't matter what we do.
		 *
		 * When using a 32bpp blitter on a 8bpp system, setting
		 * SDL_HWPALETTE messes up rendering (at least on X11),
		 * so we don't do that. In this case, SDL takes care of
		 * color approximation using its own shadow surface
		 * (which we can't force in 8bpp on 8bpp mode,
		 * unfortunately).
		 */
		want_hwpalette = bpp == 8 && _fullscreen && _support8bpp == S8BPP_HARDWARE;
	} else {
		/* User specified a value manually */
		want_hwpalette = _use_hwpalette;
	}

	if (want_hwpalette) DEBUG(driver, 1, "SDL: requesting hardware palete");

	/* Free any previously allocated shadow surface */
	if (_sdl_screen != NULL && _sdl_screen != _sdl_realscreen) SDL_CALL SDL_FreeSurface(_sdl_screen);

	if (_sdl_realscreen != NULL) {
		if (_requested_hwpalette != want_hwpalette) {
			/* SDL (at least the X11 driver), reuses the
			 * same window and palette settings when the bpp
			 * (and a few flags) are the same. Since we need
			 * to hwpalette value to change (in particular
			 * when switching between fullscreen and
			 * windowed), we restart the entire video
			 * subsystem to force creating a new window.
			 */
			DEBUG(driver, 0, "SDL: Restarting SDL video subsystem, to force hwpalette change");
			SDL_CALL SDL_QuitSubSystem(SDL_INIT_VIDEO);
			SDL_CALL SDL_InitSubSystem(SDL_INIT_VIDEO);
			ClaimMousePointer();
			SetupKeyboard();
		}
	}
	/* Remember if we wanted a hwpalette. We can't reliably query
	 * SDL for the SDL_HWPALETTE flag, since it might get set even
	 * though we didn't ask for it (when SDL creates a shadow
	 * surface, for example). */
	_requested_hwpalette = want_hwpalette;

	/* DO NOT CHANGE TO HWSURFACE, IT DOES NOT WORK */
	newscreen = SDL_CALL SDL_SetVideoMode(w, h, bpp, SDL_SWSURFACE | (want_hwpalette ? SDL_HWPALETTE : 0) | (_fullscreen ? SDL_FULLSCREEN : SDL_RESIZABLE));
	if (newscreen == NULL) {
		DEBUG(driver, 0, "SDL: Couldn't allocate a window to draw on");
		return false;
	}
	_sdl_realscreen = newscreen;

	if (bpp == 8 && (_sdl_realscreen->flags & SDL_HWPALETTE) != SDL_HWPALETTE) {
		/* Using an 8bpp blitter, if we didn't get a hardware
		 * palette (most likely because we didn't request one,
		 * see above), we'll have to set up a shadow surface to
		 * render on.
		 *
		 * Our palette will be applied to this shadow surface,
		 * while the real screen surface will use the shared
		 * system palette (which will partly contain our colors,
		 * but most likely will not have enough free color cells
		 * for all of our colors). SDL can use these two
		 * palettes at blit time to approximate colors used in
		 * the shadow surface using system colors automatically.
		 *
		 * Note that when using an 8bpp blitter on a 32bpp
		 * system, SDL will create an internal shadow surface.
		 * This shadow surface will have SDL_HWPALLETE set, so
		 * we won't create a second shadow surface in this case.
		 */
		DEBUG(driver, 1, "SDL: using shadow surface");
		newscreen = SDL_CALL SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, bpp, 0, 0, 0, 0);
		if (newscreen == NULL) {
			DEBUG(driver, 0, "SDL: Couldn't allocate a shadow surface to draw on");
			return false;
		}
	}

	/* Delay drawing for this cycle; the next cycle will redraw the whole screen */
	_num_dirty_rects = 0;

	_screen.width = newscreen->w;
	_screen.height = newscreen->h;
	_screen.pitch = newscreen->pitch / (bpp / 8);
	_screen.dst_ptr = newscreen->pixels;
	_sdl_screen = newscreen;

	/* When in full screen, we will always have the mouse cursor
	 * within the window, even though SDL does not give us the
	 * appropriate event to know this. */
	if (_fullscreen) _cursor.in_window = true;

	Blitter *blitter = BlitterFactory::GetCurrentBlitter();
	blitter->PostResize();

	InitPalette();
	switch (blitter->UsePaletteAnimation()) {
		case Blitter::PALETTE_ANIMATION_NONE:
		case Blitter::PALETTE_ANIMATION_VIDEO_BACKEND:
			UpdatePalette();
			break;

		case Blitter::PALETTE_ANIMATION_BLITTER:
			if (VideoDriver::GetInstance() != NULL) blitter->PaletteAnimate(_local_palette);
			break;

		default:
			NOT_REACHED();
	}

	seprintf(caption, lastof(caption), "OpenTTD %s", _openttd_revision);
	SDL_CALL SDL_WM_SetCaption(caption, caption);

	GameSizeChanged();

	return true;
}
Beispiel #26
0
/**
 * @brief Initialize the OpenGL context, returning true on success, false on failure.
 */
void R_InitContext(void) {
	int32_t w, h;

	memset(&r_context, 0, sizeof(r_context));

	if (SDL_WasInit(SDL_INIT_VIDEO) == 0) {
		if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) {
			Com_Error(ERROR_FATAL, "%s\n", SDL_GetError());
		}
	}

	uint32_t flags = SDL_WINDOW_OPENGL;

	if (r_allow_high_dpi->integer) {
		flags |= SDL_WINDOW_ALLOW_HIGHDPI;
	}

	if (r_fullscreen->integer) {
		w = Max(0, r_width->integer);
		h = Max(0, r_height->integer);

		if (r_width->integer == 0 && r_height->integer == 0) {
			SDL_DisplayMode best;
			SDL_GetDesktopDisplayMode(0, &best);

			w = best.w;
			h = best.h;
		}
		flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
	} else {
		w = Max(0, r_windowed_width->integer);
		h = Max(0, r_windowed_height->integer);

		flags |= SDL_WINDOW_RESIZABLE;
	}

	Com_Print("  Trying %dx%d..\n", w, h);

	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);

	SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

	const int32_t s = Clamp(r_multisample->integer, 0, 8);

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

	if ((r_context.window = SDL_CreateWindow(PACKAGE_STRING,
	                        SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, w, h, flags)) == NULL) {
		Com_Error(ERROR_FATAL, "Failed to set video mode: %s\n", SDL_GetError());
	}

	Com_Print("  Setting up OpenGL context..\n");

	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);

	if ((r_context.context = SDL_GL_CreateContext(r_context.window)) == NULL) {
		Com_Error(ERROR_FATAL, "Failed to create OpenGL context: %s\n", SDL_GetError());
	}

	int32_t attr[SDL_GL_CONTEXT_RELEASE_BEHAVIOR];
	for (int32_t i = 0; i < SDL_GL_CONTEXT_RELEASE_BEHAVIOR; i++) {
		SDL_GL_GetAttribute(i, &attr[i]);
	}

	Com_Verbose("   Buffer Sizes: r %i g %i b %i a %i depth %i stencil %i framebuffer %i\n", attr[SDL_GL_RED_SIZE],
	            attr[SDL_GL_GREEN_SIZE], attr[SDL_GL_BLUE_SIZE], attr[SDL_GL_ALPHA_SIZE], attr[SDL_GL_DEPTH_SIZE],
	            attr[SDL_GL_STENCIL_SIZE], attr[SDL_GL_BUFFER_SIZE]);
	Com_Verbose("   Double-buffered: %s\n", attr[SDL_GL_DOUBLEBUFFER] ? "yes" : "no");
	Com_Verbose("   Multisample: %i buffers, %i samples\n", attr[SDL_GL_MULTISAMPLEBUFFERS],
	            attr[SDL_GL_MULTISAMPLESAMPLES]);
	Com_Verbose("   Version: %i.%i (%i flags, %i profile)\n", attr[SDL_GL_CONTEXT_MAJOR_VERSION],
	            attr[SDL_GL_CONTEXT_MINOR_VERSION], attr[SDL_GL_CONTEXT_FLAGS], attr[SDL_GL_CONTEXT_PROFILE_MASK]);

	if (SDL_GL_SetSwapInterval(r_swap_interval->integer) == -1) {
		Com_Warn("Failed to set swap interval %d: %s\n", r_swap_interval->integer, SDL_GetError());
	}

	if (SDL_SetWindowBrightness(r_context.window, r_gamma->value) == -1) {
		Com_Warn("Failed to set gamma %1.1f: %s\n", r_gamma->value, SDL_GetError());
	}

	int32_t dw, dh;
	SDL_GL_GetDrawableSize(r_context.window, &dw, &dh);

	r_context.render_width = r_context.width = dw;
	r_context.render_height = r_context.height = dh;

	int32_t ww, wh;
	SDL_GetWindowSize(r_context.window, &ww, &wh);

	r_context.window_width = ww;
	r_context.window_height = wh;

	r_context.high_dpi = dw > ww && dh > wh;

	r_context.fullscreen = SDL_GetWindowFlags(r_context.window) & SDL_WINDOW_FULLSCREEN;

	R_SetWindowIcon();
}
Beispiel #27
0
int SDL_Init(Uint32 flags) {
	int tempOut = SDL_InitSubSystem(flags);
	return tempOut;
}
Beispiel #28
0
void SdlMixerManager::init() {
	// Start SDL Audio subsystem
	if (SDL_InitSubSystem(SDL_INIT_AUDIO) == -1) {
		error("Could not initialize SDL: %s", SDL_GetError());
	}

#if SDL_VERSION_ATLEAST(2, 0, 0)
	const char *sdlDriverName = SDL_GetCurrentAudioDriver();
#else
	const int maxNameLen = 20;
	char sdlDriverName[maxNameLen];
	sdlDriverName[0] = '\0';
	SDL_AudioDriverName(sdlDriverName, maxNameLen);
#endif
	debug(1, "Using SDL Audio Driver \"%s\"", sdlDriverName);

	// Get the desired audio specs
	SDL_AudioSpec desired = getAudioSpec(SAMPLES_PER_SEC);

	// Needed as SDL_OpenAudio as of SDL-1.2.14 mutates fields in
	// "desired" if used directly.
	SDL_AudioSpec fmt = desired;

	// Start SDL audio with the desired specs
	if (SDL_OpenAudio(&fmt, &_obtained) != 0) {
		warning("Could not open audio device: %s", SDL_GetError());

		// The mixer is not marked as ready
		_mixer = new Audio::MixerImpl(g_system, desired.freq);
		return;
	}

	// The obtained sample format is not supported by the mixer, call
	// SDL_OpenAudio again with NULL as the second argument to force
	// SDL to do resampling to the desired audio spec.
	if (_obtained.format != desired.format) {
		debug(1, "SDL mixer sound format: %d differs from desired: %d", _obtained.format, desired.format);
		SDL_CloseAudio();

		if (SDL_OpenAudio(&fmt, NULL) != 0) {
			warning("Could not open audio device: %s", SDL_GetError());

			// The mixer is not marked as ready
			_mixer = new Audio::MixerImpl(g_system, desired.freq);
			return;
		}

		_obtained = desired;
	}

	debug(1, "Output sample rate: %d Hz", _obtained.freq);
	if (_obtained.freq != desired.freq)
		debug(1, "SDL mixer output sample rate: %d differs from desired: %d", _obtained.freq, desired.freq);

	debug(1, "Output buffer size: %d samples", _obtained.samples);
	if (_obtained.samples != desired.samples)
		debug(1, "SDL mixer output buffer size: %d differs from desired: %d", _obtained.samples, desired.samples);

#ifndef __SYMBIAN32__
	// The SymbianSdlMixerManager does stereo->mono downmixing,
	// but otherwise we require stereo output.
	if (_obtained.channels != 2)
		error("SDL mixer output requires stereo output device");
#endif

	_mixer = new Audio::MixerImpl(g_system, _obtained.freq);
	assert(_mixer);
	_mixer->setReady(true);

	startAudio();
}
Beispiel #29
0
void
game_loop ()
{
    SDL_Event event;
    int done = 0,
        eventstate;

    if (GT_MP)
        net_game_fillsockaddr ();
    if ( SDL_InitSubSystem ( SDL_INIT_JOYSTICK ) < 0 ) {
        fprintf ( stderr, "Unable to initialize Joystick: %s\n", SDL_GetError() );
    }
    printf ( "%i joysticks found\n", SDL_NumJoysticks () );

    menu = NULL;
    bman.updatestatusbar = 1;   // force an update
    timestamp = SDL_GetTicks (); // needed for time sync.
    d_gamedetail ("GAME START");

    gfx_blitupdaterectclear ();
    draw_logo ();
    draw_field ();
    SDL_Flip (gfx.screen);
    draw_players ();

    if (bman.p_nr >= 0 && bman.p_nr < MAX_PLAYERS) {
        players[bman.p_nr].ready = 1;
        if (GT_MP_PTPS)
            send_playerdata (&players[bman.p_servnr].net.addr, bman.p_nr, &players[bman.p_nr]);
    }
    if (bman.p2_nr >= 0 && bman.p2_nr < MAX_PLAYERS) {
        players[bman.p2_nr].ready = 1;
        if (GT_MP_PTPS)
            send_playerdata (&players[bman.p_servnr].net.addr, bman.p2_nr, &players[bman.p2_nr]);
    }
	fire_init();
    while (!done && (bman.state == GS_running || bman.state == GS_ready)) {
        SDL_JoystickUpdate ();
        if ((eventstate = SDL_PollEvent (&event)) != 0)
            switch (event.type) {
            case (SDL_QUIT):
                done = 1;
                bman.state = GS_quit;
            }

        /*
         * input handling
         */
        keyb_loop (&event);

        game_keys_loop ();

        if (GT_MP)
            chat_loop (&event);

        if ((!IS_LPLAYER2) && (!chat.active))
            chat_setactive (1, 1);

        restore_players_screen ();

        player_check (bman.p_nr);
        if (IS_LPLAYER2)
            player_check (bman.p2_nr);

        dead_playerani ();

        special_loop ();

        player_move (bman.p_nr);
        if (IS_LPLAYER2)
            player_move (bman.p2_nr);

        if (GT_MP) {
            player_calcpos ();
            network_loop ();
        }

        if (bman.state == GS_running)
            single_loop ();

        bomb_loop ();
		/* wind_loop (); SOON */
		fire_loop ();
        field_loop ();
        flitems_loop ();

        draw_players ();
        game_draw_info ();      // will set the var bman.player_nr

        /* check if there is only one player left and the game is in multiplayer mode
           and if there the last dieing animation is done */
        if (game_check_endgame () && bman.timeout >= 0.0f)
            bman.timeout = 0.0f;

        if ((GT_SP || GT_MP_PTPM) && bman.timeout < -GAME_OVERTIMEOUT) {
            d_printf ("GAME: Game Over\n");
            done = 1;
        }

        stonelist_draw ();

        /* if there is any menu displayed do so */
        if (menu != NULL)
            game_menu_loop (&event, eventstate);

        gfx_blitdraw ();

        s_calctimesync ();
        bman.timeout -= timediff;

    }

    if (menu != NULL) {
        menu_delete (menu);
        menu = NULL;
    }

    gfx_blitdraw ();

    chat_show (-1, -1, -1, -1);
    draw_logo ();
    gfx_blitupdaterectclear ();
    SDL_Flip (gfx.screen);

    d_gamedetail ("GAME END");
    d_printf ("done = %d\n", done);
};
Beispiel #30
0
int
SDL_Init(Uint32 flags)
{
    return SDL_InitSubSystem(flags);
}