Exemplo n.º 1
0
bool P1MeterBase::MatchLine()
{
	if ((strlen((const char*)&l_buffer)<1)||(l_buffer[0]==0x0a))
		return true; //null value (startup)
	uint8_t i;
	uint8_t found=0;
	Match *t;
	char value[20]="";
	std::string vString;

	for(i=0;(i<sizeof(matchlist)/sizeof(Match))&(!found);i++)
	{
		t = &matchlist[i];
		switch(t->matchtype)
		{
		case ID:
			// start of data
			if(strncmp(t->key, (const char*)&l_buffer, strlen(t->key)) == 0) {
				m_linecount=1;
				found=1;
			}
			continue; // we do not process anything else on this line
			break;
		case EXCLMARK:
			// end of data
			if(strncmp(t->key, (const char*)&l_buffer, strlen(t->key)) == 0) {
				l_exclmarkfound=1;
				found=1;
			}
			break;
		case STD:
			if(strncmp(t->key, (const char*)&l_buffer, strlen(t->key)) == 0)
				found=1;
			break;
		case DEVTYPE:
			if(m_gasmbuschannel==0){
				vString=(const char*)t->key+3;
				if (strncmp(vString.c_str(), (const char*)&l_buffer+3, strlen(t->key)-3) == 0)
					found=1;
				else
					i+=100; // skip matches with any other gas lines - we need to find the M0-Bus channel first
			}
			break;
		case GAS:
			if(strncmp((m_gasprefix+(t->key+3)).c_str(), (const char*)&l_buffer, strlen(t->key)) == 0){
				found=1;
			}
			if (m_p1version>=4)
				i+=100; // skip matches with any DSMR v2 gas lines
			break;
		case LINE17:
			if(strncmp((m_gasprefix+(t->key+3)).c_str(), (const char*)&l_buffer, strlen(t->key)) == 0){
				m_linecount = 17;
				found=1;
			}
			break;
		case LINE18:
			if((m_linecount == 18)&&(strncmp(t->key, (const char*)&l_buffer, strlen(t->key)) == 0))
				found=1;
			break;
		} //switch

		if(!found)
			continue;

		if (l_exclmarkfound) {
			if (m_p1version==0)
			{
				_log.Log(LOG_STATUS,"P1 Smart Meter: Meter is pre DSMR 4.0 - using DSMR 2.2 compatibility");
				m_p1version=2;
			}
			time_t atime=mytime(NULL);
			if (difftime(atime,m_lastUpdateTime)>=m_ratelimit) {
				m_lastUpdateTime=atime;
				sDecodeRXMessage(this, (const unsigned char *)&m_power, "Power", 255);
				if (m_voltagel1) {
					SendVoltageSensor(0, 1, 255, m_voltagel1, "Voltage L1");
					if (m_voltagel2)
						SendVoltageSensor(0, 2, 255, m_voltagel2, "Voltage L2");
					if (m_voltagel3)
						SendVoltageSensor(0, 3, 255, m_voltagel3, "Voltage L3");
				}
				if ( (m_gas.gasusage>0)&&( (m_gas.gasusage!=m_lastgasusage)||(difftime(atime,m_lastSharedSendGas)>=300) ) ){
					//only update gas when there is a new value, or 5 minutes are passed
					if (m_gasclockskew>=300){ // just accept it - we cannot sync to our clock
						m_lastSharedSendGas=atime;
						m_lastgasusage=m_gas.gasusage;
						sDecodeRXMessage(this, (const unsigned char *)&m_gas, "Gas", 255);
					}
					else if (atime>=m_gasoktime){
						struct tm ltime;
						localtime_r(&atime, &ltime);
						char myts[16];
						sprintf(myts,"%02d%02d%02d%02d%02d%02dW",ltime.tm_year%100,ltime.tm_mon+1,ltime.tm_mday,ltime.tm_hour,ltime.tm_min,ltime.tm_sec);
						if (ltime.tm_isdst)
						myts[12]='S';
						if ( (m_gastimestamp.length()>13) || (strncmp((const char*)&myts,m_gastimestamp.c_str(),m_gastimestamp.length())>=0) )
						{
							m_lastSharedSendGas=atime;
							m_lastgasusage=m_gas.gasusage;
							m_gasoktime+=300;
							sDecodeRXMessage(this, (const unsigned char *)&m_gas, "Gas", 255);
						}
						else // gas clock is ahead
						{
							struct tm gastm;
							gastm.tm_year = atoi(m_gastimestamp.substr(0, 2).c_str()) + 100;
							gastm.tm_mon = atoi(m_gastimestamp.substr(2, 2).c_str()) - 1;
							gastm.tm_mday = atoi(m_gastimestamp.substr(4, 2).c_str());
							gastm.tm_hour = atoi(m_gastimestamp.substr(6, 2).c_str());
							gastm.tm_min = atoi(m_gastimestamp.substr(8, 2).c_str());
							gastm.tm_sec = atoi(m_gastimestamp.substr(10, 2).c_str());
							if (m_gastimestamp.length()==12)
								gastm.tm_isdst = -1;
							else if (m_gastimestamp[12]=='W')
								gastm.tm_isdst = 0;
							else
								gastm.tm_isdst = 1;

							time_t gtime=mktime(&gastm);
							m_gasclockskew=difftime(gtime,atime);
							if (m_gasclockskew>=300){
								_log.Log(LOG_ERROR, "P1 Smart Meter: Unable to synchronize to the gas meter clock because it is more than 5 minutes ahead of my time");
							}
							else {
								m_gasoktime=gtime;
								_log.Log(LOG_STATUS, "P1 Smart Meter: Gas meter clock is %i seconds ahead - wait for my clock to catch up", (int)m_gasclockskew);
							}
						}
					}
				}
			}
			m_linecount=0;
			l_exclmarkfound=0;
		}
		else
		{
			vString=(const char*)&l_buffer+t->start;
			int ePos=t->width;
			ePos=vString.find_first_of("*)");

			if (ePos==std::string::npos)
			{
				// invalid message: value not delimited
				_log.Log(LOG_NORM,"P1 Smart Meter: Dismiss incoming - value is not delimited in line \"%s\"", l_buffer);
				return false;
			}

			if (ePos>19)
			{
				// invalid message: line too long
				_log.Log(LOG_NORM,"P1 Smart Meter: Dismiss incoming - value in line \"%s\" is oversized", l_buffer);
				return false;
			}

			if (ePos>0)
			{
				strcpy(value,vString.substr(0,ePos).c_str());
#ifdef _DEBUG
				_log.Log(LOG_NORM,"P1 Smart Meter: Key: %s, Value: %s", t->topic,value);
#endif
			}

			unsigned long temp_usage = 0;
			float temp_volt = 0;
			char *validate=value+ePos;

			switch (t->type)
			{
			case P1TYPE_VERSION:
				if (m_p1version==0)
					_log.Log(LOG_STATUS,"P1 Smart Meter: Meter reports as DSMR %c.%c", value[0], value[1]);
				m_p1version=value[0]-0x30;
				break;
			case P1TYPE_MBUSDEVICETYPE:
				temp_usage = (unsigned long)(strtod(value,&validate));
				if (temp_usage == 3) {
					m_gasmbuschannel = (char)l_buffer[2];
					m_gasprefix[2]=m_gasmbuschannel;
					_log.Log(LOG_STATUS,"P1 Smart Meter: Found gas meter on M-Bus channel %c", m_gasmbuschannel);
				}
				break;
			case P1TYPE_POWERUSAGE1:
				temp_usage = (unsigned long)(strtod(value,&validate)*1000.0f);
				if (!m_power.powerusage1 || m_p1version >= 4)
					m_power.powerusage1 = temp_usage;
				else if (temp_usage - m_power.powerusage1 < 10000)
					m_power.powerusage1 = temp_usage;
				break;
			case P1TYPE_POWERUSAGE2:
				temp_usage = (unsigned long)(strtod(value,&validate)*1000.0f);
				if (!m_power.powerusage2 || m_p1version >= 4)
					m_power.powerusage2 = temp_usage;
				else if (temp_usage - m_power.powerusage2 < 10000)
					m_power.powerusage2 = temp_usage;
				break;
			case P1TYPE_POWERDELIV1:
				temp_usage = (unsigned long)(strtod(value,&validate)*1000.0f);
				if (!m_power.powerdeliv1 || m_p1version >= 4)
					m_power.powerdeliv1 = temp_usage;
				else if (temp_usage - m_power.powerdeliv1 < 10000)
					m_power.powerdeliv1 = temp_usage;
				break;
			case P1TYPE_POWERDELIV2:
				temp_usage = (unsigned long)(strtod(value,&validate)*1000.0f);
				if (!m_power.powerdeliv2 || m_p1version >= 4)
					m_power.powerdeliv2 = temp_usage;
				else if (temp_usage - m_power.powerdeliv2 < 10000)
					m_power.powerdeliv2 = temp_usage;
				break;
			case P1TYPE_USAGECURRENT:
				temp_usage = (unsigned long)(strtod(value,&validate)*1000.0f);	//Watt
				if (temp_usage < 17250)
					m_power.usagecurrent = temp_usage;
				break;
			case P1TYPE_DELIVCURRENT:
				temp_usage = (unsigned long)(strtod(value,&validate)*1000.0f);	//Watt;
				if (temp_usage < 17250)
					m_power.delivcurrent = temp_usage;
				break;
			case P1TYPE_VOLTAGEL1:
				temp_volt = strtof(value,&validate);
				if (temp_volt < 300)
					m_voltagel1 = temp_volt; //Voltage L1;
				break;
			case P1TYPE_VOLTAGEL2:
				temp_volt = strtof(value,&validate);
				if (temp_volt < 300)
					m_voltagel2 = temp_volt; //Voltage L2;
				break;
			case P1TYPE_VOLTAGEL3:
				temp_volt = strtof(value,&validate);
				if (temp_volt < 300)
					m_voltagel3 = temp_volt; //Voltage L3;
				break;
			case P1TYPE_GASTIMESTAMP:
				m_gastimestamp = std::string(value);
				break;
			case P1TYPE_GASUSAGE:
			case P1TYPE_GASUSAGEDSMR4:
				temp_usage = (unsigned long)(strtod(value,&validate)*1000.0f);
				if (!m_gas.gasusage || m_p1version >= 4)
					m_gas.gasusage = temp_usage;
				else if (temp_usage - m_gas.gasusage < 20000)
					m_gas.gasusage = temp_usage;
				break;
			}

			if (ePos>0 && ((validate - value) != ePos)) {
				// invalid message: value is not a number
				_log.Log(LOG_NORM,"P1 Smart Meter: Dismiss incoming - value in line \"%s\" is not a number", l_buffer);
				return false;
			}

			if (t->type == P1TYPE_GASUSAGEDSMR4){ // need to get timestamp from this line as well
				vString=(const char*)&l_buffer+11;
				m_gastimestamp=vString.substr(0,13);
#ifdef _DEBUG
				_log.Log(LOG_NORM,"P1 Smart Meter: Key: gastimestamp, Value: %s", m_gastimestamp);
#endif
			}
		}
	}
	return true;
}
Exemplo n.º 2
0
void handle_line(char *line)
{
	float freq = 0.0;
	int octave = -1;
	char *check = NULL;
	check = get_arg_to("#reset",line);
	if (check)
	{
		step_prog = 0;
		free(check);
		return;
	}

	check = get_arg_to("#step ",line);
	if (check)
	{
		step_size = (float)strtof(check,0);
		free(check);
		return;
	}

	check = get_arg_to("#amp ",line);
	if (check)
	{
		amp = (float)strtof(check,0);
		free(check);
		return;
	}

	check = get_arg_to("#duty ",line);
	if (check)
	{
		duty = (float)strtof(check,0);
		free(check);
		return;
	}

	check = get_arg_to("#wave ",line);
	if (check)
	{
		wave_sel = (int)strtoul(check,NULL,0);
		free(check);
		return;
	}

	check = get_arg_to("#decay ",line);
	if (check)
	{
		decay_len = (float)strtof(check,0);
		free(check);
		return;
	}

	check = get_arg_to("#len ",line);
	if (check)
	{
		note_len = (float)strtof(check,0);
		free(check);
		return;
	}

	check = get_arg_to("#overclock ",line);
	if (check)
	{
		overclock = (float)strtof(check,0);
		free(check);
		return;
	}

	check = get_arg_to("#tmod ",line);
	if (check)
	{
		tmod_cnt++;
		tmod = (float)strtof(check,0);
		printf("\tfloat t%d = mod(t0,%f);\n",tmod_cnt,tmod);
		free(check);
		return;	
	}

	check = get_arg_to("#tune ",line);
	if (check)
	{
		tune = (float)strtof(check,0);
		free(check);
		return;
	}

	check = get_arg_to("#left ",line);
	if (check)
	{
		left_a = (float)strtof(check,0);	
		free(check);
		return;
	}

	check = get_arg_to("#right ",line);
	if (check)
	{
		right_a = (float)strtof(check,0);	
		free(check);
		return;
	}

	check = get_arg_to("#main",line);
	if (check)
	{	
		printf("vec2 mainSound(float t0)\n{\n");
		printf("\tt0 = t0 * %f;\n",overclock);
		printf("\tvec2 result = vec2(0.0,0.0);\n");
		free(check);
		return;
	}

	check = get_arg_to("#endmain",line);
	if (check)
	{
		printf("\n\treturn result;\n}\n\n");
		free(check);
		return;
	}

	check = get_arg_to("#func ",line);
	if (check)
	{
		first_if = 1;
		tmod_cnt = 0;
		printf("float %s(float t%d)\n{\n\tfloat result = 0.0;\n",check,tmod_cnt);
		free(check);
		return;
	}

	check = get_arg_to("#endfunc",line);
	if (check)
	{
		printf("\n\treturn result;\n}\n\n");
		free(check);
		return;
	}

	check = get_arg_to("#call ",line);
	if (check)
	{
		printf("\tresult += vec2(%f,%f) * (%s(t%d));\n",left_a,right_a,check,tmod_cnt);
		free(check);
		return;
	}

// Notes
	check = get_arg_to("C#",line);
	if (check)
	{
		freq = NOTE_CS;
		octave = (int)strtoul(check,NULL,0);
		goto handle_line_finished;
	}
	check = get_arg_to("C",line);
	if (check)
	{
		freq = NOTE_C;
		octave = (int)strtoul(check,NULL,0);
		goto handle_line_finished;
	}
	check = get_arg_to("D#",line);
	if (check)
	{
		freq = NOTE_DS;
		octave = (int)strtoul(check,NULL,0);
		goto handle_line_finished;
	}
	check = get_arg_to("D",line);
	if (check)
	{
		freq = NOTE_D;
		octave = (int)strtoul(check,NULL,0);
		goto handle_line_finished;
	}
	check = get_arg_to("E",line);
	if (check)
	{
		freq = NOTE_E;
		octave = (int)strtoul(check,NULL,0);
		goto handle_line_finished;
	}
	check = get_arg_to("F#",line);
	if (check)
	{
		freq = NOTE_FS;
		octave = (int)strtoul(check,NULL,0);
		goto handle_line_finished;
	}
	check = get_arg_to("F",line);
	if (check)
	{
		freq = NOTE_F;
		octave = (int)strtoul(check,NULL,0);
		goto handle_line_finished;
	}
	check = get_arg_to("G#",line);
	if (check)
	{
		freq = NOTE_GS;
		octave = (int)strtoul(check,NULL,0);
		goto handle_line_finished;
	}
	check = get_arg_to("G",line);
	if (check)
	{
		freq = NOTE_G;
		octave = (int)strtoul(check,NULL,0);
		goto handle_line_finished;
	}
	check = get_arg_to("A#",line);
	if (check)
	{
		freq = NOTE_AS;
		octave = (int)strtoul(check,NULL,0);
		goto handle_line_finished;
	}
	check = get_arg_to("A",line);
	if (check)
	{
		freq = NOTE_A;
		octave = (int)strtoul(check,NULL,0);
		goto handle_line_finished;
	}
	check = get_arg_to("B",line);
	if (check)
	{
		freq = NOTE_B;
		octave = (int)strtoul(check,NULL,0);
		goto handle_line_finished;
	}
	check = get_arg_to("-",line);
	if (check)
	{
		freq = 0;
		octave = -1;
		goto handle_line_finished;
	}

// Unrecognized token, or a comment, etc
	free(check);
	return;

handle_line_finished:
	if (check)
	{
		free(check);
		print_line(freq, octave);
		step_prog += step_size;
	}
	return;
	
}
Exemplo n.º 3
0
// Start ISR, Fill array, Return array, Stop ISR
uint8 ultrasonic_get_reading(UltrasonicReading *reading) {
    
    int i, j;
    char depth[DEPTH_STRING_LENGTH], s[MAX_STRING_LENGTH];

    // Reset variables
    (*reading).valid = 0u;
    (*reading).temp = -9999;    
    (*reading).depth = -9999;
    uart_ultrasonic_string_reset();

    isr_byte_ultrasonic_rx_StartEx(isr_byte_ultrasonic_rx); // Start the ISR to read the UART
    ultrasonic_power_on();                                  // Power on the sensor
    CyDelay(1500u);                                         // Wait for UART to get readings from sensor
    
    isr_byte_ultrasonic_rx_Stop();                          // Stop the ISR to read the UART
    ultrasonic_power_off();                                 // Power off the sensor

    // store relevant strings to ultrasonic_packet
    strcpy(s,uart_ultrasonic_received_string);
    /*
    for(i = 0; i < strlen(uart_ultrasonic_received_string); i++){
        s = uart_ultrasonic_received_string[i];
        
        if(R_count > 4 && s == '\r'){
            (*reading).valid = 1u;
            break; 
        }else if(R_count > 4){
            depth[index] = s;
            index++;
        }
        if(s == 'R'){
            R_count++;      // increment everytime an "R" ascii character is encountered
        }
    }
    */

    for(i = 0; i < MAX_STRING_LENGTH-1-DEPTH_STRING_LENGTH; i++){
        if( s[i] == 'R' && s[i+1+DEPTH_STRING_LENGTH] == '\r' ) {
            for(j = 0; j < DEPTH_STRING_LENGTH; j++) {
                depth[j] = s[i+j+1];
            }
            (*reading).valid = 1u;
            break;
        }
    }
    
    if ((*reading).valid) {
        (*reading).depth = strtof(depth,(char **) NULL); //(float)atof(depth);
/*        
        //(*reading).depth = (float) ultrasonic_depth;
        if ((*reading).depth > 9999) { // Recorded depth greater than 4 digits... (eg 13582 vs 1358)
            (*reading).depth = (float) (int)( (*reading).depth  / 10) ;
            
            debug_write("Ultrasonic Warning.  depth > 5 digits.  Truncated depth reported.");
            debug_write(uart_ultrasonic_received_string);           
        }
    }    
    else if(R_count <= 4){
        debug_write("Ultrasonic No Reading Found.  R_count <= 4.");
        debug_write(uart_ultrasonic_received_string);
*/        
    }
    else {
        debug_write("Ultrasonic Invalid Reading.");
        debug_write(uart_ultrasonic_received_string);
    }
    
    return (*reading).valid;
}
Exemplo n.º 4
0
static int set_dev_options(struct sr_dev *dev, GHashTable *args)
{
	GHashTableIter iter;
	gpointer key, value;
	int ret, i;
	float tmp_float;
	uint64_t tmp_u64;
	struct sr_rational tmp_rat;
	gboolean tmp_bool;
	gboolean found;

	g_hash_table_iter_init(&iter, args);
	while (g_hash_table_iter_next(&iter, &key, &value)) {
		found = FALSE;
		for (i = 0; sr_hwcap_options[i].hwcap; i++) {
			if (strcmp(sr_hwcap_options[i].shortname, key))
				continue;
			if ((value == NULL) && 
			    (sr_hwcap_options[i].type != SR_T_BOOL)) {
				g_critical("Option '%s' needs a value.", (char *)key);
				return SR_ERR;
			}
			found = TRUE;
			switch (sr_hwcap_options[i].type) {
			case SR_T_UINT64:
				ret = sr_parse_sizestring(value, &tmp_u64);
				if (ret != SR_OK)
					break;
				ret = dev->driver->dev_config_set(dev->driver_index,
					sr_hwcap_options[i].hwcap, &tmp_u64);
				break;
			case SR_T_CHAR:
				ret = dev->driver->dev_config_set(dev->driver_index,
					sr_hwcap_options[i].hwcap, value);
				break;
			case SR_T_BOOL:
				if (!value)
					tmp_bool = TRUE;
				else 
					tmp_bool = sr_parse_boolstring(value);
				ret = dev->driver->dev_config_set(dev->driver_index,
						sr_hwcap_options[i].hwcap, 
						GINT_TO_POINTER(tmp_bool));
				break;
			case SR_T_FLOAT:
				tmp_float = strtof(value, NULL);
				ret = dev->driver->dev_config_set(dev->driver_index,
						sr_hwcap_options[i].hwcap, &tmp_float);
				break;
			case SR_T_RATIONAL_PERIOD:
				if ((ret = sr_parse_period(value, &tmp_rat)) != SR_OK)
					break;
				ret = dev->driver->dev_config_set(dev->driver_index,
						sr_hwcap_options[i].hwcap, &tmp_rat);
				break;
			case SR_T_RATIONAL_VOLT:
				if ((ret = sr_parse_voltage(value, &tmp_rat)) != SR_OK)
					break;
				ret = dev->driver->dev_config_set(dev->driver_index,
						sr_hwcap_options[i].hwcap, &tmp_rat);
				break;
			default:
				ret = SR_ERR;
			}

			if (ret != SR_OK) {
				g_critical("Failed to set device option '%s'.", (char *)key);
				return ret;
			}
			else
				break;
		}
		if (!found) {
			g_critical("Unknown device option '%s'.", (char *) key);
			return SR_ERR;
		}
	}

	return SR_OK;
}
Exemplo n.º 5
0
//==================================================================
//
//  Parses a string strting from linestart
//  and continues to read till a null terminator is found
//
//  Takes regards to the provided linetype_t type, and interprets
//  the contents accordingly
//
//  (ex: If a line contains v, parse a vertex)
//
//  Parameters:
//          char* linestart: Start pointer of string
//          linetype_t: Type of line (eg vertex, normal, face, etc)
//          int* out: currently not used.
//
//  Returns 0 upon success, -1 upon fail. If fail, see FileParser::GetError()
//
//==================================================================
int OBJFileParser::ParseData(char* linestart, linetype_t type, int* out)
{
    bool useOut = false;
    if(out != nullptr)
        useOut = true;
    
    char buff[255];
    strcpy(buff, linestart);
    
    switch (type) {
        case LT_VERTEX:
        {
            //vertex layout: v x y z
            char* content = ParseFindNext(buff);
            if(!content)
            {
                this->error = FP_ERROR_SYNTAX;
                return -1;
            }
            
            char* end = nullptr;
            
            tempVal = strtof(content, &end);
            content = end;
            
            tempVec3D.x = tempVal;
            
            content = ParseFindNext(content);
            tempVal = strtof(content, &end);
            content = end;
            
            tempVec3D.y = tempVal;
            
            content = ParseFindNext(content);
            tempVal = strtof(content, &end);
            
            tempVec3D.z = tempVal;
            
            temp_vertices.push_back(tempVec3D);
            
            break;
        }
            
            
        case LT_TEXTURECOORD:
        {
            //tc layout: vt u v
            char* content = ParseFindNext(buff);
            if(!content)
            {
                this->error = FP_ERROR_SYNTAX;
                return -1;
            }
            
            char* end = nullptr;
            
            tempVal = strtof(content, &end);
            content = end;
            
            tempVec2D.x = tempVal;
            
            content = ParseFindNext(content);
            tempVal = strtof(content, &end);
            content = end;
            
            tempVec2D.y = tempVal;
            
            temp_texcoords.push_back(tempVec2D);
            
            break;
        }
            
        case LT_NORMAL:
        {
            char* content = ParseFindNext(buff);
            if(!content)
            {
                this->error = FP_ERROR_SYNTAX;
                return -1;
            }
            
            char* end = nullptr;
            
            tempVal = strtof(content, &end);
            content = end;
            
            tempVec3D.x = tempVal;
            
            content = ParseFindNext(content);
            tempVal = strtof(content, &end);
            content = end;
            
            tempVec3D.y = tempVal;
            
            content = ParseFindNext(content);
            tempVal = strtof(content, &end);
            
            tempVec3D.z = tempVal;
            
            temp_normals.push_back(tempVec3D);
            break;
        }
            
        case LT_FACE:
        {
            face_t face;
            for(char* ptr = buff; *ptr != '\0'; ptr++)
            {
                indice_group_t group;
                char* end;
                
                char* val = ParseFindNext(ptr);
                if(!val)
                    break;
                
                group.vertex = (int)strtof(val, &end);
                val = end;
                
                if(*val == '/' && *(val + 1) != '/')
                {
                    group.textureCoord = (int)strtof((val + 1), &end);
                } else
                {
                    group.textureCoord = -1;
                }
                
                val = end;
                
                if(*val == '/')
                {
                    group.normal = (int)strtof((val + 1), &end);
                } else
                {
                    group.normal = -1;
                }
                val = end;
                
                ptr = val;
                
                face.indiceGroups.push_back(group);
                
            }
            
            temp_faces.push_back(face);
            break;
        }
            
        default:
            break;
    }
    
    return 0;
}
Exemplo n.º 6
0
static sc_int
ParseOption(const char* arg, sc_option handle)
{
	if(!arg || !handle)
		return SC_INVALID_VALUE;

	sc_status status;
	sc_option_t* option = (sc_option_t*)handle;
	sc_value value = (sc_value)option->value;
	switch(scGetValueType(value, &status))
	{
		case (SC_TYPE_BOOL):
			if(isdigit(arg[0]))
			{
				scSetBoolValue(value, (atoi(arg) > 0) ? (SC_TRUE) : (SC_FALSE));
				option->updated = SC_TRUE;
				return SC_SUCCESS;
			}
			else if(strcmp(arg, "true") == 0)
			{
				scSetBoolValue(value, SC_TRUE);
				option->updated = SC_TRUE;
				return SC_SUCCESS;
			}
			else if(strcmp(arg, "True") == 0)
			{
				scSetBoolValue(value, SC_TRUE);
				option->updated = SC_TRUE;
				return SC_SUCCESS;
			}
			else if(strcmp(arg, "false") == 0)
			{
				scSetBoolValue(value, SC_FALSE);
				option->updated = SC_TRUE;
				return SC_SUCCESS;
			}
			else if(strcmp(arg, "False") == 0)
			{
				scSetBoolValue(value, SC_FALSE);
				option->updated = SC_TRUE;
				return SC_SUCCESS;
			}
			break;
		case (SC_TYPE_CHAR):
			if(isdigit(arg[0]))
			{
				scSetCharValue(value, (sc_char)atoi(arg));
				option->updated = SC_TRUE;
				return SC_SUCCESS;
			}
			break;
		case (SC_TYPE_UCHAR):
			if(isdigit(arg[0]))
			{
				scSetUCharValue(value, (sc_char)atoi(arg));
				option->updated = SC_TRUE;
				return SC_SUCCESS;
			}
			break;
		case (SC_TYPE_SHORT):
			if(isdigit(arg[0]))
			{
				scSetShortValue(value, (sc_short)atoi(arg));
				option->updated = SC_TRUE;
				return SC_SUCCESS;
			}
			break;
		case (SC_TYPE_USHORT):
			if(isdigit(arg[0]))
			{
				scSetUShortValue(value, (sc_short)atoi(arg));
				option->updated = SC_TRUE;
				return SC_SUCCESS;
			}
			break;
		case (SC_TYPE_INT):
			if(isdigit(arg[0]))
			{
				scSetIntValue(value, (sc_int)atoi(arg));
				option->updated = SC_TRUE;
				return SC_SUCCESS;
			}
			break;
		case (SC_TYPE_UINT):
			if(isdigit(arg[0]))
			{
				scSetUIntValue(value, (sc_uint)atoi(arg));
				option->updated = SC_TRUE;
				return SC_SUCCESS;
			}
			break;
		case (SC_TYPE_LONG):
			if(isdigit(arg[0]))
			{
				scSetLongValue(value, (sc_long)atol(arg));
				option->updated = SC_TRUE;
				return SC_SUCCESS;
			}
			break;
		case (SC_TYPE_ULONG):
			if(isdigit(arg[0]))
			{
				scSetULongValue(value, (sc_ulong)atol(arg));
				option->updated = SC_TRUE;
				return SC_SUCCESS;
			}
			break;
		case (SC_TYPE_FLOAT):
			{
				char* end = 0;
				scSetFloatValue(value, (sc_float)strtof(arg, &end));
				if(end != arg)
				{
					option->updated = SC_TRUE;
					return SC_SUCCESS;
				}
			}
			break;
		case (SC_TYPE_DOUBLE):
			{
				char* end = 0;
				scSetDoubleValue(value, (sc_double)strtod(arg, &end));
				if(end != arg)
				{
					option->updated = SC_TRUE;
					return SC_SUCCESS;
				}
			}
			break;
		case (SC_TYPE_SYMBOL):
			{
				scSetSymbolValue(value, scCreateSymbol(NULL, arg, strlen(arg)));
				option->updated = SC_TRUE;
				return SC_SUCCESS;
			}
			break;
		default:
			return SC_INVALID_VALUE;	
	}
	
	return SC_INVALID_VALUE;	
}
float CameraParameters::getFloat(const char *key) const
{
    const char *v = get(key);
    if (v == 0) return -1;
    return strtof(v, 0);
}
Exemplo n.º 8
0
int main(int argc, char** argv)
{
	--argc;
	++argv;

	const int WIDTH = 800;
	const int HEIGHT = 600;

	/*
	*	Create window
	*/
	sf::RenderWindow window(sf::VideoMode(WIDTH, HEIGHT), "Window", sf::Style::Default, sf::ContextSettings(32));
	
	/*
	*	Initialize GLEW
	*/
	GLenum status = glewInit();
	if(status != GLEW_OK)
	{
		std::cerr << "[F] GLEW NOT INITIALIZED: ";
		std::cerr << glewGetErrorString(status) << std::endl;
	
		window.close();
	
		return -1;
	}

	/*
	*	Create GUI
	*/
	tgui::Gui gui(window);
	tgui::Gui gui2(window);
	gui.setGlobalFont("fonts/DejaVuSans.ttf");
	loadWidgets(gui, gui2, window);
	
	char* args[argc + 1];
	
	/*
	*	load geometry
	*/
	Model cube;
	getArgs(argc, argv, ".obj", args);
	
	if (!args[0])
	{
		std::cerr << "[F] MUST SUPPLY 1+ OBJ FILES IN COMMAND LINE ARGS <filename.obj>" << std::endl;
		exit(-1);
	} //if
	
	cube.mesh = loadMesh(args[0]);
	
	getArgs(argc, argv, ".scale", args);
	if (args[0])
	{
		cube.scale = glm::vec3(strtof(args[0], NULL));
	} //if
	else
	{
		cube.scale = glm::vec3(1.0f);
	} //else
	
	/*
	*	load shaders
	*/
	Shader vertexShader(GL_VERTEX_SHADER);
	getArgs(argc, argv, ".vs", args);
	vertexShader.loadFromFile(args[0]? args[0] : ".vs");
	vertexShader.compile();
	
	Shader fragmentShader(GL_FRAGMENT_SHADER);
	getArgs(argc, argv, ".fs", args);
	fragmentShader.loadFromFile(args[0]? args[0] : ".fs");
	fragmentShader.compile();
	
	/*
	*	create program
	*/
	ShaderProgram program;
	
	program.attachShader(vertexShader);
	program.attachShader(fragmentShader);
	program.linkProgram();
	
	program.addAttribute("vertexPosition_modelspace");
	program.addAttribute("vertexUV");
	//program.addAttribute("vertexNormal_modelspace");
	
	program.addUniform("MVP");
	program.addUniform("myTextureSampler");
	
	glEnable(GL_DEPTH_TEST);
	glDepthMask(GL_TRUE);
	glEnable(GL_CULL_FACE);
	glClearDepth(1.f);
	glShadeModel (GL_SMOOTH);
	
	glUniform1i(program.uniform("myTextureSampler"), 0);

	Camera camera;
	
	sf::Event event;
	tgui::Callback callback;
	
	Planet p(&cube);
	
	/*
	*	main loop
	*/
	
	while (window.isOpen())
	{
		while (window.pollEvent(event))
		{
			switch (event.type)
			{
				case sf::Event::Closed:
					window.close();
				
					break;
				case sf::Event::Resized:
					glViewport(0, 0, event.size.width, event.size.height);
					camera.projection = glm::perspective(45.0f, float(event.size.width)/float(event.size.height), 0.01f, 100.0f);
					
					break;
				default:
					break;
			} //switch
			
			gui.handleEvent(event);
		} //if
		
		while (gui.pollCallback(callback))
		{
			gui.handleEvent(event);
		} //if
		
		window.clear();
		guiDraw(window, gui2);
		glClear(GL_DEPTH_BUFFER_BIT); 
		
		/*
		*	render OpenGL here
		*/
		//glValidateProgram(program.program);
		
		for (Planet* planet : planets)
		{
			render(*planet, camera, program);
		} //for
		
		guiDraw(window, gui);
		
		window.display();
	} //while

	// Clean up after ourselves
	if (window.isOpen())
	{
		window.close();
	} //if
	
	return EXIT_SUCCESS;
} //main
Exemplo n.º 9
0
// Parse a line in sparse data format and convert it to SparseVector.
// Return pointer to first unread chararcter, i.e. a successful
// parse ends at '\0' or at '#'.
const char *sdf_parse_line (const char *line, SparseVector &features)
{
  const char *pos = line;
  char *end;

  // target value
  float value = strtof (pos, &end);
  if (pos == end)
  {
    FATAL << "Can't read target value" << std::endl;
    return pos; 
  }
  features.set_target (value);
  pos = end;

  // TODO: optional query id

  // eat white space
  while (isspace (*pos)) ++pos;  

  // features
  int last_id = 0;
  while ((*pos) && (*pos != '#')) // until end of line or comment char
  {
    // read feature id
    unsigned long convert_buffer = strtoul (pos, &end, 10);
    if (pos == end)
    {
      FATAL << "Can't read feature id" << std::endl;
      return pos;
    }
    pos = end;
    id_t id (convert_buffer); // TODO: check for overflow

    // check increasing order
    if (last_id >= id)
    {
      FATAL << "Feature ids must be in increasing order, but " <<
        last_id << " >= " << id << std::endl;
      return pos;
    }
    last_id = id;

    // read separator
    if (*pos != ':')
    {
      FATAL << "Colon ':' expected" << std::endl;
      return pos; 
    }
    ++pos;

    // read feature value
    float value = strtof (pos, &end);
    if (pos == end)
    {
      FATAL << "Can't read feature value" << std::endl;
      return pos;    
    }
    pos = end;

    // append to vector
    features.push_back (std::make_pair (id, value));

    // eat white space
    while (isspace (*pos)) ++pos;  
  }  

  return pos; 
}
Exemplo n.º 10
0
bool ASessionDescription::getDurationUs(int64_t *durationUs) const {
    *durationUs = 0;

    CHECK(mIsValid);

    AString value;
    if (!findAttribute(0, "a=range", &value)) {
        return false;
    }

#ifndef ANDROID_DEFAULT_CODE 
    if (strncmp(value.c_str(), "npt=", 4) && strncmp(value.c_str(), "npt:", 4)) {
#else
    if (strncmp(value.c_str(), "npt=", 4)) {
#endif // #ifndef ANDROID_DEFAULT_CODE
        return false;
    }

    float from, to;
    if (!parseNTPRange(value.c_str() + 4, &from, &to)) {
        return false;
    }

    *durationUs = (int64_t)((to - from) * 1E6);

    return true;
}

// static
void ASessionDescription::ParseFormatDesc(
        const char *desc, int32_t *timescale, int32_t *numChannels) {
    const char *slash1 = strchr(desc, '/');
    CHECK(slash1 != NULL);

    const char *s = slash1 + 1;
    char *end;
    unsigned long x = strtoul(s, &end, 10);
    CHECK_GT(end, s);
    CHECK(*end == '\0' || *end == '/');

    *timescale = x;
    *numChannels = 1;

    if (*end == '/') {
        s = end + 1;
        unsigned long x = strtoul(s, &end, 10);
        CHECK_GT(end, s);
        CHECK_EQ(*end, '\0');

        *numChannels = x;
    }
}

// static
bool ASessionDescription::parseNTPRange(
        const char *s, float *npt1, float *npt2) {
    if (s[0] == '-') {
        return false;  // no start time available.
    }

    if (!strncmp("now", s, 3)) {
        return false;  // no absolute start time available
    }

    char *end;
    *npt1 = strtof(s, &end);

    if (end == s || *end != '-') {
        // Failed to parse float or trailing "dash".
        return false;
    }

    s = end + 1;  // skip the dash.

    if (!strncmp("now", s, 3)) {
        return false;  // no absolute end time available
    }

    *npt2 = strtof(s, &end);
	
#ifndef ANDROID_DEFAULT_CODE
	//We support range string as "Range: npt=1.0000-"
	return true;
#else
	if (end == s || *end != '\0') {
		return false;
	}
	return *npt2 > *npt1;
#endif
}

#ifndef ANDROID_DEFAULT_CODE 
bool ASessionDescription::getBitrate(size_t index, int32_t* bitrate) const {
    char key[] = "b=AS";
    AString value;
    if (!findAttribute(index, key, &value))
        return false;
    int32_t b = atoi(value.c_str());
    b *= 1000;
    if (b < 0)
        return false;
    *bitrate = b;
    return true;
}
Exemplo n.º 11
0
NEOERR* session_init(CGI *cgi, HASH *dbh, session_t **ses)
{
    session_t *lses;
    HDF *node, *onode;
    char tok[LEN_HDF_KEY], *s;

    /*
     * follow cgi_parse(), to process _type_object
     */
    s = hdf_get_value(cgi->hdf, PRE_QUERY"._type_object", NULL);
    if (s) {
        ULIST *list;
        string_array_split(&list, s, ",", 50);
        ITERATE_MLIST(list) {
            snprintf(tok, sizeof(tok), "%s.%s",
                     PRE_QUERY, neos_strip((char*)list->items[t_rsv_i]));
            onode = hdf_get_obj(cgi->hdf, tok);
            if (onode) {
                mjson_export_to_hdf(onode, NULL, MJSON_EXPORT_NONE, false);
            }
        }
        uListDestroy(&list, ULIST_FREE);
    }
    
    *ses = NULL;

    lses = calloc(1, sizeof(session_t));
    if (!lses) return nerr_raise(NERR_NOMEM, "calloc memory for session_t failure");

    /*
     * mname
     */
    HDF_FETCH_STR(cgi->hdf, PRE_COOKIE".mname", s);
    if (!s) HDF_FETCH_STR(cgi->hdf, PRE_COOKIE".username", s);
    if (s) lses->mname = strdup(s);

    /*
     * province
     */
    HDF_FETCH_STR(cgi->hdf, PRE_COOKIE".province", s);
    hdf_init(&lses->province);
    if (s) {
        neos_unescape((UINT8*)s, strlen(s), '%');
        hdf_set_value(lses->province, NULL, s);
        mjson_export_to_hdf(lses->province, MJSON_EXPORT_NONE, NULL, false);
    }

    /*
     * city
     */
    HDF_FETCH_STR(cgi->hdf, PRE_COOKIE".city", s);
    hdf_init(&lses->city);
    if (s) {
        neos_unescape((UINT8*)s, strlen(s), '%');
        hdf_set_value(lses->city, NULL, s);
        mjson_export_to_hdf(lses->city, MJSON_EXPORT_NONE, NULL, false);
    }

    /*
     * browser
     */
    HDF_FETCH_STR(cgi->hdf, PRE_HTTP".UserAgent", s);
    if (s) {
        mstr_repchr(s, ' ', '\0');
        for (int i = 0; i < m_browsers_size; i++) {
            if (!strncasecmp(s, m_browsers[i], strlen(m_browsers[i]))) {
                lses->browser = i;
                break;
            }
        }
        s = strchr(s, '/');
        if (s) lses->bversion = strtof(s+1, NULL);
    }

    /*
     * reqtype
     */
    lses->reqtype = CGI_REQ_HTML;
    char *uri = hdf_get_value(cgi->hdf, PRE_REQ_URI_RW, NULL);
    if (!uri) {
        uri = "terminal";
        lses->reqtype = CGI_REQ_TERMINAL;
    }
    mstr_repchr(uri, '/', '_');
    uri = mstr_strip(uri, '_');
    if (!strncmp(uri, "json_", 5)) {
        uri = uri+5;
        lses->reqtype = CGI_REQ_AJAX;
    } else if (!strncmp(uri, "image_", 6)) {
        uri = uri+6;
        lses->reqtype = CGI_REQ_IMAGE;
    }

    /*
     * dataer, render
     */
    switch (http_req_method(cgi)) {
        case CGI_REQ_POST:
            snprintf(tok, sizeof(tok), "%s_data_mod", uri);
            break;
        case CGI_REQ_PUT:
            snprintf(tok, sizeof(tok), "%s_data_add", uri);
            break;
        case CGI_REQ_DEL:
            snprintf(tok, sizeof(tok), "%s_data_del", uri);
            break;
        default:
        case CGI_REQ_GET:
            snprintf(tok, sizeof(tok), "%s_data_get", uri);
            break;
    }
    lses->dataer = strdup(tok);
    lses->render = strdup(uri);

    /*
     * tm_cache_browser
     */
    node = hdf_get_obj(g_cfg, PRE_CFG_FILECACHE".0");
    while (node != NULL) {
        if (reg_search(hdf_get_value(node, "uri", "NULL"), uri)) {
            lses->tm_cache_browser = hdf_get_int_value(node, "tm_cache", 0);
            break;
        }
        node = hdf_obj_next(node);
    }

    /*
     * DONE
     */
    *ses = lses;
    
    return STATUS_OK;
}
Exemplo n.º 12
0
//// ini_get_var() ////
void* ini_get_var(const ini_cfg_t* cfg, int cur_section, char* buf)
{
  int i=0, j=0;
  int var_id = -1;

  // find var
  while(1) {
    if (buf[i] == '=') {
      buf[i] = '\0';
      break;
    } else if (buf[i] == '\0') return (void*)0;
    i++;
  }

  // convert to uppercase
  for (j=0; j<=i; j++) {
    if (!buf[j]) break;
    else buf[j] = CHAR_TO_UPPERCASE(buf[j]);
  }

  // parse var
  for (j=0; j<cfg->nvars; j++) {
    if ((!strcmp(buf, cfg->vars[j].name)) && (cfg->vars[j].section_id == cur_section)) var_id = j;
  }

  // get data
  if (var_id != -1) {
    ini_parser_debugf("Got VAR '%s' with VALUE %s", buf, &(buf[i+1]));
    i++;
    switch (cfg->vars[var_id].type) {
      case UINT8:
        *(uint8_t*)(cfg->vars[var_id].var) = strtoul(&(buf[i]), NULL, 0);
        if (*(uint8_t*)(cfg->vars[var_id].var) > cfg->vars[var_id].max) *(uint8_t*)(cfg->vars[var_id].var) = cfg->vars[var_id].max;
        if (*(uint8_t*)(cfg->vars[var_id].var) < cfg->vars[var_id].min) *(uint8_t*)(cfg->vars[var_id].var) = cfg->vars[var_id].min;
        break;
      case INT8:
        *(int8_t*)(cfg->vars[var_id].var) = strtol(&(buf[i]), NULL, 0);
        if (*(int8_t*)(cfg->vars[var_id].var) > cfg->vars[var_id].max) *(int8_t*)(cfg->vars[var_id].var) = cfg->vars[var_id].max;
        if (*(int8_t*)(cfg->vars[var_id].var) < cfg->vars[var_id].min) *(int8_t*)(cfg->vars[var_id].var) = cfg->vars[var_id].min;
        break;
      case UINT16:
        *(uint8_t*)(cfg->vars[var_id].var) = strtoul(&(buf[i]), NULL, 0);
        if (*(uint16_t*)(cfg->vars[var_id].var) > cfg->vars[var_id].max) *(uint16_t*)(cfg->vars[var_id].var) = cfg->vars[var_id].max;
        if (*(uint16_t*)(cfg->vars[var_id].var) < cfg->vars[var_id].min) *(uint16_t*)(cfg->vars[var_id].var) = cfg->vars[var_id].min;
        break;
      case INT16:
        *(int16_t*)(cfg->vars[var_id].var) = strtol(&(buf[i]), NULL, 0);
        if (*(int16_t*)(cfg->vars[var_id].var) > cfg->vars[var_id].max) *(int16_t*)(cfg->vars[var_id].var) = cfg->vars[var_id].max;
        if (*(int16_t*)(cfg->vars[var_id].var) < cfg->vars[var_id].min) *(int16_t*)(cfg->vars[var_id].var) = cfg->vars[var_id].min;
        break;
      case UINT32:
        *(uint8_t*)(cfg->vars[var_id].var) = strtoul(&(buf[i]), NULL, 0);
        if (*(uint32_t*)(cfg->vars[var_id].var) > cfg->vars[var_id].max) *(uint32_t*)(cfg->vars[var_id].var) = cfg->vars[var_id].max;
        if (*(uint32_t*)(cfg->vars[var_id].var) < cfg->vars[var_id].min) *(uint32_t*)(cfg->vars[var_id].var) = cfg->vars[var_id].min;
        break;
      case INT32:
        *(int32_t*)(cfg->vars[var_id].var) = strtol(&(buf[i]), NULL, 0);
        if (*(int32_t*)(cfg->vars[var_id].var) > cfg->vars[var_id].max) *(int32_t*)(cfg->vars[var_id].var) = cfg->vars[var_id].max;
        if (*(int32_t*)(cfg->vars[var_id].var) < cfg->vars[var_id].min) *(int32_t*)(cfg->vars[var_id].var) = cfg->vars[var_id].min;
        break;
#ifdef INI_ENABLE_FLOAT
      case FLOAT:
        *(float*)(cfg->vars[var_id].var) = strtof(&(buf[i]), NULL);
        if (*(float*)(cfg->vars[var_id].var) > cfg->vars[var_id].max) *(float*)(cfg->vars[var_id].var) = cfg->vars[var_id].max;
        if (*(float*)(cfg->vars[var_id].var) < cfg->vars[var_id].min) *(float*)(cfg->vars[var_id].var) = cfg->vars[var_id].min;
        break;
#endif
      case STRING:
        strncpy((char*)(cfg->vars[var_id].var), &(buf[i]), cfg->vars[var_id].max);
        break;
      case CUSTOM_HANDLER:
        ((custom_handler_t*)(cfg->vars[var_id].var))(&(buf[i]));
	break;
    }
    return (void*)(&(cfg->vars[var_id].var));
  }

  return (void*)0;
}
Exemplo n.º 13
0
static int
test (const char str[])
{
  char *endp;
  int result = 0;

  puts (str);

  double d = strtod (str, &endp);
  if (!isnan (d))
    {
      puts ("strtod did not return NAN");
      result = 1;
    }
  if (issignaling (d))
    {
      puts ("strtod returned a sNAN");
      result = 1;
    }
  if (strcmp (endp, "something") != 0)
    {
      puts  ("strtod set incorrect end pointer");
      result = 1;
    }

  float f = strtof (str, &endp);
  if (!isnanf (f))
    {
      puts ("strtof did not return NAN");
      result = 1;
    }
  if (issignaling (f))
    {
      puts ("strtof returned a sNAN");
      result = 1;
    }
  if (strcmp (endp, "something") != 0)
    {
      puts  ("strtof set incorrect end pointer");
      result = 1;
    }

  long double ld = strtold (str, &endp);
  if (!isnan (ld))
    {
      puts ("strtold did not return NAN");
      result = 1;
    }
  if (issignaling (ld))
    {
      puts ("strtold returned a sNAN");
      result = 1;
    }
  if (strcmp (endp, "something") != 0)
    {
      puts  ("strtold set incorrect end pointer");
      result = 1;
    }

  return result;
}
Exemplo n.º 14
0
TEST(stdlib, strtof) {
  ASSERT_FLOAT_EQ(1.23, strtof("1.23", NULL));
}
Exemplo n.º 15
0
bool BootAnimation::movie()
{

    char bootenabled[PROPERTY_VALUE_MAX];
    char bootsound[PROPERTY_VALUE_MAX];
    char bootvolume[PROPERTY_VALUE_MAX];
    property_get("persist.sys.boot_enabled", bootenabled, "1");
    property_get("persist.sys.boot_sound", bootsound, "1");
    property_get("persist.sys.boot_volume", bootvolume, "0.2");

    bool bootEnabled = atoi(bootenabled) != 0;
    bool enableSound = atoi(bootsound) != 0;
    float bootVolume = strtof(bootvolume, NULL);

    if(!bootEnabled) {
        return false;
    }

    if(enableSound){
      sp<MediaPlayer> mediaplay = new MediaPlayer();
      mediaplay->setDataSource ("/system/media/audio.mp3", NULL);
      mediaplay->setVolume (bootVolume, bootVolume);
      mediaplay->prepare();
      mediaplay->start();
    }

    ZipFileRO& zip(mZip);

    size_t numEntries = zip.getNumEntries();
    ZipEntryRO desc = zip.findEntryByName("desc.txt");
    FileMap* descMap = zip.createEntryFileMap(desc);
    ALOGE_IF(!descMap, "descMap is null");
    if (!descMap) {
        return false;
    }

    String8 desString((char const*)descMap->getDataPtr(),
            descMap->getDataLength());
    char const* s = desString.string();

    Animation animation;

    float r = 0.0f;
    float g = 0.0f;
    float b = 0.0f;

    // Parse the description file
    for (;;) {
        const char* endl = strstr(s, "\n");
        if (!endl) break;
        String8 line(s, endl - s);
        const char* l = line.string();
        int fps, width, height, count, pause, red, green, blue;
        char path[256];
        char pathType;
        if (sscanf(l, "%d %d %d %d %d %d", &width, &height, &fps, &red, &green, &blue) == 6) {
            //ALOGD("> w=%d, h=%d, fps=%d, rgb=(%d, %d, %d)", width, height, fps, red, green, blue);
            animation.width = width;
            animation.height = height;
            animation.fps = fps;
            r = (float) red / 255.0f;
            g = (float) green / 255.0f;
            b = (float) blue / 255.0f;
        }
        else if (sscanf(l, "%d %d %d", &width, &height, &fps) == 3) {
            //LOGD("> w=%d, h=%d, fps=%d", width, height, fps);
            animation.width = width;
            animation.height = height;
            animation.fps = fps;
        }
        else if (sscanf(l, " %c %d %d %s", &pathType, &count, &pause, path) == 4) {
            //LOGD("> type=%c, count=%d, pause=%d, path=%s", pathType, count, pause, path);
            Animation::Part part;
            part.playUntilComplete = pathType == 'c';
            part.count = count;
            part.pause = pause;
            part.path = path;
            animation.parts.add(part);
        }

        s = ++endl;
    }

    // read all the data structures
    const size_t pcount = animation.parts.size();
    for (size_t i=0 ; i<numEntries ; i++) {
        char name[256];
        ZipEntryRO entry = zip.findEntryByIndex(i);
        if (zip.getEntryFileName(entry, name, 256) == 0) {
            const String8 entryName(name);
            const String8 path(entryName.getPathDir());
            const String8 leaf(entryName.getPathLeaf());
            if (leaf.size() > 0) {
                for (size_t j=0 ; j<pcount ; j++) {
                    if (path == animation.parts[j].path) {
                        int method;
                        // supports only stored png files
                        if (zip.getEntryInfo(entry, &method, 0, 0, 0, 0, 0)) {
                            if (method == ZipFileRO::kCompressStored) {
                                FileMap* map = zip.createEntryFileMap(entry);
                                if (map) {
                                    Animation::Frame frame;
                                    frame.name = leaf;
                                    frame.map = map;
                                    Animation::Part& part(animation.parts.editItemAt(j));
                                    part.frames.add(frame);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

#ifndef CONTINUOUS_SPLASH
    // clear screen
    glShadeModel(GL_FLAT);
    glDisable(GL_DITHER);
    glDisable(GL_SCISSOR_TEST);
    glDisable(GL_BLEND);
    glClearColor(r,g,b,1);
    glClear(GL_COLOR_BUFFER_BIT);

    eglSwapBuffers(mDisplay, mSurface);
#endif

    glBindTexture(GL_TEXTURE_2D, 0);
    glEnable(GL_TEXTURE_2D);
    glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    const int xc = (mWidth - animation.width) / 2;
    const int yc = ((mHeight - animation.height) / 2);
    nsecs_t lastFrame = systemTime();
    nsecs_t frameDuration = s2ns(1) / animation.fps;

    Region clearReg(Rect(mWidth, mHeight));
    clearReg.subtractSelf(Rect(xc, yc, xc+animation.width, yc+animation.height));

    for (int i=0 ; i<pcount ; i++) {
        const Animation::Part& part(animation.parts[i]);
        const size_t fcount = part.frames.size();

        // can be 1, 0, or not set
        #ifdef NO_TEXTURE_CACHE
        const int noTextureCache = NO_TEXTURE_CACHE;
        #else
        const int noTextureCache = ((animation.width * animation.height * fcount) >
                                 48 * 1024 * 1024) ? 1 : 0;
        #endif

        glBindTexture(GL_TEXTURE_2D, 0);

        for (int r=0 ; !part.count || r<part.count ; r++) {
            // Exit any non playuntil complete parts immediately
            if(exitPending() && !part.playUntilComplete)
                break;

            for (int j=0 ; j<fcount && (!exitPending() || part.playUntilComplete) ; j++) {
                const Animation::Frame& frame(part.frames[j]);
                nsecs_t lastFrame = systemTime();

                if (r > 0 && !noTextureCache) {
                    glBindTexture(GL_TEXTURE_2D, frame.tid);
                } else {
                    if (part.count != 1) {
                        glGenTextures(1, &frame.tid);
                        glBindTexture(GL_TEXTURE_2D, frame.tid);
                        glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
                        glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
                    }
                    initTexture(
                            frame.map->getDataPtr(),
                            frame.map->getDataLength());
                }

                if (!clearReg.isEmpty()) {
                    Region::const_iterator head(clearReg.begin());
                    Region::const_iterator tail(clearReg.end());
                    glEnable(GL_SCISSOR_TEST);
                    while (head != tail) {
                        const Rect& r(*head++);
                        glScissor(r.left, mHeight - r.bottom,
                                r.width(), r.height());
                        glClear(GL_COLOR_BUFFER_BIT);
                    }
                    glDisable(GL_SCISSOR_TEST);
                }
                glDrawTexiOES(xc, yc, 0, animation.width, animation.height);
                eglSwapBuffers(mDisplay, mSurface);

                nsecs_t now = systemTime();
                nsecs_t delay = frameDuration - (now - lastFrame);
                //ALOGD("%lld, %lld", ns2ms(now - lastFrame), ns2ms(delay));
                lastFrame = now;

                if (delay > 0) {
                    struct timespec spec;
                    spec.tv_sec  = (now + delay) / 1000000000;
                    spec.tv_nsec = (now + delay) % 1000000000;
                    int err;
                    do {
                        err = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &spec, NULL);
                    } while (err<0 && errno == EINTR);
                }

                checkExit();

                if (noTextureCache)
                    glDeleteTextures(1, &frame.tid);
            }

            usleep(part.pause * ns2us(frameDuration));

            // For infinite parts, we've now played them at least once, so perhaps exit
            if(exitPending() && !part.count)
                break;
        }

        // free the textures for this part
        if (part.count != 1 && !noTextureCache) {
            for (size_t j=0 ; j<fcount ; j++) {
                const Animation::Frame& frame(part.frames[j]);
                glDeleteTextures(1, &frame.tid);
            }
        }
    }

    return false;
}
Exemplo n.º 16
0
static void
float_reply (rr_dev dev, char **i, rr_reply type)
{
  if (dev->reply_cb)
    dev->reply_cb (dev, type, strtof (*i + 2, i), NULL, dev->reply_cl);
}
Exemplo n.º 17
0
void XModel_LoadXModelFromFile( const char *filename, XModel **model )
{
	// --------------- read contents of file
	char *contents;
	unsigned int contentLength = XML_ReadFile( filename, &contents );
	assert( contentLength > 0 );

	XML_TokenList *tokenList = XML_Tokenize( contents, contentLength );

	free( contents );

	XML_Element *root = XML_Parse( tokenList );

	delete tokenList;

	// ---------------- transfer xml elements into xmodel
	assert( strcmp( root->data, "xmodel" ) == 0 );
	XModel *newModel = new XModel();

	XML_ElementAttribute *attributeIterator = root->attributes;
	while ( attributeIterator != NULL )
	{
		if ( strcmp( attributeIterator->key, "vs" ) == 0 )
		{
			size_t len = strlen( attributeIterator->value ) + 1;
			newModel->vertexShaderPath = ( wchar_t * ) malloc( sizeof( wchar_t ) * len );
			MultiByteToWideChar( 0, 0, attributeIterator->value, -1, newModel->vertexShaderPath, len );
		}
		else if ( strcmp( attributeIterator->key, "ps" ) == 0 )
		{
			size_t len = strlen( attributeIterator->value ) + 1;
			newModel->pixelShaderPath = ( wchar_t * ) malloc( sizeof( wchar_t ) * len );
			MultiByteToWideChar( 0, 0, attributeIterator->value, -1, newModel->pixelShaderPath, len );
		}
		attributeIterator = attributeIterator->next;
	}

	XML_Element *xmodelChildIterator = root->child;
	while ( xmodelChildIterator != NULL )
	{
		if ( strcmp( xmodelChildIterator->data, "vertices" ) == 0 )
		{
			unsigned int vertexCount = 0;
			XML_ElementAttribute *vertexAttributeIterator = xmodelChildIterator->attributes;
			while ( vertexAttributeIterator != NULL )
			{
				if ( strcmp( vertexAttributeIterator->key, "count" ) == 0 )
				{
					vertexCount = atoi( vertexAttributeIterator->value );
				}
				vertexAttributeIterator = vertexAttributeIterator->next;
			}

			assert( vertexCount > 0 );

			const char *vertexStringIterator = ( char * ) xmodelChildIterator->child->data;

			newModel->vertices = new XVertex[vertexCount];
			newModel->vertexCount = vertexCount;
			for ( unsigned int i = 0; i < vertexCount; i++ )
			{
				char floatStringBuffer[256];
				unsigned int bufferIndex = 0;
				float x, y, z;

				char *error;

				assert( *vertexStringIterator == '(' );
				vertexStringIterator++;
				while ( *vertexStringIterator != ',' )
				{
					floatStringBuffer[bufferIndex++] = *vertexStringIterator;
					vertexStringIterator++;
				}
				vertexStringIterator++;
				floatStringBuffer[bufferIndex++] = '\0';
				bufferIndex = 0;
				x = strtof( floatStringBuffer, &error );

				while ( *vertexStringIterator != ',' )
				{
					floatStringBuffer[bufferIndex++] = *vertexStringIterator;
					vertexStringIterator++;
				}
				vertexStringIterator++;
				floatStringBuffer[bufferIndex++] = '\0';
				bufferIndex = 0;
				y = strtof( floatStringBuffer, &error );

				while ( *vertexStringIterator != ')' )
				{
					floatStringBuffer[bufferIndex++] = *vertexStringIterator;
					vertexStringIterator++;
				}
				floatStringBuffer[bufferIndex++] = '\0';
				bufferIndex = 0;
				z = strtof( floatStringBuffer, &error );

				newModel->vertices[i].position = XMFLOAT3( x, y, z );

				assert( *vertexStringIterator == ')' );
				vertexStringIterator++;
				if ( i != vertexCount - 1 )
				{
					assert( *vertexStringIterator == ',' );
					vertexStringIterator++;
				}
			}
		}
		else if ( strcmp( xmodelChildIterator->data, "indices" ) == 0 )
		{
			unsigned int indexCount = 0;
			XML_ElementAttribute *indexAttributeIterator = xmodelChildIterator->attributes;
			while ( indexAttributeIterator != NULL )
			{
				if ( strcmp( indexAttributeIterator->key, "count" ) == 0 )
				{
					indexCount = atoi( indexAttributeIterator->value );
				}
				indexAttributeIterator = indexAttributeIterator->next;
			}

			newModel->indices = new WORD[indexCount];
			newModel->indexCount = indexCount;
			char *indexStringIterator = ( char * ) xmodelChildIterator->child->data;
			for ( unsigned int i = 0; i < indexCount; i++ )
			{
				char intStringBuffer[512];
				unsigned int intStringBufferIndex = 0;

				while ( *indexStringIterator != ',' && *indexStringIterator != '\0' )
				{
					intStringBuffer[intStringBufferIndex++] = *indexStringIterator;
					indexStringIterator++;
				}

				assert( intStringBufferIndex > 0 );
				assert( ( i < indexCount - 1 && *indexStringIterator == ',' ) || ( *indexStringIterator == '\0' ) );
				indexStringIterator++;

				newModel->indices[i] = atoi( intStringBuffer );
			}
		}
		xmodelChildIterator = xmodelChildIterator->sibling;
	}

	assert( newModel->vertexShaderPath != NULL );
	assert( newModel->pixelShaderPath != NULL );

	*model = newModel;

	// ------------ free TODO
	//XML_Element_Free(&root);
}
Exemplo n.º 18
0
gk_graph_t *gk_graph_Read(char *filename, int format, int isfewgts, 
                int isfvwgts, int isfvsizes)
{
  ssize_t i, k, l;
  size_t nfields, nvtxs, nedges, fmt, ncon, lnlen;
  int32_t ival;
  float fval;
  int readsizes=0, readwgts=0, readvals=0, numbering=0;
  char *line=NULL, *head, *tail, fmtstr[256];
  FILE *fpin=NULL;
  gk_graph_t *graph=NULL;


  if (!gk_fexists(filename)) 
    gk_errexit(SIGERR, "File %s does not exist!\n", filename);

  if (format == GK_GRAPH_FMT_METIS) {
    fpin = gk_fopen(filename, "r", "gk_graph_Read: fpin");
    do {
      if (gk_getline(&line, &lnlen, fpin) <= 0)
        gk_errexit(SIGERR, "Premature end of input file: file:%s\n", filename);
    } while (line[0] == '%');

    fmt = ncon = 0;
    nfields = sscanf(line, "%zu %zu %zu %zu", &nvtxs, &nedges, &fmt, &ncon);
    if (nfields < 2)
      gk_errexit(SIGERR, "Header line must contain at least 2 integers (#vtxs and #edges).\n");

    nedges *= 2;

    if (fmt > 111)
      gk_errexit(SIGERR, "Cannot read this type of file format [fmt=%zu]!\n", fmt);

    sprintf(fmtstr, "%03zu", fmt%1000);
    readsizes = (fmtstr[0] == '1');
    readwgts  = (fmtstr[1] == '1');
    readvals  = (fmtstr[2] == '1');
    numbering = 1;
    ncon      = (ncon == 0 ? 1 : ncon);
  }
  else {
    gk_errexit(SIGERR, "Unrecognized format: %d\n", format);
  }

  graph = gk_graph_Create();

  graph->nvtxs = nvtxs;

  graph->xadj   = gk_zmalloc(nvtxs+1, "gk_graph_Read: xadj");
  graph->adjncy = gk_i32malloc(nedges, "gk_graph_Read: adjncy");
  if (readvals) {
    if (isfewgts)
      graph->fadjwgt = gk_fmalloc(nedges, "gk_graph_Read: fadjwgt");
    else
      graph->iadjwgt = gk_i32malloc(nedges, "gk_graph_Read: iadjwgt");
  }

  if (readsizes) {
    if (isfvsizes)
      graph->fvsizes = gk_fmalloc(nvtxs, "gk_graph_Read: fvsizes");
    else
      graph->ivsizes = gk_i32malloc(nvtxs, "gk_graph_Read: ivsizes");
  }

  if (readwgts) {
    if (isfvwgts)
      graph->fvwgts = gk_fmalloc(nvtxs*ncon, "gk_graph_Read: fvwgts");
    else
      graph->ivwgts = gk_i32malloc(nvtxs*ncon, "gk_graph_Read: ivwgts");
  }


  /*----------------------------------------------------------------------
   * Read the sparse graph file
   *---------------------------------------------------------------------*/
  numbering = (numbering ? - 1 : 0);
  for (graph->xadj[0]=0, k=0, i=0; i<nvtxs; i++) {
    do {
      if (gk_getline(&line, &lnlen, fpin) == -1)
        gk_errexit(SIGERR, "Pregraphure end of input file: file while reading row %d\n", i);
    } while (line[0] == '%');

    head = line;
    tail = NULL;

    /* Read vertex sizes */
    if (readsizes) {
      if (isfvsizes) {
#ifdef __MSC__
        graph->fvsizes[i] = (float)strtod(head, &tail);
#else
        graph->fvsizes[i] = strtof(head, &tail);
#endif
        if (tail == head)
          gk_errexit(SIGERR, "The line for vertex %zd does not have size information\n", i+1);
        if (graph->fvsizes[i] < 0)
          gk_errexit(SIGERR, "The size for vertex %zd must be >= 0\n", i+1);
      }
      else {
        graph->ivsizes[i] = strtol(head, &tail, 0);
        if (tail == head)
          gk_errexit(SIGERR, "The line for vertex %zd does not have size information\n", i+1);
        if (graph->ivsizes[i] < 0)
          gk_errexit(SIGERR, "The size for vertex %zd must be >= 0\n", i+1);
      }
      head = tail;
    }

    /* Read vertex weights */
    if (readwgts) {
      for (l=0; l<ncon; l++) {
        if (isfvwgts) {
#ifdef __MSC__
          graph->fvwgts[i*ncon+l] = (float)strtod(head, &tail);
#else
          graph->fvwgts[i*ncon+l] = strtof(head, &tail);
#endif
          if (tail == head)
            gk_errexit(SIGERR, "The line for vertex %zd does not have enough weights "
                    "for the %d constraints.\n", i+1, ncon);
          if (graph->fvwgts[i*ncon+l] < 0)
            gk_errexit(SIGERR, "The weight vertex %zd and constraint %zd must be >= 0\n", i+1, l);
        }
        else {
          graph->ivwgts[i*ncon+l] = strtol(head, &tail, 0);
          if (tail == head)
            gk_errexit(SIGERR, "The line for vertex %zd does not have enough weights "
                    "for the %d constraints.\n", i+1, ncon);
          if (graph->ivwgts[i*ncon+l] < 0)
            gk_errexit(SIGERR, "The weight vertex %zd and constraint %zd must be >= 0\n", i+1, l);
        }
        head = tail;
      }
    }

   
    /* Read the rest of the row */
    while (1) {
      ival = (int)strtol(head, &tail, 0);
      if (tail == head) 
        break;
      head = tail;
      
      if ((graph->adjncy[k] = ival + numbering) < 0)
        gk_errexit(SIGERR, "Error: Invalid column number %d at row %zd.\n", ival, i);

      if (readvals) {
        if (isfewgts) {
#ifdef __MSC__
          fval = (float)strtod(head, &tail);
#else
    	  fval = strtof(head, &tail);
#endif
          if (tail == head)
            gk_errexit(SIGERR, "Value could not be found for edge! Vertex:%zd, NNZ:%zd\n", i, k);

          graph->fadjwgt[k] = fval;
        }
        else {
    	  ival = strtol(head, &tail, 0);
          if (tail == head)
            gk_errexit(SIGERR, "Value could not be found for edge! Vertex:%zd, NNZ:%zd\n", i, k);

          graph->iadjwgt[k] = ival;
        }
        head = tail;
      }
      k++;
    }
    graph->xadj[i+1] = k;
  }

  if (k != nedges)
    gk_errexit(SIGERR, "gk_graph_Read: Something wrong with the number of edges in "
                       "the input file. nedges=%zd, Actualnedges=%zd.\n", nedges, k);

  gk_fclose(fpin);

  gk_free((void **)&line, LTERM);

  return graph;
}
Exemplo n.º 19
0
int main(int argc, char* argv[])
{
    if (argc != 2) {
        std::cout << "Proper usage ./prog numThreads" << std::endl;
        return 1;
    }
    int numThreads = strtof(argv[1], NULL);
    for(int i=1; i<m-1; i++) {
        for (int j = 1; j < n-1; j++) {
            Un[i][j]=0.0;
        }

    }

    for (int i = 0; i < m; i++) {
        Un[i][0] = exactSolution(x(i), y(0));
        Un[i][n -1] = exactSolution(x(i), y(n - 1));
        Unp1[i][0] = exactSolution(x(i), y(0));
        Unp1[i][n -1] = exactSolution(x(i), y(n - 1));
    }
    for (int i = 0; i < n; i++) {
        Un[0][i] = exactSolution(x(0), y(i));
        Un[m - 1][i] = exactSolution(x(m-1), y(i));
        Unp1[0][i] = exactSolution(x(0), y(i));
        Unp1[m - 1][i] = exactSolution(x(m-1), y(i));
    }
    int iterations=0;
    double iterationError = 1.;
    double time = omp_get_wtime();
    while(iterationError > tolerance && iterations < maxIterations) {
        iterations++; //
        // if(iterations % 1000 == 0) std::cout<<"iteration " << iterations << std::endl;
        #pragma omp parallel for num_threads(numThreads)
        for(int i=1; i< m-1; i++) {
            for (int j = 1; j < n -1; j++) {

                Unp1[i][j] = (dy*dy*dx*dx*S(x(i), y(j)) - \
                              dy*dy*(Un[i -1][j] + Un[i + 1][j]) - \
                              dx*dx*(Un[i][j -1] + Un[i][j+1])) / (-2*dy*dy - 2*dx*dx);
            }
        }
        iterationError=0.0;
        // Calculate diff between Un, Up+1
        #pragma omp parallel for num_threads(numThreads)
        for(int i = 0; i< m; i++) {
            for (int j = 0; j < n; j++) {
                error[i][j] = fabs(Unp1[i][j] - Un[i][j]);

            }
        }
        for (int i = 0; i<m; i++)
            for (int j = 0; j <n; j++)
                iterationError = (iterationError > error[i][j] ? iterationError : error[i][j]);



// Testing revealed it was faster to *NOT* parallelize this loop.
        for(int i=0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                Un[i][j] = Unp1[i][j];
            }
        }

        // if(iterations % 1000 == 0) std::cout<< "The error between two iterates is " << iterationError << std::endl;
    }

    double time2 = omp_get_wtime();

    double solution_error=0.0;
    for(int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            double local_solution_error=fabs(Unp1[i][j]- exactSolution(x(i), y(j)) );
            {
                if (local_solution_error > solution_error)
                    solution_error = local_solution_error;
            }
        }
    }


    // Output:
    std::cout                                                              << std::endl << std::endl;
    std::cout<< "-------------------------------------------------------"               << std::endl;
    std::cout<< "SUMMARY:"                                                 << std::endl << std::endl;
    std::cout<< "The error between two iterates is "    << iterationError << std::endl << std::endl;
    std::cout<< "The maximum error in the solution is " << solution_error               << std::endl;
    std::cout<< "The time taken is " << time2 - time << std::endl;
    std::cout<< "-------------------------------------------------------"  << std::endl << std::endl;
    return 0;
}
float t19(char **x) { return strtof("123.4", x); }
  //------------------------------------------------------------------------------
  node_alignment_analyzer::node_alignment_analyzer(const osm_diff_analyzer_if::module_configuration * p_conf,
                                                   node_alignment_common_api & p_api):
    osm_diff_analyzer_cpp_if::cpp_analyzer_base("node_alignment_analyser",p_conf->get_name(),""),
    m_api(p_api),
    m_report()
  {
     // Register module to be able to use User Interface
    m_api.ui_register_module(*this,get_name());

   const std::map<std::string,std::string> & l_conf_parameters = p_conf->get_parameters();

    std::map<std::string,std::string>::const_iterator l_iter = l_conf_parameters.find("min_way_node_nb");
    if(l_iter == l_conf_parameters.end())
    {
      {
	std::stringstream l_stream;
	l_stream << this->get_name() << " : Using default value for parameter \"min_way_node_nb\" : " << changeset::get_min_way_node_nb() ;
	m_api.ui_append_log_text(*this,l_stream.str());
      }
    }
    else
      {
	float l_min_way_node_nb = strtof(l_iter->second.c_str(),NULL);

	{
	  std::stringstream l_stream;
	  l_stream << this->get_name() << " : Using value " << l_min_way_node_nb << " for parameter \"min_way_node_nb\"" ;
	  m_api.ui_append_log_text(*this,l_stream.str());
	}
	changeset::set_min_way_node_nb(l_min_way_node_nb);
      }
    l_iter = l_conf_parameters.find("modif_rate_min_level");
    if(l_iter == l_conf_parameters.end())
    {
      std::stringstream l_stream;
      l_stream << this->get_name() << " : Using default value for parameter \"modif_rate_min_level\" : " << changeset::get_modif_rate_min_level();
      m_api.ui_append_log_text(*this,l_stream.str());
    }
    else
      {
	float l_modif_rate_min_level = strtof(l_iter->second.c_str(),NULL);
	std::stringstream l_stream;
	l_stream << this->get_name() << " : Using value " << l_modif_rate_min_level << " for parameter \"modif_rate_min_level\"" ;
	m_api.ui_append_log_text(*this,l_stream.str());
	changeset::set_modif_rate_min_level(l_modif_rate_min_level);
      }

    l_iter = l_conf_parameters.find("min_alignment_modification_rate");
    if(l_iter == l_conf_parameters.end())
    {
	std::stringstream l_stream;
	l_stream << this->get_name() << " : Using default value for parameter \"min_alignment_modification_rate\" : " << changeset::get_min_alignment_modification_rate();
	m_api.ui_append_log_text(*this,l_stream.str());	
    }
    else
      {
	float l_min_alignment_modification_rate = strtof(l_iter->second.c_str(),NULL);
	std::stringstream l_stream;
	l_stream << this->get_name() << " : Using value " << l_min_alignment_modification_rate << " for parameter \"min_alignment_modification_rate\"" ;
	m_api.ui_append_log_text(*this,l_stream.str());
	changeset::set_min_alignment_modification_rate(l_min_alignment_modification_rate);
      }

    changeset::set_api(m_api);

  }
Exemplo n.º 22
0
int
main(int argc, char *argv[])
{
	char buf[128];
	long double ld = 0.0;
	double d = 0.0;
	float f = 0.0;
	char *endp;

	printf("1..4\n");

	buf[0] = '\0';
	assert(setlocale(LC_NUMERIC, ""));

	/*
	 * Various tests for normalized numbers
	 */
	sscanf("3.141592", "%e", &f);
	assert(eq(FLT, f, 3.141592));

	sscanf("3.141592653589793", "%lf", &d);
	assert(eq(DBL, d, 3.141592653589793));

	sscanf("1.234568e+06", "%E", &f);
	assert(eq(FLT, f, 1.234568e+06));

	sscanf("-1.234568e6", "%lF", &d);
	assert(eq(DBL, d, -1.234568e6));

	sscanf("+1.234568e-52", "%LG", &ld);
	assert(eq(LDBL, ld, 1.234568e-52L));

	sscanf("0.1", "%la", &d);
	assert(eq(DBL, d, 0.1));

	sscanf("00.2", "%lA", &d);
	assert(eq(DBL, d, 0.2));

	sscanf("123456", "%5le%s", &d, buf);
	assert(eq(DBL, d, 12345.));
	assert(strcmp(buf, "6") == 0);

	sscanf("1.0Q", "%*5le%s", buf);
	assert(strcmp(buf, "Q") == 0);

	sscanf("-1.23e", "%e%s", &f, buf);
	assert(eq(FLT, f, -1.23));
	assert(strcmp(buf, "e") == 0);

	sscanf("1.25e+", "%le%s", &d, buf);
	assert(eq(DBL, d, 1.25));
	assert(strcmp(buf, "e+") == 0);

	sscanf("1.23E4E5", "%le%s", &d, buf);
	assert(eq(DBL, d, 1.23e4));
	assert(strcmp(buf, "E5") == 0);

	sscanf("12e6", "%le", &d);
	assert(eq(DBL, d, 12e6));

	sscanf("1.a", "%le%s", &d, buf);
	assert(eq(DBL, d, 1.0));
	assert(strcmp(buf, "a") == 0);

	sscanf(".0p4", "%le%s", &d, buf);
	assert(eq(DBL, d, 0.0));
	assert(strcmp(buf, "p4") == 0);

	d = 0.25;
	assert(sscanf(".", "%le", &d) == 0);
	assert(d == 0.25);

	sscanf("0x08", "%le", &d);
	assert(d == 0x8p0);

	sscanf("0x90a.bcdefP+09a", "%le%s", &d, buf);
	assert(d == 0x90a.bcdefp+09);
	assert(strcmp(buf, "a") == 0);

#if (LDBL_MANT_DIG > DBL_MANT_DIG) && !defined(__i386__)
	sscanf("3.14159265358979323846", "%Lg", &ld);
	assert(eq(LDBL, ld, 3.14159265358979323846L));

	sscanf("  0X.0123456789abcdefffp-3g", "%Le%s", &ld, buf);
	assert(ld == 0x0.0123456789abcdefffp-3L);
	assert(strcmp(buf, "g") == 0);
#endif

	sscanf("0xg", "%le%s", &d, buf);
	assert(d == 0.0);
	assert(strcmp(buf, "xg") == 0);

	assert(setlocale(LC_NUMERIC, "ru_RU.ISO8859-5")); /* decimalpoint==, */

	sscanf("1.23", "%le%s", &d, buf);
	assert(d == 1.0);
	assert(strcmp(buf, ".23") == 0);

	sscanf("1,23", "%le", &d);
	assert(d == 1.23);

	assert(setlocale(LC_NUMERIC, ""));

	printf("ok 1 - scanfloat\n");

	/*
	 * Infinity and NaN tests
	 */
	sscanf("-Inf", "%le", &d);
	assert(d < 0.0 && isinf(d));

	sscanf("iNfInItY and beyond", "%le%s", &d, buf);
	assert(d > 0.0 && isinf(d));
	assert(strcmp(buf, " and beyond"));

	sscanf("NaN", "%le", &d);
	assert(isnan(d));

	sscanf("NAN(123Y", "%le%s", &d, buf);
	assert(isnan(d));
	assert(strcmp(buf, "(123Y") == 0);

	sscanf("nan(f00f)plugh", "%le%s", &d, buf);
	assert(isnan(d));
	assert(strcmp(buf, "plugh") == 0);

	sscanf("-nan", "%le", &d);
	assert(isnan(d));

	/* Only quiet NaNs should be returned. */
	sscanf("NaN", "%e", &f);
	sscanf("nan", "%le", &d);
	sscanf("nan", "%Le", &ld);
	feclearexcept(FE_ALL_EXCEPT);
	assert(f != f);
	assert(d != d);
	assert(ld != ld);
	assert(fetestexcept(FE_INVALID) == 0);
	sscanf("nan(1234)", "%e", &f);
	sscanf("nan(1234)", "%le", &d);
	sscanf("nan(1234)", "%Le", &ld);
	feclearexcept(FE_ALL_EXCEPT);
	assert(f != f);
	assert(d != d);
	assert(ld != ld);
	/* POSIX says we should only generate quiet NaNs. */
	assert(fetestexcept(FE_INVALID) == 0);

	printf("ok 2 - scanfloat\n");

	/*
	 * Rounding tests
	 */

	fesetround(FE_DOWNWARD);

	sscanf("1.999999999999999999999999999999999", "%le", &d);
	assert(d < 2.0);
	sscanf("0x1.ffffffffffffffp0", "%le", &d);
	assert(d < 2.0);
	sscanf("1.999999999999999999999999999999999", "%Le", &ld);
	assert(ld < 2.0);

	sscanf("1.0571892669084007", "%le", &d);
	assert(d == 0x1.0ea3f4af0dc59p0);
	sscanf("-1.0571892669084007", "%le", &d);
	assert(d == -0x1.0ea3f4af0dc5ap0);
	sscanf("1.0571892669084010", "%le", &d);
	assert(d == 0x1.0ea3f4af0dc5ap0);

	sscanf("0x1.23p-5000", "%le", &d);
	assert(d == 0.0);

	sscanf("0x1.2345678p-1050", "%le", &d);
	assert(d == 0x1.234567p-1050);

	fesetround(FE_UPWARD);

	sscanf("1.0571892669084007", "%le", &d);
	assert(d == 0x1.0ea3f4af0dc5ap0);
	sscanf("-1.0571892669084007", "%le", &d);
	assert(d == -0x1.0ea3f4af0dc59p0);
	sscanf("1.0571892669084010", "%le", &d);
	assert(d == 0x1.0ea3f4af0dc5bp0);

	sscanf("0x1.23p-5000", "%le", &d);
	assert(d == 0x1p-1074);

	sscanf("0x1.2345678p-1050", "%le", &d);
	assert(d == 0x1.234568p-1050);

	fesetround(FE_TOWARDZERO);

	sscanf("1.0571892669084007", "%le", &d);
	assert(d == 0x1.0ea3f4af0dc59p0);
	sscanf("-1.0571892669084007", "%le", &d);
	assert(d == -0x1.0ea3f4af0dc59p0);
	sscanf("1.0571892669084010", "%le", &d);
	assert(d == 0x1.0ea3f4af0dc5ap0);

	sscanf("0x1.23p-5000", "%le", &d);
	assert(d == 0.0);

	sscanf("0x1.2345678p-1050", "%le", &d);
	assert(d == 0x1.234567p-1050);

	fesetround(FE_TONEAREST);

	/* 1.0571892669084007 is slightly closer to 0x1.0ea3f4af0dc59p0 */
	sscanf("1.0571892669084007", "%le", &d);
	assert(d == 0x1.0ea3f4af0dc59p0);
	sscanf("-1.0571892669084007", "%le", &d);
	assert(d == -0x1.0ea3f4af0dc59p0);
	sscanf("1.0571892669084010", "%le", &d);
	assert(d == 0x1.0ea3f4af0dc5bp0);

	/* strtod() should round small numbers to 0. */
	sscanf("0x1.23p-5000", "%le", &d);
	assert(d == 0.0);

	/* Extra digits in a denormal shouldn't break anything. */
	sscanf("0x1.2345678p-1050", "%le", &d);
	assert(d == 0x1.234568p-1050);

	printf("ok 3 - scanfloat\n");

	/*
	 * Tests specific to strtod().
	 */

	assert(strtod("0xy", &endp) == 0);
	assert(strcmp("xy", endp) == 0);

	/* This used to cause an infinite loop and round the wrong way. */
	fesetround(FE_DOWNWARD);
	assert(strtof("3.5e38", &endp) == FLT_MAX);
	assert(strtod("2e308", &endp) == DBL_MAX);
	fesetround(FE_UPWARD);
	assert(strtof("3.5e38", &endp) == INFINITY);
	assert(strtod("2e308", &endp) == INFINITY);
	fesetround(FE_TOWARDZERO);
	assert(strtof("3.5e38", &endp) == FLT_MAX);
	assert(strtod("2e308", &endp) == DBL_MAX);
	fesetround(FE_TONEAREST);
	assert(strtof("3.5e38", &endp) == INFINITY);
	assert(strtod("2e308", &endp) == INFINITY);

	printf("ok 4 - scanfloat\n");

	return (0);
}
Exemplo n.º 23
0
static struct http_request * uh_http_header_parse(struct client *cl, char *buffer, int buflen)
{
	char *method  = &buffer[0];
	char *path    = NULL;
	char *version = NULL;

	char *headers = NULL;
	char *hdrname = NULL;
	char *hdrdata = NULL;

	int i;
	int hdrcount = 0;

	static struct http_request req;

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


	/* terminate initial header line */
	if( (headers = strfind(buffer, buflen, "\r\n", 2)) != NULL )
	{
		buffer[buflen-1] = 0;

		*headers++ = 0;
		*headers++ = 0;

		/* find request path */
		if( (path = strchr(buffer, ' ')) != NULL )
			*path++ = 0;

		/* find http version */
		if( (path != NULL) && ((version = strchr(path, ' ')) != NULL) )
			*version++ = 0;


		/* check method */
		if( strcmp(method, "GET") && strcmp(method, "HEAD") && strcmp(method, "POST") )
		{
			/* invalid method */
			uh_http_response(cl, 405, "Method Not Allowed");
			return NULL;
		}
		else
		{
			switch(method[0])
			{
				case 'G':
					req.method = UH_HTTP_MSG_GET;
					break;

				case 'H':
					req.method = UH_HTTP_MSG_HEAD;
					break;

				case 'P':
					req.method = UH_HTTP_MSG_POST;
					break;
			}
		}

		/* check path */
		if( !path || !strlen(path) )
		{
			/* malformed request */
			uh_http_response(cl, 400, "Bad Request");
			return NULL;
		}
		else
		{
			req.url = path;
		}

		/* check version */
		if( (version == NULL) || (strcmp(version, "HTTP/0.9") &&
		    strcmp(version, "HTTP/1.0") && strcmp(version, "HTTP/1.1")) )
		{
			/* unsupported version */
			uh_http_response(cl, 400, "Bad Request");
			return NULL;
		}
		else
		{
			req.version = strtof(&version[5], NULL);
		}


		/* process header fields */
		for( i = (int)(headers - buffer); i < buflen; i++ )
		{
			/* found eol and have name + value, push out header tuple */
			if( hdrname && hdrdata && (buffer[i] == '\r' || buffer[i] == '\n') )
			{
				buffer[i] = 0;

				/* store */
				if( (hdrcount + 1) < array_size(req.headers) )
				{
					req.headers[hdrcount++] = hdrname;
					req.headers[hdrcount++] = hdrdata;

					hdrname = hdrdata = NULL;
				}

				/* too large */
				else
				{
					uh_http_response(cl, 413, "Request Entity Too Large");
					return NULL;
				}
			}

			/* have name but no value and found a colon, start of value */
			else if( hdrname && !hdrdata && ((i+2) < buflen) &&
				(buffer[i] == ':') && (buffer[i+1] == ' ')
			) {
				buffer[i] = 0;
				hdrdata = &buffer[i+2];
			}

			/* have no name and found [A-Z], start of name */
			else if( !hdrname && isalpha(buffer[i]) && isupper(buffer[i]) )
			{
				hdrname = &buffer[i];
			}
		}

		/* valid enough */
		req.redirect_status = 200;
		return &req;
	}

	/* Malformed request */
	uh_http_response(cl, 400, "Bad Request");
	return NULL;
}
Exemplo n.º 24
0
bool RAUX::MTLFile :: ProcessTransmissionFilter ( const std :: string & Line, uint32_t Index )
{
	
	if ( Materials.size () == 0 )
		return false;
	
	Vec3 Coefficients ( MTLFILE_VEC3_NOINIT );
	bool IsCIEXYZ = false;
	
	uint32_t StringIndex;
	
	Index ++;
	
	while ( ( Index < Line.size () ) && ( Line.at ( Index ) == ' ' ) )
		Index ++;
	
	if ( Index >= Line.size () )
		return false;
	
	StringIndex = Index;
	
	while ( ( Index < Line.size () ) && ( Line.at ( Index ) != ' ' ) )
		Index ++;
	
	if ( Index >= Line.size () )
		return false;
	
	std :: string FloatString = Line.substr ( StringIndex, Index - StringIndex );
	
	if ( FloatString == "xyz" )
	{
		
		IsCIEXYZ = true;
		
		Index ++;
		
		while ( ( Index < Line.size () ) && ( Line.at ( Index ) == ' ' ) )
			Index ++;
		
		if ( Index >= Line.size () )
			return false;
		
		StringIndex = Index;
		
		while ( ( Index < Line.size () ) && ( Line.at ( Index ) != ' ' ) )
			Index ++;
		
		if ( Index >= Line.size () )
			return false;
		
		FloatString = Line.substr ( StringIndex, Index - StringIndex );
		
	}
	
	Coefficients.X = strtof ( FloatString.c_str (), NULL );
	
	while ( ( Index < Line.size () ) && ( Line.at ( Index ) == ' ' ) )
		Index ++;
	
	if ( Index >= Line.size () )
		return false;
	
	StringIndex = Index;
	
	while ( ( Index < Line.size () ) && ( Line.at ( Index ) != ' ' ) )
		Index ++;
	
	if ( Index >= Line.size () )
		return false;
	
	FloatString = Line.substr ( StringIndex, Index - StringIndex );
	Coefficients.Y = strtof ( FloatString.c_str (), NULL );
	
	while ( ( Index < Line.size () ) && ( Line.at ( Index ) == ' ' ) )
		Index ++;
	
	if ( Index >= Line.size () )
		return false;
	
	StringIndex = Index;
	
	while ( ( Index < Line.size () ) && ( Line.at ( Index ) != ' ' ) )
		Index ++;
	
	FloatString = Line.substr ( StringIndex, Index - StringIndex );
	Coefficients.Z = strtof ( FloatString.c_str (), NULL );
	
	Materials [ Materials.size () - 1 ].TransmissionFilter = Coefficients;
	Materials [ Materials.size () - 1 ].TransmissionIsCIEXYZ = IsCIEXYZ;
	
	return true;
	
}
symbol* assembler::identify(string s, symbol& ans)
{
    ans.name = s;
    ans.value = 0;
    char c = s[0];
    if (s == end_of_line)
        ans.kind = the_end;
    else if (c == '\"')
        ans.kind = a_string;
    else if (c == ',')
        ans.kind = a_comma;
    else if (c == ':')
        ans.kind = a_colon;
    else if (c == '=')
        ans.kind = an_equals_sign;
    else if (c == '+')
        ans.kind = a_plus_sign;
    else if (c == '-')
        ans.kind = a_minus_sign;
    else if (c == '[')
        ans.kind = an_open_bracket;
    else if (c == ']')
        ans.kind = a_close_bracket;
    else if (c == '.')
    {
        c = s[1];
        if (c >= '0' && c <= '9')
        {
            s = s.substr(1);
            ans.name = s;
            int last = s.length() - 1;
            if (last > 0 && (s[last] == 'H' || s[last] == 'L'))
                s = s.substr(0, last);
            union
            {
                float fv;
                int iv;
            } converter;
            converter.fv = strtof(s.c_str(), NULL);
            ans.value = converter.iv;
            ans.kind = a_float;
        }
        else
            ans.kind = a_command;
    }
    else if (c == '\'')
    {
        int len = s.length();
        ans.value = 0;
        for (int i = 1; i < len; i += 1)
        {
            char c = s[i];
            if (c == '\\')
            {
                i += 1;
                c = backstroke_char(s[i]);
            }
            ans.value = ans.value * 256 + c;
        }
        ans.kind = a_number;
    }
    else if (c >= '0' && c <= '9')
    {
        int last = s.length() - 1;
        if (last > 0 && (s[last] == 'H' || s[last] == 'L'))
            s = s.substr(0, last);
        bool ok = string_to_int(s, ans.value);
        if (ok)
            ans.kind = a_number;
        else
            ans.kind = a_bad_number;
    }
    else if (c == '#')
    {
        s = s.substr(1);
        symbol* e = symtab.find(s);
        if (pass == 2 && e->kind == a_name)
            error("There is nothing matching '%s' in the symbol table\n", s.c_str());
        ans.kind = a_number;
        ans.value = e->value;
    }
    else if (c >= 'A' && c <= 'Z' || c == '_' || c == '%' || c == '$' || c == '@')
    {
        symbol* e = symtab.find(s);
        return e;
    }
    else
        ans.kind = something_else;
    return & ans;
}
Exemplo n.º 26
0
/**
 * Converts string to float (32 bit) representation
 * @param str   string value
 * @param val   float result
 * @return      number of bytes used in string
 */
size_t strToFloat(const char * str, float * val) {
    char * endptr;
    *val = strtof(str, &endptr);
    return endptr - str;
}