Exemple #1
0
int Resume_playback(int nc,int nrc)
{
//    char SoundcardName[256];
	int audio_rate = 44100;
	int audio_channels = 2;
	int audio_bufsize = AUDIO_BUFFER;
	Uint16 audio_format = AUDIO_S16;
	SDL_version compile_version;
	n_channels=8;

	sound_enabled=true;
#ifdef __DEBUG_MESSAGES
	output_debug_message("Initializing SDL_mixer.\n");
#endif
	if (Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_bufsize))  {
	  sound_enabled=false;
#ifdef __DEBUG_MESSAGES
  	  output_debug_message("Unable to open audio: %s\n", Mix_GetError());
  	  output_debug_message("Running the game without audio.\n");
#endif
	  return -1;	
	} // if 

#ifndef __EMSCRIPTEN__
	Mix_QuerySpec (&audio_rate, &audio_format, &audio_channels);
#ifdef __DEBUG_MESSAGES
	output_debug_message("    opened %d Hz %d bit %s, %d bytes audio buffer\n",
						 audio_rate, audio_format & 0xFF,
						 audio_channels > 1 ? "stereo" : "mono", audio_bufsize);
#endif
#endif

	MIX_VERSION (&compile_version);
#ifdef __DEBUG_MESSAGES
	output_debug_message("    compiled with SDL_mixer version: %d.%d.%d\n",
						 compile_version.major,
						 compile_version.minor,
						 compile_version.patch);
	output_debug_message("    running with SDL_mixer version: %d.%d.%d\n",
						 Mix_Linked_Version()->major,
						 Mix_Linked_Version()->minor,
						 Mix_Linked_Version()->patch);
#endif

	if (nc>0) n_channels=Mix_AllocateChannels(nc);
	if (nrc>0) Mix_ReserveChannels(nrc);

	Sound_unpause_music();

	return n_channels;
} /* Resume_playback */ 
bool Sound_initialization(void)
{
    char SoundcardName[256];
	int audio_rate = 44100;
	int audio_channels = 2;
	int audio_bufsize = AUDIO_BUFFER;
	Uint16 audio_format = AUDIO_S16;
	SDL_version compile_version;

	sound_enabled=true;
	fprintf (stderr, "Initializing SDL_mixer.\n");

	int flags = MIX_INIT_OGG | MIX_INIT_MOD;
	int initted = Mix_Init(flags);
	if (initted & flags != flags) {
		printf("Mix_Init: Failed to init required ogg and mod support!\n");
		printf("Mix_Init: %s\n", Mix_GetError());
		sound_enabled = false;
		return false;
	}

	if (Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_bufsize))  {
	  fprintf (stderr, "Unable to open audio: %s\n", Mix_GetError());
	  sound_enabled=false;
	  fprintf (stderr, "Running the game without audio.\n");
	  return false;	
	} /* if */ 

	SDL_AudioDriverName (SoundcardName, sizeof (SoundcardName));
	Mix_QuerySpec (&audio_rate, &audio_format, &audio_channels);
	fprintf (stderr, "    opened %s at %d Hz %d bit %s, %d bytes audio buffer\n",
			 SoundcardName, audio_rate, audio_format & 0xFF,
			 audio_channels > 1 ? "stereo" : "mono", audio_bufsize);
	MIX_VERSION (&compile_version);
	fprintf (stderr, "    compiled with SDL_mixer version: %d.%d.%d\n",
			 compile_version.major,
			 compile_version.minor,
			 compile_version.patch);
	fprintf (stderr, "    running with SDL_mixer version: %d.%d.%d\n",
			 Mix_Linked_Version()->major,
			 Mix_Linked_Version()->minor,
			 Mix_Linked_Version()->patch);

	Sound_Init();
	Mix_HookMusic(myMusicPlayer, 0);

	return true;
} /* Sound_init */ 
Exemple #3
0
/**
 * @brief Prints the current and compiled SDL_Mixer versions.
 */
static void print_MixerVersion (void)
{
   int frequency;
   Uint16 format;
   int channels;
   SDL_version compiled;
   const SDL_version *linked;
   char device[PATH_MAX];

   /* Query stuff. */
   Mix_QuerySpec(&frequency, &format, &channels);
   MIX_VERSION(&compiled);
   linked = Mix_Linked_Version();
   SDL_AudioDriverName(device, PATH_MAX);

   /* Version itself. */
   DEBUG("SDL_Mixer Started: %d Hz %s", frequency,
         (channels == 2) ? "Stereo" : "Mono" );
   /* Check if major/minor version differ. */
   if ((linked->major*100 + linked->minor) > compiled.major*100 + compiled.minor)
      WARN("SDL_Mixer is newer than compiled version");
   if ((linked->major*100 + linked->minor) < compiled.major*100 + compiled.minor)
      WARN("SDL_Mixer is older than compiled version.");
   /* Print other debug info. */
   DEBUG("Renderer: %s",device);
   DEBUG("Version: %d.%d.%d [compiled: %d.%d.%d]", 
         compiled.major, compiled.minor, compiled.patch,
         linked->major, linked->minor, linked->patch);
   DEBUG();
}
Exemple #4
0
/**\brief Audio system initialization.
 */
bool Audio::Initialize( void ){
	if ( this -> initstatus )
		return false;				// Already initialized

	SDL_Init(SDL_INIT_AUDIO);

	if(Mix_OpenAudio(this->audio_rate,
				this->audio_format,
				this->audio_channels,
				this->audio_buffers)){
		LogMsg(CRITICAL,"Audio initialization failed!");
		return false;
	}

#if defined(SDL_MIXER_MAJOR_VERSION) && (SDL_MIXER_MAJOR_VERSION>1) \
	&& (SDL_MIXER_MINOR_VERSON>2) && (SDL_MIXER_PATCHLEVEL>=10)
	// Load MOD and OGG libraries (If SDL_mixer version supports it)
	const SDL_version *mix_version=Mix_Linked_Version();
	if( (mix_version->major >= 1) && (mix_version->minor >= 2) && (mix_version->patch >= 10) ){
		LogMsg(INFO,"This SDL_mixer version supports dynamic library loading.");
		Mix_Init( MIX_INIT_MOD | MIX_INIT_OGG );
	}
#endif // SDL_MIXER version requirements

	// Allocate channels
	Mix_AllocateChannels( this->max_chan);
	assert( this->max_chan == static_cast<unsigned int>(this->GetTotalChannels()) );

	return true;
}
Exemple #5
0
/**\brief Audio system shutdown.
 */
bool Audio::Shutdown( void ){
	/* This is the cleaning up part */
	this->HaltAll();


#if defined(SDL_MIXER_MAJOR_VERSION) && (SDL_MIXER_MAJOR_VERSION>1) \
	&& (SDL_MIXER_MINOR_VERSON>2) && (SDL_MIXER_PATCHLEVEL>=10)
	// Free every library loaded
	const SDL_version *mix_version=Mix_Linked_Version();
	if( (mix_version->major>=1) && (mix_version->minor>=2) && (mix_version->patch>=10) ){
		while(Mix_Init(0))
			Mix_Quit();
	}
#endif // SDL_Mixer version requirements

	// Query number of times audio device was opened (should be 1)
	int freq, chan, ntimes;
	Uint16 format;
	ntimes = Mix_QuerySpec( &freq, &format, &chan );

	LogMsg(INFO,"Audio Query: %d Frequencies, Format: %d, Channels: %s.", freq, format, (chan==2?"Stereo":"Mono"));

	if(ntimes != 1 ) {
		LogMsg(WARN,"Audio was initialized %d times.", ntimes);
	}

	// Close only if open
	if( ntimes ) {
		Mix_CloseAudio();
	}

	return true;
}
Exemple #6
0
/**\brief Audio system shutdown.
 */
bool Audio::Shutdown( void ){
	/* This is the cleaning up part */
	this->HaltAll();


#if defined(SDL_MIXER_MAJOR_VERSION) && (SDL_MIXER_MAJOR_VERSION>1) \
	&& (SDL_MIXER_MINOR_VERSON>2) && (SDL_MIXER_PATCHLEVEL>=10)
	// Free every library loaded
	const SDL_version *mix_version=Mix_Linked_Version();
	if( (mix_version->major>=1) && (mix_version->minor>=2) && (mix_version->patch>=10) ){
		while(Mix_Init(0))
			Mix_Quit();
	}
#endif // SDL_Mixer version requirements

	// Query number of times audio device was opened (should be 1)
	int freq, chan, ntimes;
	Uint16 format;
	if ( (ntimes = Mix_QuerySpec( &freq, &format, &chan )) != 1 )
		LogMsg(WARN,"Audio was initialized multiple times.");

	// Close as many times as opened.
	for ( int i = 0; i < ntimes; i++ )
		Mix_CloseAudio();
	return true;
}
aboutDialog::aboutDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::aboutDialog)
{
    ui->setupUi(this);

    #ifdef Q_OS_MAC
    this->setWindowIcon(QIcon(":/cat_builder.icns"));
    #endif
    #ifdef Q_OS_WIN
    this->setWindowIcon(QIcon(":/cat_builder.ico"));

    if(QSysInfo::WindowsVersion>=QSysInfo::WV_VISTA)
    {
        if(QtWin::isCompositionEnabled())
        {
            this->setAttribute(Qt::WA_TranslucentBackground, true);
            QtWin::extendFrameIntoClientArea(this, -1,-1,-1, -1);
            QtWin::enableBlurBehindWindow(this);
        }
        else
        {
            QtWin::resetExtendedFrame(this);
            setAttribute(Qt::WA_TranslucentBackground, false);
        }
    }
    #endif

    SDL_version sdlVer;
    SDL_GetVersion(&sdlVer);
    const SDL_version *mixerXVer = Mix_Linked_Version();

    ui->About1->setText(ui->About1->text()
                        .arg(V_FILE_VERSION)
                        .arg(V_FILE_RELEASE)
                        .arg(FILE_CPU)
                        .arg(QString("<b>Revision:</b> %1-%2, <b>Build date:</b> <u>%3</u><br/>"
                                     "<b>Qt:</b> %4, <b>SDL2:</b> %5.%6.%7, <b>SDL Mixer X:</b> %8.%9.%10")
                             .arg(V_BUILD_VER)
                             .arg(V_BUILD_BRANCH)
                             .arg(V_DATE_OF_BUILD)
                             .arg(qVersion())
                             .arg(sdlVer.major).arg(sdlVer.minor).arg(sdlVer.patch)
                             .arg(mixerXVer->major).arg(mixerXVer->minor).arg(mixerXVer->patch)
                             )
                        );

    QFile mFile(":/credits.html");
    if(!mFile.open(QFile::ReadOnly | QFile::Text)){
        return;
    }

    QTextStream in(&mFile);
    in.setCodec("UTF-8");
    QString mText = in.readAll();
    ui->About2->setText(mText);
    mFile.close();
}
Exemple #8
0
bool C4MusicFileSDL::Play(bool loop)
{
	const SDL_version * link_version = Mix_Linked_Version();
	if (link_version->major < 1
	    || (link_version->major == 1 && link_version->minor < 2)
	    || (link_version->major == 1 && link_version->minor == 2 && link_version->patch < 7))
	{
		// Check existance and try extracting it
		if (!FileExists(FileName)) if (!ExtractFile())
				// Doesn't exist - or file is corrupt
			{
				LogF("Error reading %s", FileName);
				return false;
			}
		// Load
		Music = Mix_LoadMUS(SongExtracted ? Config.AtTempPath(C4CFN_TempMusic2) : FileName);
		// Load failed
		if (!Music)
		{
			LogF("SDL_mixer: %s", SDL_GetError());
			return false;
		}
		// Play Song
		if (Mix_PlayMusic(Music, loop? -1 : 1) == -1)
		{
			LogF("SDL_mixer: %s", SDL_GetError());
			return false;
		}
	}
	else
	{
		// Load Song
		// Fixme: Try loading this from the group incrementally for less lag
		size_t filesize;
		if (!C4Group_ReadFile(FileName, &Data, &filesize))
		{
			LogF("Error reading %s", FileName);
			return false;
		}
		// Mix_FreeMusic frees the RWop
		Music = Mix_LoadMUS_RW(SDL_RWFromConstMem(Data, filesize));
		if (!Music)
		{
			LogF("SDL_mixer: %s", SDL_GetError());
			return false;
		}
		if (Mix_PlayMusic(Music, loop? -1 : 1) == -1)
		{
			LogF("SDL_mixer: %s", SDL_GetError());
			return false;
		}
	}
	return true;
}
Exemple #9
0
void MainManager::initSDLmixer()
{

  log_.i("Initializing SDL_mixer");
  int mixFlags = MIX_INIT_FLAC;
  int mixFlagsInit = Mix_Init(mixFlags);
  if ((mixFlagsInit & mixFlags) != mixFlags)
    throw log_.exception("Failed to initialize SDL_mixer", Mix_GetError);
  if( Mix_OpenAudio( 22050, MIX_DEFAULT_FORMAT, 2, 1024 ) == -1 )
    throw log_.exception("Failed to aquire sound device", Mix_GetError);
  atexit(Mix_CloseAudio);
  atexit(Mix_Quit);

  // Write version information to log
  SDL_version compiled;
  SDL_MIXER_VERSION(&compiled);
  logSDLVersion("SDL_mixer", compiled, *Mix_Linked_Version());

  // Write music decoder information to log
  const int nMusicDecoders = Mix_GetNumMusicDecoders();
  std::stringstream ss;
  if (nMusicDecoders > 0)
    ss << Mix_GetMusicDecoder(0);
  for (int i = 1 ; i < nMusicDecoders ; ++i) {
    ss << ", " << Mix_GetMusicDecoder(i) << Log::end;
  }
  log_.d() << "Music decoders (" << nMusicDecoders << "): "
           << ss.str() << Log::end;


  // Write audio decoder information to log
  const int nChunkDecoders =  Mix_GetNumChunkDecoders();
  ss.str(std::string(""));
  if (nChunkDecoders > 0)
    ss << Mix_GetChunkDecoder(0);
  for (int i = 1 ; i < nChunkDecoders ; ++i) {
    ss << ", " << Mix_GetChunkDecoder(i) << Log::end;
  }
  log_.d() << "Audio decoders (" << nChunkDecoders << "): "
           << ss.str() << Log::end;

  (void)Mix_VolumeMusic(MIX_MAX_VOLUME);

  (void)Mix_Volume(-1, MIX_MAX_VOLUME);
  // (void)Mix_VolumeMusic(MIX_MAX_VOLUME);
  log_.d() << "Music Volume level: "
           << 100.0f * (float)Mix_VolumeMusic(-1) / MIX_MAX_VOLUME << "%"
           << Log::end;

  // TODO swarminglogic, 2014-02-08: Move to audio configuration setting.
  // Setting 64 channels to be played simulatenously
  Mix_AllocateChannels(64);
}
Exemple #10
0
	void Application::setup(Int32 argc, char** argv)
	{
		srand((unsigned)time(nullptr));

		if (SDL_Init(SDL_INIT_VIDEO) != 0)
		{
			D6_THROW(VideoException, Format("Unable to set graphics mode: {0}") << SDL_GetError());
		}
		if (TTF_Init() != 0)
		{
			D6_THROW(FontException, Format("Unable to initialize font subsystem: {0}") << TTF_GetError());
		}

		// Print application info
		SDL_version sdlVersion;
		console.printLine("\n===Application information===");
		console.printLine(Format("{0} version: {1}") << APP_NAME << APP_VERSION);
		SDL_GetVersion(&sdlVersion);
		console.printLine(Format("SDL version: {0}.{1}.{2}") << sdlVersion.major << sdlVersion.minor << sdlVersion.patch);
		const SDL_version* mixVersion = Mix_Linked_Version();
		console.printLine(Format("SDL_mixer version: {0}.{1}.{2}") << mixVersion->major << mixVersion->minor << mixVersion->patch);
		const SDL_version* ttfVersion = TTF_Linked_Version();
		console.printLine(Format("SDL_ttf version: {0}.{1}.{2}") << ttfVersion->major << ttfVersion->minor << ttfVersion->patch);

		Console::registerBasicCommands(console);
		ConsoleCommands::registerCommands(console, service, menu, gameSettings);

		Math::initialize();

		console.printLine("\n===Font initialization===");
		font.load(D6_FILE_TTF_FONT, console);

		video.initialize(APP_NAME, APP_FILE_ICON, console);
		menu.initialize();

		gameResources = std::make_unique<GameResources>(service);
		game = std::make_unique<Game>(service, *gameResources, gameSettings);
		menu.setGameReference(game.get());

		for (Weapon weapon : Weapon::values())
		{
			gameSettings.enableWeapon(weapon, true);
		}

		// Execute config script and command line arguments
		console.printLine("\n===Config===");
		console.exec(std::string("exec ") + D6_FILE_CONFIG);

		for (int i = 1; i < argc; i++)
		{
			console.exec(argv[i]);
		}
	}
Exemple #11
0
static void test_versions(void)
{
	SDL_version compiled;
	const SDL_version *linked;

	SDL_VERSION(&compiled);
	linked = SDL_Linked_Version();
	output_versions("SDL", &compiled, linked);

	SDL_MIXER_VERSION(&compiled);
	linked = Mix_Linked_Version();
	output_versions("SDL_mixer", &compiled, linked);
}
Exemple #12
0
int SDL_mixver(){
	SDL_version compile_version;
	const SDL_version *link_version=Mix_Linked_Version();
	SDL_MIXER_VERSION(&compile_version);
	printf("compiled with SDL_mixer version: %d.%d.%d\n",
			compile_version.major,
			compile_version.minor,
			compile_version.patch);
	
	printf("running with SDL_mixer version: %d.%d.%d\n",
			link_version->major,
			link_version->minor,
			link_version->patch);
}
bool C4MusicSystem::InitializeMOD()
{
#if AUDIO_TK == AUDIO_TK_SDL_MIXER
	SDL_version compile_version;
	const SDL_version * link_version;
	MIX_VERSION(&compile_version);
	link_version=Mix_Linked_Version();
	LogF("SDL_mixer runtime version is %d.%d.%d (compiled with %d.%d.%d)",
	     link_version->major, link_version->minor, link_version->patch,
	     compile_version.major, compile_version.minor, compile_version.patch);
	if (!SDL_WasInit(SDL_INIT_AUDIO) && SDL_Init(SDL_INIT_AUDIO | SDL_INIT_JOYSTICK | SDL_INIT_NOPARACHUTE))
	{
		LogF("SDL: %s", SDL_GetError());
		return false;
	}
	//frequency, format, stereo, chunksize
	if (Mix_OpenAudio(44100, AUDIO_S16SYS, 2, 1024))
	{
		LogF("SDL_mixer: %s", SDL_GetError());
		return false;
	}
	MODInitialized = true;
	return true;
#elif AUDIO_TK == AUDIO_TK_OPENAL
	alcDevice = alcOpenDevice(NULL);
	if (!alcDevice)
	{
		LogF("Sound system: OpenAL create context error");
		return false;
	}
	alcContext = alcCreateContext(alcDevice, NULL);
	if (!alcContext)
	{
		LogF("Sound system: OpenAL create context error");
		return false;
	}
#ifndef __APPLE__
	if (!alutInitWithoutContext(NULL, NULL))
	{
		LogF("Sound system: ALUT init error");
		return false;
	}
#endif
	MODInitialized = true;
	return true;
#endif
	return false;
}
Exemple #14
0
static boolean I_SDL_InitSound(void)
{
    int i;

    // No sounds yet
    for (i = 0; i < NUMSFX; ++i)
        sound_chunks[i].abuf = NULL;

    for (i = 0; i < NUM_CHANNELS; ++i)
        channels_playing[i] = sfx_None;

    if (SDL_InitSubSystem(SDL_INIT_AUDIO) < 0)
        return false;

#if defined(SDL20)
    {
        const SDL_version       *linked = Mix_Linked_Version();

        if (linked->major != MIX_MAJOR_VERSION || linked->minor != MIX_MINOR_VERSION)
            I_Error("The wrong version of SDL2_MIXER.DLL was found. "PACKAGE_NAME" requires "
                "v%d.%d.%d, not v%d.%d.%d.", linked->major, linked->minor, linked->patch,
                MIX_MAJOR_VERSION, MIX_MINOR_VERSION, MIX_PATCHLEVEL);

        if (linked->patch != MIX_PATCHLEVEL)
            C_Warning("The wrong version of SDL2_MIXER.DLL was found. "PACKAGE_NAME" requires "
                "v%d.%d.%d, not v%d.%d.%d.", linked->major, linked->minor, linked->patch,
                MIX_MAJOR_VERSION, MIX_MINOR_VERSION, MIX_PATCHLEVEL);
    }
#endif

    if (Mix_OpenAudio(snd_samplerate, AUDIO_S16SYS, 2, GetSliceSize()) < 0)
        return false;

    Mix_QuerySpec(&mixer_freq, &mixer_format, &mixer_channels);

    // precache sounds to avoid slowdown inside game
    for (i = 0; i < NUMSFX; i++)
        CacheSFX_SDL(i);

    Mix_AllocateChannels(NUM_CHANNELS);

    SDL_PauseAudio(0);

    sound_initialized = true;

    return true;
}
	void ConsoleCommands::registerCommands(Console& console, AppService& appService, Menu& menu, GameSettings& gameSettings)
	{
		SDL_version sdlVersion;
		std::string verStr = D6_L("version");

		// Print application info
		console.printLine(D6_L("\n===Application information==="));
		console.printLine(Format("{0} {1}: {2}") << APP_NAME << verStr << APP_VERSION);
		SDL_GetVersion(&sdlVersion);
		console.printLine(Format("SDL {0}: {1}.{2}.{3}") << verStr << sdlVersion.major << sdlVersion.minor << sdlVersion.patch);
		const SDL_version* mixVersion = Mix_Linked_Version();
		console.printLine(Format("SDL_mixer {0}: {1}.{2}.{3}") << verStr << mixVersion->major << mixVersion->minor << mixVersion->patch);
		console.printLine(D6_L("Language: english"));

		// Set some console functions
		console.setLast(15);
		console.registerCommand("switch_render_mode", [&gameSettings](Console& con, const Console::Arguments& args) {
			toggleRenderMode(con, args, gameSettings);
		});
		console.registerCommand("show_fps", [&gameSettings](Console& con, const Console::Arguments& args) {
			toggleShowFps(con, args, gameSettings);
		});
		console.registerCommand("gl_info", openGLInfo);
		console.registerCommand("lang", language);
		console.registerCommand("volume", [&appService](Console& con, const Console::Arguments& args) {
			volume(con, args, appService.getSound());
		});
		console.registerCommand("rounds", [&gameSettings](Console& con, const Console::Arguments& args) {
			maxRounds(con, args, gameSettings);
		});
		console.registerCommand("ghosts", [&gameSettings](Console& con, const Console::Arguments& args) {
			ghostMode(con, args, gameSettings);
		});
		console.registerCommand("music", [&menu](Console& con, const Console::Arguments& args) {
			musicOnOff(con, args, menu);
		});
		console.registerCommand("joy_scan", [&menu](Console& con, const Console::Arguments& args) {
			joyScan(con, args, menu);
		});
		console.registerCommand("skin", [&menu](Console& con, const Console::Arguments& args) {
			loadSkin(con, args, menu);
		});
		console.registerCommand("gun", enableWeapon);
		console.registerCommand("start_ammo_range", [&gameSettings](Console& con, const Console::Arguments& args) {
			ammoRange(con, args, gameSettings);
		});
	}
Exemple #16
0
void Sound::info()
{
    SDL_version compiledVersion;
    const SDL_version *linkedVersion;
    char driver[40] = "Unknown";
    const char *format = "Unknown";
    int rate = 0;
    uint16_t audioFormat = 0;
    int channels = 0;

    MIX_VERSION(&compiledVersion);
    linkedVersion = Mix_Linked_Version();

    SDL_AudioDriverName(driver, 40);

    Mix_QuerySpec(&rate, &audioFormat, &channels);
    switch (audioFormat)
    {
        case AUDIO_U8: format = "U8"; break;
        case AUDIO_S8: format = "S8"; break;
        case AUDIO_U16LSB: format = "U16LSB"; break;
        case AUDIO_S16LSB: format = "S16LSB"; break;
        case AUDIO_U16MSB: format = "U16MSB"; break;
        case AUDIO_S16MSB: format = "S16MSB"; break;
        default: break;
    }

    logger->log("Sound::info() SDL_mixer: %i.%i.%i (compiled)",
            compiledVersion.major,
            compiledVersion.minor,
            compiledVersion.patch);
    if (linkedVersion)
    {
        logger->log("Sound::info() SDL_mixer: %i.%i.%i (linked)",
            linkedVersion->major,
            linkedVersion->minor,
            linkedVersion->patch);
    }
    else
    {
        logger->log1("Sound::info() SDL_mixer: unknown");
    }
    logger->log("Sound::info() Driver: %s", driver);
    logger->log("Sound::info() Format: %s", format);
    logger->log("Sound::info() Rate: %i", rate);
    logger->log("Sound::info() Channels: %i", channels);
}
Exemple #17
0
void Window::showDebugInfo()
{
	// TODO: add information about versions added in compilation proces
	printf("Compiled with GCC version: %s\n", __VERSION__);

	const SDL_version* sdlVersion = SDL_Linked_Version();
	printf("Running with SDL version: %u.%u.%u\n", sdlVersion->major, sdlVersion->minor, sdlVersion->patch);

	const SDL_version* imageVersion = IMG_Linked_Version();
	printf("Running with SDL_image version: %u.%u.%u\n", imageVersion->major, imageVersion->minor, imageVersion->patch);

	const SDL_version* ttfVersion = TTF_Linked_Version();
	printf("Running with SDL_ttf version: %u.%u.%u\n", ttfVersion->major, ttfVersion->minor, ttfVersion->patch);

	const SDL_version* mixerVersion = Mix_Linked_Version();
	printf("Running with SDL_mixer version: %u.%u.%u\n", mixerVersion->major, mixerVersion->minor, mixerVersion->patch);
}
Exemple #18
0
void I_BindSoundVariables(void)
{
    extern char *snd_dmxoption;
    extern int use_libsamplerate;
    extern float libsamplerate_scale;

    M_BindIntVariable("snd_musicdevice",         &snd_musicdevice);
    M_BindIntVariable("snd_sfxdevice",           &snd_sfxdevice);
    M_BindIntVariable("snd_sbport",              &snd_sbport);
    M_BindIntVariable("snd_sbirq",               &snd_sbirq);
    M_BindIntVariable("snd_sbdma",               &snd_sbdma);
    M_BindIntVariable("snd_mport",               &snd_mport);
    M_BindIntVariable("snd_maxslicetime_ms",     &snd_maxslicetime_ms);
    M_BindStringVariable("snd_musiccmd",         &snd_musiccmd);
    M_BindStringVariable("snd_dmxoption",        &snd_dmxoption);
    M_BindIntVariable("snd_samplerate",          &snd_samplerate);
    M_BindIntVariable("snd_cachesize",           &snd_cachesize);
    M_BindIntVariable("opl_io_port",             &opl_io_port);
    M_BindIntVariable("snd_pitchshift",          &snd_pitchshift);

    M_BindStringVariable("timidity_cfg_path",    &timidity_cfg_path);
    M_BindStringVariable("gus_patch_path",       &gus_patch_path);
    M_BindIntVariable("gus_ram_kb",              &gus_ram_kb);

#ifdef FEATURE_SOUND
    M_BindIntVariable("use_libsamplerate",       &use_libsamplerate);
    M_BindFloatVariable("libsamplerate_scale",   &libsamplerate_scale);
#endif

    // Before SDL_mixer version 1.2.11, MIDI music caused the game
    // to crash when it looped.  If this is an old SDL_mixer version,
    // disable MIDI.

#ifdef __MACOSX__
    {
        const SDL_version *v = Mix_Linked_Version();

        if (SDL_VERSIONNUM(v->major, v->minor, v->patch)
          < SDL_VERSIONNUM(1, 2, 11))
        {
            snd_musicdevice = SNDDEVICE_NONE;
        }
    }
#endif
}
Exemple #19
0
void M_ApplyPlatformDefaults(void)
{
#ifdef _WIN32_WCE
    M_ApplyWindowsCEDefaults();
#endif

    // Before SDL_mixer version 1.2.11, MIDI music caused the game
    // to crash when it looped.  If this is an old SDL_mixer version,
    // disable MIDI.

#ifdef __MACOSX__
    {
        const SDL_version *v = Mix_Linked_Version();

        if (SDL_VERSIONNUM(v->major, v->minor, v->patch)
          < SDL_VERSIONNUM(1, 2, 11))
        {
            snd_musicdevice = SNDDEVICE_NONE;
        }
    }
#endif

    // Windows Vista or later?  Set screen color depth to
    // 32 bits per pixel, as 8-bit palettized screen modes
    // don't work properly in recent versions.

#if defined(_WIN32) && !defined(_WIN32_WCE)
    {
        OSVERSIONINFOEX version_info;

        ZeroMemory(&version_info, sizeof(OSVERSIONINFOEX));
        version_info.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);

        GetVersionEx((OSVERSIONINFO *) &version_info);

        if (version_info.dwPlatformId == VER_PLATFORM_WIN32_NT
         && version_info.dwMajorVersion >= 6)
        {
            screen_bpp = 32;
        }
    }
#endif
}
void M_ApplyPlatformDefaults(void)
{
#ifdef _WIN32_WCE
    M_ApplyWindowsCEDefaults();
#endif

    // Before SDL_mixer version 1.2.11, MIDI music caused the game
    // to crash when it looped.  If this is an old SDL_mixer version,
    // disable MIDI.

#ifdef __MACOSX__
    {
        const SDL_version *v = Mix_Linked_Version();

        if (SDL_VERSIONNUM(v->major, v->minor, v->patch)
          < SDL_VERSIONNUM(1, 2, 11))
        {
            snd_musicdevice = SNDDEVICE_NONE;
        }
    }
#endif
}
Exemple #21
0
dboolean I_SDL_InitSound(void)
{
    int i;

    // No sounds yet
    for (i = 0; i < NUM_CHANNELS; ++i)
        channels_playing[i] = NULL;

    if (SDL_InitSubSystem(SDL_INIT_AUDIO) < 0)
        return false;

    {
        const SDL_version       *linked = Mix_Linked_Version();

        if (linked->major != MIX_MAJOR_VERSION || linked->minor != MIX_MINOR_VERSION)
            I_Error("The wrong version of SDL2_MIXER.DLL was found. "PACKAGE_NAME" requires "
                "v%d.%d.%d, not v%d.%d.%d.", linked->major, linked->minor, linked->patch,
                MIX_MAJOR_VERSION, MIX_MINOR_VERSION, MIX_PATCHLEVEL);

        if (linked->patch != MIX_PATCHLEVEL)
            C_Warning("The wrong version of SDL2_MIXER.DLL was found. "PACKAGE_NAME" requires "
                "v%d.%d.%d, not v%d.%d.%d.", linked->major, linked->minor, linked->patch,
                MIX_MAJOR_VERSION, MIX_MINOR_VERSION, MIX_PATCHLEVEL);
    }

    if (Mix_OpenAudio(snd_samplerate, AUDIO_S16SYS, 2, GetSliceSize()) < 0)
        return false;

    Mix_QuerySpec(&mixer_freq, &mixer_format, &mixer_channels);

    Mix_AllocateChannels(NUM_CHANNELS);

    SDL_PauseAudio(0);

    sound_initialized = true;

    return true;
}
void eir_snd_api_init()
{
   SDL_version compile_version;
   const SDL_version * link_version = Mix_Linked_Version();

   SDL_MIXER_VERSION(&compile_version);
   EIR_KER_LOG_MESSAGE(
      "SDL mixer compile vers: %d.%d.%d",
      compile_version.major,
      compile_version.minor,
      compile_version.patch
      );
   EIR_KER_LOG_MESSAGE(
      "SDL mixer link vers: %d.%d.%d",
      link_version->major,
      link_version->minor,
      link_version->patch
      );

   if (Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, 2, 1024) == -1)
   {
      EIR_KER_LOG_ERROR("SDL mixer open audio init failed: %s", Mix_GetError());
   }
}
int main(int argc, char *argv[])
{
  (void) argc;
  (void) argv;

  if (SDL_Init(SDL_INIT_EVERYTHING) == -1)
    std::cout << "Failed to initialize SDL" << SDL_GetError() << std::endl;
  std::cout << "Hello SDL!" << std::endl;

  // Display SDL version information
  SDL_version compiled;
  SDL_version linked;
  SDL_VERSION(&compiled);
  SDL_GetVersion(&linked);
  logSDLVersion(std::cout, "SDL", compiled, linked, SDL_GetRevision());


  // Initialize SDL_image and display version information
  int imgFlags = IMG_INIT_PNG | IMG_INIT_JPG;
  int imgFlagsInit = IMG_Init(imgFlags);
  if ((imgFlagsInit & imgFlags) != imgFlags)
    std::cout << "Failed to initialize SDL_image:"
              << IMG_GetError() << std::endl;
  std::cout << "Hello SDL_image!" << std::endl;
  SDL_IMAGE_VERSION(&compiled);
  logSDLVersion(std::cout, "SDL_image", compiled, *IMG_Linked_Version(), "");


  // Initialize SDL_mixer and display version information
  int mixFlags = MIX_INIT_OGG;
  int mixFlagsInit = Mix_Init(mixFlags);
  if ((mixFlagsInit & mixFlags) != mixFlags) {
    std::cout << "Failed to initialize SDL_mixer"
              << Mix_GetError() << std::endl;
  }
  if (Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 1024) == -1) {
    std::cout << "Failed to acquire sound device"
              << Mix_GetError() << std::endl;
  }
  std::cout << "Hello SDL_mixer!" << std::endl;
  SDL_MIXER_VERSION(&compiled);
  logSDLVersion(std::cout, "SDL_mixer", compiled, *Mix_Linked_Version(), "");
  logSDLMixerMediaInfo(std::cout);


  // Initialize SDL_mixer and display version information
  if (TTF_Init() != 0)
    std::cout << "Failed to initialize SDL_ttf:"
              << SDL_GetError() << std::endl;
  std::cout << "Hello SDL_ttf!" << std::endl;
  SDL_TTF_VERSION(&compiled);
  logSDLVersion(std::cout, "SDL_ttf", compiled, *TTF_Linked_Version(), "");


  // Create a window and OpenGL glContext using SDL and GLEW
  SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK,
                      SDL_GL_CONTEXT_PROFILE_CORE);
  SDL_Window* window = SDL_CreateWindow("SDL Window",
                                        SDL_WINDOWPOS_UNDEFINED,
                                        SDL_WINDOWPOS_UNDEFINED,
                                        640, 480,
                                        SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);
  SDL_GLContext glContext = nullptr;
  const std::pair<int, int> glVersions[11]
     {{4, 4}, {4, 3}, {4, 2}, {4, 1}, {4, 0},
      {3, 3}, {3, 2}, {3, 1}, {3, 0},
      {2, 1}, {2, 0}
  };
  const std::string glName = "OpenGL";
  for (auto& glVersion : glVersions) {
    std::cout << "Trying to create " << glName << " " << glVersion.first << "."
              << glVersion.second << " glContext" << std::endl;
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, glVersion.first);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, glVersion.second);
    glContext = SDL_GL_CreateContext(window);
    if (glContext != nullptr)
      break;
  }
  if (glContext == nullptr)
    std::cout << "Failed to create OpenGL Context " << std::endl;

  bool isOk = SDL_GL_MakeCurrent(window, glContext) <= 0;
  if (!isOk)
    std::cout << "Failed to set OpenGL context" << SDL_GetError() << std::endl;

  glewExperimental = true;
  if (glewInit() != GLEW_OK)
    std::cout << "Failed to initialize GLEW" << std::endl;

  logAcquiredGlVersion(std::cout, glName);
  logOpenGLContextInfo(std::cout);
  logGraphicsDriverInfo(std::cout);

  glClearColor(0.1f, 0.2f, 0.3f, 1.0f);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  SDL_GL_SwapWindow(window);

  // Wait for user event before closing
  bool isRunning = true;
  SDL_Event event;
  while (isRunning) {
    while (SDL_PollEvent(&event)) {
      if (event.type == SDL_KEYDOWN &&
          event.key.keysym.scancode == SDL_SCANCODE_ESCAPE)
        isRunning = false;
      else if (event.type == SDL_QUIT)
        isRunning = false;
    }

    SDL_Delay(30);
  }

  // Cleanup
  SDL_DestroyWindow(window);
  SDL_GL_DeleteContext(glContext);
  IMG_Quit();
  const int nOpenAudio = Mix_QuerySpec(nullptr, nullptr, nullptr);
  for (int i = 0 ; i < nOpenAudio ; ++i)
    Mix_CloseAudio();
  while (Mix_Init(0))
    Mix_Quit();
  TTF_Quit();
  SDL_Quit();
  return 0;
}
Exemple #24
0
void I_InitSound (void)
{
	if(Args.CheckParm("-nosound"))
		return;

	const char *driver = getenv("SDL_AUDIODRIVER");

	if(!driver)
		driver = "default";

	Printf(PRINT_HIGH, "I_InitSound: Initializing SDL's sound subsystem (%s)\n", driver);

	if (SDL_InitSubSystem(SDL_INIT_AUDIO) < 0)
	{
		Printf(PRINT_HIGH, 
               "I_InitSound: Unable to set up sound: %s\n", 
               SDL_GetError());
               
		return;
	}

	const SDL_version *ver = Mix_Linked_Version();

	if(ver->major != MIX_MAJOR_VERSION
		|| ver->minor != MIX_MINOR_VERSION)
	{
		Printf(PRINT_HIGH, "I_InitSound: SDL_mixer version conflict (%d.%d.%d vs %d.%d.%d dll)\n",
			MIX_MAJOR_VERSION, MIX_MINOR_VERSION, MIX_PATCHLEVEL,
			ver->major, ver->minor, ver->patch);
		return;
	}

	if(ver->patch != MIX_PATCHLEVEL)
	{
		Printf(PRINT_HIGH, "I_InitSound: SDL_mixer version warning (%d.%d.%d vs %d.%d.%d dll)\n",
			MIX_MAJOR_VERSION, MIX_MINOR_VERSION, MIX_PATCHLEVEL,
			ver->major, ver->minor, ver->patch);
	}

	Printf(PRINT_HIGH, "I_InitSound: Initializing SDL_mixer\n");

    if (Mix_OpenAudio(22050, AUDIO_S16SYS, 2, 1024) < 0)
	{
		Printf(PRINT_HIGH, 
               "I_InitSound: Error initializing SDL_mixer: %s\n", 
               Mix_GetError());
		return;
	}

    if(!Mix_QuerySpec(&mixer_freq, &mixer_format, &mixer_channels))
	{
		Printf(PRINT_HIGH, 
               "I_InitSound: Error initializing SDL_mixer: %s\n", 
               Mix_GetError());
		return;
	}
	
	Printf(PRINT_HIGH, 
           "I_InitSound: Using %d channels (freq:%d, fmt:%d, chan:%d)\n",
           Mix_AllocateChannels(NUM_CHANNELS),
		   mixer_freq, mixer_format, mixer_channels);

	atterm(I_ShutdownSound);

	sound_initialized = true;

	SDL_PauseAudio(0);

	Printf(PRINT_HIGH, "I_InitSound: sound module ready\n");

	I_InitMusic();

        // Half of fix for stopping wrong sound, these need to be -1
        // to be regarded as empty (they'd be initialised to something weird)
    memset(channel_in_use, -1, sizeof(channel_in_use));
}
Exemple #25
0
void BindSoundVariables(void)
{
    M_BindIntVariable("snd_sfxdevice",            &snd_sfxdevice);
    M_BindIntVariable("snd_musicdevice",          &snd_musicdevice);
    M_BindIntVariable("snd_channels",             &numChannels);
    M_BindIntVariable("snd_samplerate",           &snd_samplerate);
    M_BindIntVariable("sfx_volume",               &sfxVolume);
    M_BindIntVariable("music_volume",             &musicVolume);

    M_BindIntVariable("use_libsamplerate",        &use_libsamplerate);
    M_BindFloatVariable("libsamplerate_scale",    &libsamplerate_scale);

    M_BindIntVariable("gus_ram_kb",               &gus_ram_kb);
    M_BindStringVariable("gus_patch_path",        &gus_patch_path);
    M_BindStringVariable("timidity_cfg_path",     &timidity_cfg_path);

    M_BindIntVariable("snd_sbport",               &snd_sbport);
    M_BindIntVariable("snd_sbirq",                &snd_sbirq);
    M_BindIntVariable("snd_sbdma",                &snd_sbdma);
    M_BindIntVariable("snd_mport",                &snd_mport);
    M_BindIntVariable("snd_maxslicetime_ms",      &snd_maxslicetime_ms);
    M_BindStringVariable("snd_musiccmd",          &snd_musiccmd);
    M_BindStringVariable("snd_dmxoption",         &snd_dmxoption);

    M_BindIntVariable("snd_cachesize",            &snd_cachesize);
    M_BindIntVariable("opl_io_port",              &opl_io_port);

    M_BindIntVariable("snd_pitchshift",           &snd_pitchshift);

    if (gamemission == strife)
    {
        M_BindIntVariable("voice_volume",         &voiceVolume);
        M_BindIntVariable("show_talk",            &show_talk);
    }

    timidity_cfg_path = M_StringDuplicate("");
    gus_patch_path = M_StringDuplicate("");

    // All versions of Heretic and Hexen did pitch-shifting.
    // Most versions of Doom did not and Strife never did.
    snd_pitchshift = gamemission == heretic || gamemission == hexen;

    // Default sound volumes - different games use different values.

    switch (gamemission)
    {
        case doom:
        default:
            sfxVolume = 8;  musicVolume = 8;
            break;
        case heretic:
        case hexen:
            sfxVolume = 10; musicVolume = 10;
            break;
        case strife:
            sfxVolume = 8;  musicVolume = 13;
            break;
    }

    // Before SDL_mixer version 1.2.11, MIDI music caused the game
    // to crash when it looped.  If this is an old SDL_mixer version,
    // disable MIDI.

#ifdef __MACOSX__
    {
        const SDL_version *v = Mix_Linked_Version();

        if (SDL_VERSIONNUM(v->major, v->minor, v->patch)
          < SDL_VERSIONNUM(1, 2, 11))
        {
            snd_musicdevice = SNDDEVICE_NONE;
        }
    }
#endif
}
void KPSdl2UserInterface::OpenWindow(int /* argc */ , char ** /* argv */)
{
    auto flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE;
    SDL_version compiled;
    SDL_version linked;
    std::stringstream message;

    SDL_VERSION(&compiled);
    SDL_GetVersion(&linked);

    BLogger::Log("SDL UserInterface initialization");
    BLogger::Log("SDL linked version: ",
                 static_cast<unsigned int>(linked.major), '.',
                 static_cast<unsigned int>(linked.minor), '.',
                 static_cast<unsigned int>(linked.patch));
    BLogger::Log("SDL compiled version: ",
                 static_cast<unsigned int>(compiled.major), '.',
                 static_cast<unsigned int>(compiled.minor), '.',
                 static_cast<unsigned int>(compiled.patch));
    BLogger::Log("SDL Header version: ",
                 SDL_MAJOR_VERSION, '.', SDL_MINOR_VERSION, '.',
                 SDL_PATCHLEVEL);
    BLogger::Log("SDL Revision: ", SDL_GetRevision());
    auto pVersion = Mix_Linked_Version();
    BLogger::Log("SDL_mixer Linked version: ",
                 static_cast<unsigned int>(pVersion->major), '.',
                 static_cast<unsigned int>(pVersion->minor), '.',
                 static_cast<unsigned int>(pVersion->patch));
    BLogger::Log("SDL_mixer Header version: ",
                 MIX_MAJOR_VERSION, '.', MIX_MINOR_VERSION, '.',
                 MIX_PATCHLEVEL);

    // Set OpenGL's context to 2.1 subset functionality profile.
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);

    // Open OpenGL Window with SDL
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) != 0)
    {
        message << "Error in SDL_Init: " << SDL_GetError();
        SDL_Quit();
        throw std::runtime_error(message.str());
    }

    if (config->FullScreen)
    {
        flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
    }

    if (!IsWindowResolutionSupported(config->ScreenXResolution,
                                     (config->ScreenXResolution * 3) / 4))
    {
        config->ScreenXResolution = 640;
    }

    window = SDL_CreateWindow(
                 GetWindowTitle().c_str(),
                 SDL_WINDOWPOS_UNDEFINED,
                 SDL_WINDOWPOS_UNDEFINED,
                 config->ScreenXResolution,
                 (config->ScreenXResolution * 3) / 4,
                 flags);

    if (window == nullptr)
    {
        message << "Error in SDL_CreateWindow: " << SDL_GetError();
        SDL_Quit();
        throw std::runtime_error(message.str());
    }

    // We intentionally do not use the SDL renderer. It only supports 2D
    // and on Windows would use DirectX and not the OpenGL backend.
    // Instead the OpenGL renderer is used together with ligGLEW.
    glContext = SDL_GL_CreateContext(window);

    if (glContext == nullptr)
    {
        message << "Error in SDL_GL_CreateContext: " << SDL_GetError();
        SDL_Quit();
        throw std::runtime_error(message.str());
    }

    // Do updates synchronized with VSync
    SDL_GL_SetSwapInterval(1);

    auto glewReturn = glewInit();

    if (glewReturn != GLEW_OK)
    {
        message << "Error in glewInit: " << glewGetErrorString(glewReturn);
        SDL_Quit();
        throw std::runtime_error(message.str());
    }

    BLogger::Log("GLEW version: ", glewGetString(GLEW_VERSION));

    SDL_DisplayMode mode;

    SDL_GetWindowDisplayMode(window, &mode);
    BLogger::Log("SDL pixel format: ", SDL_GetPixelFormatName(mode.format));
    BLogger::Log("SDL refresh rate: ", mode.refresh_rate, " Hz");

    DebugPrintOpenGLVersion();
    DebugPrintOpenGLContextVersion();
    InitializeAudio(config->TextureName);
    InitializeAfterOpen();
}
Exemple #27
0
static int main(int argc, char *argv[])
{
	if (!PHYSFSX_init(argc, argv))
		return 1;
	con_init();  // Initialise the console

	setbuf(stdout, NULL); // unbuffered output via printf
#ifdef _WIN32
	freopen( "CON", "w", stdout );
	freopen( "CON", "w", stderr );
#endif

	if (CGameArg.SysShowCmdHelp) {
		print_commandline_help();

		return(0);
	}

	printf("\nType '%s -help' for a list of command-line options.\n\n", PROGNAME);

	PHYSFSX_listSearchPathContent();
	
	if (!PHYSFSX_checkSupportedArchiveTypes())
		return(0);

#if defined(DXX_BUILD_DESCENT_I)
	if (! PHYSFSX_contfile_init("descent.hog", 1))
#define DXX_NAME_NUMBER	"1"
#define DXX_HOGFILE_NAMES	"descent.hog"
#elif defined(DXX_BUILD_DESCENT_II)
	if (! PHYSFSX_contfile_init("descent2.hog", 1) && ! PHYSFSX_contfile_init("d2demo.hog", 1))
#define DXX_NAME_NUMBER	"2"
#define DXX_HOGFILE_NAMES	"descent2.hog or d2demo.hog"
#endif
	{
#if defined(__unix__) && !defined(__APPLE__)
#define DXX_HOGFILE_PROGRAM_DATA_DIRECTORY	\
			      "\t$HOME/.d" DXX_NAME_NUMBER "x-rebirth\n"	\
			      "\t" SHAREPATH "\n"
#else
#define DXX_HOGFILE_PROGRAM_DATA_DIRECTORY	\
				  "\tDirectory containing D" DXX_NAME_NUMBER "X\n"
#endif
#if (defined(__APPLE__) && defined(__MACH__)) || defined(macintosh)
#define DXX_HOGFILE_APPLICATION_BUNDLE	\
				  "\tIn 'Resources' inside the application bundle\n"
#else
#define DXX_HOGFILE_APPLICATION_BUNDLE	""
#endif
#define DXX_MISSING_HOGFILE_ERROR_TEXT	\
		"Could not find a valid hog file (" DXX_HOGFILE_NAMES ")\nPossible locations are:\n"	\
		DXX_HOGFILE_PROGRAM_DATA_DIRECTORY	\
		"\tIn a subdirectory called 'Data'\n"	\
		DXX_HOGFILE_APPLICATION_BUNDLE	\
		"Or use the -hogdir option to specify an alternate location."
		UserError(DXX_MISSING_HOGFILE_ERROR_TEXT);
	}

#if defined(DXX_BUILD_DESCENT_I)
	switch (PHYSFSX_fsize("descent.hog"))
	{
		case D1_MAC_SHARE_MISSION_HOGSIZE:
		case D1_MAC_MISSION_HOGSIZE:
			MacHog = 1;	// used for fonts and the Automap
			break;
	}
#endif

	load_text();

	//print out the banner title
#if defined(DXX_BUILD_DESCENT_I)
	con_printf(CON_NORMAL, "%s  %s", DESCENT_VERSION, g_descent_build_datetime); // D1X version
	con_puts(CON_NORMAL, "This is a MODIFIED version of Descent, based on " BASED_VERSION ".");
	con_printf(CON_NORMAL, "%s\n%s",TXT_COPYRIGHT,TXT_TRADEMARK);
	con_puts(CON_NORMAL, "Copyright (C) 2005-2013 Christian Beckhaeuser, 2013-2017 Kp");
#elif defined(DXX_BUILD_DESCENT_II)
	con_printf(CON_NORMAL, "%s%s  %s", DESCENT_VERSION, PHYSFSX_exists(MISSION_DIR "d2x.hog",1) ? "  Vertigo Enhanced" : "", g_descent_build_datetime); // D2X version
	con_puts(CON_NORMAL, "This is a MODIFIED version of Descent 2, based on " BASED_VERSION ".");
	con_printf(CON_NORMAL, "%s\n%s",TXT_COPYRIGHT,TXT_TRADEMARK);
	con_puts(CON_NORMAL, "Copyright (C) 1999 Peter Hawkins, 2002 Bradley Bell, 2005-2013 Christian Beckhaeuser, 2013-2017 Kp");
#endif

	if (CGameArg.DbgVerbose)
	{
		{
			PHYSFS_Version vc, vl;
			PHYSFS_VERSION(&vc);
			PHYSFS_getLinkedVersion(&vl);
			con_printf(CON_VERBOSE, "D" DXX_NAME_NUMBER "X-Rebirth built with PhysFS %u.%u.%u; loaded with PhysFS %u.%u.%u", vc.major, vc.minor, vc.patch, vl.major, vl.minor, vl.patch);
		}
		{
			SDL_version vc;
			SDL_VERSION(&vc);
#if SDL_MAJOR_VERSION == 1
			const auto vl = SDL_Linked_Version();
#else
			SDL_version vlv;
			const auto vl = &vlv;
			SDL_GetVersion(vl);
#endif
			con_printf(CON_VERBOSE, "D" DXX_NAME_NUMBER "X-Rebirth built with libSDL %u.%u.%u; loaded with libSDL %u.%u.%u", vc.major, vc.minor, vc.patch, vl->major, vl->minor, vl->patch);
		}
#if DXX_USE_SDLMIXER
		{
			SDL_version vc;
			SDL_MIXER_VERSION(&vc);
			const auto vl = Mix_Linked_Version();
			con_printf(CON_VERBOSE, "D" DXX_NAME_NUMBER "X-Rebirth built with SDL_mixer %u.%u.%u; loaded with SDL_mixer %u.%u.%u", vc.major, vc.minor, vc.patch, vl->major, vl->minor, vl->patch);
		}
#endif
		con_puts(CON_VERBOSE, TXT_VERBOSE_1);
	}
	
	ReadConfigFile();

	PHYSFSX_addArchiveContent();

	arch_init();

#if !DXX_USE_OGL
	select_tmap(CGameArg.DbgTexMap);

#if defined(DXX_BUILD_DESCENT_II)
	Lighting_on = 1;
#endif
#endif

	con_puts(CON_VERBOSE, "Going into graphics mode...");
	gr_set_mode(Game_screen_mode);

	// Load the palette stuff. Returns non-zero if error.
	con_puts(CON_DEBUG, "Initializing palette system...");
#if defined(DXX_BUILD_DESCENT_I)
	gr_use_palette_table( "PALETTE.256" );
#elif defined(DXX_BUILD_DESCENT_II)
	gr_use_palette_table(D2_DEFAULT_PALETTE );
#endif

	con_puts(CON_DEBUG, "Initializing font system...");
	gamefont_init();	// must load after palette data loaded.

#if defined(DXX_BUILD_DESCENT_II)
	con_puts(CON_DEBUG, "Initializing movie libraries...");
	init_movies();		//init movie libraries
#endif

	show_titles();

	set_screen_mode(SCREEN_MENU);
#ifdef DEBUG_MEMORY_ALLOCATIONS
	/* Memdebug runs before global destructors, so it incorrectly
	 * reports as leaked any allocations that would be freed by a global
	 * destructor.  This local will force the newmenu globals to be
	 * reset before memdebug scans, which prevents memdebug falsely
	 * reporting them as leaked.
	 *
	 * External tools, such as Valgrind, know to run global destructors
	 * before checking for leaks, so this hack is only necessary when
	 * memdebug is used.
	 */
	struct hack_free_global_backgrounds
	{
		~hack_free_global_backgrounds()
		{
			newmenu_free_background();
		}
	};
	hack_free_global_backgrounds hack_free_global_background;
#endif

	con_puts(CON_DEBUG, "Doing gamedata_init...");
	gamedata_init();

#if defined(DXX_BUILD_DESCENT_II)
#if DXX_USE_EDITOR
	if (GameArg.EdiSaveHoardData) {
		save_hoard_data();
		exit(1);
	}
	#endif
#endif

	if (CGameArg.DbgNoRun)
		return(0);

	con_puts(CON_DEBUG, "Initializing texture caching system...");
	texmerge_init();		// 10 cache bitmaps

#if defined(DXX_BUILD_DESCENT_II)
	piggy_init_pigfile("groupa.pig");	//get correct pigfile
#endif

	con_puts(CON_DEBUG, "Running game...");
	init_game();

	get_local_player().callsign = {};

#if defined(DXX_BUILD_DESCENT_I)
	key_flush();
#elif defined(DXX_BUILD_DESCENT_II)
	//	If built with editor, option to auto-load a level and quit game
	//	to write certain data.
	#ifdef	EDITOR
	if (!GameArg.EdiAutoLoad.empty()) {
		Players[0u].callsign = "dummy";
	} else
	#endif
#endif
	{
		if (!CGameArg.SysPilot.empty())
		{
			char filename[sizeof(PLAYER_DIRECTORY_TEXT) + CALLSIGN_LEN + 4];

			/* Step over the literal PLAYER_DIRECTORY_TEXT when it is
			 * present.  Point at &filename[0] when
			 * PLAYER_DIRECTORY_TEXT is absent.
			 */
			const auto b = &filename[-CGameArg.SysUsePlayersDir];
			snprintf(filename, sizeof(filename), PLAYER_DIRECTORY_STRING("%.12s"), CGameArg.SysPilot.c_str());
			/* The pilot name is never used after this.  Clear it to
			 * free the allocated memory, if any.
			 */
			CGameArg.SysPilot.clear();
			auto p = b;
			for (const auto &facet = std::use_facet<std::ctype<char>>(std::locale::classic()); char &c = *p; ++p)
			{
				c = facet.tolower(static_cast<uint8_t>(c));
			}
			auto j = p - filename;
			if (j < sizeof(filename) - 4 && (j <= 4 || strcmp(&filename[j - 4], ".plr"))) // if player hasn't specified .plr extension in argument, add it
			{
				strcpy(&filename[j], ".plr");
				j += 4;
			}
			if(PHYSFSX_exists(filename,0))
			{
				get_local_player().callsign.copy(b, std::distance(b, &filename[j - 4]));
				read_player_file();
				WriteConfigFile();
			}
		}
	}

#if defined(DXX_BUILD_DESCENT_II)
#if DXX_USE_EDITOR
	if (!GameArg.EdiAutoLoad.empty()) {
		/* Any number >= FILENAME_LEN works */
		Level_names[0].copy_if(GameArg.EdiAutoLoad.c_str(), GameArg.EdiAutoLoad.size());
		LoadLevel(1, 1);
	}
	else
#endif
#endif
	{
		Game_mode = GM_GAME_OVER;
		DoMenu();
	}

	while (window_get_front())
		// Send events to windows and the default handler
		event_process();
	
	// Tidy up - avoids a crash on exit
	{
		window *wind;

		show_menus();
		while ((wind = window_get_front()))
			window_close(wind);
	}

	WriteConfigFile();
	show_order_form();

	con_puts(CON_DEBUG, "Cleanup...");
	close_game();
	texmerge_close();
	gamedata_close();
	gamefont_close();
	Current_mission.reset();
	PHYSFSX_removeArchiveContent();

	return(0);		//presumably successful exit
}
Exemple #28
0
static boolean I_SDL_InitSound(boolean _use_sfx_prefix)
{
    int i;

    use_sfx_prefix = _use_sfx_prefix;

    // No sounds yet

    for (i=0; i<NUM_CHANNELS; ++i)
    {
        channels_playing[i] = NULL;
    }

    if (SDL_Init(SDL_INIT_AUDIO) < 0)
    {
        fprintf(stderr, "Unable to set up sound.\n");
        return false;
    }

    if (Mix_OpenAudio(snd_samplerate, AUDIO_S16SYS, 2, GetSliceSize()) < 0)
    {
        fprintf(stderr, "Error initialising SDL_mixer: %s\n", Mix_GetError());
        return false;
    }

    ExpandSoundData = ExpandSoundData_SDL;

    Mix_QuerySpec(&mixer_freq, &mixer_format, &mixer_channels);

#ifdef HAVE_LIBSAMPLERATE
    if (use_libsamplerate != 0)
    {
        if (SRC_ConversionMode() < 0)
        {
            I_Error("I_SDL_InitSound: Invalid value for use_libsamplerate: %i",
                    use_libsamplerate);
        }

        ExpandSoundData = ExpandSoundData_SRC;
    }
#else
    if (use_libsamplerate != 0)
    {
        fprintf(stderr, "I_SDL_InitSound: use_libsamplerate=%i, but "
                        "libsamplerate support not compiled in.\n",
                        use_libsamplerate);
    }
#endif

    // SDL_mixer version 1.2.8 and earlier has a bug in the Mix_SetPanning
    // function that can cause the game to lock up.  If we're using an old
    // version, we need to apply a workaround.  But the workaround has its
    // own drawbacks ...

    {
        const SDL_version *mixer_version;
        int v;

        mixer_version = Mix_Linked_Version();
        v = SDL_VERSIONNUM(mixer_version->major,
                           mixer_version->minor,
                           mixer_version->patch);

        if (v <= SDL_VERSIONNUM(1, 2, 8))
        {
            setpanning_workaround = true;
            fprintf(stderr, "\n"
              "ATTENTION: You are using an old version of SDL_mixer!\n"
              "           This version has a bug that may cause "
                          "your sound to stutter.\n"
              "           Please upgrade to a newer version!\n"
              "\n");
        }
    }

    Mix_AllocateChannels(NUM_CHANNELS);

    SDL_PauseAudio(0);

    sound_initialized = true;

    return true;
}
Exemple #29
0
int32_t MUSIC_Init(int32_t SoundCard, int32_t Address)
{
#ifdef __ANDROID__
	music_initialized = 1;
	return(MUSIC_Ok);
#endif
    // Use an external MIDI player if the user has specified to do so
    char *command = getenv("EDUKE32_MUSIC_CMD");
    const SDL_version *linked = Mix_Linked_Version();

    UNREFERENCED_PARAMETER(SoundCard);
    UNREFERENCED_PARAMETER(Address);

    if (music_initialized)
    {
        setErrorMessage("Music system is already initialized.");
        return(MUSIC_Error);
    } // if

    if (SDL_VERSIONNUM(linked->major,linked->minor,linked->patch) < MIX_REQUIREDVERSION)
    {
        // reject running with SDL_Mixer versions older than what is stated in sdl_inc.h
        initprintf("You need at least v%d.%d.%d of SDL_mixer for music\n",SDL_MIXER_MIN_X,SDL_MIXER_MIN_Y,SDL_MIXER_MIN_Z);
        return(MUSIC_Error);
    }

    external_midi = (command != NULL && command[0] != 0);

    if (external_midi)
    {
#if defined FORK_EXEC_MIDI
        int32_t ws=1, numargs=0, pagesize=sysconf(_SC_PAGE_SIZE);
        char *c, *cmd;
        size_t sz;
#endif

        initprintf("Setting music command to \"%s\".\n", command);

#if !defined FORK_EXEC_MIDI
        if (Mix_SetMusicCMD(command)==-1)
        {
            perror("Mix_SetMusicCMD");
            goto fallback;
        }
#else

        if (pagesize==-1)
            goto fallback;

        for (c=command; *c; c++)
        {
            if (isspace(*c))
                ws = 1;
            else if (ws)
            {
                ws = 0;
                numargs++;
            }
        }

        if (numargs==0)
            goto fallback;

        sz = (numargs+2)*sizeof(char *) + (c-command+1);
        sz = ((sz+pagesize-1)/pagesize)*pagesize;
#if defined(__APPLE__) || defined(__ANDROID__)
        external_midi_argv = Xcalloc(1,sz+pagesize);
        external_midi_argv = (char **)((intptr_t)external_midi_argv + (pagesize-(((intptr_t)external_midi_argv)&(pagesize-1))));
#else
        if (posix_memalign((void **)&external_midi_argv, pagesize, sz))
            goto fallback;
#endif
        cmd = (char *)external_midi_argv + (numargs+2)*sizeof(char *);
        Bmemcpy(cmd, command, c-command+1);

        ws = 1;
        numargs = 0;
        for (c=cmd; *c; c++)
        {
            if (isspace(*c))
            {
                ws = 1;
                *c = 0;
            }
            else if (ws)
            {
                ws = 0;
                external_midi_argv[numargs++] = c;
            }
        }
        external_midi_argv[numargs] = external_midi_tempfn;
        external_midi_argv[numargs+1] = NULL;

        if (mprotect(external_midi_argv, sz, PROT_READ)==-1)  // make argv and command string read-only
        {
            perror("MUSIC_Init: mprotect");
            goto fallback;
        }
# if 0
        {
            int i;
            initprintf("----Music argv:\n");
            for (i=0; i<numargs+1; i++)
                initprintf("  %s\n", external_midi_argv[i]);
            initprintf("----\n");
        }
# endif
#endif
        music_initialized = 1;
        return(MUSIC_Ok);

fallback:
        initprintf("Error setting music command, falling back to timidity.\n");
    }

    {
        static const char *s[] = { "/etc/timidity.cfg", "/etc/timidity/timidity.cfg", "/etc/timidity/freepats.cfg" };
        FILE *fp;
        int32_t i;

        for (i = ARRAY_SIZE(s)-1; i>=0; i--)
        {
            fp = Bfopen(s[i], "r");
            if (fp == NULL)
            {
                if (i == 0)
                {
                    initprintf("Error: couldn't open any of the following files:\n");
                    for (i = ARRAY_SIZE(s)-1; i>=0; i--)
                        initprintf("%s\n",s[i]);
                    return(MUSIC_Error);
                }
                continue;
            }
            else break;
        }
        Bfclose(fp);
    }

    music_initialized = 1;
    return(MUSIC_Ok);
} // MUSIC_Init
void KPSdl12UserInterface::OpenWindow(int /* argc */ , char ** /* argv */)
{
    auto flags = SDL_OPENGL | SDL_RESIZABLE;

    BLogger::Log("SDL UserInterface initialization");
    auto pVersion = SDL_Linked_Version();
    BLogger::Log("SDL Linked version: ",
                 static_cast<unsigned int>(pVersion->major), '.',
                 static_cast<unsigned int>(pVersion->minor), '.',
                 static_cast<unsigned int>(pVersion->patch));
    BLogger::Log("SDL Header version: ",
                 SDL_MAJOR_VERSION, '.', SDL_MINOR_VERSION, '.',
                 SDL_PATCHLEVEL);
    pVersion = Mix_Linked_Version();
    BLogger::Log("SDL_mixer Linked version: ",
                 static_cast<unsigned int>(pVersion->major), '.',
                 static_cast<unsigned int>(pVersion->minor), '.',
                 static_cast<unsigned int>(pVersion->patch));
    BLogger::Log("SDL_mixer Header version: ",
                 MIX_MAJOR_VERSION, '.', MIX_MINOR_VERSION, '.',
                 MIX_PATCHLEVEL);

    // Open OpenGL Window with SDL
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_NOPARACHUTE) < 0)
    {
        std::stringstream message;

        message << "Error in SDL_Init: " << SDL_GetError();
        throw std::runtime_error(message.str());
    }

    // Full-screen mode is not supported. Disable full-screen flag.
    config->FullScreen = false;

    if (!IsWindowResolutionSupported(config->ScreenXResolution,
                                     (config->ScreenXResolution * 3) / 4))
    {
        config->ScreenXResolution = 640;
    }

    screen = SDL_SetVideoMode(
                 config->ScreenXResolution,
                 (config->ScreenXResolution * 3) / 4,
                 config->ColorDepth,
                 flags);

    if (screen == nullptr)
    {
        std::stringstream message;

        message << "Error in SDL_SetVideoMode: " << SDL_GetError();
        SDL_Quit();
        throw std::runtime_error(message.str());
    }

    SDL_WM_SetCaption(GetWindowTitle().c_str(), GetWindowTitle().c_str());

    DebugPrintOpenGLVersion();
    InitializeAudio(config->TextureName);
    InitializeAfterOpen();
}