示例#1
0
quint32 FunctionManager::createFunction(int type, QStringList fileList)
{
    Function* f = NULL;
    QString name;

    switch(type)
    {
        case Function::SceneType:
        {
            f = new Scene(m_doc);
            name = tr("New Scene");
            m_sceneCount++;
            emit sceneCountChanged();
        }
        break;
        case Function::ChaserType:
        {
            f = new Chaser(m_doc);
            name = tr("New Chaser");
            if (f != NULL)
            {
                /* give the Chaser a meaningful common duration, to avoid
                 * that awful effect of playing steps with 0 duration */
                Chaser *chaser = qobject_cast<Chaser*>(f);
                chaser->setDuration(1000);
            }
            m_chaserCount++;
            emit chaserCountChanged();
        }
        break;
        case Function::SequenceType:
        {
            /* a Sequence depends on a Scene, so let's create
             * a new hidden Scene first */
            Function *scene = new Scene(m_doc);
            scene->setVisible(false);

            if (m_doc->addFunction(scene) == true)
            {
                f = new Sequence(m_doc);
                name = tr("New Sequence");
                Sequence *sequence = qobject_cast<Sequence *>(f);
                sequence->setBoundSceneID(scene->id());
                m_sequenceCount++;
                emit sequenceCountChanged();
            }
            else
                delete scene;
        }
        break;
        case Function::EFXType:
        {
            f = new EFX(m_doc);
            name = tr("New EFX");
            m_efxCount++;
            emit efxCountChanged();
        }
        break;
        case Function::CollectionType:
        {
            f = new Collection(m_doc);
            name = tr("New Collection");
            if (m_selectedIDList.count())
            {
                Collection *collection = qobject_cast<Collection *>(f);
                for (QVariant fID : m_selectedIDList)
                    collection->addFunction(fID.toUInt());
            }

            m_collectionCount++;
            emit collectionCountChanged();
        }
        break;
        case Function::RGBMatrixType:
        {
            f = new RGBMatrix(m_doc);
            name = tr("New RGB Matrix");
            m_rgbMatrixCount++;
            emit rgbMatrixCountChanged();
        }
        break;
        case Function::ScriptType:
        {
            f = new Script(m_doc);
            name = tr("New Script");
            m_scriptCount++;
            emit scriptCountChanged();
        }
        break;
        case Function::ShowType:
        {
            f = new Show(m_doc);
            name = tr("New Show");
            m_showCount++;
            emit showCountChanged();
        }
        break;
        case Function::AudioType:
        {
            name = tr("New Audio");

            if (fileList.isEmpty())
            {
                f = new Audio(m_doc);
                m_audioCount++;
                emit audioCountChanged();
            }
            else
            {
                quint32 lastFuncID = Function::invalidId();
                for (QString filePath : fileList)
                {
                    filePath = filePath.replace("file://", "");
                    f = new Audio(m_doc);
                    lastFuncID = addFunctiontoDoc(f, name, fileList.count() == 1 ? true : false);
                    if (lastFuncID != Function::invalidId())
                    {
                        Audio *audio = qobject_cast<Audio *>(f);
                        audio->setSourceFileName(filePath);
                    }
                    m_audioCount++;
                }
                emit audioCountChanged();
                return lastFuncID;
            }
        }
        break;
        case Function::VideoType:
        {
            name = tr("New Video");

            if (fileList.isEmpty())
            {
                f = new Video(m_doc);
                m_videoCount++;
                emit videoCountChanged();
            }
            else
            {
                quint32 lastFuncID = Function::invalidId();
                for (QString filePath : fileList)
                {
                    filePath = filePath.replace("file://", "");
                    f = new Video(m_doc);
                    lastFuncID = addFunctiontoDoc(f, name, fileList.count() == 1 ? true : false);
                    if (lastFuncID != Function::invalidId())
                    {
                        Video *video = qobject_cast<Video *>(f);
                        video->setSourceUrl(filePath);
                    }
                    m_videoCount++;
                }
                emit videoCountChanged();
                return lastFuncID;
            }
        }
        break;
        default:
        break;
    }

    return addFunctiontoDoc(f, name, true);
}
示例#2
0
TEST_CASE("Test Mono Operator Overloads", ""){
    
    int sampleRate = 44100,
        bitCount = 16,
        channels = 1;
        
    std::vector<int16_t> samplesA = {-1, 1, 2, -2, 3, -3, 10, -10};
    Audio<int16_t> a(sampleRate, bitCount, channels, samplesA);
    
    SECTION("Test concatenate operator a|b"){
        //GIVEN: some audio objects a and b
        std::vector<int16_t> samplesB = {-1, 1, 2, -2, 3, -3, 10, -10};
        Audio<int16_t> b(sampleRate, bitCount, channels, samplesB);
        
        //WHEN: we concatenate them using the concatenation operator
        Audio<int16_t> concatenated = a | b;
        
        //THEN: the result should be the two files back to back
        std::vector<int16_t> expected = {-1, 1, 2, -2, 3, -3, 10, -10, -1, 1, 2, -2, 3, -3, 10, -10};
        REQUIRE( concatenated.getData().size() == expected.size() );
        REQUIRE( concatenated.getData() == expected );
    }
    
    SECTION("Test volume factor operator a*f"){
        //GIVEN: some audio object a        
        //WHEN: we apply the volume factor operator with 0.5
        Audio<int16_t> factored = a * std::pair<float, float>(0.5f, 0.5f);
        
        //THEN: the result should have all samples halved and clamped
        std::vector<int16_t> expected = {0, 0, 1, -1, 1, -1, 5, -5};
        REQUIRE( factored.getData().size() == expected.size() );
示例#3
0
int main(int argc, char *argv[])
{
    char *option;

    if ((argc != 3) || (*argv[1] != '-')) {
        usage();
        exit(1);
    }
    else {
        option = argv[1] + 1;
        if (*option == 'h') {
            usage();
            exit(1);
        }
        
        // Create an input bitstream
        Bitstream bs(argv[2], BS_INPUT);

        // Automatic detection
        if (*option == '-') {

            // Create our Audio object
            Audio audio;
        
            // Parse
            while (!bs.atend()) {
#ifdef USE_EXCEPTION
                try {
                    audio.get(bs); 
                    switch (audio.type) {
                    case 3: {   // WAV format
                        // For the data chunk, read one data element at a time
                        if (audio.wav->ckData->available) {
                            WAVData wd;
                            for (int i = 0; i < audio.wav->ckData->ckSize; i=i+audio.wav->ckFormat->bitsPerSample/8) 
                                wd.get(bs, audio.wav->ckFormat->bitsPerSample);
                            audio.wav->ckData->available = 0;
                        }
                        break;
                    }
                    case 2: {   // AIFF/AIFC format
                        // For the sound data chunk, read one data element at a time
                        if (audio.aiff->ckSound->available) {
                            SoundData sd;
                            for (int i = 0; i < audio.aiff->ckSound->ckSize; i++) 
                                sd.get(bs);
                            audio.aiff->ckSound->available = 0;
                        }
                        break;
                    }
                    case 1: {   // NeXT/Sun audio format
                        // Read one data element at a time
                        AUData aud;
                        for (int i = 0; i < audio.auh->dataSize; i++)
                            aud.get(bs);
                        break;
                    }
                    default:    // 8-bit raw format
                        break;
                    }
                }
                catch (Bitstream::EndOfData e) {
		            fprintf(stdout, "End of file\n");
		            exit(1);
	            }
                catch (Bitstream::Error e) {
                    fprintf(stderr, "%s: Error: %s\n", argv[2], e.getmsg());
                    exit(1);
                }
#else 
                audio.get(bs);
                switch (audio.type) {
                case 3: {   // WAV format
                    if (audio.wav->ckData->available) {
                        WAVData wd;
                        for (int i = 0; i < audio.wav->ckData->ckSize; i=i+audio.wav->ckFormat->bitsPerSample/8) 
                            wd.get(bs, audio.wav->ckFormat->bitsPerSample);
                        audio.wav->ckData->available = 0;
                    }
                    break;
                }
                case 2: {   // AIFF/AIFC format
                    if (audio.aiff->ckSound->available) {
                        SoundData sd;
                        for (int i = 0; i < audio.aiff->ckSound->ckSize; i++) 
                            sd.get(bs);
                        audio.aiff->ckSound->available = 0;
                    }
                    break;
                }
                case 1: {   // NeXT/Sun audio format
                    AUData aud;
                    for (int i = 0; i < audio.auh->dataSize; i++)
                        aud.get(bs);
                    break;
                }
                default:    // 8-bit raw format
                    break;
                }
                if (bs.geterror() == E_END_OF_DATA) {
                    fprintf(stdout, "End of file\n");
                    exit(1);
                }
                else if (bs.geterror() != E_NONE) {
                    fprintf(stderr, "%s: Error: %s\n", argv[2], bs.getmsg());
                    exit(1);
                }
#endif 
            }
        }

        // WAV format
        else if (*option == 'w') {
            printf("Reading a WAV file\n\n");

            WAV wav;
        
            // Parse
            while (1) {
#ifdef USE_EXCEPTION
                try {
                    wav.get(bs);
                    // Read one data element at a time
                    if (wav.ckData->available) {
                        WAVData wd;
                        for (int i = 0; i < wav.ckData->ckSize; i=i+wav.ckFormat->bitsPerSample/8) 
                            wd.get(bs, wav.ckFormat->bitsPerSample);
                        wav.ckData->available = 0;
                    }
                }
                catch (Bitstream::EndOfData e) {
		            fprintf(stdout, "End of file\n");
		            exit(1);
	            }
                catch (Bitstream::Error e) {
                    fprintf(stderr, "%s: Error: %s\n", argv[2], e.getmsg());
                    exit(1);
                }
#else  
                wav.get(bs);
                // Read one data element at a time
                if (wav.ckData->available) {
                    WAVData wd;
                    for (int i = 0; i < wav.ckData->ckSize; i=i+wav.ckFormat->bitsPerSample/8) 
                        wd.get(bs, wav.ckFormat->bitsPerSample);
                    wav.ckData->available = 0;
                }
                if (bs.geterror() == E_END_OF_DATA) {
                    fprintf(stdout, "End of file\n");
                    exit(1);
                }
                else if (bs.geterror() != E_NONE) {
                    fprintf(stderr, "%s: Error: %s\n", argv[2], bs.getmsg());
                    exit(1);
                }
#endif 
            }
        }
        // AIFF/AIFC format
        else if (*option == 'a') {
            printf("Reading an AIFF/AIFC file\n\n");

            AIFF aiff;
        
            // Parse
            while (1) {
#ifdef USE_EXCEPTION
                try {
                    aiff.get(bs);
                    // Read one data element at a time
                    if (aiff.ckSound->available) {
                        SoundData sd;
                        for (int i = 0; i < aiff.ckSound->ckSize; i++) 
                            sd.get(bs);
                        aiff.ckSound->available = 0;
                    }
                }
                catch (Bitstream::EndOfData e) {
		            fprintf(stdout, "End of file\n");
		            exit(1);
	            }
                catch (Bitstream::Error e) {
                    fprintf(stderr, "%s: Error: %s\n", argv[2], e.getmsg());
                    exit(1);
                }
#else 
                aiff.get(bs);
                // Read one data element at a time
                if (aiff.ckSound->available) {
                    SoundData sd;
                    for (int i = 0; i < aiff.ckSound->ckSize; i++)
                        sd.get(bs);
                }
                aiff.ckSound->available = 0;
                if (bs.geterror() == E_END_OF_DATA) {
                    fprintf(stdout, "End of file\n");
                    exit(1);
                }
                else if (bs.geterror() != E_NONE) {
                    fprintf(stderr, "%s: Error: %s\n", argv[2], bs.getmsg());
                    exit(1);
                }
#endif 
            }
        }
        // NeXT/Sun audio format
        else if (*option == 'n') {
            printf("Reading a NeXT/Sun audio file\n\n");

            AUHeader auh;
            AUData aud;
        
            // Parse
            while (1) {
#ifdef USE_EXCEPTION
                try {
                    auh.get(bs);
                    // Read one data element at a time
                    for (int i = 0; i < auh.dataSize; i++)
                        aud.get(bs);
                }
                catch (Bitstream::EndOfData e) {
		            fprintf(stdout, "End of file\n");
		            exit(1);
	            }
                catch (Bitstream::Error e) {
                    fprintf(stderr, "%s: Error: %s\n", argv[2], e.getmsg());
                    exit(1);
                }
#else 
        	    auh.get(bs);
                // Read one data element at a time
                for (int i = 0; i < auh.dataSize; i++)
                    aud.get(bs);
                if (bs.geterror() == E_END_OF_DATA) {
                    fprintf(stdout, "End of file\n");
                    exit(1);
                }
                else if (bs.geterror() != E_NONE) {
                    fprintf(stderr, "%s: Error: %s\n", argv[2], bs.getmsg());
                    exit(1);
                }
#endif 
            }
        }
        // Raw format
        else if (*option == 'r') {
            switch(*(argv[1] + 2)) {
            case '1':   
            {
                printf("Reading an 8-bit raw audio file\n\n");

                Raw8 raw;
        
                // Parse
#ifdef USE_EXCEPTION
                try {
                    raw.get(bs);
                }
                catch (Bitstream::EndOfData e) {
		            fprintf(stdout, "End of file\n");
		            exit(1);
	            }
                catch (Bitstream::Error e) {
                    fprintf(stderr, "%s: Error: %s\n", argv[2], e.getmsg());
                    exit(1);
                }
#else 
        	    raw.get(bs);
                if (bs.geterror() == E_END_OF_DATA) {
                    fprintf(stdout, "End of file\n");
                    exit(1);
                }
                else if (bs.geterror() != E_NONE) {
                    fprintf(stderr, "%s: Error: %s\n", argv[2], bs.getmsg());
                    exit(1);
                }
#endif 
                break;
            }

            case '2':
            {
                printf("Reading a 16-bit raw audio file\n\n");

                Raw16 raw;
        
                // Parse
#ifdef USE_EXCEPTION
                try {
                    raw.get(bs);
                }
                catch (Bitstream::EndOfData e) {
		            fprintf(stdout, "End of file\n");
		            exit(1);
	            }
                catch (Bitstream::Error e) {
                    fprintf(stderr, "%s: Error: %s\n", argv[2], e.getmsg());
                    exit(1);
                }
#else 
        	    raw.get(bs);
                if (bs.geterror() == E_END_OF_DATA) {
                    fprintf(stdout, "End of file\n");
                    exit(1);
                }
                else if (bs.geterror() != E_NONE) {
                    fprintf(stderr, "%s: Error: %s\n", argv[2], bs.getmsg());
                    exit(1);
                }
#endif 
                break;
            }

            case '3':
            {
                printf("Reading a 16-bit raw audio file (little-endian)\n\n");

                Raw16Little raw;
        
                // Parse
#ifdef USE_EXCEPTION
                try {
                    raw.get(bs);
                }
                catch (Bitstream::EndOfData e) {
		            fprintf(stdout, "End of file\n");
		            exit(1);
	            }
                catch (Bitstream::Error e) {
                    fprintf(stderr, "%s: Error: %s\n", argv[2], e.getmsg());
                    exit(1);
                }
#else 
        	    raw.get(bs);
                if (bs.geterror() == E_END_OF_DATA) {
                    fprintf(stdout, "End of file\n");
                    exit(1);
                }
                else if (bs.geterror() != E_NONE) {
                    fprintf(stderr, "%s: Error: %s\n", argv[2], bs.getmsg());
                    exit(1);
                }
#endif 
                break;
            }
            default:
                usage();
                exit(1);
            }
        }
        else {
            usage();
            exit(1);
        }
    }

    return 0;
}
示例#4
0
文件: Tests.cpp 项目: imaculate/SAMP
#include "Audio.h"
#include <stdlib.h>
#define CATCH_CONFIG_MAIN  
#include "catch.hpp"

using namespace MSHIMA001;
using namespace std;


TEST_CASE( "testing mono audio files ", "8 bit" ) {
   
      
      vector<int8_t> v1{3, 78, 23, -67, 12, 4};
      Audio<int8_t , 1> a1(1, 8, 2, v1);
      
        
      vector<int8_t> v2{5, 60, 43, -70, 34, 12};
      Audio<int8_t , 1> a2(1, 8, 2, v2);
      
      
            
      //additon
      //expected sum 
        vector<int8_t> v3{8, 127, 66, -127, 46, 16};

      Audio<int8_t , 1> a3(1, 8, 2, v3);

      Audio<int8_t, 1>  sum  = a1 + a2;
      REQUIRE(sum == a3);

      
示例#5
0
void MediaDialog::addAudioPressed()
      {
      QString path = audioFile->text();
      if (score->audio() || path.isEmpty())
            return;
      QFile f(path);
      if (!f.open(QIODevice::ReadOnly))
            return;
      QByteArray ba = f.readAll();
      f.close();
      Audio* audio = new Audio;
      audio->setPath(path);
      audio->setData(ba);
      score->setAudio(audio);
      score->setDirty(true);
      mscore->updatePlayMode();

#if 0
      QString wavPath = QDir::tempPath() + "/score.wav";
      mscore->saveAs(score, true, wavPath, "wav");
      QString program = "D:/HACK/sonic-annotator/bologna.bat";
      QStringList arguments;
      arguments << QDir::toNativeSeparators(path)<< QDir::toNativeSeparators(wavPath);
      QProcess myProcess(this);
      myProcess.start(program, arguments);
      myProcess.waitForFinished();
      qDebug() << myProcess.readAll();
#endif

      QFileInfo fi(path);
      QFile syncFile(fi.absolutePath() + "/" + fi.baseName() + ".txt");

      TempoMap* tmo = score->tempomap();

      if (!syncFile.open(QIODevice::ReadOnly))
            return;

      qreal t = 0;
      int tick = 0;
      qreal lastTempo = tmo->tempo(0);
      TempoMap* tmn = new TempoMap();
      tmn->setTempo(0, lastTempo);
      int resolution = 25;
      while (!syncFile.atEnd()) {
            for (int i = 0; !syncFile.atEnd() && i < resolution-1; i++)
                  syncFile.readLine();

            if (syncFile.atEnd())
                  break;

            QByteArray line = syncFile.readLine();
            QString s(line);
            QStringList sl = s.split(":");

            qreal tScore = sl[0].trimmed().toDouble();
            qreal tPerformance = sl[1].trimmed().toDouble();

            // timestamp of last
            int scoreTick = tmo->time2tick(tScore);
            qreal deltaError = tmo->tick2time(scoreTick) - tScore;
            int dt = scoreTick - tick;
            qreal deltaTime = tPerformance - t;

            if (deltaTime > 0) {
                  qreal tempo = dt / (480 * deltaTime);
                  if(tempo != lastTempo) {
                  qDebug() << tempo;
                        tmn->setTempo(tick, tempo);
                        lastTempo = tempo;
                        }
                  }

            t = tPerformance - deltaError;
            tick = scoreTick;
            }
      score->setTempomap(tmn);
      syncFile.close();
      QMessageBox::information(0, "Done", "Done");
      }
示例#6
0
bool ex_pitch_chain(void *args) {

	ITheFramework *frame = Factory::GetFramework ();

	Decorator *decorator = ssi_create (Decorator, 0, true);
	frame->AddDecorator(decorator);

	// audio sensor	
#ifndef SIMULATE
	Audio *audio = ssi_create (Audio, "audio", true);
	audio->getOptions()->scale = true;		
	ITransformable *audio_p = frame->AddProvider(audio, SSI_AUDIO_PROVIDER_NAME);
#else
	WavReader *audio = ssi_create (WavReader, 0, true);
	audio->getOptions()->setPath("audio.wav");
	audio->getOptions()->scale = true;		
	audio->getOptions()->block = 0.01;
	ITransformable *audio_p = frame->AddProvider(audio, SSI_WAVREADER_PROVIDER_NAME);
#endif	
	frame->AddSensor(audio);

	// pitch
	OSPitchChain *pitch = ssi_create (OSPitchChain, "pitch", true);	
	pitch->getOSTransformFFT()->getOptions()->nfft = 1024;
	pitch->getOSPitchShs()->getOptions()->baseSr = audio_p->getSampleRate();
	ITransformable *pitch_t = frame->AddTransformer(audio_p, pitch, "0.01s", "0.01s");

	// plot
	SignalPainter *plot = 0;	

	plot = ssi_create_id (SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("audio");
	plot->getOptions()->type = PaintSignalType::AUDIO;
	plot->getOptions()->size = 10.0;		
	frame->AddConsumer(audio_p, plot, "0.01s");
	
	plot = ssi_create_id (SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("pitch");
	plot->getOptions()->size = 10.0;
	frame->AddConsumer(pitch_t, plot, "0.01s"); 

	FileWriter *writer = ssi_create (FileWriter, 0, true);
	writer->getOptions()->setPath("pitch_chain");
	writer->getOptions()->type = File::ASCII;
	frame->AddConsumer(pitch_t, writer, "0.01s");

#ifdef SIMULATE
	AudioPlayer *player = ssi_create(AudioPlayer, "player", true);
	frame->AddConsumer(audio_p, player, "0.01s");
#endif

	// run framework
	decorator->add("console", 0, 0, 650, 800);
	decorator->add("plot*", 650, 0, 400, 400);
	decorator->add("monitor*", 650, 400, 400, 400);

	frame->Start();
	frame->Wait();
	frame->Stop();
	frame->Clear();	

	return true;
}
示例#7
0
bool ex_vad(void *args) {

	//general
	ITheFramework *frame = Factory::GetFramework ();

	Decorator *decorator = ssi_create (Decorator, 0, true);
	frame->AddDecorator(decorator);

	ITheEventBoard *board = Factory::GetEventBoard ();
	ssi_pcast (TheEventBoard, board)->getOptions()->update = 250;

	// audio sensor	
#ifndef SIMULATE
	Audio *audio = ssi_create (Audio, "audio", true);
	audio->getOptions()->scale = true;		
	ITransformable *audio_p = frame->AddProvider(audio, SSI_AUDIO_PROVIDER_NAME);
#else
	WavReader *audio = ssi_create (WavReader, 0, true);
	audio->getOptions()->setPath("audio.wav");
	audio->getOptions()->scale = true;		
	ITransformable *audio_p = frame->AddProvider(audio, SSI_WAVREADER_PROVIDER_NAME);
#endif	
	frame->AddSensor(audio);

	SignalPainter *audio_plot = ssi_create_id (SignalPainter, 0, "plot");
	audio_plot->getOptions()->setTitle("audio");
	audio_plot->getOptions()->size = 10.0;		
	audio_plot->getOptions()->type = PaintSignalType::AUDIO;
	frame->AddConsumer(audio_p, audio_plot, "0.2s");

	OSLpc * lpc = ssi_create (OSLpc, 0, true);
	lpc->getOptions()->lsp = true;
	ssi::ITransformable *lpc_p = frame->AddTransformer(audio_p, lpc, "160");
	
	OSPitchChain * pitch = ssi_create (OSPitchChain, 0, true);
	pitch->getOSPitchShs()->getOptions()->voicingC1 = true;
	pitch->getOSPitchSmoother()->getOptions()->voicingC1 = true;
	ssi::ITransformable *pitch_p = frame->AddTransformer(audio_p, pitch, "160", "160");
	
	OSEnergy * energy = ssi_create (OSEnergy, 0, true);
	energy->getOptions()->type = OSEnergy::TYPE::LOG;
	ssi::ITransformable *energy_p = frame->AddTransformer(audio_p, energy, "160");

	OSVad * vad = ssi_create (OSVad, 0, true);
	ssi::ITransformable * src[3] = {lpc_p, pitch_p, energy_p};
	frame->AddConsumer(3, src, vad, "0.01s");
	board->RegisterSender(*vad);

	EventMonitor *monitor = ssi_create_id (EventMonitor, 0, "monitor");
	board->RegisterListener(*monitor, vad->getEventAddress());

#ifdef SIMULATE
	AudioPlayer *player = ssi_create (AudioPlayer, "player", true);
	frame->AddConsumer(audio_p, player, "0.01s");
#endif

	decorator->add("console", 0, 0, 650, 800);
	decorator->add("plot*", 650, 0, 400, 400);
	decorator->add("monitor*", 650, 400, 400, 400);

	board->Start();
	frame->Start();
	frame->Wait();
	frame->Stop();
	board->Stop();
	frame->Clear();
	board->Clear();

	return true;
}
示例#8
0
//===========================================
// MusicTrack::~MusicTrack
//===========================================
MusicTrack::~MusicTrack() {
   Audio audio;
   audio.freeMusicTrack(this);
}
示例#9
0
//===========================================
// MusicTrack::MusicTrack
//===========================================
MusicTrack::MusicTrack(const string& file)
   : Asset(internString("MusicTrack")) {

   Audio audio;
   audio.newMusicTrack(this, file);
}
void check_mouse(XEvent *e, Game *game)
{
    static int savex = 0;
    static int savey = 0;
    static int n = 0;
    Audio *a;
    a = &game->sounds;


    if (e->type == ButtonRelease) {
            return;
    }
    if (e->type == ButtonPress && lvlState(game) < 0) {
        //LEFT-CLICK
        if (e->xbutton.button==1) {
            //Left button was pressed
            int y = WINDOW_HEIGHT - e->xbutton.y;
            //Check game state when LEFT-clicking
            if (gameState(game) == 1 || gameState(game) == 2) {
                a->playAudio(30);
                menuClick(game);
                a->playAudio(32);
            } else if (gameState(game) == 0) {
                // JBC Added 5/30 to only make defense 
                // missiles and play sound when enemy 
                // missiles are present
                if ((game->nmissiles > 0 ||
               game->nsmissiles > 0) &&
            game->defMissilesRemaining > 0) {
                        makeDefenseMissile(game, e->xbutton.x, y);
                        a->playAudio(20);
                        game->defMissilesRemainingAfterLevel = 
                            game->defMissilesRemaining;
                }
            }
            return;
        }
        //RIGHT-CLICK
        if (e->xbutton.button==3) {
            //Check game state when RIGHT-clicking
            if (gameState(game) == 1) {
                //Menu functions
            } else if (gameState(game) == 0) {
                //Game Functions
                // fireDefenseMissile(game);
                // JBC idea to add menu pop up for right-click
                game->gState ^= 1;
            }
            return;
        }
    }
    //Did the mouse move?
    if (savex != e->xbutton.x || savey != e->xbutton.y) {
            savex = e->xbutton.x;
            savey = e->xbutton.y;
            int y = WINDOW_HEIGHT - e->xbutton.y;
            if (++n < 10)
                    return;
            if (gameState(game) == 1 || gameState(game) == 2) {
                //Menu Functions
                mouseOver(savex, y, game);
            } else if (gameState(game) == 0) {
                //Game Functions
                if (game->lcm)
                    lastCityMode(savex, y, game);
                // JBC note 5/13
                // moved the "particle" stuff out of here 
                // makeParticle(game, e->xbutton.x, y);
            }
    }
}
示例#11
0
文件: Main.cpp 项目: Odinra/DirectX
bool Display(float timeDelta)
{
	if( Device )
	{
		if(::GetAsyncKeyState('P') & 0x8000f)
			pause = true;
		if(::GetAsyncKeyState('W') & 0x8000f)
			TheCamera.walk(1.0 * DTime);
		if(::GetAsyncKeyState('S') & 0x8000f)
			TheCamera.walk(-1.0 * DTime);
		if(::GetAsyncKeyState('A') & 0x8000f)
			TheCamera.strafe(-1.0 * DTime);
		if(::GetAsyncKeyState('D') & 0x8000f)
			TheCamera.strafe(1.0 * DTime);
		if(::GetAsyncKeyState('F') & 0x8000f)
			TheCamera.fly(-1.0 * DTime);
		if(::GetAsyncKeyState('R') & 0x8000f)
			TheCamera.fly(1.0 * DTime);
		if(::GetAsyncKeyState(VK_UP) & 0x8000f)
			TheCamera.pitch(-.250 * DTime);
		if(::GetAsyncKeyState(VK_DOWN) & 0x8000f)
			TheCamera.pitch(.250 * DTime);
		if(::GetAsyncKeyState(VK_LEFT) & 0x8000f)
			TheCamera.yaw(-.250 * DTime);
		if(::GetAsyncKeyState(VK_RIGHT) & 0x8000f)
			TheCamera.yaw(.250 * DTime);
		if(::GetAsyncKeyState(VK_HOME) & 0x8000f)
			TheCamera.roll(.250 * DTime);
		if(::GetAsyncKeyState(VK_END) & 0x8000f)
			TheCamera.roll(-.250 * DTime);
		if(TheCamera._up.y < 0)
			TheCamera._up.y *= -1;

		Device->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xff0000ff, 1.0f, 0);
		Device->BeginScene();
		DrawWalls();
		D3DXMATRIX i, tripler, grow;
		D3DXMatrixIdentity(&i);
		Device->SetTransform(D3DTS_WORLD, &i);
		
		//1
		D3DXMatrixTranslation(&tripler, TigerPos.x, TigerPos.y, TigerPos.z);
		D3DXMatrixScaling(&grow, 5/sizeModifier, 5/sizeModifier, 5/sizeModifier);
		D3DXMatrixMultiply(&tripler, &grow, &tripler);
		Device->SetTransform(D3DTS_WORLD, &tripler);
		Tiger.Draw(Stone);
		//2	
		D3DXMatrixTranslation(&tripler, CastlePos.x, CastlePos.y, CastlePos.z);
		D3DXMatrixScaling(&grow, 2.5/sizeModifier, 1/sizeModifier, 2.5/sizeModifier);
		D3DXMatrixMultiply(&tripler, &grow, &tripler);
		Device->SetTransform(D3DTS_WORLD, &tripler);
		Castle.Draw(Stone);
		//3		
		D3DXMatrixTranslation(&tripler, GrenadePos.x, GrenadePos.y, GrenadePos.z);
		D3DXMatrixScaling(&grow, .1/sizeModifier, .1/sizeModifier, .1/sizeModifier);
		D3DXMatrixMultiply(&tripler, &grow, &tripler);
		Device->SetTransform(D3DTS_WORLD, &tripler);
		Grenade.Draw(Stone);
		//4
		D3DXMatrixTranslation(&tripler, ManorPos.x, ManorPos.y, ManorPos.z);
		D3DXMatrixScaling(&grow, 5000/sizeModifier, 5000/sizeModifier, 50);
		D3DXMatrixMultiply(&tripler, &grow, &tripler);
		Device->SetTransform(D3DTS_WORLD, &tripler);
		Manor.Draw(Stone);
		//5		
		D3DXMatrixTranslation(&tripler, MonsterPos.x, MonsterPos.y, MonsterPos.z);
		D3DXMatrixScaling(&grow, 1/sizeModifier, 1/sizeModifier, 1/sizeModifier);
		D3DXMatrixMultiply(&tripler, &grow, &tripler);
		Device->SetTransform(D3DTS_WORLD, &tripler);
		Monster.Draw(Stone);
		//6		
		D3DXMatrixTranslation(&tripler, RavengerSirenPos.x, RavengerSirenPos.y, RavengerSirenPos.z);
		D3DXMatrixScaling(&grow, .1/sizeModifier, .1/sizeModifier, .1/sizeModifier);
		D3DXMatrixMultiply(&tripler, &grow, &tripler);
		Device->SetTransform(D3DTS_WORLD, &tripler);
		RavengerSiren.Draw(Stone);
		//7		
		D3DXMatrixTranslation(&tripler, SectoidPos.x, SectoidPos.y, SectoidPos.z);
		D3DXMatrixScaling(&grow, 3/sizeModifier, 3/sizeModifier, 3/sizeModifier);
		D3DXMatrixMultiply(&tripler, &grow, &tripler);
		Device->SetTransform(D3DTS_WORLD, &tripler);
		Sectoid.Draw(Stone);
		//8		
		D3DXMatrixTranslation(&tripler, SlendermanPos.x, SlendermanPos.y, SlendermanPos.z);
		D3DXMatrixScaling(&grow, .05/sizeModifier, .05/sizeModifier, .05/sizeModifier);
		D3DXMatrixMultiply(&tripler, &grow, &tripler);
		Device->SetTransform(D3DTS_WORLD, &tripler);
		Slenderman.Draw(Stone);
		//9		
		D3DXMatrixTranslation(&tripler, SoccerPos.x, SoccerPos.y, SoccerPos.z);
		D3DXMatrixScaling(&grow, .05/sizeModifier, .05/sizeModifier, .05/sizeModifier);
		D3DXMatrixMultiply(&tripler, &grow, &tripler);
		Device->SetTransform(D3DTS_WORLD, &tripler);
		Soccer.Draw(Stone);
		//10		
		D3DXMatrixTranslation(&tripler, TurretPos.x, TurretPos.y, TurretPos.z);
		D3DXMatrixScaling(&grow, .1/sizeModifier, .1/sizeModifier, .1/sizeModifier);
		D3DXMatrixMultiply(&tripler, &grow, &tripler);
		Device->SetTransform(D3DTS_WORLD, &tripler);
		Turret.Draw(Stone);
		//11		
		D3DXMatrixTranslation(&tripler, UltramanPos.x, UltramanPos.y, UltramanPos.z);
		D3DXMatrixScaling(&grow, .01/sizeModifier, .01/sizeModifier, .01/sizeModifier);
		D3DXMatrixMultiply(&tripler, &grow, &tripler);
		Device->SetTransform(D3DTS_WORLD, &tripler);
		Ultraman.Draw(Stone);
		//12		
		D3DXMatrixTranslation(&tripler, ZombiePos.x, ZombiePos.y, ZombiePos.z);
		D3DXMatrixScaling(&grow, .1/sizeModifier, .1/sizeModifier, .1/sizeModifier);
		D3DXMatrixMultiply(&tripler, &grow, &tripler);
		Device->SetTransform(D3DTS_WORLD, &tripler);
		Zombie.Draw(Stone);

		if(!shrunk && p.z > 10)
		{
			shrunk = true;
			sound.AudioPlay(Voice);
			::MessageBoxA(0, "OH NO! you appear to be Shrinking\nStart Running to try and reach the manor", "Oh No!", MB_OK);
			DTime *= 5;
		}
		else if(shrunk)
		{
			
			if(sizeModifier >1)
			{
				sizeModifier-=.005;
			}
			else if(message)
			{
				message = false;
				::MessageBoxA(0, "It's too late, however you seem to be at the entrance to a castle and there appears to be some createures on the inside.\nMaybe you should try to approach one of them, Be Careful Though: they could be Evil", "Too Late", MB_OK);
			}
		}
		static bool approach = false;
		if(!approach)
			if(p.z > 125)
			{
				::MessageBoxA(0, "The creatures seem to be frozen and have had all their color drained...\nThey look like they were once the things that only exis in nightmares\nWhat kind of Powerfull Monster could have done this?\nMaybe you shouldn't have ignored those warnings.", "", MB_OK);
				approach = true;
			}
			static bool bang = false;
		if(p.z > 0)
		{
			if(!bang)
			{
				bang = true;
				sound.AudioPlay(Bang);
			}
			Device->SetStreamSource(0, VBufferGround, 0, sizeof(Vertex));
			Device->SetFVF(FVF_VERTEX);
			Device->SetTexture(0, DoNot);
			Device->SetTransform(D3DTS_WORLD, &i);
			Device->DrawPrimitive(D3DPT_TRIANGLELIST, 36, 2);
			Device->SetRenderState(D3DRS_ALPHABLENDENABLE, false);
		}

		
		D3DXMATRIX V, T;
		TheCamera.getViewMatrix(&V);
		Device->SetTransform(D3DTS_VIEW, &V);
		TheCamera.getPosition(&p);
		if (p.y != 8.5)
			p.y = 8.5;
		TheCamera.setPosition(&p);
		TheCamera.getLook(&t);
		Device->EndScene();
		Device->Present(0, 0, 0, 0);
	}
	return true;
}
示例#12
0
	// Base class
	void PlayerState::playjumpsound() const
	{
		using Audio::Sound;
		Sound(Sound::JUMP).play();
	}
示例#13
0
void ColoredCubeApp::updateScene(float dt)
{
    for (int i = 0; i < MAX_NUM_STARS; i++)
    {
        stars[i].update(dt);
    }

    switch (gsm->getGameState()) {
    case GameStateManager::START_GAME: {
        D3DApp::updateScene(dt);
        gameObject1.update(dt);
        D3DXMATRIX w;

        D3DXMatrixTranslation(&w, 2, 2, 0);
        mfxWVPVar->SetMatrix(w);

        score = 0;

        // Build the view matrix.
        /*D3DXVECTOR3 pos(10.0f, 2.0f, 0.0f);
        D3DXVECTOR3 target(0.0f, 0.0f, 0.0f);
        D3DXVECTOR3 up(0.0f, 1.0f, 0.0f);
        D3DXMatrixLookAtLH(&mView, &pos, &target, &up);*/

        if(GetAsyncKeyState(VK_SPACE) & 0x8000 && gsm->getGameState() != GameStateManager::IN_GAME) {
            gsm->setGameState(GameStateManager::IN_GAME);
            audio->playCue(SELECT);
        }

        Vector3 oldEnemyPositions[MAX_NUM_ENEMIES];
        for (int i = 0; i < MAX_NUM_ENEMIES; i++)
        {
            oldEnemyPositions[i] = enemyObjects[i].getPosition();
        }

        Vector3 oldBulletPositions[MAX_NUM_BULLETS];
        for (int i = 0; i < MAX_NUM_BULLETS; i++)
        {
            oldBulletPositions[i] = playerBullets[i].getPosition();
        }

        //Camera Object
        camera.update(dt);
        break;
    }

    case GameStateManager::IN_GAME:
    {
        //Generate a block every three seconds
        if (enemyBuffer.elapsedTime() > 2) {
            enemyBuffer.resetClock();

            generateEnemy(enemyObjects, dt);
        }

        if (gameTimer.elapsedTime() >= 1) {
            gameTimer.resetClock();
            secondsRemaining--;
        }


        for (int i = 0; i < MAX_NUM_BULLETS; i++)
        {
            playerBullets[i].update(dt);
        }


        for (int i = 0; i < MAX_NUM_EXP_PARTICLES; i++)
        {
            particles[i].update(dt);
        }

        if (camera.isCameraRecoiling()) {
            camera.cameraRecoil(dt);
        }


        if(explosionRunning) explosionTimer += dt;
        if (explosionTimer > .55) {
            explosionTimer = 0;
            explosionRunning = false;
            for (int i = 0; i < MAX_NUM_EXP_PARTICLES; i++)
            {
                particles[i].setInActive();
            }
        }

        if(GetAsyncKeyState(VK_RETURN) & 0x8000) {
            if(shotRelease) {

                shootBullet(playerBullets, dt, gameObject1);

                //shotRelease = false;
            }
        }


        //if(!(GetAsyncKeyState(VK_RETURN) & 0x8000)) shotRelease = true;

        Vector3 oldEnemyPositions[MAX_NUM_ENEMIES];
        for (int i = 0; i < MAX_NUM_ENEMIES; i++)
        {
            oldEnemyPositions[i] = enemyObjects[i].getPosition();
        }

        Vector3 direction(0, 0, 0);
        Vector3 oldposition = gameObject1.getPosition();

        D3DApp::updateScene(dt);
        gameObject1.update(dt);
        for (int i = 0; i < MAX_NUM_ENEMIES; i++) {
            enemyObjects[i].update(dt);
        }

        if((GetAsyncKeyState('A') & 0x8000) && !(GetAsyncKeyState('D') & 0x8000))  direction.z = -1.0f;
        if((GetAsyncKeyState('D') & 0x8000) && !(GetAsyncKeyState('A') & 0x8000))  direction.z = +1.0f;

        D3DXVec3Normalize(&direction, &direction);

        for (int i = 0; i < MAX_NUM_ENEMIES; i++)
        {
            //if they collide and are active
            if(gameObject1.collided(&enemyObjects[i]) && enemyObjects[i].getActiveState())
            {
                audio->playCue(FAIL);
                enemyObjects[i].setInActive();
                //score++;
                camera.cameraShake(dt);
                score = 0;
                gsm->setGameState(GameStateManager::END_GAME);
            }


            if (enemyObjects[i].getPosition().x > 7) {
                enemyObjects[i].setInActive();
            }
        }

        for (int i = 0; i < MAX_NUM_BULLETS; i++)
        {
            for (int j = 0; j < MAX_NUM_ENEMIES; j++)
            {
                if(playerBullets[i].collided(&enemyObjects[j]) && enemyObjects[j].getActiveState())
                {
                    audio->playCue(BOOM);
                    explosionTimer = 0;
                    runExplosion(playerBullets[i].getPosition());
                    enemyObjects[j].setInActive();
                    playerBullets[i].setInActive();
                    score++;
                }
            }
        }


        gameObject1.setVelocity( direction * gameObject1.getSpeed());

        if (gameObject1.getPosition().z < -PLAYER_Z_RANGE) {
            gameObject1.setPosition(Vector3(oldposition.x, oldposition.y, -PLAYER_Z_RANGE));
            camera.setCameraMoveLeft(false);
            camera.setCameraMoveRight(true);
        }
        else if (gameObject1.getPosition().z > PLAYER_Z_RANGE) {
            gameObject1.setPosition(Vector3(oldposition.x, oldposition.y, PLAYER_Z_RANGE));
            camera.setCameraMoveRight(false);
            camera.setCameraMoveLeft(true);
        }
        else {
            camera.setCameraMoveRight(true);
            camera.setCameraMoveLeft(true);
        }

        //Destroys bullet if too far away
        for (int i = 0; i < MAX_NUM_BULLETS; i++)
        {
            if(playerBullets[i].getPosition().x < -10 && playerBullets[i].getActiveState())
                playerBullets[i].setInActive();
        }

        D3DXMATRIX w;

        D3DXMatrixTranslation(&w, 2, 2, 0);
        mfxWVPVar->SetMatrix(w);

        //Camera Object
        camera.update(dt);

        //Get Camera viewMatrix
        mView = camera.getViewMatrix();
        mProj = camera.getProjectionMatrix();
    }

    if (secondsRemaining <= 0)
    {
        gsm->setGameState(GameStateManager::END_GAME);
    }

    case GameStateManager::END_GAME:
    {
        //D3DApp::updateScene(dt);
        //gameObject1.update(dt);

        if (camera.isCameraShaking()) {
            camera.cameraShake(dt);
        }

        D3DXMATRIX w;

        D3DXMatrixTranslation(&w, 2, 2, 0);
        mfxWVPVar->SetMatrix(w);

        //// Build the view matrix.
        //D3DXVECTOR3 pos(10.0f, 2.0f, 0.0f);
        //D3DXVECTOR3 target(0.0f, 0.0f, 0.0f);
        //D3DXVECTOR3 up(0.0f, 1.0f, 0.0f);
        //D3DXMatrixLookAtLH(&mView, &pos, &target, &up);

        if(GetAsyncKeyState(VK_SPACE) & 0x8000 && gsm->getGameState() != GameStateManager::IN_GAME) {
            restartGame();
            gsm->setGameState(GameStateManager::IN_GAME);
            audio->playCue(SELECT);
        }

        //Camera Object
        camera.update(dt);

        break;
    }


    default: {
        throw(GameError(gameErrorNS::FATAL_ERROR, "Game State Error"));
        break;
    }
    }
}
示例#14
0
void ColoredCubeApp::initApp()
{

    D3DApp::initApp();
    //input->initialize(getMainWnd(), false);
    //audio->initialize();

    float boxScale = 0.5f;
    float collisionFixFactor = 1.1f;
    currentBullet = 0;
    explosionTimer = 0;
    explosionRunning = false;
    shotRelease = true;

    // increments when you run into a cube // just for now
    score = 0;
    mAxes.init(md3dDevice, 1.0f);
    mEnemy.init(md3dDevice, .5f, RED);
    mPlayer.init(md3dDevice, .5f, BLUE);
    mBullet.init(md3dDevice, .25f, D3DXCOLOR(0.0f, 1.0f, 0.0f, 0.0f));
    particleBox.init(md3dDevice, .01f, GREEN);
    particleBox2.init(md3dDevice, .04f, RED);
    starBox.init(md3dDevice, 0.05f, WHITE);
    //mBox.init(md3dDevice, boxScale);
    mLine.init(md3dDevice, 1.0f);
    //mTriangle.init(md3dDevice, 1.0f);
    //mQuad.init(md3dDevice, 10.0f);
    mQuad.init(md3dDevice, 0.0f);

    gameObject1.init(&mPlayer, sqrt(2.0f), Vector3(6,.5,0), Vector3(0,0,0), 5.0f,1.0f);
    //gameObject1.init(&mBox, sqrt(2.0f), Vector3(6,.5,0), Vector3(0,0,0), 5000.0f,1.0f);
    gameObject1.setRadius(gameObject1.getRadius()*boxScale*collisionFixFactor);

    int step = 2;
    for (int i = 0; i < MAX_NUM_ENEMIES; i++)
    {
        enemyObjects[i].init(&mEnemy, sqrt(2.0), Vector3(-5,.5,step*i - 3.8), Vector3(1,0,0), 8.0f, 1);
        //enemyObjects[i].init(&mBox, sqrt(2.0), Vector3(-5,.5,step*i - 3.8), Vector3(1,0,0), 3000.0f, 1);
        enemyObjects[i].setRadius(enemyObjects[i].getRadius()*boxScale * collisionFixFactor);
        enemyObjects[i].setInActive();
    }

    for (int i = 0; i < MAX_NUM_BULLETS; i++)
    {
        playerBullets[i].init(&mBullet, 0.5f, Vector3(0,0,0), Vector3(-12,0,0), 0.0f, 1);
        playerBullets[i].setInActive();
    }

    for (int i = 0; i < MAX_NUM_EXP_PARTICLES; i++)
    {

        if(i%5 == 0)particles[i].init(&particleBox2, 0.5f, Vector3(0,0,0), Vector3(0,0,0), 7000.0f, 1);
        else particles[i].init(&particleBox, 0.5f, Vector3(0,0,0), Vector3(0,0,0), 7000.0f, 1);
        particles[i].setInActive();
    }

    for (int i = 0; i < MAX_NUM_STARS; i++)
    {
        stars[i].init(&starBox, 0.5f, Vector3(0,0,0), Vector3(0,0,0), 7000.0f, 1);
        stars[i].setActive();
    }

    buildFX();
    buildVertexLayouts();

    audio = new Audio();

    if (*WAVE_BANK != '\0' && *SOUND_BANK != '\0')  // if sound files defined
    {
        if (!audio->initialize()) {

        }

        /*if( FAILED( hr = audio->initialize() ) )
        {
        if( hr == HRESULT_FROM_WIN32( ERROR_FILE_NOT_FOUND ) )
        throw(GameError(gameErrorNS::FATAL_ERROR, "Failed to initialize sound system because media file not found."));
        else
        throw(GameError(gameErrorNS::FATAL_ERROR, "Failed to initialize sound system."));
        }*/
    }

    enemyBuffer.resetClock();
    shotBuffer.resetClock();
    gameTimer.resetClock();


    D3DXVECTOR3 pos(10.0f, 2.0f, 0.0f);
    D3DXVECTOR3 target(0.0f, 0.0f, 0.0f);
    D3DXVECTOR3 up(0.0f, 1.0f, 0.0f);

    //Camera Object
    camera.init(pos, Vector3(0,0,0), Vector3(0,0,0));
    camera.setPerspective();
    // camera
    cameraPos = pos;

    audio->playCue(BKG);

    //Places stars in scene
    placeStars();
}
示例#15
0
void ApplicationOverlay::renderAudioMeter() {

    Application* application = Application::getInstance();

    QGLWidget* glWidget = application->getGLWidget();
    Audio* audio = application->getAudio();

    //  Display a single screen-size quad to create an alpha blended 'collision' flash
    if (audio->getCollisionFlashesScreen()) {
        float collisionSoundMagnitude = audio->getCollisionSoundMagnitude();
        const float VISIBLE_COLLISION_SOUND_MAGNITUDE = 0.5f;
        if (collisionSoundMagnitude > VISIBLE_COLLISION_SOUND_MAGNITUDE) {
            renderCollisionOverlay(glWidget->width(), glWidget->height(), audio->getCollisionSoundMagnitude());
        }
    }

    //  Audio VU Meter and Mute Icon
    const int MUTE_ICON_SIZE = 24;
    const int AUDIO_METER_INSET = 2;
    const int MUTE_ICON_PADDING = 10;
    const int AUDIO_METER_WIDTH = MIRROR_VIEW_WIDTH - MUTE_ICON_SIZE - AUDIO_METER_INSET - MUTE_ICON_PADDING;
    const int AUDIO_METER_SCALE_WIDTH = AUDIO_METER_WIDTH - 2 * AUDIO_METER_INSET;
    const int AUDIO_METER_HEIGHT = 8;
    const int AUDIO_METER_GAP = 5;
    const int AUDIO_METER_X = MIRROR_VIEW_LEFT_PADDING + MUTE_ICON_SIZE + AUDIO_METER_INSET + AUDIO_METER_GAP;

    int audioMeterY;
    if (Menu::getInstance()->isOptionChecked(MenuOption::Mirror)) {
        audioMeterY = MIRROR_VIEW_HEIGHT + AUDIO_METER_GAP + MUTE_ICON_PADDING;
    } else {
        audioMeterY = AUDIO_METER_GAP + MUTE_ICON_PADDING;
    }

    const float AUDIO_METER_BLUE[] = { 0.0, 0.0, 1.0 };
    const float AUDIO_METER_GREEN[] = { 0.0, 1.0, 0.0 };
    const float AUDIO_METER_RED[] = { 1.0, 0.0, 0.0 };
    const float AUDIO_GREEN_START = 0.25 * AUDIO_METER_SCALE_WIDTH;
    const float AUDIO_RED_START = 0.80 * AUDIO_METER_SCALE_WIDTH;
    const float CLIPPING_INDICATOR_TIME = 1.0f;
    const float AUDIO_METER_AVERAGING = 0.5;
    const float LOG2 = log(2.f);
    const float METER_LOUDNESS_SCALE = 2.8f / 5.f;
    const float LOG2_LOUDNESS_FLOOR = 11.f;
    float audioLevel = 0.f;
    float loudness = audio->getLastInputLoudness() + 1.f;

    _trailingAudioLoudness = AUDIO_METER_AVERAGING * _trailingAudioLoudness + (1.f - AUDIO_METER_AVERAGING) * loudness;
    float log2loudness = log(_trailingAudioLoudness) / LOG2;

    if (log2loudness <= LOG2_LOUDNESS_FLOOR) {
        audioLevel = (log2loudness / LOG2_LOUDNESS_FLOOR) * METER_LOUDNESS_SCALE * AUDIO_METER_SCALE_WIDTH;
    } else {
        audioLevel = (log2loudness - (LOG2_LOUDNESS_FLOOR - 1.f)) * METER_LOUDNESS_SCALE * AUDIO_METER_SCALE_WIDTH;
    }
    if (audioLevel > AUDIO_METER_SCALE_WIDTH) {
        audioLevel = AUDIO_METER_SCALE_WIDTH;
    }
    bool isClipping = ((audio->getTimeSinceLastClip() > 0.f) && (audio->getTimeSinceLastClip() < CLIPPING_INDICATOR_TIME));

    if ((audio->getTimeSinceLastClip() > 0.f) && (audio->getTimeSinceLastClip() < CLIPPING_INDICATOR_TIME)) {
        const float MAX_MAGNITUDE = 0.7f;
        float magnitude = MAX_MAGNITUDE * (1 - audio->getTimeSinceLastClip() / CLIPPING_INDICATOR_TIME);
        renderCollisionOverlay(glWidget->width(), glWidget->height(), magnitude, 1.0f);
    }

    audio->renderToolBox(MIRROR_VIEW_LEFT_PADDING + AUDIO_METER_GAP,
                         audioMeterY,
                         Menu::getInstance()->isOptionChecked(MenuOption::Mirror));

    audio->renderScope(glWidget->width(), glWidget->height());

    glBegin(GL_QUADS);
    if (isClipping) {
        glColor3f(1, 0, 0);
    } else {
        glColor3f(0.475f, 0.475f, 0.475f);
    }

    audioMeterY += AUDIO_METER_HEIGHT;

    glColor3f(0, 0, 0);
    //  Draw audio meter background Quad
    glVertex2i(AUDIO_METER_X, audioMeterY);
    glVertex2i(AUDIO_METER_X + AUDIO_METER_WIDTH, audioMeterY);
    glVertex2i(AUDIO_METER_X + AUDIO_METER_WIDTH, audioMeterY + AUDIO_METER_HEIGHT);
    glVertex2i(AUDIO_METER_X, audioMeterY + AUDIO_METER_HEIGHT);

    if (audioLevel > AUDIO_RED_START) {
        if (!isClipping) {
            glColor3fv(AUDIO_METER_RED);
        } else {
            glColor3f(1, 1, 1);
        }
        // Draw Red Quad
        glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET + AUDIO_RED_START, audioMeterY + AUDIO_METER_INSET);
        glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET + audioLevel, audioMeterY + AUDIO_METER_INSET);
        glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET + audioLevel, audioMeterY + AUDIO_METER_HEIGHT - AUDIO_METER_INSET);
        glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET + AUDIO_RED_START, audioMeterY + AUDIO_METER_HEIGHT - AUDIO_METER_INSET);
        audioLevel = AUDIO_RED_START;
    }
    if (audioLevel > AUDIO_GREEN_START) {
        if (!isClipping) {
            glColor3fv(AUDIO_METER_GREEN);
        } else {
            glColor3f(1, 1, 1);
        }
        // Draw Green Quad
        glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET + AUDIO_GREEN_START, audioMeterY + AUDIO_METER_INSET);
        glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET + audioLevel, audioMeterY + AUDIO_METER_INSET);
        glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET + audioLevel, audioMeterY + AUDIO_METER_HEIGHT - AUDIO_METER_INSET);
        glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET + AUDIO_GREEN_START, audioMeterY + AUDIO_METER_HEIGHT - AUDIO_METER_INSET);
        audioLevel = AUDIO_GREEN_START;
    }
    //   Draw Blue Quad
    if (!isClipping) {
        glColor3fv(AUDIO_METER_BLUE);
    } else {
        glColor3f(1, 1, 1);
    }
    // Draw Blue (low level) quad
    glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET, audioMeterY + AUDIO_METER_INSET);
    glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET + audioLevel, audioMeterY + AUDIO_METER_INSET);
    glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET + audioLevel, audioMeterY + AUDIO_METER_HEIGHT - AUDIO_METER_INSET);
    glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET, audioMeterY + AUDIO_METER_HEIGHT - AUDIO_METER_INSET);
    glEnd();
}
示例#16
0
//===========================================
// MusicTrack::setVolume
//===========================================
void MusicTrack::setVolume(float vol) {
   Audio audio;
   audio.setMusicTrackVolume(shared_from_this(), vol);
}
示例#17
0
bool ex_pitch(void *args) {

	ITheFramework *frame = Factory::GetFramework ();

	Decorator *decorator = ssi_create (Decorator, 0, true);
	frame->AddDecorator(decorator);

	// audio sensor	
#ifndef SIMULATE
	Audio *audio = ssi_create (Audio, "audio", true);
	audio->getOptions()->scale = true;		
	ITransformable *audio_p = frame->AddProvider(audio, SSI_AUDIO_PROVIDER_NAME);
#else
	WavReader *audio = ssi_create (WavReader, 0, true);
	audio->getOptions()->setPath("audio.wav");
	audio->getOptions()->scale = true;		
	ITransformable *audio_p = frame->AddProvider(audio, SSI_WAVREADER_PROVIDER_NAME);
#endif	
	frame->AddSensor(audio);

	// fft
	OSTransformFFT *fft = ssi_create (OSTransformFFT, "OSTransformFFT", true);
	fft->getWindow()->getOptions()->type = OSWindow::GAUSS;
	fft->getWindow()->getOptions()->gain = 1.0;
	fft->getWindow()->getOptions()->sigma = 0.4;	
	double frameSize = audio_p->getSampleRate() * 0.01;
	double deltaSize = audio_p->getSampleRate() * 0.04;
	fft->getOptions()->nfft = smileMath_ceilToNextPowOf2(frameSize + deltaSize); //we set the FFT frame size so it's a power of 2 but can also fit all the samples
	ITransformable *fft_t = frame->AddTransformer(audio_p, fft, "0.01s", "0.04s");

	// fftmag
	OSFFTmagphase *fftmag = ssi_create (OSFFTmagphase, "OSFFTmagphase", true);
	ITransformable *fftmag_t = frame->AddTransformer(fft_t, fftmag, "0.1s");

	// specscale
	OSSpecScale *specscale = ssi_create (OSSpecScale, "OSSpecScale", true);
	specscale->getOptions()->srcScale = OSSpecScale::LINEAR;
	specscale->getOptions()->dstScale = OSSpecScale::LOG;
	specscale->getOptions()->dstLogScaleBase = 2.0;	
	specscale->getOptions()->minF = 20;
	specscale->getOptions()->smooth = true;
	specscale->getOptions()->enhance = true;
	specscale->getOptions()->weight = true;
	specscale->getOptions()->fsSec = 0.064; // BUG?	
	ITransformable *specscale_t = frame->AddTransformer(fftmag_t, specscale, "0.1s");

	// pitchshs
	OSPitchShs *pitchshs = ssi_create (OSPitchShs, "OSPitchShs", false);	
	pitchshs->getOptions()->maxPitch = 620;
	pitchshs->getOptions()->minPitch = 42;
	pitchshs->getOptions()->nCandidates = 6;
	pitchshs->getOptions()->scores = true;
	pitchshs->getOptions()->voicing = true;
	pitchshs->getOptions()->F0C1 = false;
	pitchshs->getOptions()->voicingC1 = false;
	pitchshs->getOptions()->F0raw = false;
	pitchshs->getOptions()->voicingClip = false;
	pitchshs->getOptions()->voicingCutoff = 0.7f;
	pitchshs->getOptions()->octaveCorrection = false;
	pitchshs->getOptions()->fsSec = 0.064; // BUG?
	pitchshs->getOptions()->baseSr = audio_p->getSampleRate();
	ITransformable *pitchshs_t = frame->AddTransformer(specscale_t, pitchshs, "0.1s");

	// pitchsmooth
	OSPitchSmoother *pitchsmooth = ssi_create (OSPitchSmoother, "OSPitchSmoother", true);
	pitchsmooth->getOptions()->medianFilter0 = 0;
	pitchsmooth->getOptions()->postSmoothing = 0;
	pitchsmooth->getOptions()->postSmoothingMethod = OSPitchSmoother::SIMPLE;
	pitchsmooth->getOptions()->octaveCorrection = false;
	pitchsmooth->getOptions()->F0final = true;
	pitchsmooth->getOptions()->F0finalEnv = false;
	pitchsmooth->getOptions()->voicingFinalClipped = false;
	pitchsmooth->getOptions()->voicingFinalUnclipped = true;
	pitchsmooth->getOptions()->F0raw = false;
	pitchsmooth->getOptions()->voicingC1 = false;
	pitchsmooth->getOptions()->voicingClip = false;
	ITransformable *pitchsmooth_t = frame->AddTransformer(pitchshs_t, pitchsmooth, "0.1s");

	// plot
	SignalPainter *plot = 0;	

	plot = ssi_create_id (SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("audio");
	plot->getOptions()->type = PaintSignalType::AUDIO;
	plot->getOptions()->size = 10.0;		
	frame->AddConsumer(audio_p, plot, "0.1s");
	
	plot = ssi_create_id (SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("fft");
	plot->getOptions()->size = 10.0;	
	plot->getOptions()->type = PaintSignalType::IMAGE;
	frame->AddConsumer(fft_t, plot, "0.1s");
	
	plot = ssi_create_id (SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("fftmag");
	plot->getOptions()->size = 10.0;	
	plot->getOptions()->type = PaintSignalType::IMAGE;
	frame->AddConsumer(fftmag_t, plot, "0.1s"); 

	plot = ssi_create_id (SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("specscale");
	plot->getOptions()->size = 10.0;	
	plot->getOptions()->type = PaintSignalType::IMAGE;
	frame->AddConsumer(specscale_t, plot, "0.1s"); 

	plot = ssi_create_id (SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("pitchshs");
	plot->getOptions()->size = 10.0;
	frame->AddConsumer(pitchshs_t, plot, "0.1s");

	plot = ssi_create_id (SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("pitchsmooth");
	plot->getOptions()->size = 10.0;
	frame->AddConsumer(pitchsmooth_t, plot, "0.1s"); 

	FileWriter *writer = ssi_create (FileWriter, 0, true);
	writer->getOptions()->setPath("pitch");
	writer->getOptions()->type = File::ASCII;
	frame->AddConsumer(pitchsmooth_t, writer, "0.1s");

#ifdef SIMULATE
	AudioPlayer *player = ssi_create(AudioPlayer, "player", true);
	frame->AddConsumer(audio_p, player, "0.01s");
#endif

	// run framework
	decorator->add("console", 0, 0, 650, 800);
	decorator->add("plot*", 650, 0, 400, 400);
	decorator->add("monitor*", 650, 400, 400, 400);

	frame->Start();
	frame->Wait();
	frame->Stop();
	frame->Clear();	

	return true;
}
示例#18
0
//===========================================
// MusicTrack::play
//===========================================
void MusicTrack::play(bool repeat) {
   Audio audio;
   audio.playMusicTrack(shared_from_this(), repeat);
}
示例#19
0
bool ex_mfcc_chain(void *args) {

	ITheFramework *frame = Factory::GetFramework ();

	Decorator *decorator = ssi_create (Decorator, 0, true);
	frame->AddDecorator(decorator);

	// audio sensor	
#ifndef SIMULATE
	Audio *audio = ssi_create (Audio, "audio", true);
	audio->getOptions()->scale = true;		
	ITransformable *audio_p = frame->AddProvider(audio, SSI_AUDIO_PROVIDER_NAME);
#else
	WavReader *audio = ssi_create (WavReader, 0, true);
	audio->getOptions()->setPath("audio.wav");
	audio->getOptions()->scale = true;		
	ITransformable *audio_p = frame->AddProvider(audio, SSI_WAVREADER_PROVIDER_NAME);
#endif	
	frame->AddSensor(audio);

	// preemph
	OSPreemphasis *preemph = ssi_create (OSPreemphasis, "preemph", true);
	ITransformable *preemph_t = frame->AddTransformer(audio_p, preemph, "0.02s");

	// fft
	OSMfccChain *mfcc = ssi_create (OSMfccChain, "mfcc", true);	
	mfcc->getOSTransformFFT()->getOptions()->nfft = 2048;
	ITransformable *mfcc_t = frame->AddTransformer(preemph_t, mfcc, "0.01s", "0.01s");

	// plot
	SignalPainter *plot = 0;	

	plot = ssi_create_id (SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("audio");
	plot->getOptions()->type = PaintSignalType::AUDIO;
	plot->getOptions()->size = 10.0;		
	frame->AddConsumer(audio_p, plot, "0.1s");
	
	plot = ssi_create_id (SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("mfcc");
	plot->getOptions()->type =  PaintSignalType::IMAGE;
	plot->getOptions()->size = 10.0;
	frame->AddConsumer(mfcc_t, plot, "0.1s"); 

	FileWriter *writer = ssi_create (FileWriter, 0, true);
	writer->getOptions()->setPath("mfcc_chain");
	writer->getOptions()->type = File::ASCII;
	frame->AddConsumer(mfcc_t, writer, "0.1s");

#ifdef SIMULATE
	AudioPlayer *player = ssi_create(AudioPlayer, "player", true);
	frame->AddConsumer(audio_p, player, "0.01s");
#endif

	// run framework
	decorator->add("console", 0, 0, 650, 800);
	decorator->add("plot*", 650, 0, 400, 400);
	decorator->add("monitor*", 650, 400, 400, 400);

	frame->Start();
	frame->Wait();
	frame->Stop();
	frame->Clear();	

	return true;
}
示例#20
0
//===========================================
// MusicTrack::pause
//===========================================
void MusicTrack::pause() {
   Audio audio;
   audio.pauseMusicTrack(shared_from_this());
}
示例#21
0
bool ex_pitchdirection(void *args) {

	//general
	ITheFramework *frame = Factory::GetFramework ();

	Decorator *decorator = ssi_create (Decorator, 0, true);
	frame->AddDecorator(decorator);

	ITheEventBoard *board = Factory::GetEventBoard ();
	ssi_pcast (TheEventBoard, board)->getOptions()->update = 250;

	// audio sensor	
#ifndef SIMULATE
	Audio *audio = ssi_create (Audio, "audio", true);
	audio->getOptions()->scale = true;		
	ITransformable *audio_p = frame->AddProvider(audio, SSI_AUDIO_PROVIDER_NAME);
#else
	WavReader *audio = ssi_create (WavReader, 0, true);
	audio->getOptions()->setPath("audio.wav");
	audio->getOptions()->scale = true;		
	ITransformable *audio_p = frame->AddProvider(audio, SSI_WAVREADER_PROVIDER_NAME);
#endif	
	frame->AddSensor(audio);
	
	OSPitchChain * pitch = ssi_create (OSPitchChain, "pitch", true);
	pitch->getOSPitchSmoother()->getOptions()->F0final = true;
	pitch->getOSPitchSmoother()->getOptions()->F0finalEnv = true;
	double frameSize = audio_p->getSampleRate() * 0.01;
	double deltaSize = audio_p->getSampleRate() * 0.04;
	pitch->getOSTransformFFT()->getOptions()->nfft = smileMath_ceilToNextPowOf2(frameSize + deltaSize); //we set the FFT frame size so it's a power of 2 but can also fit all the samples	
	pitch->getOSPitchShs()->getOptions()->baseSr = audio_p->getSampleRate();
	ssi::ITransformable *pitch_p = frame->AddTransformer(audio_p, pitch, "0.01s", "0.04s");
	
	OSEnergy * energy = ssi_create (OSEnergy, 0, true);
	energy->getOptions()->type = OSEnergy::TYPE::RMS;
	ssi::ITransformable *energy_p = frame->AddTransformer(audio_p, energy, "0.01s");

	OSPitchDirection * dir = ssi_create (OSPitchDirection, 0, true);
	ssi::ITransformable * xtra_src[1] = {energy_p};
	ssi::ITransformable *dir_p = frame->AddTransformer(pitch_p, 1, xtra_src, dir, "0.01s");
	board->RegisterSender(*dir);

	SignalPainter *audio_plot = ssi_create_id (SignalPainter, 0, "plot");
	audio_plot->getOptions()->setTitle("audio");
	audio_plot->getOptions()->size = 10.0;		
	audio_plot->getOptions()->type = PaintSignalType::AUDIO;
	frame->AddConsumer(audio_p, audio_plot, "0.2s");

	SignalPainter *pitch_plot = ssi_create_id (SignalPainter, 0, "plot");
	pitch_plot->getOptions()->setTitle("pitch");
	pitch_plot->getOptions()->size = 10.0;		
	pitch_plot->getOptions()->type = PaintSignalType::SIGNAL;
	frame->AddConsumer(pitch_p, pitch_plot, "0.2s");

	SignalPainter *energy_plot = ssi_create_id (SignalPainter, 0, "plot");
	energy_plot->getOptions()->setTitle("energy");
	energy_plot->getOptions()->size = 10.0;		
	energy_plot->getOptions()->type = PaintSignalType::SIGNAL;
	frame->AddConsumer(energy_p, energy_plot, "0.2s");
	
	SignalPainter *dir_plot = ssi_create_id (SignalPainter, 0, "plot");
	dir_plot->getOptions()->setTitle("direction");
	dir_plot->getOptions()->size = 10.0;		
	dir_plot->getOptions()->type = PaintSignalType::SIGNAL;
	frame->AddConsumer(dir_p, dir_plot, "0.2s");

	EventMonitor *monitor = ssi_create_id (EventMonitor, 0, "monitor");
	board->RegisterListener(*monitor, dir->getEventAddress());

#ifdef SIMULATE
	AudioPlayer *player = ssi_create (AudioPlayer, "player", true);
	player->getOptions()->bufferSize = 0.2;
	player->getOptions()->remember = true;
	frame->AddConsumer(audio_p, player, "0.01s");
#endif

	decorator->add("console", 0, 0, 650, 800);
	decorator->add("plot*", 650, 0, 400, 400);
	decorator->add("monitor*", 650, 400, 400, 400);

	board->Start();
	frame->Start();
	frame->Wait();
	frame->Stop();
	board->Stop();
	frame->Clear();
	board->Clear();

	return true;
}
示例#22
0
//===========================================
// MusicTrack::stop
//===========================================
void MusicTrack::stop() {
   Audio audio;
   audio.stopMusicTrack(shared_from_this());
}
示例#23
0
bool Audio::operator <(const Audio& aud1) const
{
    return this->title() < aud1.title();
}
示例#24
0
void MyScene::UpdateScene(float msec)
{
	Scene::UpdateScene(msec);

	Proj_dir.x = -sin(m_Camera->GetYaw() * PI / 180.0f);
	Proj_dir.z = -cos(m_Camera->GetYaw() * PI / 180.0f);
	Proj_dir.y = sin(m_Camera->GetPitch() * PI / 180.0f);
	Proj_dir.Normalise();

	//Camera Control
	AssetsManager::Player_1->CameraControl();

	//AUDIO

	std::vector<CollisionPair> temp = PhysicsEngine::Instance()->GetCollisionPair();


	for (auto& m : temp)
	{
		FMOD_VECTOR pos = { m.objectA->GetPosition().x, m.objectA->GetPosition().y, m.objectA->GetPosition().z };
		FMOD_VECTOR vel = { 0.f, 0.f, 0.f };
		float volume = m.objectA->GetLinearVelocity().Length()*0.1f;


		float time = engine_timer.GetTimedMS();

		if (time > 50){

			if (m.objectA->name == "car" || m.objectB->name == "car"){
				result = system2->playSound(sound2, 0, true, &channel2);
				result = channel2->set3DAttributes(&pos, &vel);
				result = channel2->setVolume(volume);
				result = channel2->setPaused(false);
				damage++;
				this->FindGameObject("car")->SetColour(Vector4(0.2f + damage, 1.0f, 0.5f, 1.0f));
			}
		}
	}
	
	temp.clear();

	FMOD_VECTOR Carpos = { this->FindGameObject("car")->Physics()->GetPosition().x, this->FindGameObject("car")->Physics()->GetPosition().y, this->FindGameObject("car")->Physics()->GetPosition().z };
	FMOD_VECTOR Carvel = { this->FindGameObject("car")->Physics()->GetLinearVelocity().x, this->FindGameObject("car")->Physics()->GetLinearVelocity().y, this->FindGameObject("car")->Physics()->GetLinearVelocity().z };
	//FMOD_VECTOR Carvel = { 0.0f, 0.0f, 0.0f };
	result = channel3->set3DAttributes(&Carpos, &Carvel);

	float carspeed = this->FindGameObject("car")->Physics()->GetLinearVelocity().Length();
	result = channel3->setFrequency(20000.f + carspeed * 200);
	result = channel3->setVolume(carspeed);
	result = system2->update();
	result = channel3->setPaused(false);


	Audio* audio = new Audio;
	audio->GetCameraInfo(m_Camera, result, system2);

	//END AUDIO

	NCLDebug::AddStatusEntry(Vector4(1.0f, 1.0f, 1.0f, 1.0f), "Camera X:" + std::to_string((int)m_Camera->GetPosition().x)
		+ " Y:"
		+ std::to_string((int)m_Camera->GetPosition().y)
		+ " Z:"
		+ std::to_string((int)m_Camera->GetPosition().z)
		+ " Pitch:"
		+ std::to_string((float)m_Camera->GetPitch())
		+ " Yaw:"
		+ std::to_string((float)m_Camera->GetYaw())
		+ " cord:" 
		+ std::to_string((float)Proj_dir.x) + " "
		+ std::to_string((float)Proj_dir.y) + " "
		+ std::to_string((float)Proj_dir.z) + " "
		);
}
示例#25
0
void g_callback( Float32 * buffer, UInt32 numFrames, void * userData )
{
    Audio * audio = (Audio *) userData;
    
    audio->callback(buffer, numFrames, userData);
}
示例#26
0
文件: cc.cpp 项目: ndilday/virtualu
//---------- Begin of function WinMain ----------//
//!
//! WinMain - initialization, message loop
//!
//! Compilation constants:
//!
//! DEBUG  - normal debugging
//!
//! DEMO  - demo version
//! ADMIN - administrator version
//! NO_CDCHECK - no CD check
//! NO_AUTOSAVE - no autosave
//!
//! Release version defines:
//! Standard version: DEBUG, NO_MEM_CLASS
//! Administrator version: DEBUG, NO_MEM_CLASS, ADMIN
//! Demo version: DEBUG, NO_MEM_CLASS, DEMO
//!
int PASCAL WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,
		    LPSTR lpCmdLine, int nCmdShow) {
    //------ set game directory and check CD ------//

    sys.set_game_dir();

#ifndef NO_CDCHECK

#ifndef DEMO
    if( !sys.cdrom_drive ) {
#ifdef ADMIN
	char* msg = "Please insert Virtual U - Administrator Version CDROM and try again.";
#else
	char* msg = "Please insert Virtual U CDROM and try again.";
#endif

	MessageBox(sys.main_hwnd, msg, WIN_TITLE, MB_OK | MB_ICONERROR);
	return 0;
    }
#endif
#endif

    //----------- play movie ---------------//

    OSVERSIONINFO osVersion;
    memset( &osVersion, 0, sizeof(osVersion) );
    // do not play movie in Win2000
    osVersion.dwOSVersionInfoSize = sizeof(osVersion);

    if( !m.is_file_exist("SKIPAVI.SYS")
	&& GetVersionEx(&osVersion) && osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS ) {
	play_video(hInstance, 0);
    }

    config.init();

  //--------------------------------------//

    if( !sys.init(hInstance) )
	return FALSE;

    err.set_extra_handler( extra_error_handler );   // set extra error handler, save the game when a error happens

#ifdef DEBUG
    // break at exception, for debugging
    if( sys.debug_session ) {
	// directX may change fpu control word, so change after sys.init
	// all exception but no inexact, underflow and denormal number exception
	_control87( _EM_INEXACT | _EM_UNDERFLOW | _EM_DENORMAL, _MCW_EM );
    }
#endif                                          // DEBUG

#ifdef DEMO
    audio.play_wav("DEMOOPEN",audio.int_to_DsVolume(config.sound_effect_volume));
#endif

    game.main_menu();

#ifdef DEMO
    demo_screen();
#endif

    sys.deinit();

    return 0;
}
示例#27
0
int cui_main(int argc, char *argv[])
{
    uint32_t tid = syscall_mthread_create(inputLoop);
    struct audio_data_format defaultFormat = {0, 2, 16, 4400};
    Audio* audio = new Audio(&defaultFormat, AUDIO_OUTPUT);
    if (-1 == audio->start())
    {
        _printf("Can not connect to AUDIO server!\n");
    }

    strings oggFiles;
    if (strcmp(argv[1], "-d") == 0 && argc > 2)
    {
        listOggfiles(argv[2], oggFiles);
    }
    else
    {
        for (int i = 1; i < argc; i++)
        {
            oggFiles.push_back(argv[i]);
        }
    }

    for (int i = 0; i < oggFiles.size(); i++)
    {
        FILE* fp = fopen(oggFiles[i].data(), "rb");
        if (NULL == fp)
        {
            fprintf(stderr, "File open error: %s.\n", oggFiles[i].data());
            delete audio;
            return -1;
        }
        OggVorbis_File vf;
        if (ov_open(fp, &vf, NULL, 0) < 0)
        {
            fprintf(stderr, "Skipped, %s does not appear to be an Ogg bitstream.\n", argv[i]);
            continue;
        }
        char** infoTexts = ov_comment(&vf, -1)->user_comments;
        vorbis_info* vi=ov_info(&vf, -1);
        while(*infoTexts)
        {
            fprintf(stderr, "%s\n", *infoTexts);
            ++infoTexts;
        }
//         fprintf(stderr, "\nBitstream is %d channel, %dHz\n", vi->channels, vi->rate);
//         fprintf(stderr, "\nDecoded length: %d samples\n",(long)ov_pcm_total(&vf, -1));
//         fprintf(stderr, "Encoded by: %s\n\n", ov_comment(&vf, -1)->vendor);

        struct audio_data_format format = {0, vi->channels, 16, vi->rate};
        audio->setFormat(&format);
        int current_section;
        char pcmout[4096];
        fprintf(stdout, "key q(quit) <=(prev) =>(next)\n");
        for (;;)
        {
            switch(command)
            {
            case COMMAND_FORWARD:
                command = COMMAND_NONE;
                goto replay;
            case COMMAND_BACKWARD:
                command = COMMAND_NONE;
                i -= 2;
                goto replay;
            case COMMAND_EXIT:
                i = oggFiles.size();
                goto replay;
            case COMMAND_VOLUME_UP:
            case COMMAND_VOLUME_DOWN:
                break;
            default:
                break;
            }
            long ret = ov_read(&vf, pcmout, sizeof(pcmout), &current_section);
            if (ret == 0)
            {
                break;
            }
            else if (ret < 0)
            {
                fprintf(stderr, "Warning data broken? %s\n", argv[i]);
            }
            else
            {
                audio->write(pcmout, ret);
            }
        }
    replay:
        fclose(fp);
    }
    audio->stop();
    delete audio;
// cleanup causes crash!
//    ov_clear(&vf);
}
示例#28
0
文件: cc.cpp 项目: ndilday/virtualu
static void demo_screen() {
    //------- display screen -----------//

    int dataSize;
    File* filePtr = image_interface.get_file("DEMOSCR", dataSize);

    if (filePtr->file_get_short() != -1 ) {         // use common color palette
	filePtr->file_seek(filePtr->file_pos() - sizeof(short));
	vga_back.put_large_bitmap(0, 0, filePtr);
    }
    else {                                          // use own color palette
	unsigned char palette[256 * 3];
	short *remapTable;
	filePtr->file_read(palette, 256 * 3);
	PalDesc palDesc(palette, 3, 256, 6);
	ColorTable colorTable;
	colorTable.generate_table_fast(MAX_BRIGHTNESS_ADJUST_DEGREE, palDesc, ColorTable::bright_func);
	remapTable = (short *) colorTable.get_table(0);
	vga_back.put_large_bitmap(0, 0, filePtr, remapTable);
    }

    vga.blt_buf(0,0,VGA_WIDTH-1,VGA_HEIGHT-1);
    sys.blt_virtual_buf();

    //-------- detect button --------//

    int highlightButton=0;

    while(1) {
	MSG msg;

	if (PeekMessage( &msg, NULL, 0, 0, PM_NOREMOVE)) {
	    if (!GetMessage( &msg, NULL, 0, 0)) {
		return;
	    }

	    TranslateMessage(&msg);
	    DispatchMessage(&msg);
	    continue;
	}
	else if( sys.paused_flag || !sys.active_flag ) {
	    WaitMessage();
	    continue;
	}

	//---------- detect menu option buttons -----------//

	sys.yield();
	mouse.get_event();

	DemoButton* buttonPtr = demo_button_array;

	for( int i=0 ; i<DEMO_BUTTON_COUNT ; i++, buttonPtr++ ) {
	    //----- has clicked on a button -------//

	    if(  mouse.single_click( buttonPtr->x1, buttonPtr->y1,
				     buttonPtr->x1+buttonPtr->width-1, buttonPtr->y1+buttonPtr->height-1, 0 ) ) {
		audio.play_wav("BEEPS-1",audio.int_to_DsVolume(config.sound_effect_volume));

		switch(i) {
		case 0:
		    open_http( "anker.url", "http://www.ankerpub.com" );
		    return;

		case 1:
		    open_http( "vu.url", "http://www.virtual-u.org" );
		    return;

		case 2:
		    return;
		}
	    }

	    //---- if the mouse cursor is in the area ----//

	    if(  mouse.in_area( buttonPtr->x1, buttonPtr->y1,
				buttonPtr->x1+buttonPtr->width-1, buttonPtr->y1+buttonPtr->height-1 ) ) {
		if( highlightButton != i+1 ) {
		    highlightButton = i+1;

		    // restore original image first
		    vga.blt_buf(0,0,VGA_WIDTH-1,VGA_HEIGHT-1);

		    mouse.hide_area(buttonPtr->x1, buttonPtr->y1,
				    buttonPtr->x1+buttonPtr->width-1,  buttonPtr->y1+buttonPtr->height-1);

		    image_interface.put_front( buttonPtr->x1, buttonPtr->y1, buttonPtr->file_name );

		    mouse.show_area();

		    sys.blt_virtual_buf();
		}
		break;
	    }
	}

	//------- the mouse cursor is not on any of the buttons ------//

	if( i==DEMO_BUTTON_COUNT ) {
	    if( highlightButton != 0 ) {
		vga.blt_buf(0,0,VGA_WIDTH-1,VGA_HEIGHT-1);// restore original image
		highlightButton = 0;
	    }
	}
    }
}
示例#29
0
//@Override
/*public*/ QString AudioTableDataModel::getValue(QString systemName)  const
{
 Audio* m = ((AudioManager*)InstanceManager::getDefault("AudioManager"))->getBySystemName(systemName);
 return (m != nullptr) ? m->toString() : "";
}
示例#30
0
void ColoredCubeApp::updateScene(float dt)
{
	updateGameState();
	if(GetAsyncKeyState(VK_ESCAPE) & 0x8000) PostQuitMessage(0);
	if(gamestate == title)
	{
		float rad = 0.0f;
		camera.update(mTheta,mPhi,rad,0,dt,player,mView,mEyePos,true);
		maze.update(dt);
		if(once)
		{
			maze.setCeilTex(mfxDiffuseMapVar,mfxSpecMapVar,L"Title Screen.jpg",L"brickwork-bump-map.jpg");
			once = false;
		}
		ambientLight = D3DXCOLOR(1.0f,1.0f,1.0f,1.0f);
		//set ceiling texture here
	}
	if(gamestate == controls)
	{
		float rad = 0.0f;
		camera.update(mTheta,mPhi,rad,0,dt,player,mView,mEyePos,true);
		maze.update(dt);
		if(onceAgain)
		{
			maze.setCeilTex(mfxDiffuseMapVar,mfxSpecMapVar,L"Rules Screen.jpg",L"brickwork-bump-map.jpg");
			onceAgain = false;
		}
		ambientLight = D3DXCOLOR(1.0f,1.0f,1.0f,1.0f);
		//set ceiling texture here
	}
	if(gamestate == level1 || gamestate == level2)
	{
		ambientLight = D3DXCOLOR(0.3f, 0.03f, 0.2f, 1.0f);
		if(onceAgainStart)
		{
			maze.setCeilTex(mfxDiffuseMapVar,mfxSpecMapVar,L"13.free-brick-textures.jpg",L"brickwork-bump-map.jpg");
			onceAgainStart = false;
		}
		if(GetAsyncKeyState('Y') & 0x8000)
			perspective = true;
		else
			perspective = false;
		if(oldBLevel!=0 && flashLightObject.getPowerLevel()<=0)
		{
			audio->playCue(BATTERY_DIE);
		}
		oldBLevel = flashLightObject.getPowerLevel();
		//check for win game conditions	
		auto oldP = player.getPosition();
		timer -= dt;
		std::wostringstream outs; 
		//update the camera
		camera.update(mTheta,mPhi,mRadius,0,dt,player,mView,mEyePos,perspective);
		//move the player
		camera.movePlayer(player,30,camera.getTarget(),perspective);
		player.update(dt);
		Location playerLoc;
		playerLoc.x = player.getPosition().x;
		playerLoc.z = player.getPosition().z;
		//collision detection
		if(player.getPosition()!=oldP)
		{
			if(maze.collided(playerLoc))
			{
				player.setPosition(oldP);
				player.setVelocity(Vector3(0,0,0));
				player.update(dt);
			}
		}

		for(int i = 0; i < numLightObjects; i++)
		{
			lamps[i].update(dt);
		}

		for(int i = 0; i < numBatteries; i++)
		{
			batteries[i].update(dt);
			if(player.collided(&batteries[i]))
			{
				batteries[i].setInActive();
				flashLightObject.getBattery();
				audio->playCue(BATTERY_CHARGE);
			}
		}

		if(gamestate == level1)
		{
			for(int i = 0; i < totalKeys; i++)
			{
				keyObject[i].update(dt);
				if(player.collided(&keyObject[i]))
				{
					currentKeys++;
					keyObject[i].setInActive();
					audio->playCue(ITEM);
				}
			}
		}

		if(gamestate==level2)
		{
			for(int i = 0; i < ghosts.getNumEnemies(); i++)
			{
				if(flashLightObject.hitTarget(&ghosts.getEnemies()[i]))
				{
					ghosts.getEnemies()[i].decreaseHealth();
					audio->playCue(G_HIT);
				}
			}
		}

		if(gamestate==level2)
		{
			if(player.collided(&endCube))
			{
				gamestate = win;
				maze.setCeilTex(mfxDiffuseMapVar,mfxSpecMapVar,L"You Win.jpg",L"brickwork-bump-map.jpg");
				maze.update(dt);
			}
		}

		if(player.getHealth()<=0)
		{
			gamestate = gameover;
			maze.setCeilTex(mfxDiffuseMapVar,mfxSpecMapVar,L"You Lose.jpg",L"brickwork-bump-map.jpg");
			maze.update(dt);
		}

		endCube.update(dt);

		lights[1].ambient = ambientLight;
		if(gamestate == level2)
		{
			for(int i = 0; i < ghosts.getNumEnemies(); i++)
			{
				//player gets hit by a ghost
				if(player.collided(&ghosts.getEnemies()[i]))
				{
					player.setHealth(player.getHealth()-1);
					lights[1].ambient = hurtLight;
					//make flash take longer
					ghosts.getEnemies()[i].setInActive();
					audio->playCue(P_HIT);
				}
			}
		}

		maze.update(dt);
	

		if(flashLightObject.getPosition()!=(player.getPosition()+(camera.getTarget()*5)))
		{
			flashLightObject.setPosition(player.getPosition() + camera.getTarget()*5);
			int i = 0;
		}

		//orientating the flashlight
		if(flashLightObject.lightSource.dir!=camera.getTarget())
		{
			//vectors for caluclating z-rotation
			Vector2 cameraXY = Vector2(camera.getTarget().x,camera.getTarget().y);
			Vector2 startXY = Vector2(flashLightObject.lightSource.dir.x,flashLightObject.lightSource.dir.y);
			//vectors for calculating y-rotation
			Vector2 cameraXZ = Vector2(camera.getTarget().x,camera.getTarget().z);
			Vector2 startXZ = Vector2(flashLightObject.lightSource.dir.x,flashLightObject.lightSource.dir.z);
			//vectors for calculating x-rotation
			Vector2 cameraYZ = Vector2(camera.getTarget().y,camera.getTarget().z);
			Vector2 startYZ = Vector2(flashLightObject.lightSource.dir.y,flashLightObject.lightSource.dir.z);

			float xAngle = flashLightObject.getRotation().x;
			float yAngle = flashLightObject.getRotation().y;
			float zAngle = flashLightObject.getRotation().z;
			float topEquation;
			float bottomEquation;

			topEquation = Dot2(&cameraXY,&startXY);
			bottomEquation = Length2(&cameraXY)*Length2(&startXY);
			if(bottomEquation>0)
			{
				zAngle+=acos((topEquation/bottomEquation));
			}

			topEquation = Dot2(&cameraXZ,&startXZ);
			bottomEquation = Length2(&cameraXZ)*Length2(&startXZ);
			if(bottomEquation>0)
			{
				yAngle+=acos((topEquation/bottomEquation));
			}

			topEquation = Dot2(&cameraYZ,&startYZ);
			bottomEquation = Length2(&cameraYZ)*Length2(&startYZ);
			if(bottomEquation>0)
			{
				xAngle+=acos((topEquation/bottomEquation));
			}

			flashLightObject.setRotation(Vector3(xAngle,yAngle,zAngle));
			flashLightObject.lightSource.dir = camera.getTarget();
		}

		flashLightObject.update(dt);
		//batteryObject.update(dt);
		ghosts.update(dt,&player);
		//lightObject1.update(dt);
		/*floor.update(dt);
		wall1.update(dt);
		wall2.update(dt);
		wall3.update(dt);
		wall4.update(dt);*/

		//flashLightObject.setRotation(

		/*if(player.collided(&batteryObject))
		{
			flashLightObject.getBattery();
		}*/
		//mParallelLight.pos = testCube.getPosition();
		//set up the flashlight light direction based on the direction the geometry is pointing
		//D3DXVec3Normalize(&mParallelLight.dir, &(playerCamera.getTarget()-testCube.getPosition()));

		outs.precision(2);
		outs << L"Health: " << player.getHealth() << L"\n";
		outs.precision(3);
		outs << "Battery: " << flashLightObject.getPowerLevel();
		mTimer = outs.str();
	}
	if(gamestate == gameover)
	{
		float rad = 0.0f;
		camera.update(mTheta,mPhi,rad,0,dt,player,mView,mEyePos,true);
		//set ceiling texture here
		if(onceAgainEnd)
		{
			maze.setCeilTex(mfxDiffuseMapVar,mfxSpecMapVar,L"Rules Screen.jpg",L"brickwork-bump-map.jpg");
			onceAgainEnd = false;
			onceAgainStart = true;
		}
	}
}