ResearchItem::ResearchItem()
:   Building(),
    m_researchType(-1),
    m_inLibrary(false),
    m_reprogrammed(100.0),
    m_end1(NULL),
    m_end2(NULL),
    m_level(1),
	m_percentResearchedSmooth(0.0f)
{
    m_type = TypeResearchItem;
    m_researchType = GlobalResearch::TypeEngineer;
    
    SetShape( g_app->m_resource->GetShape( "researchitem.shp" ) );    

    m_front.RotateAroundY( frand(2.0 * M_PI) );

    const char end1Name[] = "MarkerGrab1";
    m_end1 = m_shape->m_rootFragment->LookupMarker( end1Name );
    AppReleaseAssert( m_end1, "ResearchItem: Can't get Marker(%s) from shape(%s), probably a corrupted file\n", end1Name, m_shape->m_name );

    const char end2Name[] = "MarkerGrab2";
    m_end2 = m_shape->m_rootFragment->LookupMarker( end2Name );
    AppReleaseAssert( m_end2, "ResearchItem: Can't get Marker(%s) from shape(%s), probably a corrupted file\n", end2Name, m_shape->m_name );
}
void LanguageTable::LoadCurrentLanguage()
{
	if( !m_lang )
	{
		char *interfaceLanguage = g_preferences->GetString( PREFS_INTERFACE_LANGUAGE, "english" );

		AppReleaseAssert( interfaceLanguage, "Couldn't find language preference '%s'", PREFS_INTERFACE_LANGUAGE );

		if( !GetLanguageSelectable( interfaceLanguage ) )
		{
			interfaceLanguage = m_defaultLanguage;
		}

		for( int i = 0; i < m_languages.Size(); i++ )
		{
			Language *thisLang = m_languages.GetData( i );
			if( stricmp( thisLang->m_name, interfaceLanguage ) == 0 )
			{
				m_lang = new Language( *thisLang );
				break;
			}
		}

		AppReleaseAssert( m_lang, "Couldn't find language '%s'", interfaceLanguage );
	}
	
    g_languageTable->LoadBaseLanguage( "data/language/english.txt" );
	if( stricmp( m_lang->m_name, "english" ) != 0 )
	{
		g_languageTable->LoadTranslation( m_lang->m_path );
	}

	SaveCurrentLanguage( m_lang );
}
예제 #3
0
void EclRegisterWindow ( EclWindow *window, EclWindow *parent )
{
    
    AppAssert( window );

    if ( EclGetWindow ( window->m_name ) )
    {
        AppReleaseAssert( false, "Window %s already exists", window->m_name );
    }

    if( parent && window->m_x == 0 && window->m_y == 0 )
    {
        // We should place the window in a decent locatiom
        int left = screenW / 2 - parent->m_x;
        int above = screenH / 2 - parent->m_y;
        if( left > window->m_w / 2 )    window->m_x = int( parent->m_x + parent->m_w * (float) rand() / (float) RAND_MAX );
        else                            window->m_x = int( parent->m_x - window->m_w * (float) rand() / (float) RAND_MAX );
        if( above > window->m_h / 2 )   window->m_y = int( parent->m_y + parent->m_h * (float) rand() / (float) RAND_MAX );
        else                            window->m_y = int( parent->m_y - window->m_h/2 * (float) rand() / (float) RAND_MAX );
    }

    if( window->m_x < 0 ) window->m_x = 0;
    if( window->m_y < 0 ) window->m_y = 0;
    if( window->m_x + window->m_w > screenW ) window->m_x = screenW - window->m_w;
    if( window->m_y + window->m_h > screenH ) window->m_y = screenH - window->m_h;

    windows.PutDataAtStart ( window );
    window->Create();

    EclSetCurrentFocus( window->m_name );
}
Building::Building()
:   m_front(1,0,0),
    m_radius(13.0),
	m_timeOfDeath(-1.0),
	m_shape(NULL),
	m_dynamic(false),
	m_isGlobal(false),
	m_destroyed(false)
{
    if( !s_controlPad )
    {
        s_controlPad = g_app->m_resource->GetShape( "controlpad.shp" );
        AppDebugAssert( s_controlPad );

        const char controlPadStatusName[] = "MarkerStatus";
        s_controlPadStatus = s_controlPad->m_rootFragment->LookupMarker( controlPadStatusName );
        AppReleaseAssert( s_controlPadStatus, "Building: Can't get Marker(%s) from shape(%s), probably a corrupted file\n", controlPadStatusName, s_controlPad->m_name );
    }

    if( g_app->IsSinglePlayer() )
    {
        m_id.SetTeamId(1);
    }
    else
    {
        m_id.SetTeamId(255);
    }
    
    m_up = g_upVector;
}
void SoundLibrary3dSoftware::EnableDspFX(int _channel, int _numFilters, int const *_filterTypes)
{
    AppReleaseAssert( _numFilters > 0, "Bad argument passed to EnableFilters" );

	SoftwareChannel *channel = &m_channels[_channel];
    for( int i = 0; i < _numFilters; ++i )
    {
		AppDebugAssert(_filterTypes[i] >= 0 && _filterTypes[i] < NUM_FILTERS);
		
		channel->m_dspFX[_filterTypes[i]].m_chainIndex = i;

		switch (_filterTypes[i])
		{
			case DSP_RESONANTLOWPASS:
				channel->m_dspFX[_filterTypes[i]].m_userFilter = new DspResLowPass(m_sampleRate);
				break;
			case DSP_BITCRUSHER:
				channel->m_dspFX[_filterTypes[i]].m_userFilter = new DspBitCrusher(m_sampleRate);
				break;
			case DSP_GARGLE:
				channel->m_dspFX[_filterTypes[i]].m_userFilter = new DspGargle(m_sampleRate);
				break;
			case DSP_ECHO:
				channel->m_dspFX[_filterTypes[i]].m_userFilter = new DspEcho(m_sampleRate);
				break;
			case DSP_SIMPLE_REVERB:
				channel->m_dspFX[_filterTypes[i]].m_userFilter = new DspReverb(m_sampleRate);
				break;
		}
    }
}
예제 #6
0
void HashTable<T>::Grow()
{
	AppReleaseAssert(m_size < 65536, "Hashtable grew too large");

	unsigned int oldSize = m_size;
	m_size *= 2;
	m_mask = m_size - 1;
	char **oldKeys = m_keys;
	m_keys = new char *[m_size];
	T *oldData = m_data;
	m_data = new T [m_size];

	m_numCollisions = 0;

	// Set all m_keys' pointers to NULL
	memset(m_keys, 0, sizeof(char *) * m_size);
	memset(m_data, 0, sizeof(T) * m_size);

	for (unsigned int i = 0; i < oldSize; ++i)
	{
		if (oldKeys[i])
		{
			unsigned int newIndex = GetInsertPos(oldKeys[i]);
			m_keys[newIndex] = oldKeys[i];
			m_data[newIndex] = oldData[i];
		}
	}

	m_slotsFree += m_size - oldSize;

	delete [] oldKeys;
	delete [] oldData;
}
// 0 = silence, 255 = full volume
void SoundLibrary3d::SetMasterVolume( int _volume )
{
	AppReleaseAssert(_volume >=0 && _volume <= 255, "Invalid value passed to SoundLibrary3d::SetMasterVolume");

	// Converts 0-255 into 1/100ths of a decibel of attenuation
	m_masterVolume = (float)(255 - _volume) * -32.0f;
}
void Bridge::SetBridgeType ( int _type )
{
    m_bridgeType = _type;
    SetShape( m_shapes[m_bridgeType] );

    const char signalName[] = "MarkerSignal";
    m_signal = m_shape->m_rootFragment->LookupMarker( signalName );
    AppReleaseAssert( m_signal, "Bridge: Can't get Marker(%s) from shape(%s), probably a corrupted file\n", signalName, m_shape->m_name );
}
void EntityBlueprint::Initialise()
{
	TextReader *theFile = g_app->m_resource->GetTextReader("stats.txt");
	AppReleaseAssert(theFile && theFile->IsOpen(), "Couldn't open stats.txt");

    int entityIndex = 0;

    while( theFile->ReadLine() )
    {
		if (!theFile->TokenAvailable()) continue;		
        AppReleaseAssert(entityIndex < Entity::NumEntityTypes, "Too many entity blueprints defined");
		
        m_names[entityIndex] = strdup(theFile->GetNextToken());
		m_stats[entityIndex][0] = iv_atof(theFile->GetNextToken());
        m_stats[entityIndex][1] = iv_atof(theFile->GetNextToken());
        m_stats[entityIndex][2] = iv_atof(theFile->GetNextToken());

        ++entityIndex;
    }

	delete theFile;
}
SoundLibrary3dSoftware::SoundLibrary3dSoftware()
:   SoundLibrary3d(),
	m_channels(NULL),
	m_listenerFront(1,0,0),
	m_listenerUp(0,1,0)
{
	AppReleaseAssert(g_soundLibrary2d, "SoundLibrary2d must be initialised before SoundLibrary3d");
	
	g_soundLibrary2d->SetCallback(SoundLib3dSoftwareCallbackWrapper);

	m_left = new float[g_soundLibrary2d->m_samplesPerBuffer];
	m_right = new float[g_soundLibrary2d->m_samplesPerBuffer];
}
예제 #11
0
SoundLibrary2dSDL::SoundLibrary2dSDL()
:	m_bufferIsThirsty(0), 
	m_callback(NULL),
	m_wavOutput(NULL)
{
	AppReleaseAssert(!g_soundLibrary2d, "SoundLibrary2dSDL already exists");

	m_freq = g_preferences->GetInt("SoundMixFreq", 44100);
	m_samplesPerBuffer = g_preferences->GetInt("SoundBufferSize", 2000);

	// Initialise the output device

	SDL_AudioSpec desired;
	
	desired.freq = m_freq;
	desired.format = AUDIO_S16SYS;
	desired.samples = m_samplesPerBuffer;
	desired.channels = 2;
	desired.userdata = 0;
	desired.callback = sdlAudioCallback;
	
	AppDebugOut("Initialising SDL Audio\n");
	if (SDL_OpenAudio(&desired, &s_audioSpec) < 0) {
		const char *errString = SDL_GetError();
		AppReleaseAssert(false, "Failed to open audio output device: \"%s\"", errString);
	}
	else {
		AppDebugOut("Frequency: %d\nFormat: %d\nChannels: %d\nSamples: %d\n", s_audioSpec.freq, s_audioSpec.format, s_audioSpec.channels, s_audioSpec.samples);
		AppDebugOut("Size of Stereo Sample: %u\n", sizeof(StereoSample));
	}
	
	s_audioStarted = 1;
	
	m_samplesPerBuffer = s_audioSpec.samples;
	
	// Start the callback function
	if (g_preferences->GetInt("Sound", 1)) 
		SDL_PauseAudio(0);
}
FeedingTube::FeedingTube()
:   m_receiverId(-1),
    m_range(0.0),
	m_signal(0.0)
{
    m_type = Building::TypeFeedingTube;
    //m_front.Set(0,0,1);    

    SetShape( g_app->m_resource->GetShape( "feedingtube.shp" ) );

	const char focusMarkerName[] = "MarkerFocus";
	m_focusMarker = m_shape->m_rootFragment->LookupMarker( focusMarkerName );
	AppReleaseAssert( m_focusMarker, "FeedingTube: Can't get Marker(%s) from shape(%s), probably a corrupted file\n", focusMarkerName, m_shape->m_name );
}
void SoulDestroyer::Begin()
{
    if( !s_shapeHead[m_id.GetTeamId()] || !s_shapeTail[m_id.GetTeamId()] )
    {
        char headfilename[256], headshapename[256], tailfilename[256], tailshapename[256];

        Team *team = g_app->m_location->m_teams[m_id.GetTeamId()];
        int colourId = team->m_lobbyTeam->m_colourId;
        int groupId = team->m_lobbyTeam->m_coopGroupPosition;

        strcpy( headshapename, "souldestroyerhead.shp" );
        strcpy( tailshapename, "souldestroyertail.shp");

        sprintf( headfilename, "%s_%d_%d", headshapename, colourId, groupId );
        sprintf( tailfilename, "%s_%d_%d", tailshapename, colourId, groupId );

        Shape *head = g_app->m_resource->GetShape( headfilename, false );
        if( !head )
        {
            head = g_app->m_resource->GetShapeCopy( headshapename, false );
            ConvertShapeColoursToTeam( head, m_id.GetTeamId(), false );
            g_app->m_resource->AddShape( head, headfilename );
        }
        s_shapeHead[m_id.GetTeamId()] = head;

        Shape *tail = g_app->m_resource->GetShape( tailfilename, false );
        if( !tail )
        {
            tail = g_app->m_resource->GetShapeCopy( tailshapename, false );
            ConvertShapeColoursToTeam( tail, m_id.GetTeamId(), false );
            g_app->m_resource->AddShape( tail, tailfilename );
        }
        s_shapeTail[m_id.GetTeamId()] = tail;

        const char tailMarkerName[] = "MarkerTail";
        s_tailMarker[m_id.GetTeamId()] = s_shapeHead[m_id.GetTeamId()]->m_rootFragment->LookupMarker( tailMarkerName );
        AppReleaseAssert( s_tailMarker[m_id.GetTeamId()], "SoulDestroyer: Can't get Marker(%s) from shape(%s), probably a corrupted file\n", tailMarkerName, s_shapeHead[m_id.GetTeamId()]->m_name );
    }
    m_shape = s_shapeTail[ m_id.GetTeamId() ];

    Entity::Begin();

    m_up = g_upVector;
    m_pos.y = g_app->m_location->m_landscape.m_heightMap->GetValue( m_pos.x, m_pos.z );

    // This line to make it a bit easier to hit them with missiles
    m_radius *= 1.5;
}
bool SoundLibrary3dSoftware::Initialise(int _mixFreq, int _numChannels, bool _hw3d, 
										int _mainBufNumSamples, int _musicBufNumSamples )
{
	m_sampleRate = _mixFreq;
	m_musicChannelId = _numChannels - 1;

	int log2NumChannels = ceilf(Log2(_numChannels));
	m_numChannels = 1 << log2NumChannels;
	AppReleaseAssert(m_numChannels == _numChannels, "Num channels must be a power of 2");

	m_channels = new SoftwareChannel[m_numChannels];

	// Initialise music channel
	SetChannel3DMode(m_musicChannelId, 2);
	SetChannelVolume(m_musicChannelId, 10.0f);

	return true;
}
void SoundLibrary3dDirectSound::SetChannelMinDistance( int _channel, float _minDistance )
{
	DirectSoundChannel *channel;
	if (_channel == m_musicChannelId) channel = m_musicChannel;
	else				channel = &m_channels[_channel];

	if (!NearlyEquals(_minDistance, channel->m_minDist))
	{
        AppReleaseAssert( _minDistance >= DS3D_DEFAULTMINDISTANCE && 
                       _minDistance <= DS3D_DEFAULTMAXDISTANCE,
                       "Channel MinDistance must be between %2.2f and %2.2f."
                       "You requested %2.2f", 
                       DS3D_DEFAULTMINDISTANCE, DS3D_DEFAULTMAXDISTANCE,
                       _minDistance );
        

		channel->m_minDist = _minDistance;
		
		IDirectSound3DBuffer *buffer3d = channel->m_buffer3DInterface;
		int errCode = buffer3d->SetMinDistance( _minDistance, DS3D_DEFERRED );
		SOUNDASSERT(errCode, "Direct sound couldn't set buffer3d min distance");
	}
}
예제 #16
0
파일: defcon.cpp 프로젝트: cahocachi/DEFCON
void DefconMain()
{
    g_app = new App();
    g_app->MinimalInit();

	g_app->FinishInit();

    double nextServerAdvanceTime = GetHighResTime();
    double serverAdvanceStartTime = -1;
    double lastRenderTime = GetHighResTime();

    bool serverRunning = false;

#ifdef TESTBED
    FILE *file = fopen("testbed-results.txt", "w" );
    if( file ) fclose( file );
#endif

    //
    // Main loops

	while(true)
    {
        //
        // Get the time
        double timeNow = GetHighResTime();

        //
        // Advance the server
        if( g_app->GetServer() && g_app->GetServer()->IsRunning() )
        {
            if( !serverRunning )
            {
                nextServerAdvanceTime = GetHighResTime();
                serverAdvanceStartTime = -1;
                serverRunning = true;
            }


#ifdef TESTBED
            if( g_app->m_gameRunning )
            {
                if( g_app->GetServer()->TestBedReadyToContinue() ||
                    timeNow > nextServerAdvanceTime )
                {
                    g_app->GetServer()->Advance();
                    nextServerAdvanceTime = GetHighResTime() + 0.3f;
                }
            }
            else
            {
                if( timeNow > nextServerAdvanceTime )            
                {
                    g_app->GetServer()->Advance();
                    nextServerAdvanceTime = GetHighResTime() + 0.5f;
                }
            }            
#else
            if( timeNow > nextServerAdvanceTime )            
            {
                g_app->GetServer()->Advance();
                float timeToAdd = SERVER_ADVANCE_PERIOD.DoubleValue();
                if( !g_app->m_gameRunning ) timeToAdd *= 5.0f;
                nextServerAdvanceTime += timeToAdd;
                if (timeNow > nextServerAdvanceTime)
                {
                    nextServerAdvanceTime = timeNow + timeToAdd;
                }
            }        
#endif
        }        

        if( g_app->GetClientToServer() )        
        {            
            START_PROFILE("Client Main Loop");

			g_app->GetClientToServer()->Advance();

#ifdef TESTBED
            if( g_app->m_gameRunning &&
                g_app->GetGame()->m_winner != -1 )
            {
                RestartTestBed(1, "Game Over");
            }

            if( g_app->GetClientToServer()->m_outOfSyncClients.Size() )
            {                
                char notes[256];
                sprintf( notes, "SYNC ERROR at %s", g_app->GetWorld()->m_theDate.GetTheDate() );
                RestartTestBed(-1, notes );
            }

            if( g_app->m_gameRunning &&
                g_app->GetWorld()->m_theDate.m_theDate > 10 )
            {
                float estimatedLatency = g_app->GetClientToServer()->GetEstimatedLatency();
                if( estimatedLatency > 60.0f )
                {
                    RestartTestBed(-1, "Connection lost" );
                }

                if( g_app->GetServer() &&
                    g_app->GetServer()->m_clients.NumUsed() < g_app->GetGame()->GetOptionValue("MaxTeams") )
                {
                    RestartTestBed(-1, "Client lost connection" );
                }
            }
#endif


            //
            // Read latest update from Server
            Directory *letter = g_app->GetClientToServer()->GetNextLetter();

            if( letter )
            {
                if( !strcmp(letter->m_name, NET_DEFCON_MESSAGE) == 0 ||
                    !letter->HasData(NET_DEFCON_SEQID, DIRECTORY_TYPE_INT) )
                {
                    AppDebugOut( "Client received bogus message, discarded (5)\n" );
                    delete letter;
                }
                else
                {
                    int seqId = letter->GetDataInt( NET_DEFCON_SEQID );                
                    if( seqId == -1 )
                    {
                        // This letter is just for us
                        ProcessServerLetters( letter );
                        delete letter;
                    }
                    else
                    {
                        AppReleaseAssert( seqId == g_lastProcessedSequenceId + 1, "Networking broken!" );

                        bool handled = ProcessServerLetters(letter);
                        if(!handled)
                        {
                            g_app->GetClientToServer()->ProcessServerUpdates( letter );
                        }
                
                        if( g_app->m_gameRunning )
                        {
                            g_app->GetWorld()->Update();
                        }
                        else
                        {
                            HandleGameStart();
                        }

                        g_lastServerAdvance = (float)seqId * SERVER_ADVANCE_PERIOD.DoubleValue() + g_startTime;
                        g_lastProcessedSequenceId = seqId;       

                        delete letter;            
                               
                        if( seqId == 0 && g_app->GetClientToServer()->m_resynchronising > 0.0f )
                        {
                            AppDebugOut( "Client successfully began Resynchronising\n" );
                            g_app->GetClientToServer()->m_resynchronising = -1.0f;
                        }

                        unsigned char sync = GenerateSyncValue();
                        SyncRandLog( "Sync %d = %d", g_lastProcessedSequenceId, sync );
                        g_app->GetClientToServer()->SendSyncronisation( g_lastProcessedSequenceId, sync );
                    }
                }
            }

            END_PROFILE("Client Main Loop");
        }

        //
        // Render

        UpdateAdvanceTime();

        if( TimeToRender(lastRenderTime) )
        {
            lastRenderTime = GetHighResTime();
            g_app->Update();
            g_app->Render();
            g_soundSystem->Advance();
            if( g_profiler ) g_profiler->Advance();
        }
    }
	delete g_app;
	g_app = NULL;
}
void LanguageTable::LoadLanguage(char *_filename, BTree<char *> &_langTable )
{
    TextReader *in = g_fileSystem->GetTextReader(_filename);
	AppReleaseAssert(in && in->IsOpen(), "Couldn't open language file %s", _filename );

    //
	// Read all the phrases from the language file

	while (in->ReadLine())
	{
		if (!in->TokenAvailable()) continue;

		char *key = in->GetNextToken();	


#ifdef TARGET_OS_MACOSX
        // 
        // Special case hack
        // If this is the Mac version and there is a replacement string
        // Use the replacement string instead
        #define MACOSX_MARKER "macosx_"
        if( strncmp( key, MACOSX_MARKER, strlen(MACOSX_MARKER) ) == 0 )
        {
            key += strlen(MACOSX_MARKER);
        }
#endif


        //
		// Make sure the this key isn't already used

		if(_langTable.LookupTree(key))
        {
            //AppDebugOut( "Warning : found duplicate key '%s' in language file %s\n", key, _filename );
            _langTable.RemoveData( key );
        }

		char *aString = strdup( in->GetRestOfLine() ); 
        
        //
		// Make sure a language key always has a some text with it

		if( !aString || aString[0] == '\0' )
		{
            AppDebugOut( "Warning : found key '%s' with no translation in language file %s\n", key, _filename );

			if( aString )
			{
				delete [] aString;
			}
			continue;
		}

        //
        // Convert the string "\n" into a genuine '\n'

        for( unsigned int i = 0; i < strlen(aString)-1; ++i )
        {
            if( aString[i] == '\\' && aString[i+1] == 'n' )
            {
                aString[i] = ' ';
                aString[i+1] = '\n';
            }
        }
        
        //
        // Strip trailing '\n'
        
        int stringLength = strlen( aString );
        if( aString[stringLength-1] == '\n' ) 
        {
            aString[stringLength-1] = '\x0';
        }

        if( aString[stringLength-2] == '\r' )
        {
            aString[stringLength-2] = '\x0';
        }

		_langTable.PutData(key, aString);
	}

    delete in;
}
void LanguageTable::TestTranslation( char *_logFilename )
{
    //
    // Open the errors file

    FILE *output = fopen( _logFilename, "wt" );
    AppReleaseAssert( output, "Failed to open logfile %s", _logFilename );
    
    
    //
    // Look for strings in the base that are not in the translation
    
    DArray<char *> *basePhraseIndex = m_baseLanguage.ConvertIndexToDArray();
    DArray<char *> *basePhrases = m_baseLanguage.ConvertToDArray();

    for( int i = 0; i < basePhraseIndex->Size(); ++i )
    {
        if( basePhraseIndex->ValidIndex(i) )
        {
            char *baseIndex = basePhraseIndex->GetData(i);
            char *basePhrase = basePhrases->GetData(i);

            if( !DoesTranslationExist( baseIndex ) )
            {
                fprintf( output, "ERROR : Failed to find translation for string ID '%s'\n", baseIndex );
            }
            else
            {
                char *translatedPhrase = m_translation.GetData( baseIndex );
                if( strcmp( basePhrase, translatedPhrase ) == 0 )
                {
                    fprintf( output, "Warning : String ID appears not to be translated : '%s'\n", baseIndex );
                }
            }
        }
    }

    delete basePhraseIndex;
    delete basePhrases;


    //
    // Look for phrases in the translation that are not in the base

    DArray<char *> *translatedIndex = m_translation.ConvertIndexToDArray();

    for( int i = 0; i < translatedIndex->Size(); ++i )
    {
        if( translatedIndex->ValidIndex(i) )
        {
            char *index = translatedIndex->GetData(i);

            if( !DoesPhraseExist( index ) )
            {
                fprintf( output, "Warning : Found new string ID not present in original English : '%s'\n", index );               
            }
        }
    }

    delete translatedIndex;

    
    //
    // Clean up
    
    fclose( output );
}
void SoundLibrary3dDirectSound::UpdateDspFX( int _channel, int _filterType, int _numParams, float const *_params )
{
	AppDebugAssert(_channel >= 0 && _channel < m_numChannels);
	AppDebugAssert(GetNumFilters(_channel) > 0);

	DirectSoundChannel *channel;
	if (_channel == m_musicChannelId) channel = m_musicChannel;
	else				channel = &m_channels[_channel];

	if (_filterType <= DSP_DSOUND_WAVESREVERB)
	{
		int errCode;
		IDirectSoundBuffer8 *buffer = (IDirectSoundBuffer8 *) channel->m_bufferInterface;
        
		IUnknown *effect;
		GUID sfxClass = *s_dxDescriptors[_filterType].m_sfxClass;
		GUID interfaceClass = *s_dxDescriptors[_filterType].m_interfaceClass;
		errCode = buffer->GetObjectInPath(sfxClass, 
										  0, 
										  interfaceClass, 
										  (void **) &effect );
		SOUNDASSERT( errCode, "Failed to get hold of DirectFX filter" );
    
		switch( _filterType )
		{
			case DSP_DSOUND_CHORUS:         
				errCode = ((IDirectSoundFXChorus8 *)effect)->SetAllParameters( (DSFXChorus *)_params );          
				break;
			case DSP_DSOUND_COMPRESSOR:     
				errCode = ((IDirectSoundFXCompressor8 *)effect)->SetAllParameters( (DSFXCompressor *)_params );          
				break;
			case DSP_DSOUND_DISTORTION:     
				errCode = ((IDirectSoundFXDistortion8 *)effect)->SetAllParameters( (DSFXDistortion *)_params );          
				break;
			case DSP_DSOUND_ECHO:           
				errCode = ((IDirectSoundFXEcho8 *)effect)->SetAllParameters( (DSFXEcho *)_params );          
				break;
			case DSP_DSOUND_FLANGER:        
				errCode = ((IDirectSoundFXFlanger8 *)effect)->SetAllParameters( (DSFXFlanger *)_params );          
				break;
			case DSP_DSOUND_GARGLE:         
				errCode = ((IDirectSoundFXGargle8 *)effect)->SetAllParameters( (DSFXGargle *)_params );          
				break;
			case DSP_DSOUND_PARAMEQ:        
				errCode = ((IDirectSoundFXParamEq8 *)effect)->SetAllParameters( (DSFXParamEq *)_params );          
				break;
			case DSP_DSOUND_WAVESREVERB:    
				errCode = ((IDirectSoundFXWavesReverb8 *)effect)->SetAllParameters( (DSFXWavesReverb *)_params );          
				break;
			case DSP_DSOUND_I3DL2REVERB:    
				errCode = ((IDirectSoundFXI3DL2Reverb8 *)effect)->SetAllParameters( (DSFXI3DL2Reverb *)_params );
				errCode = ((IDirectSoundFXI3DL2Reverb8 *)effect)->SetQuality( _params[12] );                                 
				break;
			default:
				AppReleaseAssert( false, "Unknown filter type" );
		}
	
		SOUNDASSERT( errCode, "Failed to set filter parameters" );
	}
    else
	{
		AppDebugAssert(channel->m_dspFX[_filterType].m_userFilter);
        channel->m_dspFX[_filterType].m_userFilter->SetParameters( _params );
    }
}
예제 #20
0
void SoundLibrary2dSDL::StartRecordToFile(char const *_filename)
{
	m_wavOutput = fopen(_filename, "wb");
	AppReleaseAssert(m_wavOutput != NULL, "Couldn't create wave outout file %s", _filename);
}
bool SoundLibrary3dDirectSound::Initialise(int _mixFreq, int _numChannels, bool _hw3d, 
										   int _mainBufNumSamples, int _musicBufNumSamples )
{    
    int errCode;

    AppReleaseAssert( g_systemInfo->m_directXVersion >= 9.0f, APP_NAME " requires DirectX9 or Greater" );
	AppReleaseAssert( _numChannels > 0, "SoundLibrary3d asked to create too few channels" );


    //
    // Initialise COM
    // We need to do this in order to use the directX FX stuff

    errCode = CoInitialize( NULL );

    
    //
	// Create Direct Sound Device

	errCode = DirectSoundCreate8(NULL,              // Specifies default device 
								 &m_directSound->m_device,
								 NULL);             // Has to be NULL - stupid, stupid Microsoft
	SOUNDASSERT(errCode, "Direct Sound couldn't create a sound device");
    

	errCode = m_directSound->m_device->SetCooperativeLevel((HWND)g_windowManager->Window(), DSSCL_PRIORITY);
	SOUNDASSERT(errCode, "Direct Sound couldn't set the cooperative level");

	
    RefreshCapabilities();


	m_sampleRate = _mixFreq;
	m_hw3dDesired = _hw3d;
	m_numChannels = min( _numChannels, GetMaxChannels() ) - 1;	// Reserve one channel for the music
	m_musicChannelId = -1;

    
	// 
	// Create the Primary Sound Buffer
	
	{		
        int flags = DSBCAPS_PRIMARYBUFFER |
                    DSBCAPS_CTRL3D;
        if( Hardware3DSupport() && m_hw3dDesired )   flags |= DSBCAPS_LOCHARDWARE;
        else                                         flags |= DSBCAPS_LOCSOFTWARE;
        
		DSBUFFERDESC dsbd;
		ZeroMemory( &dsbd, sizeof(DSBUFFERDESC) );
		dsbd.dwSize        = sizeof(DSBUFFERDESC);
		dsbd.dwFlags       = flags;
		dsbd.dwBufferBytes = 0;
		dsbd.lpwfxFormat   = NULL;
       
		errCode = m_directSound->m_device->CreateSoundBuffer(&dsbd, &m_directSound->m_primaryBuffer, NULL);
		SOUNDASSERT(errCode, "Direct sound couldn't create the primary sound buffer");

		WAVEFORMATEX wfx;
		ZeroMemory( &wfx, sizeof(WAVEFORMATEX) ); 
		wfx.wFormatTag      = (WORD) WAVE_FORMAT_PCM; 
		wfx.nChannels       = 2; 
		wfx.nSamplesPerSec  = _mixFreq; 
		wfx.wBitsPerSample  = 16;
		wfx.nBlockAlign     = (WORD) (wfx.wBitsPerSample / 8 * wfx.nChannels);
		wfx.nAvgBytesPerSec = (DWORD) (wfx.nSamplesPerSec * wfx.nBlockAlign);

		errCode = m_directSound->m_primaryBuffer->SetFormat(&wfx);
		SOUNDASSERT(errCode, "Direct sound couldn't set the primary sound buffer format");
	}

    
	//
	// Create a streaming secondary buffer for each channel

    m_channels = new DirectSoundChannel[ m_numChannels ];

    for( int i = 0; i < m_numChannels; ++i )
    {
        m_channels[i].m_bufferInterface = CreateSecondaryBuffer(_mainBufNumSamples);

		//
		// Earlier return if CreateSecondaryBuffer fails

		if( !m_channels[i].m_bufferInterface )
		{
			return false;
		}

		m_channels[i].m_numBufferSamples = _mainBufNumSamples;
		m_channels[i].m_lastSampleWritten = m_channels[i].m_numBufferSamples - 1;     // We just filled all of it with zeros remember
		m_channels[i].m_simulatedPlayCursor = -1;
		m_channels[i].m_freq = _mixFreq;

		// Get the DirectSound3DBuffer interface
		errCode = m_channels[i].m_bufferInterface->QueryInterface( IID_IDirectSound3DBuffer, 
														  (void **) &m_channels[i].m_buffer3DInterface );
		SOUNDASSERT(errCode, "Direct sound couldn't get Sound3DBuffer interface");
	}    


	// 
	// Create a streaming secondary buffer for music

	m_musicChannel = new DirectSoundChannel;
	m_musicChannel->m_bufferInterface = CreateSecondaryBuffer(_musicBufNumSamples);

	//
	// Earlier return if CreateSecondaryBuffer fails

	if( !m_musicChannel->m_bufferInterface )
	{
		return false;
	}

	m_musicChannel->m_numBufferSamples = _musicBufNumSamples;
	m_musicChannel->m_lastSampleWritten = m_musicChannel->m_numBufferSamples - 1;
	m_musicChannel->m_simulatedPlayCursor = -1;
	m_musicChannel->m_freq = _mixFreq;
	// Get the DirectSound3DBuffer interface
	errCode = m_musicChannel->m_bufferInterface->QueryInterface( IID_IDirectSound3DBuffer, 
													  (void **)&(m_musicChannel->m_buffer3DInterface) );
	SOUNDASSERT(errCode, "Direct sound couldn't get Sound3DBuffer interface");
	SetChannel3DMode(m_musicChannelId, 2);
	SetChannelVolume(m_musicChannelId, 10.0f);
	SetChannelFrequency(m_musicChannelId, 44100);


    //
    // Set our listener properties

    IDirectSound3DListener *listener = NULL;
    errCode = m_directSound->m_primaryBuffer->QueryInterface( IID_IDirectSound3DListener, (void **) &listener );
    SOUNDASSERT(errCode, "Direct sound couldn't get Sound3DListener interface");

    errCode = listener->SetDopplerFactor( 0.0f, DS3D_IMMEDIATE );

	return true;
}
예제 #22
0
파일: app.cpp 프로젝트: BITINT/DEFCON2
void App::InitialiseWindow()
{
    int screenW         = g_preferences->GetInt( PREFS_SCREEN_WIDTH );
    int screenH         = g_preferences->GetInt( PREFS_SCREEN_HEIGHT );
    int colourDepth     = g_preferences->GetInt( PREFS_SCREEN_COLOUR_DEPTH );
    int screenRefresh   = g_preferences->GetInt( PREFS_SCREEN_REFRESH );
    int zDepth          = g_preferences->GetInt( PREFS_SCREEN_Z_DEPTH );
	int antiAlias		= g_preferences->GetInt( PREFS_SCREEN_ANTIALIAS, 0 );
    bool windowed       = g_preferences->GetInt( PREFS_SCREEN_WINDOWED );

    if( screenW == 0 || screenH == 0 )
    {
        g_windowManager->SuggestDefaultRes( &screenW, &screenH, &screenRefresh, &colourDepth );
        g_preferences->SetInt( PREFS_SCREEN_WIDTH, screenW );
        g_preferences->SetInt( PREFS_SCREEN_HEIGHT, screenH );
        g_preferences->SetInt( PREFS_SCREEN_REFRESH, screenRefresh );
        g_preferences->SetInt( PREFS_SCREEN_COLOUR_DEPTH, colourDepth );
    }

    if(m_gameRunning &&
       m_game->GetOptionValue("GameMode") == GAMEMODE_OFFICEMODE ) 
    {
        windowed = true;
    }


    bool success = g_windowManager->CreateWin( screenW, screenH, windowed, colourDepth, screenRefresh, zDepth, antiAlias, "DEFCON" );

    if( !success )
    {
        // Safety values
        int safeScreenW = 800;
        int safeScreenH = 600;
        bool safeWindowed = 1;
        int safeColourDepth = 16;
        int safeZDepth = 16;
        int safeScreenRefresh = 60;

		char caption[512];
		sprintf( caption, LANGUAGEPHRASE("dialog_screen_error_caption") );

		LPREPLACEINTEGERFLAG( 'W', screenW, caption );
		LPREPLACEINTEGERFLAG( 'H', screenH, caption );
		ReplaceStringFlagColorBit( caption, 'C', colourDepth );
		ReplaceStringFlagWindowed( caption, 'S', windowed );

		LPREPLACEINTEGERFLAG( 'w', safeScreenW, caption );
		LPREPLACEINTEGERFLAG( 'h', safeScreenH, caption );
		ReplaceStringFlagColorBit( caption, 'c', safeColourDepth );
		ReplaceStringFlagWindowed( caption, 's', safeWindowed );

		
		MessageDialog *dialog = new MessageDialog( "Screen Error", caption, false, "dialog_screen_error_title", true );
        EclRegisterWindow( dialog );
        dialog->m_x = 100;
        dialog->m_y = 100;


        // Go for safety values
        screenW = safeScreenW;
        screenH = safeScreenH;
        windowed = safeWindowed;
        colourDepth = safeColourDepth;
        zDepth = safeZDepth;
        screenRefresh = safeScreenRefresh;
		antiAlias = 0;

        success = g_windowManager->CreateWin(screenW, screenH, windowed, colourDepth, screenRefresh, zDepth, antiAlias, "DEFCON");
        AppReleaseAssert( success, "Failed to set screen mode" );

        g_preferences->SetInt( PREFS_SCREEN_WIDTH, screenW );
        g_preferences->SetInt( PREFS_SCREEN_HEIGHT, screenH );
        g_preferences->SetInt( PREFS_SCREEN_WINDOWED, windowed );
        g_preferences->SetInt( PREFS_SCREEN_COLOUR_DEPTH, colourDepth );
        g_preferences->SetInt( PREFS_SCREEN_Z_DEPTH, zDepth );
        g_preferences->SetInt( PREFS_SCREEN_REFRESH, screenRefresh );
        g_preferences->Save();
    }    

#ifdef TARGET_MSVC
	WindowManagerWin32 *wm32 = (WindowManagerWin32*) g_windowManager;

	DWORD dwStyle = GetWindowLong( wm32->m_hWnd, GWL_STYLE );
	dwStyle &= ~(WS_MAXIMIZEBOX);
	SetWindowLong( wm32->m_hWnd, GWL_STYLE, dwStyle );

	HICON hIcon = LoadIcon( wm32->GethInstance(), MAKEINTRESOURCE(IDI_ICON1) );
	//SendMessage( wm32->m_hWnd, (UINT)WM_SETICON, ICON_SMALL, (LPARAM)hIcon );
	SendMessage( wm32->m_hWnd, (UINT)WM_SETICON, ICON_BIG, (LPARAM)hIcon );
#endif // TARGET_MSVC

    g_windowManager->HideMousePointer();
	SetMousePointerVisible(true);
}
void SoundLibrary3dDirectSound::EnableDspFX(int _channel, int _numFilters, int const *_filterTypes)
{
    AppReleaseAssert( _numFilters > 0, "Bad argument passed to EnableFilters" );

	AppDebugAssert(_channel >= 0 && _channel < m_numChannels);
	DirectSoundChannel *channel;
	if (_channel == m_musicChannelId) channel = m_musicChannel;
	else				channel = &m_channels[_channel];

    int errCode;
    IDirectSoundBuffer8 *buffer = (IDirectSoundBuffer8 *) channel->m_bufferInterface;


	if (GetNumFilters(_channel) > 0)
	{
		DisableDspFX(_channel);
	}


    //
    // Prepare the sound descriptions

    DSEFFECTDESC desc[DSP_DSOUND_WAVESREVERB];
    int numDSoundFilters = 0;
	for( int i = 0; i < _numFilters; ++i )
    {
		if (_filterTypes[i] <= DSP_DSOUND_WAVESREVERB)
		{
			ZeroMemory( &desc[numDSoundFilters], sizeof(DSEFFECTDESC) );
			desc[numDSoundFilters].dwSize = sizeof( DSEFFECTDESC );
			desc[numDSoundFilters].dwFlags = DSFX_LOCSOFTWARE;    
			desc[numDSoundFilters].guidDSFXClass = *s_dxDescriptors[ _filterTypes[i] ].m_sfxClass;

			AppDebugAssert(
				desc[numDSoundFilters].guidDSFXClass == GUID_DSFX_STANDARD_CHORUS ||
				desc[numDSoundFilters].guidDSFXClass == GUID_DSFX_STANDARD_COMPRESSOR ||
				desc[numDSoundFilters].guidDSFXClass == GUID_DSFX_STANDARD_DISTORTION ||
				desc[numDSoundFilters].guidDSFXClass == GUID_DSFX_STANDARD_ECHO ||
				desc[numDSoundFilters].guidDSFXClass == GUID_DSFX_STANDARD_FLANGER ||
				desc[numDSoundFilters].guidDSFXClass == GUID_DSFX_STANDARD_GARGLE ||
				desc[numDSoundFilters].guidDSFXClass == GUID_DSFX_STANDARD_I3DL2REVERB ||
				desc[numDSoundFilters].guidDSFXClass == GUID_DSFX_STANDARD_PARAMEQ ||
				desc[numDSoundFilters].guidDSFXClass == GUID_DSFX_WAVES_REVERB
				);
			++numDSoundFilters;
		}
    }
    
	unsigned long results[NUM_FILTERS];
	if (numDSoundFilters > 0)
	{
		//
		// Stop the channel

		errCode = buffer->Stop();
		SOUNDASSERT( errCode, "Direct sound couldn't stop a secondary buffer from playing" );


		//
		// Set up the filters

		errCode = buffer->SetFX( numDSoundFilters, desc, results );
		SOUNDASSERT( errCode, "Direct sound couldn't set fx" );


		//
		// Restart the channel

		errCode = buffer->Play( 0, 0,  DSBPLAY_LOOPING );
		SOUNDASSERT( errCode, "Direct sound couldn't play a secondary buffer" );
	}


    for( int i = 0; i < _numFilters; ++i )
    {
		AppDebugAssert(_filterTypes[i] >= 0);
		
		if (_filterTypes[i] <= DSP_DSOUND_WAVESREVERB)
		{
	        AppReleaseAssert( results[i] == DSFXR_LOCSOFTWARE, "DirectSound couldn't enable filter" );
			channel->m_dspFX[i].m_dxFilter = true;
		}

		switch (_filterTypes[i])
		{
			case DSP_RESONANTLOWPASS:
				channel->m_dspFX[_filterTypes[i]].m_userFilter = new DspResLowPass(m_sampleRate);
				break;
			case DSP_BITCRUSHER:
				channel->m_dspFX[_filterTypes[i]].m_userFilter = new DspBitCrusher(m_sampleRate);
				break;
			case DSP_GARGLE:
				channel->m_dspFX[_filterTypes[i]].m_userFilter = new DspGargle(m_sampleRate);
				break;
			case DSP_ECHO:
				channel->m_dspFX[_filterTypes[i]].m_userFilter = new DspEcho(m_sampleRate);
				break;
			case DSP_SIMPLE_REVERB:
				channel->m_dspFX[_filterTypes[i]].m_userFilter = new DspReverb(m_sampleRate);
				break;
		}
    }
}