Пример #1
0
StationAccessPoint
Esp8266WiFiPhy::GetConnectedStationAP(bool flashStored){
	string ATCommand;

	testprintf("\r\nEntering %s ...", __PRETTY_FUNCTION__);
	// header
	ATCommand = "AT+CWJAP_";
	if (flashStored){
		ATCommand += "DEF";
	}
	else {
		ATCommand += "CUR";
	}
	ATCommand +="\?\r\n";

	// resets the buffer from any spurious previous output and send
	m_UART->rxBufferFlush();
	UART_TX(ATCommand);
	dbgprintf("SEND:\r\n%s",ATCommand.c_str());

	if(!WaitFor("OK")){
		printf("Error: Missed OK reply - AT+CWJAP\?\r\n");
		return StationAccessPoint("","","");
	}

	size_t from = 0;
	string ssid = StringUnescape(GetStringBetweenTokens(':',',',m_lastATreply, from));
	string bssid = StringUnescape(GetStringBetweenTokens(',',',',m_lastATreply, from));
	string channel = GetStringBetweenTokens(',',',',m_lastATreply, from);
	string rssi = GetStringBetweenTokens(',','\r',m_lastATreply, from);

	dbgprintf("AccessPoint: <%s>,<%s>,<%s>,<%s>\r\n", ssid.c_str(), bssid.c_str(), channel.c_str(), rssi.c_str());
	testprintf("Ended!\r\n");
	return StationAccessPoint(ssid,bssid,StringToInteger(channel),StringToInteger(rssi));
}
Пример #2
0
/** Parses a string containing a range in which both values are optional ("<MinHeight>|<MaxHeight>") into Min, Range.
Returns true if successful, false on failure.
If a_LogWarnings is true, outputs failure reasons to console.
The range is returned in a_Min and a_Range, they are left unchanged if the range value is not present in the string. */
static bool ParseRange(const AString & a_Params, int & a_Min, int & a_Range, bool a_LogWarnings)
{
	auto params = StringSplitAndTrim(a_Params, "|");
	if (params.size() == 0)
	{
		// No params, generate directly on top:
		return true;
	}
	if (!StringToInteger(params[0], a_Min))
	{
		// Failed to parse the min rel height:
		CONDWARNING(a_LogWarnings, "Cannot parse minimum height from string \"%s\"!", params[0].c_str());
		return false;
	}
	if (params.size() == 1)
	{
		// Only one param was given, there's no range
		return true;
	}
	int maxHeight = a_Min;
	if (!StringToInteger(params[1], maxHeight))
	{
		CONDWARNING(a_LogWarnings, "Cannot parse maximum height from string \"%s\"!", params[1].c_str());
		return false;
	}
	if (maxHeight < a_Min)
	{
		std::swap(maxHeight, a_Min);
	}
	a_Range = maxHeight - a_Min + 1;
	return true;
}
Пример #3
0
RationalExpression::RationalExpression(Scanner& s) {
	this->numerator = StringToInteger(s.nextToken());
	string lookahead = s.nextToken();
	if (lookahead == "/") {
		this->denominator = StringToInteger(s.nextToken());
	} else {
		s.saveToken(lookahead);
		this->denominator = 1;
	}
	
	reduce();
}
Пример #4
0
PRBool
nsAttrValue::ParseSpecialIntValue(const nsAString& aString)
{
  ResetIfSet();

  PRInt32 ec;
  PRBool strict;
  PRBool isPercent = PR_FALSE;
  nsAutoString tmp(aString);
  PRInt32 originalVal = StringToInteger(aString, &strict, &ec, PR_TRUE, &isPercent);

  if (NS_FAILED(ec)) {
    return PR_FALSE;
  }

  PRInt32 val = NS_MAX(originalVal, 0);

  // % (percent)
  if (isPercent || tmp.RFindChar('%') >= 0) {
    isPercent = PR_TRUE;
  }

  strict = strict && (originalVal == val);

  SetIntValueAndType(val,
                     isPercent ? ePercent : eInteger,
                     strict ? nsnull : &aString);
  return PR_TRUE;
}
Пример #5
0
ship_p GetData(FILE *infile,class_p *class_p_p,ship_p *ship_p_p,int *ship_num_p)
{
	int n,m,i,k;
	string clas;
	fscanf(infile,"Num Classes: %d\n",&n);
	*class_p_p=GetBlock( n * sizeof(**class_p_p));
	for (i=0;i<=n-1;i++)
	{
		(*class_p_p+i)->name=ReadLine(infile);
		(*class_p_p+i)->length=StringToInteger(ReadLine(infile));
		(*class_p_p+i)->color=ReadLine(infile);
		(*class_p_p+i)->sound=ReadLine(infile);
		(*class_p_p+i)->num=0;
		ReadLine(infile);
	}
	fscanf(infile,"Num Ships: %d\n",&m);
	*ship_num_p=m;
	*ship_p_p=GetBlock( m * sizeof(**ship_p_p));
	for (i=0;i<=m-1;i++)
	{
		(*ship_p_p+i)->name=ReadLine(infile);
		clas=ReadLine(infile);
		for (k=0;k<=n-1;k++)
		{
			if ( StringEqual( clas,(*class_p_p+k)->name ) )
			{
				(*ship_p_p+i)->clas=k;
				( (*class_p_p+k)->num )++;
				(*ship_p_p+i)->contain=GetBlock( (*class_p_p+k)->length * sizeof(coord) );
			}
		}
		ReadLine(infile);
	}
	return *ship_p_p;
}
Пример #6
0
void cHTTPMessage::AddHeader(const AString & a_Key, const AString & a_Value)
{
	AString Key = StrToLower(a_Key);
	cNameValueMap::iterator itr = m_Headers.find(Key);
	if (itr == m_Headers.end())
	{
		m_Headers[Key] = a_Value;
	}
	else
	{
		// The header-field key is specified multiple times, combine into comma-separated list (RFC 2616 @ 4.2)
		itr->second.append(", ");
		itr->second.append(a_Value);
	}

	// Special processing for well-known headers:
	if (Key == "content-type")
	{
		m_ContentType = m_Headers[Key];
	}
	else if (Key == "content-length")
	{
		if (!StringToInteger(m_Headers[Key], m_ContentLength))
		{
			m_ContentLength = 0;
		}
	}
}
Пример #7
0
bool cServer::Start(void)
{
	for (auto port: m_Ports)
	{
		UInt16 PortNum;
		if (!StringToInteger(port, PortNum))
		{
			LOGWARNING("Invalid port specified for server: \"%s\". Ignoring.", port.c_str());
			continue;
		}
		auto Handle = cNetwork::Listen(PortNum, std::make_shared<cServerListenCallbacks>(*this, PortNum));
		if (Handle->IsListening())
		{
			m_ServerHandles.push_back(Handle);
		}
	}  // for port - Ports[]
	if (m_ServerHandles.empty())
	{
		LOGERROR("Couldn't open any ports. Aborting the server");
		return false;
	}
	if (!m_TickThread.Start())
	{
		return false;
	}
	return true;
}
Пример #8
0
	bool ResolveItem(const AString & a_ItemName, cItem & a_Item)
	{
		// Split into parts divided by either ':' or '^'
		AStringVector Split = StringSplitAndTrim(a_ItemName, ":^");
		if (Split.empty())
		{
			return false;
		}

		ItemMap::iterator itr = m_Map.find(Split[0]);
		if (itr != m_Map.end())
		{
			// Resolved as a string, assign the type and the default damage / count
			a_Item.m_ItemType = itr->second.first;
			a_Item.m_ItemDamage = itr->second.second;
			if (a_Item.m_ItemDamage == -1)
			{
				a_Item.m_ItemDamage = 0;
			}
		}
		else
		{
			// Not a resolvable string, try pure numbers: "45:6", "45^6" etc.
			if (!StringToInteger(Split[0], a_Item.m_ItemType))
			{
				// Parsing the number failed
				return false;
			}
		}
		
		// Parse the damage, if present:
		if (Split.size() < 2)
		{
			// Not present, set the item as valid and return success:
			a_Item.m_ItemCount = 1;
			return true;
		}

		if (!StringToInteger(Split[1], a_Item.m_ItemDamage))
		{
			// Parsing the number failed
			return false;
		}
		a_Item.m_ItemCount = 1;
		return true;
	}
Пример #9
0
int main(int argc, char ** argv)
{
	// Initialize logging subsystem:
	auto consoleLogListener = MakeConsoleListener(false);
	auto consoleAttachment = cLogger::GetInstance().AttachListener(std::move(consoleLogListener));
	auto fileLogListenerRet = MakeFileListener();
	if (!fileLogListenerRet.first)
	{
		LOGERROR("Failed to open log file, aborting");
		return EXIT_FAILURE;
	}
	auto fileAttachment = cLogger::GetInstance().AttachListener(std::move(fileLogListenerRet.second));

	cLogger::InitiateMultithreading();

	UInt16 ListenPort = 25564;
	UInt16 ConnectPort = 25565;
	if (argc > 1)
	{
		if (!StringToInteger(argv[1], ListenPort))
		{
			LOGERROR("Invalid argument 1, expected port number, got \"%s\". Aborting.", argv[1]);
			return 1;
		}
		if (argc > 2)
		{
			if (!StringToInteger(argv[2], ConnectPort))
			{
				LOGERROR("Invalid argument 2, expected port number, got \"%s\". Aborting.", argv[2]);
				return 2;
			}
		}
	}
	cServer Server;
	int res = Server.Init(ListenPort, ConnectPort);
	if (res != 0)
	{
		LOGERROR("Server initialization failed: %d", res);
		return res;
	}

	Server.Run();

	return 0;
}
Пример #10
0
int GetPointSize()
{
    if (TcpClient == NULL) Error("Graphics not initialized");
    string resp = TcpClient->ExchangeMsg("GETPOINTSIZE");
    int val;
    try { val = StringToInteger(resp); }
    catch (ErrorException e) { Error("GetPointSize: " + resp); }
    return val;
}
Пример #11
0
	virtual bool InitializeFromString(const AString & a_Params, bool a_LogWarnings) override
	{
		// Params: "<Height>", compulsory
		if (!StringToInteger(a_Params, m_Height))
		{
			CONDWARNING(a_LogWarnings, "Cannot parse the fixed height from string \"%s\"!", a_Params.c_str());
			return false;
		}
		return true;
	}
Пример #12
0
Vector<int> getInput() {
	int* pointer;
	Vector<int> vect;
	while(true) {	
		cout << "Enter value (enter to quit): " ;
		string input = GetLine();
		if (input  == "") break;
		int value = StringToInteger(input);
		vect.add(value);
	}
	return vect;
}
Пример #13
0
	virtual bool InitializeFromString(const AString & a_Params, bool a_LogWarnings) override
	{
		// Params: "<MinHeight>|<MaxHeight>", all compulsory
		auto params = StringSplitAndTrim(a_Params, "|");
		if (params.size() != 2)
		{
			CONDWARNING(a_LogWarnings, "Cannot parse the range parameters from string \"%s\"!", a_Params.c_str());
			return false;
		}
		int Max = 0;
		if (!StringToInteger(params[0], m_Min) || !StringToInteger(params[1], Max))
		{
			CONDWARNING(a_LogWarnings, "Cannot parse the minimum or maximum height from string \"%s\"!", a_Params.c_str());
			return false;
		}
		if (m_Min > Max)
		{
			std::swap(m_Min, Max);
		}
		m_Range = Max - m_Min + 1;
		return true;
	}
Пример #14
0
static void SelectionOperation(dataBlockT db, string lhs)
{
    string var;
    int pos;

    if (lhs != NULL) Error("NthElement result cannot be assigned");
    CheckForToken(db->scanner, "(");
    var = ConvertToLowerCase(ReadToken(db->scanner));
    CheckForToken(db->scanner, ",");
    pos = StringToInteger(ReadToken(db->scanner));
    CheckForToken(db->scanner, ")");
    printf("%s\n", NthElement(GetValue(db, var), pos));
}
Пример #15
0
SoftAccessPoint
Esp8266WiFiPhy::GetConfigurationSoftAP(bool flashStored){
	string ATCommand;

	testprintf("\r\nEntering %s ...", __PRETTY_FUNCTION__);
	// header
	ATCommand = "AT+CWSAP_";
	// store
	if (flashStored){
		ATCommand += "DEF";
	}
	else {
		ATCommand += "CUR";
	}
	ATCommand +="\?\r\n";

	// resets the buffer from any spurious previous output and send
	m_UART->rxBufferFlush();
	UART_TX(ATCommand);
	dbgprintf("SEND:\r\n%s",ATCommand.c_str());
	if(!WaitFor("OK")){
		printf("Error: Missed OK reply - AT+CWSAP\?\r\n");
		return SoftAccessPoint("","",-1,-1,-1,-1);
	}

	size_t from = 0;
	string ssid = StringUnescape(GetStringBetweenTokens(':',',',m_lastATreply, from));
	string password = StringUnescape(GetStringBetweenTokens(',',',',m_lastATreply, from));
	string channel = GetStringBetweenTokens(',',',',m_lastATreply, from);
	string encryption = GetStringBetweenTokens(',',',',m_lastATreply, from);
	string max_conn = GetStringBetweenTokens(',',',',m_lastATreply, from);
	string ssid_bcast = GetStringBetweenTokens(',','\r',m_lastATreply, from);

	dbgprintf("AccessPoint: <%s>,<%s>,<%s>,<%s>,<%s>,<%s>\r\n", ssid.c_str(), password.c_str(), channel.c_str(), encryption.c_str(), max_conn.c_str(), ssid_bcast.c_str());
	testprintf("Ended!\r\n");
	return SoftAccessPoint(ssid,password,StringToInteger(channel),StringToInteger(encryption),StringToInteger(max_conn),StringToInteger(ssid_bcast));

}
Пример #16
0
	void AddToMap(const AString & a_Name, const AString & a_Value)
	{
		AStringVector Split = StringSplit(a_Value, ":");
		if (Split.size() == 1)
		{
			Split = StringSplit(a_Value, "^");
		}
		if (Split.empty())
		{
			return;
		}
		short ItemType;
		if (!StringToInteger(Split[0], ItemType))
		{
			ASSERT(!"Invalid item type");
		}
		short ItemDamage = -1;
		if (Split.size() > 1 && !StringToInteger(Split[1], ItemDamage))
		{
			ASSERT(!"Invalid item damage");
		}
		m_Map[a_Name] = std::make_pair(ItemType, ItemDamage);
	}
Пример #17
0
PRBool
nsAttrValue::ParsePositiveIntValue(const nsAString& aString)
{
  ResetIfSet();

  PRInt32 ec;
  PRBool strict;
  PRInt32 originalVal = StringToInteger(aString, &strict, &ec);
  if (NS_FAILED(ec) || originalVal <= 0) {
    return PR_FALSE;
  }

  SetIntValueAndType(originalVal, eInteger, nsnull);

  return PR_TRUE;
}
Пример #18
0
/*
Function: DevelopHistogram
Usage: DevelopHistogram(scores, histo, n)
-----------------------------------------
Upon receiving a vector of numeric strings 'scores', which range as
0 <= score <= 99, we examine the number that start with any given digit,
updating the counts within the array 'histo'.  'histo' will have 'n'
different categories/slots, could probably hardcode as 10 since 0<n<100.
 */
void DevelopHistogram(scoresV scores, int histo[], int n) {
    // Initialize the histogram
    for (int i = 0; i < n; i++) {
        histo[i] = 0;
    }

    for (int i = 0; i < scores.size(); i++) {
        // get first char of score
        if (scores[i].length() > 1) {
            //tens_char.push_back( (scores[i])[0] );    // from earlier efforts...
            histo[ StringToInteger(string ("") + (scores[i])[0]) ] ++;
        }
        else {
            histo[0] ++;
        }
    }
}
Пример #19
0
static bool ReadOneQuestion(FILE *infile, courseDB course)
{
    questionT question;
    string line;
    int qnum;

    line = ReadLine(infile);
    if (line == NULL) return (FALSE);
    qnum = StringToInteger(line);
    if (qnum < 1 || qnum > MaxQuestions) {
        Error("Question number %d out of range", qnum);
    }
    question = New(questionT);
    ReadQuestionText(infile, question);
    ReadAnswers(infile, question);
    course->questions[qnum] = question;
    return (TRUE);
}
Пример #20
0
/*
Function: DevelopHistogram
Usage: DevelopHistogram(scores, histo, n)
-----------------------------------------
Upon receiving a vector of numeric strings 'scores', which range as
0 <= score <= 99, we examine the number that start with any given digit,
updating the counts within the array 'histo'.  'histo' will have 'n'
different categories/slots, could probably hardcode as 10 since 0<n<100.
 */
void DevelopHistogram(scoresV scores, int histo[], int n) {
    // Initialize the histogram
    for (int i = 0; i < n; i++) {
        histo[i] = 0;
    }

    for (int i = 0; i < scores.size(); i++) {
        // get first char of score
        if (scores[i].length() > 1) {
            string tens_char = "";
            tens_char.push_back( (scores[i])[0] );
            histo[ StringToInteger(tens_char) ] ++;
        }
        else {
            histo[0] ++;
        }
    }
}
Пример #21
0
void ReadScores1(ifstream &in1, Vector<int> &scores) {
    while (true) {
        string line;
        getline(in1, line);
    
        if (in1.fail()) {
            break; // no more lines to read
        }
        cout << line << endl;
        //Input line must be well form. Only digits. No letters, punctuation or whitespace.
        int x = StringToInteger(line);
        
        if (x >= 0 && x <= 99) {
            scores[x / 10] += 1;
        }
        
    } 
}
Пример #22
0
static void ReadAnswers(FILE *infile, questionT q)
{
    string line, ans;
    int len, cpos, nextq, nAnswers;

    nAnswers = 0;
    while ((line = ReadLine(infile)) != NULL
           && (len = StringLength(line)) != 0) {
        cpos = FindChar(':', line, 0);
        if (cpos == -1) Error("Illegal answer format");
        ans = SubString(line, 0, cpos - 1);
        nextq = StringToInteger(SubString(line, cpos+1, len-1));
        q->answers[nAnswers].ans = ConvertToUpperCase(ans);
        q->answers[nAnswers].nextq = nextq;
        nAnswers++;
    }
    q->nAnswers = nAnswers;
}
Пример #23
0
bool Encoding::compress(ibstream &inStream, obstream &outStream){
	buildEncodingForInput(inStream);
	int input;
	string code;

	map<int, string>::iterator it;
	outStream.put(mp.size());
	outStream.put('|');
	for (it = mp.begin(); it != mp.end(); it++){
		outStream.put(it->first);
		//cout << it->first << " has the code ";
		for (int i = 0; i < it->second.size(); i++){
			outStream.put(it->second[i]);
			//cout << it->second[i];
		}
		outStream.put('|');
		//cout << endl;
	}

	inStream.rewind();
	string temp;
	int letter;
	int temps;
	for (int i = 0; i < inStream.size(); i++){
		temps = inStream.size();
		input = inStream.get();
		code = mp[input];
		for (int i = 0; i < code.length(); i++){
			temp = code[i];
			outStream.writebit(StringToInteger(temp));
			//cout << code[i];
		}
		//cout << endl;
	}
	outStream.put(_EOF_);
	outStream.close();


	return true;

}
Пример #24
0
PRBool
nsAttrValue::ParseIntWithBounds(const nsAString& aString,
                                PRInt32 aMin, PRInt32 aMax)
{
  NS_PRECONDITION(aMin < aMax, "bad boundaries");

  ResetIfSet();

  PRInt32 ec;
  PRBool strict;
  PRInt32 originalVal = StringToInteger(aString, &strict, &ec);
  if (NS_FAILED(ec)) {
    return PR_FALSE;
  }

  PRInt32 val = NS_MAX(originalVal, aMin);
  val = NS_MIN(val, aMax);
  strict = strict && (originalVal == val);
  SetIntValueAndType(val, eInteger, strict ? nsnull : &aString);

  return PR_TRUE;
}
Пример #25
0
bool cHTTPServer::Start(cCallbacks & a_Callbacks, const AStringVector & a_Ports)
{
	m_Callbacks = &a_Callbacks;

	// Open up requested ports:
	for (auto port : a_Ports)
	{
		UInt16 PortNum;
		if (!StringToInteger(port, PortNum))
		{
			LOGWARNING("WebServer: Invalid port value: \"%s\". Ignoring.", port.c_str());
			continue;
		}
		auto Handle = cNetwork::Listen(PortNum, std::make_shared<cHTTPServerListenCallbacks>(*this, PortNum));
		if (Handle->IsListening())
		{
			m_ServerHandles.push_back(Handle);
		}
	}  // for port - a_Ports[]
	
	// Report success if at least one port opened successfully:
	return !m_ServerHandles.empty();
}
Пример #26
0
bool cHTTPServer::Start(cCallbacks & a_Callbacks, const AStringVector & a_Ports)
{
	m_Callbacks = &a_Callbacks;

	// Open up requested ports:
	AStringVector ports;
	for (auto port : a_Ports)
	{
		UInt16 PortNum;
		if (!StringToInteger(port, PortNum))
		{
			LOGWARNING("WebServer: Invalid port value: \"%s\". Ignoring.", port.c_str());
			continue;
		}
		auto Handle = cNetwork::Listen(PortNum, std::make_shared<cHTTPServerListenCallbacks>(*this, PortNum));
		if (Handle->IsListening())
		{
			m_ServerHandles.push_back(Handle);
			ports.push_back(port);
		}
	}  // for port - a_Ports[]

	// Inform the admin about the ports opened:
	AString reportPorts;
	for (const auto & port: ports)
	{
		if (!reportPorts.empty())
		{
			reportPorts.append(", ");
		}
		reportPorts.append(port);
	}
	LOGINFO("WebAdmin is running on port(s) %s", reportPorts.c_str());

	// Report success if at least one port opened successfully:
	return !m_ServerHandles.empty();
}
Пример #27
0
eDimension StringToDimension(const AString & a_DimensionString)
{
	// First try decoding as a number
	int res;
	if (StringToInteger(a_DimensionString, res))
	{
		// It was a valid number
		return static_cast<eDimension>(res);
	}
	
	// Decode using a built-in map:
	static struct
	{
		eDimension m_Dimension;
		const char * m_String;
	} DimensionMap [] =
	{
		{ dimOverworld, "Overworld"},
		{ dimOverworld, "Normal"},
		{ dimOverworld, "World"},
		{ dimNether,    "Nether"},
		{ dimNether,    "Hell"},  // Alternate name for Nether
		{ dimEnd,       "End"},
		{ dimEnd,       "Sky"},  // Old name for End
	} ;
	for (size_t i = 0; i < ARRAYCOUNT(DimensionMap); i++)
	{
		if (NoCaseCompare(DimensionMap[i].m_String, a_DimensionString) == 0)
		{
			return DimensionMap[i].m_Dimension;
		}
	}  // for i - DimensionMap[]
	
	// Not found
	LOGWARNING("Unknown dimension: \"%s\". Setting to Overworld", a_DimensionString.c_str());
	return dimOverworld;
}
Пример #28
0
void cEnchantments::AddFromString(const AString & a_StringSpec)
{
	// Add enchantments in the stringspec; if a specified enchantment already exists, overwrites it
	
	// Split the StringSpec into separate declarations, each in the form "id=lvl":
	AStringVector Decls = StringSplit(a_StringSpec, ";");
	for (AStringVector::const_iterator itr = Decls.begin(), end = Decls.end(); itr != end; ++itr)
	{
		// Split each declaration into the id and lvl part:
		if (itr->empty())
		{
			// The decl is empty (may happen if there's an extra semicolon at the end), ignore silently
			continue;
		}
		AStringVector Split = StringSplitAndTrim(*itr, "=");
		if (Split.size() != 2)
		{
			// Malformed decl
			LOG("%s: Malformed enchantment decl: \"%s\", skipping.", __FUNCTION__, itr->c_str());
			continue;
		}
		int id = StringToEnchantmentID(Split[0]);
		if (id < 0)
		{
			LOG("%s: Failed to parse enchantment \"%s\", skipping.", __FUNCTION__, Split[0].c_str());
			continue;
		}
		unsigned int lvl;
		if (!StringToInteger(Split[1], lvl))
		{
			// Level failed to parse
			LOG("%s: Failed to parse enchantment level \"%s\", skipping.", __FUNCTION__, Split[1].c_str());
			continue;
		}
		SetLevel(id, lvl);
	}  // for itr - Decls[]
}
Пример #29
0
/// Translates a damage type string to damage type. Takes either a number or a damage type alias (built-in). Returns -1 on failure
eDamageType StringToDamageType(const AString & a_DamageTypeString)
{
	// First try decoding as a number:
	int res;
	if (!StringToInteger(a_DamageTypeString, res))
	{
		// It was a valid number
		return static_cast<eDamageType>(res);
	}
	
	// Decode using a built-in map:
	static struct
	{
		eDamageType  m_DamageType;
		const char * m_String;
	} DamageTypeMap [] =
	{
		// Cannonical names:
		{ dtAttack,          "dtAttack"},
		{ dtRangedAttack,    "dtRangedAttack"},
		{ dtLightning,       "dtLightning"},
		{ dtFalling,         "dtFalling"},
		{ dtDrowning,        "dtDrowning"},
		{ dtSuffocating,     "dtSuffocation"},
		{ dtStarving,        "dtStarving"},
		{ dtCactusContact,   "dtCactusContact"},
		{ dtLavaContact,     "dtLavaContact"},
		{ dtPoisoning,       "dtPoisoning"},
		{ dtWithering,       "dtWithering"},
		{ dtOnFire,          "dtOnFire"},
		{ dtFireContact,     "dtFireContact"},
		{ dtInVoid,          "dtInVoid"},
		{ dtPotionOfHarming, "dtPotionOfHarming"},
		{ dtAdmin,           "dtAdmin"},
		{ dtExplosion,       "dtExplosion"},

		// Common synonyms:
		{ dtAttack,        "dtPawnAttack"},
		{ dtAttack,        "dtEntityAttack"},
		{ dtAttack,        "dtMob"},
		{ dtAttack,        "dtMobAttack"},
		{ dtRangedAttack,  "dtArrowAttack"},
		{ dtRangedAttack,  "dtArrow"},
		{ dtRangedAttack,  "dtProjectile"},
		{ dtFalling,       "dtFall"},
		{ dtDrowning,      "dtDrown"},
		{ dtSuffocating,   "dtSuffocation"},
		{ dtStarving,      "dtStarvation"},
		{ dtStarving,      "dtHunger"},
		{ dtCactusContact, "dtCactus"},
		{ dtCactusContact, "dtCactuses"},
		{ dtCactusContact, "dtCacti"},
		{ dtLavaContact,   "dtLava"},
		{ dtPoisoning,     "dtPoison"},
		{ dtWithering,     "dtWither"},
		{ dtOnFire,        "dtBurning"},
		{ dtFireContact,   "dtInFire"},
		{ dtAdmin,         "dtPlugin"},
	} ;
	for (size_t i = 0; i < ARRAYCOUNT(DamageTypeMap); i++)
	{
		if (NoCaseCompare(DamageTypeMap[i].m_String, a_DamageTypeString) == 0)
		{
			return DamageTypeMap[i].m_DamageType;
		}
	}  // for i - DamageTypeMap[]
	
	// Not found:
	return static_cast<eDamageType>(-1);
}
Пример #30
0
static Image *ReadJP2Image(const ImageInfo *image_info,ExceptionInfo *exception)
{
  const char
    *option;

  Image
    *image;

  int
    jp2_status;

  MagickBooleanType
    status;

  opj_codec_t
    *jp2_codec;

  opj_codestream_index_t
    *codestream_index = (opj_codestream_index_t *) NULL;

  opj_dparameters_t
    parameters;

  opj_image_t
    *jp2_image;

  opj_stream_t
    *jp2_stream;

  register ssize_t
    i;

  ssize_t
    y;

  unsigned char
    sans[4];

  /*
    Open image file.
  */
  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickCoreSignature);
  if (image_info->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
      image_info->filename);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickCoreSignature);
  image=AcquireImage(image_info,exception);
  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
  if (status == MagickFalse)
    {
      image=DestroyImageList(image);
      return((Image *) NULL);
    }
  /*
    Initialize JP2 codec.
  */
  if (ReadBlob(image,4,sans) != 4)
    {
      image=DestroyImageList(image);
      return((Image *) NULL);
    }
  (void) SeekBlob(image,SEEK_SET,0);
  if (LocaleCompare(image_info->magick,"JPT") == 0)
    jp2_codec=opj_create_decompress(OPJ_CODEC_JPT);
  else
    if (IsJ2K(sans,4) != MagickFalse)
      jp2_codec=opj_create_decompress(OPJ_CODEC_J2K);
    else
      jp2_codec=opj_create_decompress(OPJ_CODEC_JP2);
  opj_set_warning_handler(jp2_codec,JP2WarningHandler,exception);
  opj_set_error_handler(jp2_codec,JP2ErrorHandler,exception);
  opj_set_default_decoder_parameters(&parameters);
  option=GetImageOption(image_info,"jp2:reduce-factor");
  if (option != (const char *) NULL)
    parameters.cp_reduce=StringToInteger(option);
  option=GetImageOption(image_info,"jp2:quality-layers");
  if (option != (const char *) NULL)
    parameters.cp_layer=StringToInteger(option);
  if (opj_setup_decoder(jp2_codec,&parameters) == 0)
    {
      opj_destroy_codec(jp2_codec);
      ThrowReaderException(DelegateError,"UnableToManageJP2Stream");
    }
  jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,1);
  opj_stream_set_read_function(jp2_stream,JP2ReadHandler);
  opj_stream_set_write_function(jp2_stream,JP2WriteHandler);
  opj_stream_set_seek_function(jp2_stream,JP2SeekHandler);
  opj_stream_set_skip_function(jp2_stream,JP2SkipHandler);
  opj_stream_set_user_data(jp2_stream,image,NULL);
  opj_stream_set_user_data_length(jp2_stream,GetBlobSize(image));
  if (opj_read_header(jp2_stream,jp2_codec,&jp2_image) == 0)
    {
      opj_stream_destroy(jp2_stream);
      opj_destroy_codec(jp2_codec);
      ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
    }
  jp2_status=1;
  if ((image->columns != 0) && (image->rows != 0))
    {
      /*
        Extract an area from the image.
      */
      jp2_status=opj_set_decode_area(jp2_codec,jp2_image,
        (OPJ_INT32) image->extract_info.x,(OPJ_INT32) image->extract_info.y,
        (OPJ_INT32) (image->extract_info.x+(ssize_t) image->columns),
        (OPJ_INT32) (image->extract_info.y+(ssize_t) image->rows));
      if (jp2_status == 0)
        {
          opj_stream_destroy(jp2_stream);
          opj_destroy_codec(jp2_codec);
          opj_image_destroy(jp2_image);
          ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
        }
    }
   if ((image_info->number_scenes != 0) && (image_info->scene != 0))
    jp2_status=opj_get_decoded_tile(jp2_codec,jp2_stream,jp2_image,
      (unsigned int) image_info->scene-1);
  else
    if (image->ping == MagickFalse)
      {
        jp2_status=opj_decode(jp2_codec,jp2_stream,jp2_image);
        if (jp2_status != 0)
          jp2_status=opj_end_decompress(jp2_codec,jp2_stream);
      }
  if (jp2_status == 0)
    {
      opj_stream_destroy(jp2_stream);
      opj_destroy_codec(jp2_codec);
      opj_image_destroy(jp2_image);
      ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
    }
  opj_stream_destroy(jp2_stream);
  for (i=0; i < (ssize_t) jp2_image->numcomps; i++)
  {
    if ((jp2_image->comps[i].dx == 0) || (jp2_image->comps[i].dy == 0))
      {
        opj_destroy_codec(jp2_codec);
        opj_image_destroy(jp2_image);
        ThrowReaderException(CoderError,"IrregularChannelGeometryNotSupported")
      }
  }