예제 #1
0
static void processBlockEnterExit (CtnrBlock *block, EnumEnterOrExit enteringOrExiting) {
	unsigned int code, LEDhyperlink, speedChange, volumeChange;
	BOOL red, green, onoff, fliponoff;
	APP_IRAM static unsigned int enteringVolume;

	code = block->actionEnterExit;
	if (enteringOrExiting == ENTERING) {
		code &= 0x00FF;
		enteringVolume = getVolume();
	}
	else {
		if (context.isHyperlinked && ((code & 0x00FF) == 0x04)) { // checks if enter action was hyperlink
			context.isHyperlinked = FALSE;
			setLED(LED_RED,FALSE);
		}
		code >>= 8;
	}

	if (code) {
		LEDhyperlink = code & 0x0F; // bits 0-3
		speedChange  = (code & 0x30) >> 4;  // bits 4-5
		volumeChange = (code & 0xC0) >> 6; // bits 6-7
	
		switch (speedChange) {
			case 0x01:
				adjustSpeed(3,TRUE);
				break;
			case 0x02:
				adjustSpeed(-3,TRUE);
				break;
			case 0x03:
				adjustSpeed(NORMAL_SPEED,FALSE);
				break;
		}
		switch (volumeChange) {
			case 0x01:
				adjustVolume(3,TRUE,TRUE);
				break;
			case 0x02:
				adjustVolume(-3,TRUE,TRUE);
				break;
			case 0x03:
				//return to user selected volume
				restoreVolume(FALSE);
				break;
		}  // switch
		if (LEDhyperlink == 0x04) {
			if (enteringOrExiting == ENTERING) {
				context.isHyperlinked = TRUE;
				context.USB = FALSE;
				setLED(LED_RED,TRUE);
				insertSound(&pkgSystem.files[HYPERLINK_SOUND_FILE_IDX],NULL,TRUE);
			}
			else {
				context.isHyperlinked = FALSE;
				setLED(LED_RED,FALSE);
			}
		}
		else {
			if (LEDhyperlink == 0x08) { 
				context.USB = TRUE;
				stop();
				setUSBDevice(TRUE);
			}
			else {
				green = LEDhyperlink & 0x01;
				red = LEDhyperlink & 0x02;
				onoff = LEDhyperlink & 0x04;
				fliponoff = LEDhyperlink & 0x08;
				
				if ((green && onoff) || (green && fliponoff))	
					setLED(LED_GREEN,TRUE);
				else if ((green && !onoff) || (!green && fliponoff))	
					setLED(LED_GREEN,FALSE);
				if ((red && onoff) || (red && fliponoff))
					setLED(LED_RED,TRUE);
				else if ((red && !onoff) || (!red && fliponoff))	
					setLED(LED_RED,FALSE);
			}
		}			
	}  //	if (code)
}	
예제 #2
0
bool Item::isLarge() const {
    return getVolume() >= LARGE_ITEM_VOLUME;
}
예제 #3
0
 /**
  * @brief Calculate color of fluorescent proteins.
  *
  * @return
  */
 render::Color calcFluorescentColor() const noexcept
 {
     return calcFluorescentColor(getVolume());
 }
예제 #4
0
void MoviePlayerDXA::startSound() {
	start();

	if (_bgSoundStream != NULL) {
		_vm->_mixer->stopHandle(_bgSound);
		_vm->_mixer->playStream(Audio::Mixer::kSFXSoundType, &_bgSound, _bgSoundStream, -1, getVolume(), getBalance());
	}
}
예제 #5
0
	void GeomData::mappingNodesIds(pMesh theMesh){
		int ndom = getNumDomains();
		const int* domainList = getDomainList();
		std::map<int,int> mapIDtoIndex, mapBdryIDtoIndex, mapIDtoIndex_global;
		std::set<int> setID, setBdryID;
		int i, j, k, id, id0, id1;
		pEntity node, edge, face, tetra;

		i = 0;
		// set a sequential numbering for each vertex ID: from 0 to n-1, where n is the number of vertices
		VIter vit = M_vertexIter(theMesh);
		while ( (node=VIter_next(vit))){
			mapIDtoIndex_global[EN_id(node)] = i++;
		}
		VIter_delete(vit);

		pEntity v1,v2,v3;
		bool extElem = true;// PERFORME ONLY ONCE

		// STEP1: get all vertices ID from domain "dom" and its boundary.
		// All IDs are stored into setID and setBdryID set containers.
		for (k=0; k<ndom; k++){
			int dom = domainList[k];

			if (dim==2){
				FIter fit = M_faceIter(theMesh);
				while ( (face=FIter_next(fit) )){
					int faceflag = getFaceFlag(face);
					if (faceflag==domainList[k]){
						for(i=0; i<3; i++){
							setID.insert( EN_id(face->get(0,i)) );				// nodes domain
						}
						for(i=0; i<3; i++){
							if (getVertexFlag(face->get(0,i))!=faceflag){
								setBdryID.insert(EN_id(face->get(0,i)));		// boundary nodes
							}
						}
					}
				}
				FIter_delete(fit);
			}
			else{
				RIter rit = M_regionIter(theMesh);
				while ( (tetra = RIter_next(rit) )){
					int tetraflag = getTetraFlag(tetra);
					if (tetraflag==domainList[k]){
						for(i=0; i<4; i++){
							setID.insert( EN_id(tetra->get(0,i)) );				// nodes domain
						}
						for(i=0; i<4; i++){
							if (getVertexFlag(tetra->get(0,i))!=tetraflag){
								setBdryID.insert(EN_id(tetra->get(0,i)));		// boundary nodes
							}
						}
					}
				}
				RIter_delete(rit);
			}

			// get external boundary edges/faces only: It's for saturation gradient calculation
			if (extElem){
				i = 0;
				if (dim==2){
					EIter eit = M_edgeIter(theMesh);
					while ( (edge=EIter_next(eit)) ){
						/* ONLY EXTERNAL EDGES */
						if (E_numFaces(edge)==1){
							v1 = edge->get(0,0);
							v2 = edge->get(0,1);
							external_bdry_elem[0].setValue(i,0,mapIDtoIndex_global[EN_id(v1)]);
							external_bdry_elem[0].setValue(i,1,mapIDtoIndex_global[EN_id(v2)]);
							external_bdry_elem[0].setValue(i,2,GEN_tag(v1->getClassification()));
							external_bdry_elem[0].setValue(i,3,GEN_tag(v2->getClassification()));
							i++;
						}
					}
					EIter_delete(eit);
				}
				else{
					FIter fit = M_faceIter(theMesh);
					while ( (face = FIter_next(fit)) ){
						/* ONLY EXTERNAL FACES */
						if ( F_numRegions(face)==1 ){
							v1 = face->get(0,0);
							v2 = face->get(0,1);
							v3 = face->get(0,2);
							external_bdry_elem[0].setValue(i,0,mapIDtoIndex_global[EN_id(v1)]);
							external_bdry_elem[0].setValue(i,1,mapIDtoIndex_global[EN_id(v2)]);
							external_bdry_elem[0].setValue(i,2,mapIDtoIndex_global[EN_id(v3)]);
							external_bdry_elem[0].setValue(i,3,GEN_tag(v1->getClassification()));
							external_bdry_elem[0].setValue(i,4,GEN_tag(v2->getClassification()));
							external_bdry_elem[0].setValue(i,5,GEN_tag(v3->getClassification()));
							i++;
						}
					}
					FIter_delete(fit);
				}
				extElem = false;
			}

			// STEP2: map IDs from step1 like this:
			//		id0 = 0;
			//		id1 = 1;
			//		id2 = 2;
			//		...
			//		idn = n;

			if (setID.size() > this->getNumNodesPerDomain(k)){
				char msg[256]; sprintf(msg,"NUmber of elements collected [%d] is greater than the max [%d]",(int)setID.size(),this->getNumNodesPerDomain(k));
				throw Exception(__LINE__,__FILE__,msg);
			}

			// domain
			i = 0;
			pVertex node;
			for (std::set<int>::iterator iter=setID.begin(); iter!= setID.end(); iter++){
				int id = *iter;			// vertex ID
				mapIDtoIndex[id] = i;	// gives a sequential numbering (0,1,2,...) for all vertices ID for domain k
				ID[k].setValue(i,id);
				node = theMesh->getVertex(id);
				volume[k].setValue(i,getVolume(node,dom) );
				nodes[k].setValue(i,mapIDtoIndex_global[id]);
				i++;
			}
			setID.clear();

			// boundary
			i = 0;
			for (std::set<int>::iterator iter=setBdryID.begin(); iter!= setBdryID.end(); iter++){
				int id = *iter;					// boundary vertex ID
				mapBdryIDtoIndex[id] = i;		// gives a sequential numbering (0,1,2,...) for all boundary vertices ID for domain k
				ID_bdry[k].setValue(i,id);
				node = theMesh->getVertex(id);
				volume_bdry[k].setValue(i,getVolume(node,dom) );
				i++;
			}
			setBdryID.clear();

			// STEP3: use mapped ID to initialize edge struct, where:
			//		edge_id0 = index_mapped
			//		edge_id1 = index_mapped

			// ALL EDGES
			i = 0;
			EIter eit = M_edgeIter(theMesh);
			while ( (edge=EIter_next(eit)) ){
				if ( edgeBelongToDomain(edge,domainList[k]) ){
					v1 = edge->get(0,0);
					v2 = edge->get(0,1);
					id0 = EN_id( v1 );
					id1 = EN_id( v2 );
					edges[k].setValue(i,0,mapIDtoIndex[id0]);					// index number for vertex ID for domain k
					edges[k].setValue(i,1,mapIDtoIndex[id1]); 					// index number for vertex ID for domain k
					edges[k].setValue(i,2,mapIDtoIndex_global[id0]);			// global index number for vertex ID
					edges[k].setValue(i,3,mapIDtoIndex_global[id1]);			// global index number for vertex ID
					edges[k].setValue(i,4,GEN_tag(v1->getClassification()));
					edges[k].setValue(i,5,GEN_tag(v2->getClassification()));
					i++;
				}
			}

			if (!i){
				throw Exception(__LINE__,__FILE__,"Any edge detected!");
			}

			i = 0;
			bool bdryElem_detected = false;
			if (dim==2){
				// BOUNDARY EDGES PER DOMAIN
				eit = M_edgeIter(theMesh);
				while ( (edge=EIter_next(eit)) ){
					if ( edgeBelongToDomain(edge,domainList[k]) ){
						if (belongsToBoundary(edge)){
							bdryElem_detected = true;
							for (j=0;j<2;j++){
								id = EN_id( edge->get(0,j) );
								edges_bdry[k].setValue(i,j,mapBdryIDtoIndex[id]);		// index number for boundary vertex ID for domain k
								edges_bdry[k].setValue(i,j+2,mapIDtoIndex[id]); 		// index number for vertex ID for domain k
								edges_bdry[k].setValue(i,j+4,mapIDtoIndex_global[id]);	// global index number for vertex ID
							}
							i++;
						}
					}
				}
			}
			else{
				// BOUNDARY FACES PER DOMAIN
				FIter fit = M_faceIter(theMesh);
				while ( (face = FIter_next(fit)) ){
					if ( faceBelongToDomain(face,domainList[k]) ){
						if ( belongsToBoundary(face) ){
							bdryElem_detected = true;
							for (j=0;j<3;j++){
								id = EN_id( face->get(0,j) );
								faces_bdry[k].setValue(i,j,mapBdryIDtoIndex[id]);		// index number for boundary vertex ID for domain k
								faces_bdry[k].setValue(i,j+3,mapIDtoIndex[id]);			// index number for vertex ID for domain k
								faces_bdry[k].setValue(i,j+6,mapIDtoIndex_global[id]);	// global index number for vertex ID
							}
							i++;
						}
					}
				}
				FIter_delete(fit);
				if (!bdryElem_detected){
					throw Exception(__LINE__,__FILE__,"Any boundary element detected! You must use Physical command in .geo Gmsh to define them.");
				}
			}
			mapBdryIDtoIndex.clear();
			mapIDtoIndex.clear();
		}
		mapIDtoIndex_global.clear();
	}
예제 #6
0
파일: main.c 프로젝트: astephens4/b-rad
int main(void)
{
    init_serial();
    initLCD();
    initRadio();

    unsigned char volume = getVolume();

    // tune this bitch to 102.7
    seek(FM, UP, 1);
    tuneStatus();

    char lcdStr[33];

    putsLCD("Radio!", LCD_SAMELINE);

    enum DisplayModes dispMode;
    int refresh = 0;

    while(1) {
        if(available_serial() >= 6) {
            char current = read_serial();
            if(current != 128) {
                continue;
            }
            refresh = 1;
            // read the 4-bytes length
            long length = (long)read_serial() << 24;
            length |= (long)read_serial() << 16;
            length |= (long)read_serial() << 8;
            length |= (long)read_serial();

            current = read_serial();
            char opcode = (current & 0xE) >> 5;
            switch(opcode) {
                case TUNE:
                {
                    enum Band band = current & 0x10 >> 4;
                    char freq_b = read_serial();
                    int freq = convert_freq(band, freq_b);
                    //tuneStation(band, freq);
                    if(band == FM) {
                        sprintf(lcdStr, "Tune FM: %d", freq);
                    }
                    else {
                        sprintf(lcdStr, "Tune AM: %d", freq);
                    }
                    break;
                }
                case TUNE_PRESET:
                {
                    enum Band band = current & 0x10 >> 4;
                    int preset = current & 0x0F;
                    //tunePreset(band, preset);
                    if(band == FM) {
                        sprintf(lcdStr, "Tune FM Preset: %d", preset);
                    }
                    else {
                        sprintf(lcdStr, "Tune AM Preset: %d", preset);
                    }
                }
                    break;
                case VOLUME:
                {
                    enum Direction dir = current & 0x10 >> 4;
                    if(dir == UP) {
                        ++volume;
                    }
                    else {
                        --volume;
                    }
                    //setVolume(volume);
                    sprintf(lcdStr, "Volume %d", volume);
                }
                    break;
                case BAND:
                {
                    enum Band band = current & 0x10 >> 4;
                    //tuneStation(band, getLastStation(band));
                    if(band == FM) {
                        sprintf(lcdStr, "Band set to FM");
                    }
                    else {
                        sprintf(lcdStr, "Band set to AM");
                    }
                }
                    break;
                case SET_PRESET:
                {
                    enum Band band = current & 0x10 >> 4;
                    int preset = current & 0x0F;
                    char freq_b = read_serial();
                    int freq = convert_freq(band, freq_b);
                    //setPreset(band, preset, freq);
                    if(band == FM) {
                        sprintf(lcdStr, "Set FM Preset %d: %d", preset,  freq);
                    }
                    else {
                        sprintf(lcdStr, "Set AM Preset %d: %d", preset,  freq);
                    }
                    break;
                }
                    break;
                case NEXT:
                {
                    enum Direction dir = current & 0x10 >> 4;
                    enum Mode mode = current & 0x0C >> 2;
                    if(mode == PRESET) {
                        currentPreset += (dir) ? 1 : -1;
                        if(currentPreset < 0) currentPreset = 5;
                        if(currentPreset > 5) currentPreset = 0;
                        //tunePreset(currentBand, currentPreset);
                        sprintf(lcdStr, "Tune preset %d", currentPreset);

                    }
                    else if(mode == FREQUENCY) {
                        int currentFreq = getFrequency();
                        currentFreq += (dir) ? 10 : -10;
                        if(currentBand == FM) {
                            if(currentFreq < FM_MIN_FREQ) currentFreq = FM_MAX_FREQ;
                            if(currentFreq > FM_MAX_FREQ) currentFreq = FM_MIN_FREQ;
                            sprintf(lcdStr, "Tune FM %d", currentFreq);
                        }
                        else {
                            if(currentFreq < AM_MIN_FREQ) currentFreq = AM_MAX_FREQ;
                            if(currentFreq > AM_MAX_FREQ) currentFreq = AM_MIN_FREQ;
                            sprintf(lcdStr, "Tune AM %d", currentFreq);
                        }
                        tuneStation(currentBand, currentFreq);
                    }
                    else if(mode == SCAN) {
                        //seek(currentBand, dir);
                        sprintf(lcdStr, "Seek activated");
                    }
                }
                    break;
                case DISPLAY:
                {
                    dispMode = (current & 0x1C) >> 2;
                    sprintf(lcdStr, "Set displayMode %d", dispMode);
                }
                    break;
            }
        }
        if(refresh) {
            refresh = 0;
            clearLCD();
            putsLCD(lcdStr, LCD_NEXTLINE);
            LCD_DELAY(0xFFFF);
            LCD_DELAY(0xFFFF);
            LCD_DELAY(0xFFFF);
        }
    }
예제 #7
0
void Bluetooth::onReadyRead(void)
{
    qDebug() << "Ready read..." << "request:" << m_request;

    if (!m_socket)
        return;

    while (m_socket->canReadLine()) {
        QByteArray data = m_socket->readLine();
        QString line = QString::fromUtf8(data.constData(), data.length()).trimmed();
        if (line.length() > 0) {
            qDebug() << "Received:" << line << "request:" << m_request;

            if (m_timer->isActive()) {
                m_timer->stop();
            }

            switch (m_request) {
                case REQUEST_BATTERY:
                    if (line.contains(BLUETOOTH_CMD_BATTERY)) {
                        line.remove(BLUETOOTH_CMD_BATTERY + QString(": "));
                        line.remove(QChar('%'));
                        unsigned int capacity = line.toInt();
                        m_request = REQUEST_NO_REQUEST;
                        emit battery(capacity);
                    } else {
                        // FIXME: ERROR
                    }
                    break;

                case REQUEST_EYES:
                    if (line.contains(BLUETOOTH_CMD_EYES)) {
                        PowerState state;
                        if (line.contains(BLUETOOTH_PARAM_ON)) {
                            state = PowerOn;
                        } else {
                            state = PowerOff;
                        }
                        m_request = REQUEST_NO_REQUEST;
                        emit eyes(state);
                    } else {
                        getEyes();
                    }
                    break;

                case REQUEST_HELMET:
                    if (line.contains(BLUETOOTH_CMD_HELMET)) {
                        HelmetState state;
                        if (line.contains(BLUETOOTH_PARAM_CLOSE)) {
                            state = HelmetClose;
                        } else {
                            state = HelmetOpen;
                        }
                        m_request = REQUEST_NO_REQUEST;
                        emit helmet(state);
                    } else {
                        getHelmet();
                    }
                    break;

                case REQUEST_INTENSITY:
                    if (line.contains(BLUETOOTH_CMD_INTENSITY)) {
                        line.remove(BLUETOOTH_CMD_INTENSITY + QString(": "));
                        PowerIntensity value = (PowerIntensity) line.toInt();
                        m_request = REQUEST_NO_REQUEST;
                        emit intensity(m_intensityDevice, value);
                    } else {
                        getIntensity(m_intensityDevice);
                    }
                    break;

                case REQUEST_QUOTE:
                    if (line.contains("OK")) {
                        m_request = REQUEST_NO_REQUEST;
                        emit quoteFinished();
                    } else {
                        // FIXME: ERROR
                    }
                    break;

                case REQUEST_REPULSOR:
                    if (line.contains("OK")) {
                        emit repulsorBlastGenerated(m_repulsor);
                    }
                    m_request = REQUEST_NO_REQUEST;
                    break;

                case REQUEST_REPULSORS:
                    if (line.contains(BLUETOOTH_CMD_REPULSORS)) {
                        PowerState state;
                        if (line.contains(BLUETOOTH_PARAM_ON)) {
                            state = PowerOn;
                        } else {
                            state = PowerOff;
                        }
                        m_request = REQUEST_NO_REQUEST;
                        emit repulsors(state);
                    } else {
                        getRepulsors();
                    }
                    break;

                case REQUEST_UNIBEAM:
                    if (line.contains(BLUETOOTH_CMD_UNIBEAM)) {
                        PowerState state;
                        if (line.contains(BLUETOOTH_PARAM_ON)) {
                            state = PowerOn;
                        } else {
                            state = PowerOff;
                        }
                        m_request = REQUEST_NO_REQUEST;
                        emit unibeam(state);
                    } else {
                        getUnibeam();
                    }
                    break;

                case REQUEST_VERSION:
                    if (m_revision.isEmpty()) {
                        m_revision = line;
                    } else if (m_build.isEmpty()) {
                        m_build = line;
                        m_request = REQUEST_NO_REQUEST;
                        emit version(m_revision, m_build);
                    }
                    break;

                case REQUEST_VOLUME:
                    if (line.contains(BLUETOOTH_CMD_VOLUME)) {
                        line.remove(BLUETOOTH_CMD_VOLUME + QString(": "));
                        VolumeLevel level = (VolumeLevel) line.toInt();
                        emit volume(level);
                        m_request = REQUEST_NO_REQUEST;
                    } else {
                        getVolume();
                    }
                    break;

                default:
                    break;
            }
        }
    }
}
예제 #8
0
float
Music::getVolume(const Ice::Current& c)
{
	return getVolume();
}
예제 #9
0
void InstrumentTrack::processAudioBuffer( sampleFrame* buf, const fpp_t frames, NotePlayHandle* n )
{
	// we must not play the sound if this InstrumentTrack is muted...
	if( isMuted() || ( n && n->isBbTrackMuted() ) || ! m_instrument )
	{
		return;
	}

	// Test for silent input data if instrument provides a single stream only (i.e. driven by InstrumentPlayHandle)
	// We could do that in all other cases as well but the overhead for silence test is bigger than
	// what we potentially save. While playing a note, a NotePlayHandle-driven instrument will produce sound in
	// 99 of 100 cases so that test would be a waste of time.
	if( m_instrument->flags().testFlag( Instrument::IsSingleStreamed ) &&
		MixHelpers::isSilent( buf, frames ) )
	{
		// at least pass one silent buffer to allow
		if( m_silentBuffersProcessed )
		{
			// skip further processing
			return;
		}
		m_silentBuffersProcessed = true;
	}
	else
	{
		m_silentBuffersProcessed = false;
	}

	// if effects "went to sleep" because there was no input, wake them up
	// now
	m_audioPort.effects()->startRunning();

	// get volume knob data
	static const float DefaultVolumeRatio = 1.0f / DefaultVolume;
	ValueBuffer * volBuf = m_volumeModel.valueBuffer();
	float v_scale = volBuf
		? 1.0f
		: getVolume() * DefaultVolumeRatio;

	// instruments using instrument-play-handles will call this method
	// without any knowledge about notes, so they pass NULL for n, which
	// is no problem for us since we just bypass the envelopes+LFOs
	if( m_instrument->flags().testFlag( Instrument::IsSingleStreamed ) == false && n != NULL )
	{
		const f_cnt_t offset = n->noteOffset();
		m_soundShaping.processAudioBuffer( buf + offset, frames - offset, n );
		v_scale *= ( (float) n->getVolume() * DefaultVolumeRatio );
	}

	m_audioPort.setNextFxChannel( m_effectChannelModel.value() );
	
	// get panning knob data
	ValueBuffer * panBuf = m_panningModel.valueBuffer();
	int panning = panBuf
		? 0
		: m_panningModel.value();

	if( n )
	{
		panning += n->getPanning();
		panning = tLimit<int>( panning, PanningLeft, PanningRight );
	}

	// apply sample-exact volume/panning data
	if( volBuf )
	{
		for( f_cnt_t f = 0; f < frames; ++f )
		{
			float v = volBuf->values()[ f ] * 0.01f;
			buf[f][0] *= v;
			buf[f][1] *= v;
		}
	}
	if( panBuf )
	{
		for( f_cnt_t f = 0; f < frames; ++f )
		{
			float p = panBuf->values()[ f ] * 0.01f;
			buf[f][0] *= ( p <= 0 ? 1.0f : 1.0f - p );
			buf[f][1] *= ( p >= 0 ? 1.0f : 1.0f + p );
		}
	}

	engine::mixer()->bufferToPort( buf, frames, panningToVolumeVector( panning, v_scale ), &m_audioPort );
}
예제 #10
0
void Sphere::print() {
	cout<< "I'm a sphere. My area is: "<< getArea() << " and my volume is: "<< getVolume()<< endl;
}
예제 #11
0
파일: main.cpp 프로젝트: chhavi1996/guipro
LRESULT CALLBACK MainWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	static UINT s_uTaskBarCreated = 0;

	switch(uMsg)
	{
	case WM_CREATE:
		s_uTaskBarCreated = RegisterWindowMessage(L"TaskbarCreated");
		g_hwndMain = hwnd;

		// Set icons
		SendMessage(hwnd, WM_SETICON, ICON_BIG, 
			(LONG)(LONG_PTR)LoadImage(g_hInst, MAKEINTRESOURCE(IDI_MAIN_ICON), IMAGE_ICON, 
			GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON), LR_DEFAULTCOLOR));

		SendMessage(hwnd, WM_SETICON, ICON_SMALL, 
			(LONG)(LONG_PTR)LoadImage(g_hInst, MAKEINTRESOURCE(IDI_TRAY_ICON), IMAGE_ICON, 
			GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR));

		// call uninstall hook keyboard to clean the override key array
		uninstallHookKeyboard();

		// Set the Tray Icon
		ReloadExTrayIcon();

		if (openConfig() == 1)
		{
			MessageBox(g_hwndMain, L"No config file", L"Error", NULL);
			GUIProQuit();
			return 0;
		}

		if (!registerConfig(TRUE))
		{
			GUIProQuit();
			return 0;
		}

		/*
		myRegisterHotKey(VK_ADD, MOD_CONTROL | MOD_WIN, IDH_HOTKEY_VOL_UP, true);
		myRegisterHotKey(VK_SUBTRACT, MOD_CONTROL | MOD_WIN, IDH_HOTKEY_VOL_DOWN, true);
		myRegisterHotKey(VK_NUMPAD0, MOD_CONTROL | MOD_WIN, IDH_HOTKEY_VOL_MUTE, true);
		*/
		// Clean the memory in order to have a light application
		FlushMemory();
		break;

	case WM_DESTROY:
		GUIProQuit();
		break;

	case WM_HOTKEY:
		{
			int ret = -2;
			switch (wParam) {
				case IDH_HOTKEY_VOL_UP:
					ret = changeVolumeUp();
					break;
				case IDH_HOTKEY_VOL_DOWN:
					ret = changeVolumeDown();
					break;
				case IDH_HOTKEY_VOL_MUTE:
					ret = changeVolumeMute();
					if (ret > 0)
						ret = getVolume();
					break;
			}

			if (ret >= 0)
			{
				ShowVolumeBalloon(ret);
			}

			unloadVolumeInterface();
			FlushMemory();
		}
		break;

	case WM_MYTRAYMSG:
		// Tray Icon event
		if (wParam == IDI_MAIN_ICON)
		{
			if ((UINT)lParam == WM_RBUTTONUP) 
			{
				ShowTrayMenu();
				FlushMemory();
			}
			else if ((UINT)lParam == WM_LBUTTONUP)
			{
				ShowVolumeBalloon(-1);
				FlushMemory();
			}
		}
		break;

	default:
		if( uMsg == s_uTaskBarCreated )
		{
			ReloadExTrayIcon();
			FlushMemory();
		}
		else
		{
			return(DefWindowProc(hwnd, uMsg, wParam, lParam));
		}
		break;
	}
	return 0;
}
예제 #12
0
void HLL::initBuffers() {
	Super::initBuffers();

	eigenvaluesBuffer = cl.alloc(sizeof(real) * numStates() * getVolume() * app->dim);
}
예제 #13
0
void VoxelPoolsBase::backwardReacVolumeFactor( unsigned int i, double volume )
{
	assert( i < xReacScaleProducts_.size() );
	xReacScaleProducts_[i] *= volume / getVolume();
	// cout << "backwardReacVolumeFactor[" << i << "] = "<< xReacScaleProducts_[i] <<endl;
}
예제 #14
0
void VoxelPoolsBase::forwardReacVolumeFactor( unsigned int i, double volume )
{
	assert( i < xReacScaleSubstrates_.size() );
	xReacScaleSubstrates_[i] *= volume / getVolume();
	// cout << "forwardReacVolumeFactor[" << i << "] = " << xReacScaleSubstrates_[i] <<endl;
}
예제 #15
0
bool LapsusAlsaMixer::init()
{
	int err;
	snd_ctl_t *ctl_handle;
	snd_ctl_card_info_t *hw_info;

	snd_ctl_card_info_alloca(&hw_info);

	if ((err = snd_ctl_open (&ctl_handle, "default", 0)) < 0)
		return false;
	if ((err = snd_ctl_card_info (ctl_handle, hw_info)) < 0)
		return false;

	snd_ctl_close (ctl_handle);

	if ((err = snd_mixer_open (&_handle, 0)) < 0)
		return false;
	if ((err = snd_mixer_attach (_handle, "default")) < 0)
		return false;
	if ((err = snd_mixer_selem_register (_handle, 0, 0)) < 0)
		return false;

	if ((err = snd_mixer_load (_handle)) < 0)
		return false;

	// printf("Card name: '%s'\n", snd_ctl_card_info_get_name(hw_info));
	// printf("Device name: '%s'\n", snd_ctl_card_info_get_mixername(hw_info));

	snd_mixer_elem_t *elem;
	snd_mixer_selem_id_t *tmp_sid = 0;

	for (elem = snd_mixer_first_elem(_handle); elem; elem = snd_mixer_elem_next(elem))
	{
		if (snd_mixer_selem_is_active(elem))
		{
			if (!tmp_sid) tmp_sid = (snd_mixer_selem_id_t*) malloc(snd_mixer_selem_id_sizeof());

			snd_mixer_selem_get_id(elem, tmp_sid);

			const char *name = snd_mixer_selem_id_get_name( tmp_sid );

			if (!strcasecmp(name, "Headphone"))
			{
				if (sids[ID_HP]) delete sids[ID_HP];
				sids[ID_HP] = new SIDInfo(_handle, tmp_sid);
				tmp_sid = 0;
			}
			else if (!strcasecmp(name, "Front"))
			{
				if (sids[ID_F]) delete sids[ID_F];
				sids[ID_F] = new SIDInfo(_handle, tmp_sid);
				tmp_sid = 0;
			}
			else if (!strcasecmp(name, "Master"))
			{
				if (sids[ID_M]) delete sids[ID_M];
				sids[ID_M] = new SIDInfo(_handle, tmp_sid);
				tmp_sid = 0;
			}
		}
	}

	if (tmp_sid) free(tmp_sid);

	bool foundAny = false;

	for (int i = 0; i < ID_LAST; ++i)
	{
		if (sids[i])
		{
			if (sids[i]->hasMute)
			{
				foundAny = true;
			}

			if (sids[i]->hasVolume)
			{
				foundAny = true;

				long range = sids[i]->max - sids[i]->min;

				if (range > _globalMax)
					_globalMax = range;
			}
		}
	}

	if (_globalMax > INT_MAX)
		_globalMax = INT_MAX;

	if (!foundAny) return false;

	for (int i = 0; i < ID_LAST; ++i)
	{
		if (sids[i]) sids[i]->setGlobalMax(_globalMax);
	}

	if ((_count = snd_mixer_poll_descriptors_count(_handle)) < 0)
		return false;

	_fds = (struct pollfd*) calloc(_count, sizeof(struct pollfd));

	if (!_fds) return false;

	if ((err = snd_mixer_poll_descriptors(_handle, _fds, _count)) < 0)
		return false;

	if (err != _count) return 0;

	_sns = new QSocketNotifier*[_count];

	for ( int i = 0; i < _count; ++i )
	{
		_sns[i] = new QSocketNotifier(_fds[i].fd, QSocketNotifier::Read);
		connect(_sns[i], SIGNAL(activated(int)), this, SLOT(alsaEvent()));
	}

	// To read our current parameters. Signals will be emited, but those signals
	// are not yet connected to anything - this method is called from constructor
	// only.
	getVolume();
	mixerIsMuted();

	return true;
}
예제 #16
0
bool TheoraDecoder::loadStream(Common::SeekableReadStream *stream) {
	close();

	_endOfAudio = false;
	_endOfVideo = false;
	_fileStream = stream;

	// start up Ogg stream synchronization layer
	ogg_sync_init(&_oggSync);

	// init supporting Vorbis structures needed in header parsing
	vorbis_info_init(&_vorbisInfo);
	vorbis_comment_init(&_vorbisComment);

	// init supporting Theora structures needed in header parsing
	th_comment_init(&_theoraComment);
	th_info_init(&_theoraInfo);

	// Ogg file open; parse the headers
	// Only interested in Vorbis/Theora streams
	bool foundHeader = false;
	while (!foundHeader) {
		int ret = bufferData();

		if (ret == 0)
			break;

		while (ogg_sync_pageout(&_oggSync, &_oggPage) > 0) {
			ogg_stream_state test;

			// is this a mandated initial header? If not, stop parsing
			if (!ogg_page_bos(&_oggPage)) {
				// don't leak the page; get it into the appropriate stream
				queuePage(&_oggPage);
				foundHeader = true;
				break;
			}

			ogg_stream_init(&test, ogg_page_serialno(&_oggPage));
			ogg_stream_pagein(&test, &_oggPage);
			ogg_stream_packetout(&test, &_oggPacket);

			// identify the codec: try theora
			if (!_theoraPacket && th_decode_headerin(&_theoraInfo, &_theoraComment, &_theoraSetup, &_oggPacket) >= 0) {
				// it is theora
				memcpy(&_theoraOut, &test, sizeof(test));
				_theoraPacket = 1;
			} else if (!_vorbisPacket && vorbis_synthesis_headerin(&_vorbisInfo, &_vorbisComment, &_oggPacket) >= 0) {
				// it is vorbis
				memcpy(&_vorbisOut, &test, sizeof(test));
				_vorbisPacket = 1;
			} else {
				// whatever it is, we don't care about it
				ogg_stream_clear(&test);
			}
		}
		// fall through to non-bos page parsing
	}

	// we're expecting more header packets.
	while ((_theoraPacket && _theoraPacket < 3) || (_vorbisPacket && _vorbisPacket < 3)) {
		int ret;

		// look for further theora headers
		while (_theoraPacket && (_theoraPacket < 3) && (ret = ogg_stream_packetout(&_theoraOut, &_oggPacket))) {
			if (ret < 0)
				error("Error parsing Theora stream headers; corrupt stream?");

			if (!th_decode_headerin(&_theoraInfo, &_theoraComment, &_theoraSetup, &_oggPacket))
				error("Error parsing Theora stream headers; corrupt stream?");

			_theoraPacket++;
		}

		// look for more vorbis header packets
		while (_vorbisPacket && (_vorbisPacket < 3) && (ret = ogg_stream_packetout(&_vorbisOut, &_oggPacket))) {
			if (ret < 0)
				error("Error parsing Vorbis stream headers; corrupt stream?");

			if (vorbis_synthesis_headerin(&_vorbisInfo, &_vorbisComment, &_oggPacket))
				error("Error parsing Vorbis stream headers; corrupt stream?");

			_vorbisPacket++;

			if (_vorbisPacket == 3)
				break;
		}

		// The header pages/packets will arrive before anything else we
		// care about, or the stream is not obeying spec

		if (ogg_sync_pageout(&_oggSync, &_oggPage) > 0) {
			queuePage(&_oggPage); // demux into the appropriate stream
		} else {
			ret = bufferData(); // someone needs more data

			if (ret == 0)
				error("End of file while searching for codec headers.");
		}
	}

	// and now we have it all.  initialize decoders
	if (_theoraPacket) {
		_theoraDecode = th_decode_alloc(&_theoraInfo, _theoraSetup);
		debugN(1, "Ogg logical stream %lx is Theora %dx%d %.02f fps",
		       _theoraOut.serialno, _theoraInfo.pic_width, _theoraInfo.pic_height,
		       (double)_theoraInfo.fps_numerator / _theoraInfo.fps_denominator);

		switch (_theoraInfo.pixel_fmt) {
		case TH_PF_420:
			debug(1, " 4:2:0 video");
			break;
		case TH_PF_422:
			debug(1, " 4:2:2 video");
			break;
		case TH_PF_444:
			debug(1, " 4:4:4 video");
			break;
		case TH_PF_RSVD:
		default:
			debug(1, " video\n  (UNKNOWN Chroma sampling!)");
			break;
		}

		if (_theoraInfo.pic_width != _theoraInfo.frame_width || _theoraInfo.pic_height != _theoraInfo.frame_height)
			debug(1, "  Frame content is %dx%d with offset (%d,%d).",
			      _theoraInfo.frame_width, _theoraInfo.frame_height, _theoraInfo.pic_x, _theoraInfo.pic_y);

		switch (_theoraInfo.colorspace){
		case TH_CS_UNSPECIFIED:
			/* nothing to report */
			break;
		case TH_CS_ITU_REC_470M:
			debug(1, "  encoder specified ITU Rec 470M (NTSC) color.");
			break;
		case TH_CS_ITU_REC_470BG:
			debug(1, "  encoder specified ITU Rec 470BG (PAL) color.");
			break;
		default:
			debug(1, "warning: encoder specified unknown colorspace (%d).", _theoraInfo.colorspace);
			break;
		}

		debug(1, "Encoded by %s", _theoraComment.vendor);
		if (_theoraComment.comments) {
			debug(1, "theora comment header:");
			for (int i = 0; i < _theoraComment.comments; i++) {
				if (_theoraComment.user_comments[i]) {
					int len = _theoraComment.comment_lengths[i];
					char *value = (char *)malloc(len + 1);
					if (value) {
						memcpy(value, _theoraComment.user_comments[i], len);
						value[len] = '\0';
						debug(1, "\t%s", value);
						free(value);
					}
				}
			}
		}

		th_decode_ctl(_theoraDecode, TH_DECCTL_GET_PPLEVEL_MAX, &_ppLevelMax, sizeof(_ppLevelMax));
		_ppLevel = _ppLevelMax;
		th_decode_ctl(_theoraDecode, TH_DECCTL_SET_PPLEVEL, &_ppLevel, sizeof(_ppLevel));
		_ppInc = 0;
	} else {
		// tear down the partial theora setup
		th_info_clear(&_theoraInfo);
		th_comment_clear(&_theoraComment);
	}

	th_setup_free(_theoraSetup);
	_theoraSetup = 0;

	if (_vorbisPacket) {
		vorbis_synthesis_init(&_vorbisDSP, &_vorbisInfo);
		vorbis_block_init(&_vorbisDSP, &_vorbisBlock);
		debug(3, "Ogg logical stream %lx is Vorbis %d channel %ld Hz audio.",
		      _vorbisOut.serialno, _vorbisInfo.channels, _vorbisInfo.rate);

		_audStream = Audio::makeQueuingAudioStream(_vorbisInfo.rate, _vorbisInfo.channels);

		// Get enough audio data to start us off
		while (_audStream->numQueuedStreams() == 0) {
			// Queue more data
			bufferData();
			while (ogg_sync_pageout(&_oggSync, &_oggPage) > 0)
				queuePage(&_oggPage);

			queueAudio();
		}

		if (_audStream)
			g_system->getMixer()->playStream(Audio::Mixer::kPlainSoundType, _audHandle, _audStream, -1, getVolume(), getBalance());
	} else {
		// tear down the partial vorbis setup
		vorbis_info_clear(&_vorbisInfo);
		vorbis_comment_clear(&_vorbisComment);
		_endOfAudio = true;
	}

	_surface.create(_theoraInfo.frame_width, _theoraInfo.frame_height, g_system->getScreenFormat());

	// Set up a display surface
	_displaySurface.pixels = _surface.getBasePtr(_theoraInfo.pic_x, _theoraInfo.pic_y);
	_displaySurface.w = _theoraInfo.pic_width;
	_displaySurface.h = _theoraInfo.pic_height;
	_displaySurface.format = _surface.format;
	_displaySurface.pitch = _surface.pitch;

	// Set the frame rate
	_frameRate = Common::Rational(_theoraInfo.fps_numerator, _theoraInfo.fps_denominator);

	return true;
}
예제 #17
0
파일: command.c 프로젝트: dkulp/fpp
  void ProcessCommand(char *command)
  {
    char *s;
    char *s2;
    char *s3;
    char *s4;
    char *response2 = NULL;
    int i;
		char NextPlaylist[128] = "No playlist scheduled.";
		char NextScheduleStartText[64] = "";
		char CommandStr[64];
		LogExcess(VB_COMMAND, "CMD: %s\n", command);
		s = strtok(command,",");
		strcpy(CommandStr, s);
		if (!strcmp(CommandStr, "s"))
		{
				Json::Value info = player->GetCurrentPlaylistInfo();
				char currentEntryType = 'u'; // Unknown
				const char *currentSequenceName = NULL;
				const char *currentMediaName = NULL;

				if (info["currentEntry"].isMember("sequenceName"))
					currentSequenceName = info["currentEntry"]["sequenceName"].asString().c_str();

				if (info["currentEntry"].isMember("mediaFilename"))
					currentMediaName = info["currentEntry"]["mediaFilename"].asString().c_str();

				if (info["currentEntry"].isMember("type"))
				{
					std::string type = info["currentEntry"]["type"].asString();
					if (type == "both")
						currentEntryType = 'b';
					else if (type == "event")
						currentEntryType = 'e';
					else if (type == "media")
						currentEntryType = 'm';
					else if (type == "pause")
						currentEntryType = 'p';
					else if (type == "plugin")
						currentEntryType = 'P';
					else if (type == "sequence")
						currentEntryType = 's';
				}

				player->GetNextScheduleStartText(NextScheduleStartText);
				player->GetNextPlaylistText(NextPlaylist);
				if(FPPstatus==FPP_STATUS_IDLE)
				{
					if (getFPPmode() == REMOTE_MODE)
					{
						sprintf(response,"%d,%d,%d,%s,%s,%d,%d\n",
							getFPPmode(), 0, getVolume(),
							currentSequenceName,
							currentMediaName,
							player->GetPlaybackSecondsElapsed(),
							player->GetPlaybackSecondsRemaining());
					}
					else
					{
						sprintf(response,"%d,%d,%d,%s,%s\n",
							getFPPmode(),0,getVolume(),
							NextPlaylist,NextScheduleStartText);
					}
				}
				else
				{
					sprintf(response,"%d,%d,%d,%s,%c,%s,%s,%d,%d,%d,%d,%s,%s,%d\n",
							getFPPmode(),FPPstatus,getVolume(),
							info["name"].asString().c_str(),
							currentEntryType,
							currentSequenceName,
							currentMediaName,
							info["currentPosition"].asInt() + 1,
							info["size"].asInt(),
							info["currentEntry"]["secondsElapsed"].asInt(),
							info["currentEntry"]["secondsRemaining"].asInt(),
							NextPlaylist,NextScheduleStartText,
							info["repeat"].asInt());
				}
		}
		else if ((!strcmp(CommandStr, "p")) ||
				 (!strcmp(CommandStr, "P")))
		{
				if(FPPstatus==FPP_STATUS_PLAYLIST_PLAYING || FPPstatus==FPP_STATUS_STOPPING_GRACEFULLY)
				{
					player->PlaylistStopNow();
					sleep(1);
				}
	
				s = strtok(NULL,",");
				if (s)
				{
					std::string playlistName(s);
					int repeat = !strcmp(CommandStr, "p") ? 1 : 0;
					int position = 0;

					s = strtok(NULL,",");
					if (s)
						position = atoi(s);

					if (player->PlaylistStart(playlistName, position, repeat))
					{
						sprintf(response,"%d,%d,Playlist Started,,,,,,,,,,\n",getFPPmode(),COMMAND_SUCCESS);
					}
					else
					{
						sprintf(response,"%d,%d,Playlist Start Failed,,,,,,,,,,\n",getFPPmode(),COMMAND_FAILED);
					}
				}
				else
				{
					sprintf(response,"%d,%d,Unknown Playlist,,,,,,,,,,\n",getFPPmode(),COMMAND_FAILED);
				}
		}
		else if (!strcmp(CommandStr, "S"))
		{
				if(FPPstatus==FPP_STATUS_PLAYLIST_PLAYING)
				{
					player->PlaylistStopGracefully();
					player->ReLoadCurrentScheduleInfo();
					sprintf(response,"%d,%d,Playlist Stopping Gracefully,,,,,,,,,,\n",getFPPmode(),COMMAND_SUCCESS);
				}
				else
				{
					sprintf(response,"%d,Not playing,,,,,,,,,,,\n",COMMAND_FAILED);
				}
		}
		else if (!strcmp(CommandStr, "d"))
		{
				if(FPPstatus==FPP_STATUS_PLAYLIST_PLAYING || FPPstatus==FPP_STATUS_STOPPING_GRACEFULLY)
				{
					player->PlaylistStopNow();
					player->ReLoadCurrentScheduleInfo();
					sprintf(response,"%d,%d,Playlist Stopping Now,,,,,,,,,,\n",getFPPmode(),COMMAND_SUCCESS);
				}
				else
				{
					sprintf(response,"%d,%d,Not playing,,,,,,,,,,\n",getFPPmode(),COMMAND_FAILED);
				}
		}
		else if (!strcmp(CommandStr, "R"))
		{
				if(FPPstatus==FPP_STATUS_IDLE)
				{
					player->ReLoadCurrentScheduleInfo();
				}
				player->ReLoadNextScheduleInfo();
				
				
				sprintf(response,"%d,%d,Reloading Schedule,,,,,,,,,,\n",getFPPmode(),COMMAND_SUCCESS);
		}
		else if (!strcmp(CommandStr, "v"))
		{
				s = strtok(NULL,",");
				if (s)
				{
					setVolume(atoi(s));
					sprintf(response,"%d,%d,Setting Volume,,,,,,,,,,\n",getFPPmode(),COMMAND_SUCCESS);
				}
				else
				{
					sprintf(response,"%d,%d,Invalid Volume,,,,,,,,,,\n",getFPPmode(),COMMAND_FAILED);
				}
		}
		else if (!strcmp(CommandStr, "w"))
		{
				LogInfo(VB_SETTING, "Sending Falcon hardware config\n");
				if (!DetectFalconHardware(1))
					SendFPDConfig();
		}
		else if (!strcmp(CommandStr, "r"))
		{
				WriteBytesReceivedFile();
				sprintf(response,"true\n");
		}
		else if (!strcmp(CommandStr, "q"))
		{
			// Quit/Shutdown fppd
			ShutdownFPPD();
		}
		else if (!strcmp(CommandStr, "e"))
		{
			// Start an Effect
			s = strtok(NULL,",");
			s2 = strtok(NULL,",");
			s3 = strtok(NULL,",");
			if (s && s2)
			{
				i = StartEffect(s, atoi(s2), atoi(s3));
				if (i >= 0)
					sprintf(response,"%d,%d,Starting Effect,%d,,,,,,,,,\n",getFPPmode(),COMMAND_SUCCESS,i);
				else
					sprintf(response,"%d,%d,Invalid Effect,,,,,,,,,,\n",getFPPmode(),COMMAND_FAILED);
			}
			else
				sprintf(response,"%d,%d,Invalid Effect,,,,,,,,,,\n",getFPPmode(),COMMAND_FAILED);
		}
		else if (!strcmp(CommandStr, "t"))
		{
			// Trigger an event
			s = strtok(NULL,",");
			pluginCallbackManager.eventCallback(s, "command");
			i = TriggerEventByID(s);
			if (i >= 0)
				sprintf(response,"%d,%d,Event Triggered,%d,,,,,,,,,\n",getFPPmode(),COMMAND_SUCCESS,i);
			else
				sprintf(response,"%d,%d,Event Failed,,,,,,,,,,\n",getFPPmode(),COMMAND_FAILED);
		}
		else if (!strcmp(CommandStr, "GetTestMode"))
		{
			strcpy(response, channelTester->GetConfig().c_str());
			strcat(response, "\n");
		}
		else if (!strcmp(CommandStr, "SetTestMode"))
		{
			if (channelTester->SetupTest(std::string(s + strlen(s) + 1)))
			{
				sprintf(response, "0,%d,Test Mode Activated,,,,,,,,,\n",
					COMMAND_SUCCESS);
			}
			else
			{
				sprintf(response, "0,%d,Test Mode Deactivated,,,,,,,,,\n",
					COMMAND_SUCCESS);
			}
		}
		else if (!strcmp(CommandStr, "LogLevel"))
		{
			s = strtok(NULL,",");

			if (SetLogLevel(s)) {
				sprintf(response,"%d,%d,Log Level Updated,%d,%d,,,,,,,,,\n",
					getFPPmode(),COMMAND_SUCCESS,logLevel,logMask);
			} else {
				sprintf(response,"%d,%d,Error Updating Log Level,%d,%d,,,,,,,,,\n",
					getFPPmode(),COMMAND_FAILED,logLevel,logMask);
			}
		}
		else if (!strcmp(CommandStr, "LogMask"))
		{
			s = strtok(NULL,",");

			if ((s && SetLogMask(s)) || SetLogMask("")) {
				sprintf(response,"%d,%d,Log Mask Updated,%d,%d,,,,,,,,,\n",
					getFPPmode(),COMMAND_SUCCESS,logLevel,logMask);
			} else {
				sprintf(response,"%d,%d,Error Updating Log Mask,%d,%d,,,,,,,,,\n",
					getFPPmode(),COMMAND_FAILED,logLevel,logMask);
			}
		}
		else if (!strcmp(CommandStr, "SetSetting"))
		{
			char name[128];

			s = strtok(NULL,",");
			if (s)
			{
				strcpy(name, s);
				s = strtok(NULL,",");
				if (s)
					parseSetting(name, s);
			}
		}
		else if (!strcmp(CommandStr, "StopAllEffects"))
		{
			StopAllEffects();
			sprintf(response,"%d,%d,All Effects Stopped,,,,,,,,,,\n",getFPPmode(),COMMAND_SUCCESS);
		}
		else if (!strcmp(CommandStr, "StopEffectByName"))
		{
			s = strtok(NULL,",");
			if (strlen(s))
			{
				if (StopEffect(s))
						sprintf(response,"%d,%d,Stopping Effect,%s,,,,,,,,,\n",getFPPmode(),COMMAND_SUCCESS,s);
				else
						sprintf(response,"%d,%d,Stop Effect Failed,,,,,,,,,,\n",getFPPmode(),COMMAND_FAILED);
			}
		}
		else if (!strcmp(CommandStr, "StopEffect"))
		{
			s = strtok(NULL,",");
			i = atoi(s);
			if (StopEffect(i))
					sprintf(response,"%d,%d,Stopping Effect,%d,,,,,,,,,\n",getFPPmode(),COMMAND_SUCCESS,i);
			else
					sprintf(response,"%d,%d,Stop Effect Failed,,,,,,,,,,\n",getFPPmode(),COMMAND_FAILED);
		}
		else if (!strcmp(CommandStr, "GetRunningEffects"))
		{
			sprintf(response,"%d,%d,Running Effects",getFPPmode(),COMMAND_SUCCESS);
			GetRunningEffects(response, &response2);
		}
		else if (!strcmp(CommandStr, "ReloadChannelRemapData"))
		{
			if ((FPPstatus==FPP_STATUS_IDLE) &&
				(LoadChannelRemapData())) {
				sprintf(response,"%d,%d,Channel Remap Data Reloaded,,,,,,,,,,\n",getFPPmode(),COMMAND_SUCCESS);
			} else {
				sprintf(response,"%d,%d,Failed to reload Channel Remap Data,,,,,,,,,,\n",getFPPmode(),COMMAND_FAILED);
			}
		}
		else if (!strcmp(CommandStr, "GetFPPDUptime"))
		{
			sprintf(response,"%d,%d,FPPD Uptime,%d,,,,,,,,,\n",getFPPmode(),COMMAND_SUCCESS, time(NULL) - fppdStartTime);
		}
		else if (!strcmp(CommandStr, "StartSequence"))
		{
			s = strtok(NULL,",");
			s2 = strtok(NULL,",");
			if (s && s2)
			{
				i = atoi(s2);
				player->StartSequence(s, 0, i);
				sprintf(response,"%d,%d,Sequence Started,,,,,,,,,,,,\n",
					getFPPmode(), COMMAND_SUCCESS);
			}
			else
			{
				LogErr(VB_COMMAND, "Tried to start a sequence when a playlist or "
						"sequence is already running\n");
				sprintf(response,"%d,%d,Sequence Failed,,,,,,,,,,,,\n",
					getFPPmode(), COMMAND_FAILED);
			}
		}
		else if (!strcmp(CommandStr, "StopSequence"))
		{
			s = strtok(NULL,",");
			if (s)
			{
				player->StopSequence(s);
				sprintf(response,"%d,%d,Sequence Stopped,,,,,,,,,,,,\n",
					getFPPmode(), COMMAND_SUCCESS);
			}
			else
			{
				LogDebug(VB_COMMAND, "Invalid command: %s\n", command);
				sprintf(response,"%d,%d,Sequence Name Missing,,,,,,,,,,,,\n",
					getFPPmode(), COMMAND_FAILED);
			}
		}
		else if (!strcmp(CommandStr, "ToggleSequencePause"))
		{
			if ((player->SequencesRunning()) &&
				((FPPstatus == FPP_STATUS_IDLE) ||
				 (FPPstatus != FPP_STATUS_IDLE)))
			{
				player->ToggleSequencePause();
			}
		}
		else if (!strcmp(CommandStr, "SingleStepSequence"))
		{
			if ((player->SequencesRunning()) &&
				(player->SequencesArePaused()) &&
				((FPPstatus == FPP_STATUS_IDLE) ||
				 ((FPPstatus != FPP_STATUS_IDLE))))
			{
				player->SingleStepSequences();
			}
		}
		else if (!strcmp(CommandStr, "SingleStepSequenceBack"))
		{
			if ((player->SequencesRunning()) &&
				(player->SequencesArePaused()) &&
				((FPPstatus == FPP_STATUS_IDLE) ||
				 ((FPPstatus != FPP_STATUS_IDLE))))
			{
				player->SingleStepSequencesBack();
			}
		}
		else if (!strcmp(CommandStr, "NextPlaylistItem"))
		{
			switch (FPPstatus)
			{
				case FPP_STATUS_IDLE:
					sprintf(response,"%d,%d,No playlist running\n",getFPPmode(),COMMAND_FAILED);
					break;
				case FPP_STATUS_PLAYLIST_PLAYING:
					sprintf(response,"%d,%d,Skipping to next playlist item\n",getFPPmode(),COMMAND_SUCCESS);
					player->NextPlaylistItem();
					break;
				case FPP_STATUS_STOPPING_GRACEFULLY:
					sprintf(response,"%d,%d,Playlist is stopping gracefully\n",getFPPmode(),COMMAND_FAILED);
					break;
			}
		}
		else if (!strcmp(CommandStr, "PrevPlaylistItem"))
		{
			switch (FPPstatus)
			{
				case FPP_STATUS_IDLE:
					sprintf(response,"%d,%d,No playlist running\n",getFPPmode(),COMMAND_FAILED);
					break;
				case FPP_STATUS_PLAYLIST_PLAYING:
					sprintf(response,"%d,%d,Skipping to previous playlist item\n",getFPPmode(),COMMAND_SUCCESS);
					player->PrevPlaylistItem();
					break;
				case FPP_STATUS_STOPPING_GRACEFULLY:
					sprintf(response,"%d,%d,Playlist is stopping gracefully\n",getFPPmode(),COMMAND_FAILED);
					break;
			}
		}
		else if (!strcmp(CommandStr, "SetupExtGPIO"))
		{
			// Configure the given GPIO to the given mode
			s = strtok(NULL,",");
			s2 = strtok(NULL,",");
			if (s && s2)
			{
				
				if (!SetupExtGPIO(atoi(s), s2))
				{
					sprintf(response, "%d,%d,Configuring GPIO,%d,%s,,,,,,,,,\n",getFPPmode(),COMMAND_SUCCESS,atoi(s),s2);
				}
				else
				{
					sprintf(response, "%d,%d,Configuring GPIO,%d,%s,,,,,,,,,\n",getFPPmode(),COMMAND_FAILED,atoi(s),s2);
				}
			}
		}
		else if (!strcmp(CommandStr, "ExtGPIO"))
		{
			s = strtok(NULL,",");
			s2 = strtok(NULL,",");
			s3 = strtok(NULL,",");
			if (s && s2 && s3)
			{
				i = ExtGPIO(atoi(s), s2, atoi(s3));
				if (i >= 0) 
				{
					sprintf(response, "%d,%d,Setting GPIO,%d,%s,%d,%d,,,,,,,\n",getFPPmode(),COMMAND_SUCCESS,atoi(s),s2,atoi(s3),i);
				}
				else
				{
					sprintf(response, "%d,%d,Setting GPIO,%d,%s,%d,,,,,,,,\n",getFPPmode(),COMMAND_FAILED,atoi(s),s2,atoi(s3));
				}
			}
		}
		else
		{
			sprintf(response,"Invalid command: '%s'\n", CommandStr);
		}

		if (response2)
		{
			bytes_sent = sendto(socket_fd, response2, strlen(response2), 0,
                          (struct sockaddr *) &(client_address), sizeof(struct sockaddr_un));
			LogDebug(VB_COMMAND, "%s %s", CommandStr, response2);
			free(response2);
			response2 = NULL;
		}
		else
		{
			bytes_sent = sendto(socket_fd, response, strlen(response), 0,
                          (struct sockaddr *) &(client_address), sizeof(struct sockaddr_un));
			LogDebug(VB_COMMAND, "%s %s", CommandStr, response);
		}
  }
예제 #18
0
파일: command.c 프로젝트: ihbar/fpp
char *ProcessCommand(char *command, char *response)
{
    char *s;
    char *s2;
    char *s3;
    char *s4;
    char *response2 = NULL;
    int i;
    char NextPlaylist[128] = "No playlist scheduled.";
    char NextScheduleStartText[64] = "";
    char CommandStr[64];
    LogExcess(VB_COMMAND, "CMD: %s\n", command);
    s = strtok(command,",");
    strcpy(CommandStr, s);
    if (!strcmp(CommandStr, "s")) {
        scheduler->GetNextScheduleStartText(NextScheduleStartText);
        scheduler->GetNextPlaylistText(NextPlaylist);
        if(FPPstatus==FPP_STATUS_IDLE) {
            if (getFPPmode() == REMOTE_MODE) {
                int secsElapsed = 0;
                int secsRemaining = 0;
                char seqFilename[1024];
                char mediaFilename[1024];

                if (sequence->IsSequenceRunning()) {
                    strcpy(seqFilename, sequence->m_seqFilename);
                    secsElapsed = sequence->m_seqSecondsElapsed;
                    secsRemaining = sequence->m_seqSecondsRemaining;
                } else {
                    strcpy(seqFilename, "");
                }

                if (mediaOutput) {
                    strcpy(mediaFilename, mediaOutput->m_mediaFilename.c_str());
                    secsElapsed = mediaOutputStatus.secondsElapsed;
                    secsRemaining = mediaOutputStatus.secondsRemaining;
                } else {
                    strcpy(mediaFilename, "");
                }

                sprintf(response,"%d,%d,%d,%s,%s,%d,%d\n",
                        getFPPmode(), 0, getVolume(), seqFilename,
                        mediaFilename, secsElapsed, secsRemaining);
            } else if (sequence->IsSequenceRunning()) {
                sprintf(response,"%d,%d,%d,,,%s,,0,0,%d,%d,%s,%s,0\n",
                        getFPPmode(),
                        1,
                        getVolume(),
                        sequence->m_seqFilename,
                        sequence->m_seqSecondsElapsed,
                        sequence->m_seqSecondsRemaining,
                        NextPlaylist,
                        NextScheduleStartText);
            } else {
                sprintf(response,"%d,%d,%d,%s,%s\n",getFPPmode(),0,getVolume(),NextPlaylist,NextScheduleStartText);
            }
        } else {
            Json::Value pl = playlist->GetInfo();
            if (pl["currentEntry"].isMember("dynamic"))
                pl["currentEntry"] = pl["currentEntry"]["dynamic"];

            if ((pl["currentEntry"]["type"] == "both") ||
                (pl["currentEntry"]["type"] == "media")) {
                //printf(" %s\n", pl.toStyledString().c_str());
                sprintf(response,"%d,%d,%d,%s,%s,%s,%s,%d,%d,%d,%d,%s,%s,%d\n",
                    getFPPmode(),
                    FPPstatus,
                    getVolume(),
                    pl["name"].asString().c_str(),
                    pl["currentEntry"]["type"].asString().c_str(),
                    pl["currentEntry"]["type"].asString() == "both" ? pl["currentEntry"]["sequence"]["sequenceName"].asString().c_str() : "",
                    pl["currentEntry"]["type"].asString() == "both"
                        ? pl["currentEntry"]["media"]["mediaFilename"].asString().c_str()
                        : pl["currentEntry"]["mediaFilename"].asString().c_str() ,
//							pl["currentEntry"]["entryID"].asInt() + 1,
                    playlist->GetPosition(),
                    pl["size"].asInt(),
                    pl["currentEntry"]["type"].asString() == "both"
                        ? pl["currentEntry"]["media"]["secondsElapsed"].asInt()
                        : pl["currentEntry"]["secondsElapsed"].asInt(),
                    pl["currentEntry"]["type"].asString() == "both"
                        ? pl["currentEntry"]["media"]["secondsRemaining"].asInt()
                        : pl["currentEntry"]["secondsRemaining"].asInt(),
                    NextPlaylist,
                    NextScheduleStartText,
                    pl["repeat"].asInt());
            } else if (pl["currentEntry"]["type"] == "sequence") {
                sprintf(response,"%d,%d,%d,%s,%s,%s,%s,%d,%d,%d,%d,%s,%s,%d\n",
                    getFPPmode(),
                    FPPstatus,
                    getVolume(),
                    pl["name"].asString().c_str(),
                    pl["currentEntry"]["type"].asString().c_str(),
                    pl["currentEntry"]["sequenceName"].asString().c_str(),
                    "",
//							pl["currentEntry"]["entryID"].asInt() + 1,
                    playlist->GetPosition(),
                    pl["size"].asInt(),
                    sequence->m_seqSecondsElapsed,
                    sequence->m_seqSecondsRemaining,
                    NextPlaylist,
                    NextScheduleStartText,
                    pl["repeat"].asInt());
            } else {
                sprintf(response,"%d,%d,%d,%s,%s,%s,%s,%d,%d,%d,%d,%s,%s,%d\n",
                    getFPPmode(),
                    FPPstatus,
                    getVolume(),
                    pl["name"].asString().c_str(),
                    pl["currentEntry"]["type"].asString().c_str(),
                    "",
                    "",
//							pl["currentEntry"]["entryID"].asInt() + 1,
                    playlist->GetPosition(),
                    pl["size"].asInt(),
                    pl["currentEntry"]["type"].asString() == "pause" ? pl["currentEntry"]["duration"].asInt() - pl["currentEntry"]["remaining"].asInt() : 0,
                    pl["currentEntry"]["type"].asString() == "pause" ? pl["currentEntry"]["remaining"].asInt() : 0,
                    NextPlaylist,
                    NextScheduleStartText,
                    pl["repeat"].asInt());
            }
        }
    } else if ((!strcmp(CommandStr, "P")) || (!strcmp(CommandStr, "p"))) {
        s = strtok(NULL,",");
        s2 = strtok(NULL,",");

        int entry = 0;
        if (s2 && s2[0])
            entry = atoi(s2);

        if (s)
        {
            int repeat = strcmp(CommandStr, "p") ? 0 : 1;
            int scheduledRepeat = 0;
            std::string playlistName = scheduler->GetPlaylistThatShouldBePlaying(scheduledRepeat);

            if ((playlistName == s) && (repeat == scheduledRepeat)) {
                // Use CheckIfShouldBePlayingNow() so the scheduler knows when
                // to stop the playlist
                scheduler->CheckIfShouldBePlayingNow(1);
                sprintf(response,"%d,%d,Playlist Started,,,,,,,,,,\n",getFPPmode(),COMMAND_SUCCESS);
            } else if (playlist->Play(s, entry, repeat, 0)) {
                FPPstatus = FPP_STATUS_PLAYLIST_PLAYING;
                sprintf(response,"%d,%d,Playlist Started,,,,,,,,,,\n",getFPPmode(),COMMAND_SUCCESS);
		    } else {
                sprintf(response,"%d,%d,Error Starting Playlist,,,,,,,,,,\n",getFPPmode(),COMMAND_FAILED);
            }
        } else {
            sprintf(response,"%d,%d,Unknown Playlist,,,,,,,,,,\n",getFPPmode(),COMMAND_FAILED);
        }
    } else if ((!strcmp(CommandStr, "S")) ||
               (!strcmp(CommandStr, "StopGracefully"))) {
        if (FPPstatus==FPP_STATUS_PLAYLIST_PLAYING) {
            playlist->StopGracefully(1);
            scheduler->ReLoadCurrentScheduleInfo();
            sprintf(response,"%d,%d,Playlist Stopping Gracefully,,,,,,,,,,\n",getFPPmode(),COMMAND_SUCCESS);
        } else {
            sprintf(response,"%d,Not playing,,,,,,,,,,,\n",COMMAND_FAILED);
        }
    } else if ((!strcmp(CommandStr, "d")) ||
               (!strcmp(CommandStr, "StopNow"))) {
        if (FPPstatus==FPP_STATUS_PLAYLIST_PLAYING || FPPstatus==FPP_STATUS_STOPPING_GRACEFULLY) {
            playlist->StopNow(1);
            scheduler->ReLoadCurrentScheduleInfo();
            sprintf(response,"%d,%d,Playlist Stopping Now,,,,,,,,,,\n",getFPPmode(),COMMAND_SUCCESS);
        } else if ((FPPstatus == FPP_STATUS_IDLE) &&
                   (sequence->IsSequenceRunning())) {
            sequence->CloseSequenceFile();
            sprintf(response,"%d,%d,Sequence Stopping Now,,,,,,,,,,\n",getFPPmode(),COMMAND_SUCCESS);
        } else {
            sprintf(response,"%d,%d,Not playing,,,,,,,,,,\n",getFPPmode(),COMMAND_FAILED);
        }
    } else if (!strcmp(CommandStr, "R")) {
        scheduler->ReLoadNextScheduleInfo();
        if (FPPstatus==FPP_STATUS_IDLE) {
            scheduler->ReLoadCurrentScheduleInfo();
            scheduler->CheckIfShouldBePlayingNow();
        }
        sprintf(response,"%d,%d,Reloading Schedule,,,,,,,,,,\n",getFPPmode(),COMMAND_SUCCESS);
    } else if (!strcmp(CommandStr, "v")) {
        s = strtok(NULL,",");
        if (s) {
            setVolume(atoi(s));
            sprintf(response,"%d,%d,Setting Volume,,,,,,,,,,\n",getFPPmode(),COMMAND_SUCCESS);
        } else {
            sprintf(response,"%d,%d,Invalid Volume,,,,,,,,,,\n",getFPPmode(),COMMAND_FAILED);
        }
    } else if (!strcmp(CommandStr, "q")) {
        // Quit/Shutdown fppd
        if ((FPPstatus == FPP_STATUS_PLAYLIST_PLAYING) ||
            (FPPstatus == FPP_STATUS_STOPPING_GRACEFULLY)) {
            playlist->StopNow(1);
            sleep(2);
        }

        ShutdownFPPD();

        sleep(1);
    } else if (!strcmp(CommandStr, "e")) {
        // Start an Effect
        s = strtok(NULL,",");
        s2 = strtok(NULL,",");
        s3 = strtok(NULL,",");
        if (s && s2) {
            i = StartEffect(s, atoi(s2), atoi(s3));
            if (i >= 0)
                sprintf(response,"%d,%d,Starting Effect,%d,,,,,,,,,\n",getFPPmode(),COMMAND_SUCCESS,i);
            else
                sprintf(response,"%d,%d,Invalid Effect,,,,,,,,,,\n",getFPPmode(),COMMAND_FAILED);
        } else
            sprintf(response,"%d,%d,Invalid Effect,,,,,,,,,,\n",getFPPmode(),COMMAND_FAILED);
    } else if (!strcmp(CommandStr, "t")) {
        // Trigger an event
        s = strtok(NULL,",");
        pluginCallbackManager.eventCallback(s, "command");
        i = TriggerEventByID(s);
        if (i >= 0)
            sprintf(response,"%d,%d,Event Triggered,%d,,,,,,,,,\n",getFPPmode(),COMMAND_SUCCESS,i);
        else
            sprintf(response,"%d,%d,Event Failed,,,,,,,,,,\n",getFPPmode(),COMMAND_FAILED);
    } else if (!strcmp(CommandStr, "GetTestMode")) {
        strcpy(response, channelTester->GetConfig().c_str());
        strcat(response, "\n");
    } else if (!strcmp(CommandStr, "SetTestMode")) {
        if (channelTester->SetupTest(std::string(s + strlen(s) + 1)))
        {
            sprintf(response, "0,%d,Test Mode Activated,,,,,,,,,\n",
                COMMAND_SUCCESS);
        } else {
            sprintf(response, "0,%d,Test Mode Deactivated,,,,,,,,,\n",
                COMMAND_SUCCESS);
        }
    } else if (!strcmp(CommandStr, "LogLevel")) {
        s = strtok(NULL,",");

        if (SetLogLevel(s)) {
            sprintf(response,"%d,%d,Log Level Updated,%d,%d,,,,,,,,,\n",
                getFPPmode(),COMMAND_SUCCESS,logLevel,logMask);
        } else {
            sprintf(response,"%d,%d,Error Updating Log Level,%d,%d,,,,,,,,,\n",
                getFPPmode(),COMMAND_FAILED,logLevel,logMask);
        }
    } else if (!strcmp(CommandStr, "LogMask")) {
        s = strtok(NULL,",");

        if ((s && SetLogMask(s)) || SetLogMask("")) {
            sprintf(response,"%d,%d,Log Mask Updated,%d,%d,,,,,,,,,\n",
                getFPPmode(),COMMAND_SUCCESS,logLevel,logMask);
        } else {
            sprintf(response,"%d,%d,Error Updating Log Mask,%d,%d,,,,,,,,,\n",
                getFPPmode(),COMMAND_FAILED,logLevel,logMask);
        }
    } else if (!strcmp(CommandStr, "SetSetting")) {
        char name[128];

        s = strtok(NULL,",");
        if (s) {
            strcpy(name, s);
            s = strtok(NULL,",");
            if (s)
                parseSetting(name, s);
        }
    } else if (!strcmp(CommandStr, "StopAllEffects")) {
        StopAllEffects();
        sprintf(response,"%d,%d,All Effects Stopped,,,,,,,,,,\n",getFPPmode(),COMMAND_SUCCESS);
    } else if (!strcmp(CommandStr, "StopEffectByName")) {
        s = strtok(NULL,",");
        if (strlen(s)) {
            if (StopEffect(s))
                sprintf(response,"%d,%d,Stopping Effect,%s,,,,,,,,,\n",getFPPmode(),COMMAND_SUCCESS,s);
            else
                sprintf(response,"%d,%d,Stop Effect Failed,,,,,,,,,,\n",getFPPmode(),COMMAND_FAILED);
        }
    } else if (!strcmp(CommandStr, "StopEffect")) {
        s = strtok(NULL,",");
        i = atoi(s);
        if (StopEffect(i))
            sprintf(response,"%d,%d,Stopping Effect,%d,,,,,,,,,\n",getFPPmode(),COMMAND_SUCCESS,i);
        else
            sprintf(response,"%d,%d,Stop Effect Failed,,,,,,,,,,\n",getFPPmode(),COMMAND_FAILED);
    } else if (!strcmp(CommandStr, "GetRunningEffects")) {
        sprintf(response,"%d,%d,Running Effects",getFPPmode(),COMMAND_SUCCESS);
        GetRunningEffects(response, &response2);
    } else if (!strcmp(CommandStr, "GetFPPDUptime")) {
        sprintf(response,"%d,%d,FPPD Uptime,%ld,,,,,,,,,\n",getFPPmode(),COMMAND_SUCCESS, time(NULL) - fppdStartTime);
    } else if (!strcmp(CommandStr, "StartSequence")) {
        if ((FPPstatus == FPP_STATUS_IDLE) &&
            (!sequence->IsSequenceRunning())) {
            s = strtok(NULL,",");
            s2 = strtok(NULL,",");
            if (s && s2) {
                i = atoi(s2);
                sequence->OpenSequenceFile(s, 0, i);
            } else {
                LogDebug(VB_COMMAND, "Invalid command: %s\n", command);
            }
        } else {
            LogErr(VB_COMMAND, "Tried to start a sequence when a playlist or "
                    "sequence is already running\n");
        }
    } else if (!strcmp(CommandStr, "StopSequence")) {
        if ((FPPstatus == FPP_STATUS_IDLE) &&
            (sequence->IsSequenceRunning())) {
            sequence->CloseSequenceFile();
        } else {
            LogDebug(VB_COMMAND,
                "Tried to stop a sequence when no sequence is running\n");
        }
    } else if (!strcmp(CommandStr, "ToggleSequencePause")) {
        if ((sequence->IsSequenceRunning()) &&
            ((FPPstatus == FPP_STATUS_IDLE) ||
             ((FPPstatus != FPP_STATUS_IDLE) &&
              (playlist->GetInfo()["currentEntry"]["type"] == "sequence")))) {
            sequence->ToggleSequencePause();
        }
    } else if (!strcmp(CommandStr, "SingleStepSequence")) {
        if ((sequence->IsSequenceRunning()) &&
            (sequence->SequenceIsPaused()) &&
            ((FPPstatus == FPP_STATUS_IDLE) ||
             ((FPPstatus != FPP_STATUS_IDLE) &&
              (playlist->GetInfo()["currentEntry"]["type"] == "sequence")))) {
            sequence->SingleStepSequence();
        }
    } else if (!strcmp(CommandStr, "SingleStepSequenceBack")) {
        if ((sequence->IsSequenceRunning()) &&
            (sequence->SequenceIsPaused()) &&
            ((FPPstatus == FPP_STATUS_IDLE) ||
             ((FPPstatus != FPP_STATUS_IDLE) &&
              (playlist->GetInfo()["currentEntry"]["type"] == "sequence")))) {
            sequence->SingleStepSequenceBack();
        }
    } else if (!strcmp(CommandStr, "NextPlaylistItem")) {
        switch (FPPstatus)
        {
            case FPP_STATUS_IDLE:
                sprintf(response,"%d,%d,No playlist running\n",getFPPmode(),COMMAND_FAILED);
                break;
            case FPP_STATUS_PLAYLIST_PLAYING:
                sprintf(response,"%d,%d,Skipping to next playlist item\n",getFPPmode(),COMMAND_SUCCESS);
                playlist->NextItem();
                break;
            case FPP_STATUS_STOPPING_GRACEFULLY:
                sprintf(response,"%d,%d,Playlist is stopping gracefully\n",getFPPmode(),COMMAND_FAILED);
                break;
        }
    } else if (!strcmp(CommandStr, "PrevPlaylistItem")) {
        switch (FPPstatus) {
            case FPP_STATUS_IDLE:
                sprintf(response,"%d,%d,No playlist running\n",getFPPmode(),COMMAND_FAILED);
                break;
            case FPP_STATUS_PLAYLIST_PLAYING:
                sprintf(response,"%d,%d,Skipping to previous playlist item\n",getFPPmode(),COMMAND_SUCCESS);
                playlist->PrevItem();
                break;
            case FPP_STATUS_STOPPING_GRACEFULLY:
                sprintf(response,"%d,%d,Playlist is stopping gracefully\n",getFPPmode(),COMMAND_FAILED);
                break;
        }
    } else if (!strcmp(CommandStr, "SetupExtGPIO")) {
        // Configure the given GPIO to the given mode
        s = strtok(NULL,",");
        s2 = strtok(NULL,",");
        if (s && s2)
        {
            
            if (!SetupExtGPIO(atoi(s), s2))
            {
                sprintf(response, "%d,%d,Configuring GPIO,%d,%s,,,,,,,,,\n",getFPPmode(),COMMAND_SUCCESS,atoi(s),s2);
            } else {
                sprintf(response, "%d,%d,Configuring GPIO,%d,%s,,,,,,,,,\n",getFPPmode(),COMMAND_FAILED,atoi(s),s2);
            }
        }
    } else if (!strcmp(CommandStr, "ExtGPIO")) {
        s = strtok(NULL,",");
        s2 = strtok(NULL,",");
        s3 = strtok(NULL,",");
        if (s && s2 && s3)
        {
            i = ExtGPIO(atoi(s), s2, atoi(s3));
            if (i >= 0)
            {
                sprintf(response, "%d,%d,Setting GPIO,%d,%s,%d,%d,,,,,,,\n",getFPPmode(),COMMAND_SUCCESS,atoi(s),s2,atoi(s3),i);
            } else {
                sprintf(response, "%d,%d,Setting GPIO,%d,%s,%d,,,,,,,,\n",getFPPmode(),COMMAND_FAILED,atoi(s),s2,atoi(s3));
            }
        }
    } else {
        sprintf(response,"Invalid command: '%s'\n", CommandStr);
    }

    return response2;
}
void VolumeHandlePropertyWidget::updateFromProperty() {
    VolumeHandle* handle = getVolume();
    if (handle) {
        dimensionLabel_->show();
        pathLabel_->show();
        spacingLabel_->show();
        memSizeLabel_->show();
        previewLabel_->show();
        dimensionLabelCaption_->show();
        spacingLabelCaption_->show();
        memSizeLabelCaption_->show();

        std::string name = VolumeViewHelper::getStrippedVolumeName(handle);
        std::string path = VolumeViewHelper::getVolumePath(handle);
        if(name.size() > 30) {
            volumeNameLabel_->setToolTip(QString::fromStdString(name));
            int end = static_cast<int>(name.size());
            std::string startString;
            std::string endString;
            for(size_t i = 0; i < 14; i++){
                 startString += name.at(i);
                 endString += name.at(end-14+i);
            }
            name = startString+"..."+endString;
        }
        if (path.size() > 30) {
            pathLabel_->setToolTip(QString::fromStdString(path));
            int end = static_cast<int>(path.size());
            std::string startString;
            std::string endString;
            for(size_t i = 0; i < 14; i++){
                 startString += path.at(i);
                 endString += path.at(end-14+i);
            }
            path = startString+"..."+endString;
        }

        volumeNameLabel_->setText(QString::fromStdString(" " + name + VolumeViewHelper::getVolumeTimestep(handle) + " ("+ VolumeViewHelper::getVolumeType(static_cast<VolumeHandleBase*>(handle)->getRepresentation<Volume>())+") "));
        pathLabel_->setText(QString::fromStdString(" "+path));
        dimensionLabel_->setText(QString::fromStdString(VolumeViewHelper::getVolumeDimension(handle)));
        spacingLabel_->setText(QString::fromStdString(VolumeViewHelper::getVolumeSpacing(handle)));
        memSizeLabel_->setText(QString::fromStdString(VolumeViewHelper::getVolumeMemorySize(static_cast<VolumeHandleBase*>(handle)->getRepresentation<Volume>())));
        previewLabel_->setPixmap(VolumeViewHelper::generateBorderedPreview(handle, 70, 0));

        // adjust selected index of volume selector box to currently assigned volume
        volumeSelectorBox_->setCurrentIndex(0);
        if (volumeContainer_) {
            tgtAssert(volumeContainer_->size()+1 == static_cast<size_t>(volumeSelectorBox_->count()),
                "Sizes of volume container and volume selector box do not match");
            for (size_t i=0; i < volumeContainer_->size(); ++i) {
                if (handle == volumeContainer_->at(i)) {
                    volumeSelectorBox_->setCurrentIndex(static_cast<int>(i+1));
                    break;
                }

            }
        }

    }
    else {
        volumeNameLabel_->setText(tr(" no volume"));
        volumeNameLabel_->adjustSize();

        pathLabel_->hide();
        previewLabel_->setPixmap(QPixmap());
        dimensionLabel_->hide();
        spacingLabel_->hide();
        memSizeLabel_->hide();
        previewLabel_->hide();
        dimensionLabelCaption_->hide();
        spacingLabelCaption_->hide();
        memSizeLabelCaption_->hide();
    }
}
예제 #20
0
bool Menu::handleEvent(StartMenuAction action, Common::EventType type) {
	bool clicked = (type == Common::EVENT_LBUTTONUP);

	switch(action) {
	default:
		hideOverlays();
		break;

	//////////////////////////////////////////////////////////////////////////
	case kMenuCredits:
		if (hasTimeDelta()) {
			hideOverlays();
			break;
		}

		if (clicked) {
			showFrame(kOverlayEggButtons, kButtonCreditsPushed, true);
			showFrame(kOverlayTooltip, -1, true);

			getSound()->playSound(kEntityPlayer, "LIB046");

			hideOverlays();

			_isShowingCredits = true;
			_creditsSequenceIndex = 0;

			showFrame(kOverlayCredits, 0, true);
		} else {
			// TODO check flags ?

			showFrame(kOverlayEggButtons, kButtonCredits, true);
			showFrame(kOverlayTooltip, kTooltipCredits, true);
		}
		break;

	//////////////////////////////////////////////////////////////////////////
	case kMenuQuitGame:
		showFrame(kOverlayTooltip, kTooltipQuit, true);

		if (clicked) {
			showFrame(kOverlayButtons, kButtonQuitPushed, true);

			getSound()->clearStatus();
			getSound()->updateQueue();
			getSound()->playSound(kEntityPlayer, "LIB046");

			// FIXME uncomment when sound queue is properly implemented
			/*while (getSound()->isBuffered("LIB046"))
				getSound()->updateQueue();*/

			getFlags()->shouldRedraw = false;

			Engine::quitGame();

			return false;
		} else {
			showFrame(kOverlayButtons, kButtonQuit, true);
		}
		break;

	//////////////////////////////////////////////////////////////////////////
	case kMenuCase4:
		if (clicked)
			_index = 0;
		// fall down to kMenuContinue

	//////////////////////////////////////////////////////////////////////////
	case kMenuContinue: {
		if (hasTimeDelta()) {
			hideOverlays();
			break;
		}

		// Determine the proper CD archive
		ArchiveIndex cd = kArchiveCd1;
		if (getProgress().chapter > kChapter1)
			cd = (getProgress().chapter > kChapter3) ? kArchiveCd3 : kArchiveCd2;

		// Show tooltips & buttons to start a game, continue a game or load the proper cd
		if (ResourceManager::isArchivePresent(cd)) {
			if (_isGameStarted) {
				showFrame(kOverlayEggButtons, kButtonContinue, true);

				if (_lastIndex == _index) {
					showFrame(kOverlayTooltip, getSaveLoad()->isGameFinished(_index, _lastIndex) ? kTooltipViewGameEnding : kTooltipContinueGame, true);
				} else {
					showFrame(kOverlayTooltip, kTooltipContinueRewoundGame, true);
				}

			} else {
				showFrame(kOverlayEggButtons, kButtonShield, true);
				showFrame(kOverlayTooltip, kTooltipPlayNewGame, true);
			}
		} else {
			showFrame(kOverlayEggButtons, -1, true);
			showFrame(kOverlayTooltip, cd - 1, true);
		}

		if (!clicked)
			break;

		// Try loading the archive file
		if (!_engine->getResourceManager()->loadArchive(cd))
			break;

		// Load the train data file and setup game
		getScenes()->loadSceneDataFile(cd);
		showFrame(kOverlayTooltip, -1, true);
		getSound()->playSound(kEntityPlayer, "LIB046");

		// Setup new game
		getSavePoints()->reset();
		setLogicEventHandlers();

		if (_index) {
			getSound()->processEntry(SoundManager::kSoundType11);
		} else {
			if (!getFlags()->mouseRightClick) {
				getScenes()->loadScene((SceneIndex)(5 * _gameId + 3));

				if (!getFlags()->mouseRightClick) {
					getScenes()->loadScene((SceneIndex)(5 * _gameId + 4));

					if (!getFlags()->mouseRightClick) {
						getScenes()->loadScene((SceneIndex)(5 * _gameId + 5));

						if (!getFlags()->mouseRightClick) {
							getSound()->processEntry(SoundManager::kSoundType11);

							// Show intro
							Animation animation;
							if (animation.load(getArchive("1601.nis")))
								animation.play();

							getEvent(kEventIntro) = 1;
						}
					}
				}
			}

			if (!getEvent(kEventIntro))	{
				getEvent(kEventIntro) = 1;

				getSound()->processEntry(SoundManager::kSoundType11);
			}
		}

		// Setup game
		getFlags()->isGameRunning = true;
		startGame();

		if (!_isShowingMenu)
			getInventory()->show();

		return false;
	}

	//////////////////////////////////////////////////////////////////////////
	case kMenuSwitchSaveGame:
		if (hasTimeDelta()) {
			hideOverlays();
			break;
		}

		if (clicked) {
			showFrame(kOverlayAcorn, 1, true);
			showFrame(kOverlayTooltip, -1, true);
			getSound()->playSound(kEntityPlayer, "LIB047");

			// Setup new menu screen
			switchGame();
			setup();

			// Set fight state to 0
			getFight()->resetState();

			return true;
		}

		// TODO Check for flag

		showFrame(kOverlayAcorn, 0, true);

		if (_isGameStarted) {
			showFrame(kOverlayTooltip, kTooltipSwitchBlueGame, true);
			break;
		}

		if (_gameId == kGameGold) {
			showFrame(kOverlayTooltip, kTooltipSwitchBlueGame, true);
			break;
		}

		if (!SaveLoad::isSavegameValid(getNextGameId())) {
			showFrame(kOverlayTooltip, kTooltipStartAnotherGame, true);
			break;
		}

		// Stupid tooltips ids are not in order, so we can't just increment them...
		switch(_gameId) {
		default:
			break;

		case kGameBlue:
			showFrame(kOverlayTooltip, kTooltipSwitchRedGame, true);
			break;

		case kGameRed:
			showFrame(kOverlayTooltip, kTooltipSwitchGreenGame, true);
			break;

		case kGameGreen:
			showFrame(kOverlayTooltip, kTooltipSwitchPurpleGame, true);
			break;

		case kGamePurple:
			showFrame(kOverlayTooltip, kTooltipSwitchTealGame, true);
			break;

		case kGameTeal:
			showFrame(kOverlayTooltip, kTooltipSwitchGoldGame, true);
			break;
		}
		break;

	//////////////////////////////////////////////////////////////////////////
	case kMenuRewindGame:
		if (!_index || _currentTime < _time) {
			hideOverlays();
			break;
		}

		if (clicked) {
			if (hasTimeDelta())
				_handleTimeDelta = false;

			showFrame(kOverlayEggButtons, kButtonRewindPushed, true);
			showFrame(kOverlayTooltip, -1, true);

			getSound()->playSound(kEntityPlayer, "LIB046");

			rewindTime();

			_handleTimeDelta = false;
		} else {
			showFrame(kOverlayEggButtons, kButtonRewind, true);
			showFrame(kOverlayTooltip, kTooltipRewind, true);
		}
		break;

	//////////////////////////////////////////////////////////////////////////
	case kMenuForwardGame:
		if (_lastIndex <= _index || _currentTime > _time) {
			hideOverlays();
			break;
		}

		if (clicked) {
			if (hasTimeDelta())
				_handleTimeDelta = false;

			showFrame(kOverlayEggButtons, kButtonForwardPushed, true);
			showFrame(kOverlayTooltip, -1, true);

			getSound()->playSound(kEntityPlayer, "LIB046");

			forwardTime();

			_handleTimeDelta = false;
		} else {
			showFrame(kOverlayEggButtons, kButtonForward, true);
			showFrame(kOverlayTooltip, kTooltipFastForward, true);
		}
		break;

	//////////////////////////////////////////////////////////////////////////
	case kMenuParis:
		moveToCity(kParis, clicked);
		break;

	//////////////////////////////////////////////////////////////////////////
	case kMenuStrasBourg:
		moveToCity(kStrasbourg, clicked);
		break;

	//////////////////////////////////////////////////////////////////////////
	case kMenuMunich:
		moveToCity(kMunich, clicked);
		break;

	//////////////////////////////////////////////////////////////////////////
	case kMenuVienna:
		moveToCity(kVienna, clicked);
		break;

	//////////////////////////////////////////////////////////////////////////
	case kMenuBudapest:
		moveToCity(kBudapest, clicked);
		break;

	//////////////////////////////////////////////////////////////////////////
	case kMenuBelgrade:
		moveToCity(kBelgrade, clicked);
		break;

	//////////////////////////////////////////////////////////////////////////
	case kMenuConstantinople:
		moveToCity(kConstantinople, clicked);
		break;

	//////////////////////////////////////////////////////////////////////////
	case kMenuDecreaseVolume:
		if (hasTimeDelta()) {
			hideOverlays();
			break;
		}

		// Cannot decrease volume further
		if (getVolume() == 0) {
			showFrame(kOverlayButtons, kButtonVolume, true);
			showFrame(kOverlayTooltip, -1, true);
			break;
		}

		showFrame(kOverlayTooltip, kTooltipVolumeDown, true);

		// Show highlight on button & adjust volume if needed
		if (clicked) {
			showFrame(kOverlayButtons, kButtonVolumeDownPushed, true);
			getSound()->playSound(kEntityPlayer, "LIB046");
			setVolume(getVolume() - 1);

			getSaveLoad()->saveVolumeBrightness();

			uint32 nextFrameCount = getFrameCount() + 15;
			while (nextFrameCount > getFrameCount()) {
				_engine->pollEvents();

				getSound()->updateQueue();
			}
		} else {
			showFrame(kOverlayButtons, kButtonVolumeDown, true);
		}
		break;

	//////////////////////////////////////////////////////////////////////////
	case kMenuIncreaseVolume:
		if (hasTimeDelta()) {
			hideOverlays();
			break;
		}

		// Cannot increase volume further
		if (getVolume() >= 7) {
			showFrame(kOverlayButtons, kButtonVolume, true);
			showFrame(kOverlayTooltip, -1, true);
			break;
		}

		showFrame(kOverlayTooltip, kTooltipVolumeUp, true);

		// Show highlight on button & adjust volume if needed
		if (clicked) {
			showFrame(kOverlayButtons, kButtonVolumeUpPushed, true);
			getSound()->playSound(kEntityPlayer, "LIB046");
			setVolume(getVolume() + 1);

			getSaveLoad()->saveVolumeBrightness();

			uint32 nextFrameCount = getFrameCount() + 15;
			while (nextFrameCount > getFrameCount()) {
				_engine->pollEvents();

				getSound()->updateQueue();
			}
		} else {
			showFrame(kOverlayButtons, kButtonVolumeUp, true);
		}
		break;

	//////////////////////////////////////////////////////////////////////////
	case kMenuDecreaseBrightness:
		if (hasTimeDelta()) {
			hideOverlays();
			break;
		}

		// Cannot increase brightness further
		if (getBrightness() == 0) {
			showFrame(kOverlayButtons, kButtonBrightness, true);
			showFrame(kOverlayTooltip, -1, true);
			break;
		}

		showFrame(kOverlayTooltip, kTooltipBrightnessDown, true);

		// Show highlight on button & adjust brightness if needed
		if (clicked) {
			showFrame(kOverlayButtons, kButtonBrightnessDownPushed, true);
			getSound()->playSound(kEntityPlayer, "LIB046");
			setBrightness(getBrightness() - 1);

			getSaveLoad()->saveVolumeBrightness();

			// Reshow the background and frames (they will pick up the new brightness through the GraphicsManager)
			_engine->getGraphicsManager()->draw(getScenes()->get((SceneIndex)(_isGameStarted ? _gameId * 5 + 1 : _gameId * 5 + 2)), GraphicsManager::kBackgroundC, true);
			showFrame(kOverlayTooltip, kTooltipBrightnessDown, false);
			showFrame(kOverlayButtons, kButtonBrightnessDownPushed, false);
		} else {
			showFrame(kOverlayButtons, kButtonBrightnessDown, true);
		}
		break;

	//////////////////////////////////////////////////////////////////////////
	case kMenuIncreaseBrightness:
		if (hasTimeDelta()) {
			hideOverlays();
			break;
		}

		// Cannot increase brightness further
		if (getBrightness() >= 6) {
			showFrame(kOverlayButtons, kButtonBrightness, true);
			showFrame(kOverlayTooltip, -1, true);
			break;
		}

		showFrame(kOverlayTooltip, kTooltipBrightnessUp, true);

		// Show highlight on button & adjust brightness if needed
		if (clicked) {
			showFrame(kOverlayButtons, kButtonBrightnessUpPushed, true);
			getSound()->playSound(kEntityPlayer, "LIB046");
			setBrightness(getBrightness() + 1);

			getSaveLoad()->saveVolumeBrightness();

			// Reshow the background and frames (they will pick up the new brightness through the GraphicsManager)
			_engine->getGraphicsManager()->draw(getScenes()->get((SceneIndex)(_isGameStarted ? _gameId * 5 + 1 : _gameId * 5 + 2)), GraphicsManager::kBackgroundC, true);
			showFrame(kOverlayTooltip, kTooltipBrightnessUp, false);
			showFrame(kOverlayButtons, kButtonBrightnessUpPushed, false);
		} else {
			showFrame(kOverlayButtons, kButtonBrightnessUp, true);
		}
		break;
	}

	return true;
}
예제 #21
0
/* Will validate the data retrieved from the configuration file */
int init(void) {
    int status;
    config_setting_t *conf_setting = NULL;
    const char *conf_value = NULL;
    
    /* Now the configuration file is read, we don't need to know the location
     * of the application anymore. We'll change working directory to root */
    if(chdir("/") < 0) {
        syslog(LOG_ERR, "Unable to change working directory to root: %s", strerror(errno));
        return EXIT_FAILURE;
    }
    
    syslog(LOG_INFO, "Checking presence and validity of required variables:");
    
    validateConfigBool(&config, "sync_2way", &common_data.sync_2way, 0);
    
    validateConfigBool(&config, "diff_commands", &common_data.diff_commands, 0);
    
    common_data.send_query = config_lookup(&config, "query") ? 1:0;
    if(common_data.send_query && ((conf_setting = config_lookup(&config, "query.trigger")) == NULL || 
    config_setting_is_array(conf_setting) == CONFIG_FALSE ||  (common_data.statusQueryLength = 
    config_setting_length(conf_setting)) == 0)) {
        syslog(LOG_ERR, "[ERROR] Setting is not present or not formatted as array: query.trigger");
        return EXIT_FAILURE;
    }
    if(common_data.send_query && validateConfigInt(&config, "query.interval", 
    &common_data.statusQueryInterval, -1, 0, 255, -1) == EXIT_FAILURE)
        return EXIT_FAILURE;
    
    /* Set volume (curve) functions */
    conf_value = NULL;
    config_lookup_string(&config, "volume.curve", &conf_value);
    if(!(common_data.volume = getVolume(&conf_value))) {
        syslog(LOG_ERR, "[Error] Volume curve is not recognised: %s", conf_value);
        return EXIT_FAILURE;
    }
    else {
        syslog(LOG_INFO, "[OK] volume.curve: %s", conf_value);
    }
    /* initialise volume variables */
    if(common_data.volume->init() == EXIT_FAILURE)
        return EXIT_FAILURE;
    
    /* Set and initialise process type */
    conf_value = NULL;
    config_lookup_string(&config, "data_type", &conf_value);
    if(!(common_data.process = getProcessMethod(&conf_value))) {
        syslog(LOG_ERR, "[Error] Setting 'data_type' is not recognised: %s", conf_value);
        return EXIT_FAILURE;
    }
    else {
        syslog(LOG_INFO, "[OK] data_type: %s", conf_value);
    }
    if(common_data.process->init() == EXIT_FAILURE)
        return EXIT_FAILURE;
    
    /* Set and initialise communication interface */
    conf_value = NULL;
    config_lookup_string(&config, "interface", &conf_value);
    if(!(common_data.interface = getInterface(&conf_value))) {
        syslog(LOG_ERR, "[Error] Setting 'interface' is not recognised: %s", conf_value);
        return EXIT_FAILURE;
    }
    else {
        syslog(LOG_INFO, "[OK] interface: %s", conf_value);
    }
    if(common_data.interface->init() == EXIT_FAILURE)
        return EXIT_FAILURE;
        
    /* initialise mixer device */
    if(initMixer() == EXIT_FAILURE)
        return EXIT_FAILURE;

    /* init multipliers */
    common_data.volume->regenerateMultipliers();

#ifndef DISABLE_MSQ
    /* initialise message queue */
    if(initMsQ() == EXIT_FAILURE)
        return EXIT_FAILURE;
#endif
    
    if((status = pthread_mutex_init(&lockConfig, NULL)) != 0) {
        syslog(LOG_ERR, "Failed to create config mutex: %i", status);
        return EXIT_FAILURE;
    }
    
    return EXIT_SUCCESS;
} /* end init */
예제 #22
0
float sfSoundStream_getVolume(const sfSoundStream* soundStream)
{
    CSFML_CALL_RETURN(soundStream, getVolume(), 0.f);
}
예제 #23
0
	void PCPolyhedron::addToModel(const PCPtr& nuCloud)
	{
		PCModelObject::addToModel(nuCloud);

		/// 1 - Detectar caras de la nueva nube
		/// 2 - Descartar caras que no pertenecen a la caja (caras de la mano)
		/// 3 - Matchear caras de la nube anterior con las nuevas caras
		/// 4 - Estimar caras ocultas (?)
		
		PCPtr trimmedCloud = getHalo(this->getvMin(),this->getvMax(),0.05,nuCloud);
		
		saveCloud("nucloud.pcd",*nuCloud);
		saveCloud("trimmed.pcd",*trimmedCloud);

		pcPolygonsMutex.lock();
		vector<PCPolygonPtr> prevPcPolygons = pcpolygons;

		//Detecto nuevas caras
		vector<PCPolygonPtr> nuevos = detectPolygons(trimmedCloud,Constants::OBJECT_PLANE_TOLERANCE(),Constants::CLOUD_VOXEL_SIZE * 2,false); 
		
		//Matching de las caras detectadas con las anteriores
		nuevos = mergePolygons(nuevos);

		//Estimación de caras no visibles
		bool estimationOK;
		vector<PCPolygonPtr> estimated = estimateHiddenPolygons(nuevos,estimationOK);

		bool valid = true;
		if(estimationOK)
		{
			for(int i = 0; i < nuevos.size(); i++)
				nuevos.at(i)->setEstimated(false);
			//Actualizo los nuevos polygons si no hubo errores
			nuevos.insert(nuevos.end(),estimated.begin(),estimated.end());
			pcpolygons = nuevos;

			//Unifico vertices
			unifyVertexs();

			isvalid = validate();
		}

		//Chequeo volumenes
		if(IsFeatureActive(FEATURE_INVALIDATE_OBJECT_BY_VOLUME))
		{
			float inVol = computeVolume(trimmedCloud);

			if(getVolume() < inVol * Constants::OBJECT_VOLUME_TOLERANCE)
			{
				cout << "[   INVALID VOLUME    ]" << endl;
				cout << "need: " << inVol * 0.6 << "  --- has: " << getVolume() << endl;
				isvalid = false;
			}
		}
		
		if(estimationOK && isvalid)
		{
			polygonsCache.clear();
			for (vector<PCPolygonPtr>::iterator p = pcpolygons.begin(); p != pcpolygons.end(); ++p)
			{
				polygonsCache.push_back((*p)->getPolygonModelObject());
			}

		}
		else
		{
			pcpolygons = prevPcPolygons;

			//Si hay errores en la estimación, rollback de los pcpolygons mergeados
			for(int i = 0; i < pcpolygons.size(); i++)
				pcpolygons.at(i)->rollBackMatching();

			if(!isvalid)
			{
				//Necesito unificar los vertices despues del rollback
				unifyVertexs();
			}
			isvalid = false;
		}
		
		//Seteo nueva nube
		PCPtr finalCloud (new PC());
		for(int i = 0; i < pcpolygons.size(); i ++)
		{
			*finalCloud += *pcpolygons.at(i)->getCloud();
			saveCloud("pol" + ofToString(pcpolygons.at(i)->getPolygonModelObject()->getName()) + ".pcd", *pcpolygons.at(i)->getCloud());
		}
		saveCloud("finalCloud" + ofToString(getId()) + ".pcd", *finalCloud);

		setCloud(finalCloud);
		pcPolygonsMutex.unlock();

	}
  // update boundaries (pretty inefficient).
  void updateExtendedQDPBorders(const int dim[4], QudaPrecision precision, void** const qdp_field)
  {

    const int matrix_size = 18*getRealSize(precision);

    int extended_dim[4];
    for(int dir=0; dir<4; ++dir) extended_dim[dir] = dim[dir]+4;

    const int extended_volume = getVolume(extended_dim);


    const int half_dim0 = extended_dim[0]/2;
    const int half_extended_volume = extended_volume/2;

    for(int i=0; i<extended_volume; ++i){
      int site_id = i;
      int odd_bit = 0;

      if(i >= half_extended_volume){
        site_id -= half_extended_volume;
        odd_bit  = 1;
      }

      int za     = site_id/half_dim0;
      int x1h    = site_id - za*half_dim0;
      int zb     = za/extended_dim[1];
      int x2     = za - zb*extended_dim[1];
      int x4     = zb/extended_dim[2];
      int x3     = zb - x4*extended_dim[2];
      int x1odd  = (x2 + x3 + x4 + odd_bit) & 1;
      int x1     = 2*x1h + x1odd;


      int y1, y2, y3, y4;
      int y1h = x1h;
      y1 = x1;
      y2 = x2; 
      y3 = x3; 
      y4 = x4;
      bool boundary = false;
      if(x1 < 2 || x1 > 1+dim[0]  ){
        y1 = ((2 + ( (x1 - 2 + dim[0]) % dim[0])));
        y1h = y1 >> 1;
        boundary = true;
      } 

      if(x2 < 2 || x2 > 1+dim[1] ){
        y2 = 2 + ( (x2 - 2 + dim[1]) % dim[1]);
        boundary = true;
      }

      if(x3 < 2 || x3 > 1+dim[2] ){
        y3 = 2 + ( (x3 - 2 + dim[2]) % dim[2]);
        boundary = true;
      }

      if(x4 < 2 || x4 > 1+dim[3] ){
        y4 = 2 + ( (x4 - 2 + dim[3]) % dim[3]);
        boundary = true;
      }


      if(boundary){
        int interior_index = (  y4*extended_dim[2]*extended_dim[1]*extended_dim[0]/2 
            + y3*extended_dim[1]*extended_dim[0]/2 
            + y2*extended_dim[0]/2
            + y1h 
            + odd_bit*half_extended_volume );



        for(int dir=0; dir<4; ++dir){
          char* field_ptr = (char*)qdp_field[dir];
          memcpy(field_ptr + i*matrix_size, field_ptr + interior_index*matrix_size, matrix_size);
        }
      } // if(boundary)
    } // loop over the extended volume
예제 #25
0
// get output gain, 0.0 <= { left, right } <= 1.0
// 
static void sound_Volume(double *left, double *right)
{
  getVolume(0, left, right);
}
int ACubiquityOctreeNode::processOctreeNode(const Cubiquity::OctreeNode& octreeNode, int availableNodeSyncs)
{
	int nodeSyncsPerformed = 0;

	if (availableNodeSyncs <= 0)
	{
		return nodeSyncsPerformed;
	}

	if (octreeNode.nodeOrChildrenLastChanged() > nodeAndChildrenLastSynced)
	{
		if (octreeNode.propertiesLastChanged() > propertiesLastSynced)
		{
			height = octreeNode.height();
			renderThisNode = octreeNode.renderThisNode();

			mesh->SetVisibility(renderThisNode); //Hide the mesh as needed

			propertiesLastSynced = Cubiquity::currentTime();
		}

		if (octreeNode.meshLastChanged() > meshLastSynced)
		{
			if (octreeNode.hasMesh())
			{
				//Reset all the mesh data and repopulate it
				mesh->ClearMeshTriangles();
				mesh->SetGeneratedMeshTriangles(octreeNode);
			}
			else
			{
				mesh->ClearMeshTriangles();
			}

			meshLastSynced = Cubiquity::currentTime();

			availableNodeSyncs--;
			nodeSyncsPerformed++;
		}

		if (octreeNode.structureLastChanged() > structureLastSynced)
		{
			for (uint32_t z = 0; z < 2; z++)
			{
				for (uint32_t y = 0; y < 2; y++)
				{
					for (uint32_t x = 0; x < 2; x++)
					{
						ACubiquityOctreeNode* const childActor = children[x][y][z];

						if (octreeNode.hasChildNode({ x, y, z }))
						{
							if (!childActor) //If we don't have a child actor but there is a child node ... create it
							{
								const auto& childNode = octreeNode.childNode({ x, y, z });

								const FVector childNodeVolumePosition = FVector(childNode.position().x, childNode.position().y, childNode.position().z) - FVector(octreeNode.position().x, octreeNode.position().y, octreeNode.position().z);
								
								FActorSpawnParameters spawnParameters;
								spawnParameters.Owner = this;
								ACubiquityOctreeNode* childNodeActor = GetWorld()->SpawnActor<ACubiquityOctreeNode>(childNodeVolumePosition, FRotator::ZeroRotator, spawnParameters);
								childNodeActor->initialiseOctreeNode(childNode, getVolume()->Material);

								children[x][y][z] = childNodeActor;
							}
						}
						else
						{
							if (childActor) //If we have a child actor but there is no child node ... delete it
							{
								children[x][y][z]->Destroy();
								children[x][y][z] = nullptr;
							}
						}
					}
				}
			}

			structureLastSynced = Cubiquity::currentTime();
		}

		for (uint32_t z = 0; z < 2; z++)
		{
			for (uint32_t y = 0; y < 2; y++)
			{
				for (uint32_t x = 0; x < 2; x++)
				{
					if (octreeNode.hasChildNode({ x, y, z }))
					{
						// Recursivly call the octree traversal
						children[x][y][z]->processOctreeNode(octreeNode.childNode({ x, y, z }), availableNodeSyncs);
					}
				}
			}
		}

		nodeAndChildrenLastSynced = Cubiquity::currentTime();
		
	}

	return nodeSyncsPerformed;
}
void XAudio2SubmixVoiceProxy::GetVolume(float * pVolume)
{
	*pVolume = getVolume();
}
예제 #28
0
파일: pgm.C 프로젝트: brog2610/quinoa
void publish_data_netfem(int i,  myGlobals g) {
  MPI_Barrier(MPI_COMM_WORLD);
  if (1) { //Publish data to the net
    int mesh=FEM_Mesh_default_read(); // Tell framework we are reading data from the mesh
    int rank = FEM_My_partition();
    g.nnodes=FEM_Mesh_get_length(mesh,FEM_NODE); // Get number of nodes
    g.coord=new vector3d[g.nnodes];
    int count = 0;
    vector3d *coord = new vector3d[g.nnodes];
    int *maptovalid = new int[g.nnodes];
    double *nodeid = new double[g.nnodes];
    // Get node positions
    FEM_Mesh_data(mesh, FEM_NODE, FEM_DATA+0, (double*)g.coord, 0, g.nnodes, FEM_DOUBLE, 3);
    for(int j=0; j<g.nnodes; j++) {
      if(FEM_is_valid(mesh,FEM_NODE+0,j)) {
	coord[count].x = g.coord[j].x;
	coord[count].y = g.coord[j].y;
	coord[count].z = g.coord[j].z;
	maptovalid[j] = count;
	nodeid[count] = j;
	count++;
      }
    }
    NetFEM n=NetFEM_Begin(rank,i,3,NetFEM_WRITE);
    NetFEM_Nodes(n,count,(double *)coord,"Position (m)");
    //NetFEM_Nodes(n,g.nnodes,(double *)g.coord,"Position (m)");
    NetFEM_Scalar(n,nodeid,1,"Node ID");

    // Get element data
    g.nelems=FEM_Mesh_get_length(mesh,FEM_ELEM+0); // Get number of elements
    g.conn=new connRec[g.nelems];
    connRec *conn = new connRec[g.nelems];
    double *elid = new double[g.nelems];
    count = 0;
    // Get connectivity for elements
    FEM_Mesh_data(mesh, FEM_ELEM+0, FEM_CONN, (int *)g.conn, 0, g.nelems, FEM_INDEX_0, 4);
    double totalVolume = 0.0;
    for(int j=0; j<g.nelems; j++) {
      if(FEM_is_valid(mesh,FEM_ELEM+0,j)) {
	conn[count][0] = maptovalid[g.conn[j][0]];
	conn[count][1] = maptovalid[g.conn[j][1]];
	conn[count][2] = maptovalid[g.conn[j][2]];
	conn[count][3] = maptovalid[g.conn[j][3]];
	elid[count] = j;
	totalVolume += getVolume(coord[conn[count][0]],coord[conn[count][1]],coord[conn[count][2]],coord[conn[count][3]]);
	if(totalVolume != totalVolume) {
	  CkPrintf("NAN\n");
	}
	count++;
      }
    }
    NetFEM_Elements(n,count,4,(int *)conn,"Tets");
    //NetFEM_Elements(n,g.nelems,4,(int *)g.conn,"Tets");
    NetFEM_Scalar(n,elid,1,"Element ID");
    NetFEM_End(n);

    double finalVolume;
    CkPrintf("Chunk[%d]: local volume: %.12f\n",rank,totalVolume);
    MPI_Reduce((void*)&totalVolume,(void*)&finalVolume,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD);
    if(rank == 0) CkPrintf("Chunk[%d]: total volume: %.12f\n",rank,finalVolume);

    delete [] g.coord;
    delete [] g.conn;
    delete [] coord;
    delete [] conn;
    delete [] maptovalid;
    delete [] nodeid;
    delete [] elid;
  }
}
예제 #29
0
void SoundScape::update(SubLevel* subLevel_p){
	
//////////////////////////////////////////////////////////
// /player ska bara hämtas en gång och får inte vara en weak pointer så därför görs den om till en shared pointer
//////////////////////////////////////////////////////////
	if (mBoolEntity == false){
		auto player_sp = subLevel_p->getLevel()->getPlayer();
		mPlayer_wp = player_sp;
		if (mSoundType == "narrator")
			mHasNarratorPlayed = false;
		else
			mHasNarratorPlayed = true;

		if(mSoundName == "1002.ogg") {
			int a = 4;
		}

		subLevel_p->getLevel()->registerSound(mSound, (mSoundType == "narrator" ? LevelState::NARRATOR : mSoundType == "sound" ? LevelState::SOUND : LevelState::MUSIC));

		if (getEnabled() == true && mSoundType != "narrator"){
			mSound->play();
		}
		mBoolEntity = true;
	}
//////////////////////////////////////////////////////////////////
// /när ljudet/låten stoppas så ska det inte längre vara aktiverat så att man kan aktivera de igen
//////////////////////////////////////////////////////////////////
	if (mEnabledLastFrame && mSound->getStatus() == sf::Sound::Stopped && mHasNarratorPlayed){
		setEnabled(false);
	}
	auto enabledThisFrame = getEnabled();
	
//////////////////////////////////////////////////////////////////////
// /för att ett ljud/låt ska börja att spela så behöver det gå från att inte vara aktiverad till att vara det
//////////////////////////////////////////////////////////////////////
	if (enabledThisFrame == true && mEnabledLastFrame == false){
		if (mSoundType == "narrator"){
			//mSpot = subLevel_p->getLevel()->requestNarratorSpot();

						//try to find subtitles to narrators
			
			auto sss = SoundScapeSpecs::get();
			auto it = sss.mNarratorSoundToText.find(mSoundName);

			//empty string
			auto subs = std::string();
			if(it != sss.mNarratorSoundToText.end()) {
				//found match
				subs = it->second;
			}
			subLevel_p->getLevel()->queueNarrator(this, mSound, subs);
		}
		else {
			mClock.restart();
			mSound->play();
		}

		if(mLoop)
			mQuitMusic = true;
	}

//////////////////////////////////////////////////////////////////////
// /Samma sak fast tvärtom
//////////////////////////////////////////////////////////////////////
	else if (enabledThisFrame == false && mEnabledLastFrame == true){
		//mSound->stop();
		
		//kill text if it's still alive.
		if(auto text_sp = mText_wp.lock()) {
			text_sp->setAlive(false);
		}

		//make it fade out

		mQuitMusic = false;
	}
	
	float volume = getVolume(subLevel_p);
	mSound->setVolume(volume);
	mEnabledLastFrame = enabledThisFrame;
}
예제 #30
0
/**
 * Constructor of MMSAudioCtrl class.
 *
 * The first instance of this class assigns
 * an audio channel, attaches to the mixer
 * of the sound card and gets the current
 * settings.
 *
 * @param   channel [in]    audio channel
 */
MMSAudioCtrl::MMSAudioCtrl(string channel) {
    int     err;

    if(this->channel=="") {
        this->channel=channel;
    }

    if (!this->handle) {
        /* open the mixer */
        if ((err = snd_mixer_open(&(this->handle), 0)) < 0)
            throw MMSAudioCtrlError(err,"snd_mixer_open() failed");

        /* attach the card */
        if ((err = snd_mixer_attach(this->handle, this->card.c_str())) < 0) {
            snd_mixer_close(this->handle);
            throw MMSAudioCtrlError(err,"snd_mixer_attach() with card = '"
                                            + this->card + "' failed");
        }

        /* register */
        if ((err = snd_mixer_selem_register(this->handle, NULL, NULL)) < 0) {
            snd_mixer_close(this->handle);
            string s = snd_strerror(err);
            throw MMSAudioCtrlError(err,"snd_mixer_selem_register() failed with '" + s + "'");
        }

        /* load */
        if ((err = snd_mixer_load(this->handle)) < 0) {
            snd_mixer_close(this->handle);
            string s = snd_strerror(err);
            throw MMSAudioCtrlError(err,"snd_mixer_load() failed with '" + s + "'");
        }
    }

    if (!this->elem) {
        /* searching for the first active element */
        for (this->elem = snd_mixer_first_elem(this->handle);
             this->elem;
             this->elem = snd_mixer_elem_next(this->elem)) {

            string mix = snd_mixer_selem_get_name(this->elem);
            DEBUGMSG("MMSMedia", "got mixer channel: %s", mix.c_str());
            /* is active? */
            if (!snd_mixer_selem_is_active(this->elem))
                continue;

            /* has playback volume? */
            if (!snd_mixer_selem_has_playback_volume(this->elem))
                continue;

            if (this->channel!="") {
                if(strcmp(this->channel.c_str(),snd_mixer_selem_get_name(this->elem))!=0)
                    continue;
            }

            /* we have found our channel*/
            /* get volume range */
            snd_mixer_selem_get_playback_volume_range(this->elem, &(this->pmin), &(this->pmax));

            /* check if this elem is mutable */
            isSwitchable = (snd_mixer_selem_has_playback_switch(elem) > 0);

            /* get the current volume settings */
            getVolume();

            return;
        }

        throw MMSAudioCtrlError(0,"no element found");
    }
}