Example #1
0
 //! Returns true if CharIterator is at end of the given String
 bool is_end(const String& s, const CharIterator& i) const
 { return (i >= s->end()); }
	void D3D11RenderWindow::setTitle(const String& name)
	{
		RenderWindow::setTitle(name);
		SetWindowText(mhMainWnd, std::wstring(name.begin(), name.end()).c_str());
	}
Example #3
0
void ToLowerInplace(String& inout)
{
    std::transform(inout.begin(), inout.end(), inout.begin(), tolower);
}
	String    toUpper (const String & nstr)
	{
		String retval (nstr);
		std::transform (retval.begin (), retval.end (), retval.begin (), trueUpper);
		return retval;
	} 
bool operator<(const String& lhs, const String& rhs){
    return lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());
}
Example #6
0
	ScriptTokenListPtr ScriptLexer::tokenize(const String &str, const String &source)
	{
		// State enums
		enum{ READY = 0, COMMENT, MULTICOMMENT, WORD, QUOTE, VAR, POSSIBLECOMMENT };

		// Set up some constant characters of interest
		const wchar_t varopener = '$', quote = '\"', slash = '/', backslash = '\\', openbrace = '{', closebrace = '}', colon = ':', star = '*', cr = '\r', lf = '\n';
		char c = 0, lastc = 0;

		String lexeme;
		uint32 line = 1, state = READY, lastQuote = 0;
		ScriptTokenListPtr tokens(OGRE_NEW_T(ScriptTokenList, MEMCATEGORY_GENERAL)(), SPFM_DELETE_T);

		// Iterate over the input
		String::const_iterator i = str.begin(), end = str.end();
		while(i != end)
		{
			lastc = c;
			c = *i;

			if(c == quote)
				lastQuote = line;

			switch(state)
			{
			case READY:
				if(c == slash && lastc == slash)
				{
					// Comment start, clear out the lexeme
					lexeme = "";
					state = COMMENT;
				}
				else if(c == star && lastc == slash)
				{
					lexeme = "";
					state = MULTICOMMENT;
				}
				else if(c == quote)
				{
					// Clear out the lexeme ready to be filled with quotes!
					lexeme = c;
					state = QUOTE;
				}
				else if(c == varopener)
				{
					// Set up to read in a variable
					lexeme = c;
					state = VAR;
				}
				else if(isNewline(c))
				{
					lexeme = c;
					setToken(lexeme, line, source, tokens.get());
				}
				else if(!isWhitespace(c))
				{
					lexeme = c;
					if(c == slash)
						state = POSSIBLECOMMENT;
					else
						state = WORD;
				}
				break;
			case COMMENT:
				// This newline happens to be ignored automatically
				if(isNewline(c))
					state = READY;
				break;
			case MULTICOMMENT:
				if(c == slash && lastc == star)
					state = READY;
				break;
			case POSSIBLECOMMENT:
				if(c == slash && lastc == slash)
				{
					lexeme = "";
					state = COMMENT;
					break;	
				}
				else if(c == star && lastc == slash)
				{
					lexeme = "";
					state = MULTICOMMENT;
					break;
				}
				else
				{
					state = WORD;
				}
			case WORD:
				if(isNewline(c))
				{
					setToken(lexeme, line, source, tokens.get());
					lexeme = c;
					setToken(lexeme, line, source, tokens.get());
					state = READY;
				}
				else if(isWhitespace(c))
				{
					setToken(lexeme, line, source, tokens.get());
					state = READY;
				}
				else if(c == openbrace || c == closebrace || c == colon)
				{
					setToken(lexeme, line, source, tokens.get());
					lexeme = c;
					setToken(lexeme, line, source, tokens.get());
					state = READY;
				}
				else
				{
					lexeme += c;
				}
				break;
			case QUOTE:
				if(c != backslash)
				{
					// Allow embedded quotes with escaping
					if(c == quote && lastc == backslash)
					{
						lexeme += c;
					}
					else if(c == quote)
					{
						lexeme += c;
						setToken(lexeme, line, source, tokens.get());
						state = READY;
					}
					else
					{
						// Backtrack here and allow a backslash normally within the quote
						if(lastc == backslash)
							lexeme = lexeme + "\\" + c;
						else
							lexeme += c;
					}
				}
				break;
			case VAR:
				if(isNewline(c))
				{
					setToken(lexeme, line, source, tokens.get());
					lexeme = c;
					setToken(lexeme, line, source, tokens.get());
					state = READY;
				}
				else if(isWhitespace(c))
				{
					setToken(lexeme, line, source, tokens.get());
					state = READY;
				}
				else if(c == openbrace || c == closebrace || c == colon)
				{
					setToken(lexeme, line, source, tokens.get());
					lexeme = c;
					setToken(lexeme, line, source, tokens.get());
					state = READY;
				}
				else
				{
					lexeme += c;
				}
				break;
			}

			// Separate check for newlines just to track line numbers
			if(c == cr || (c == lf && lastc != cr))
				line++;
			
			i++;
		}

		// Check for valid exit states
		if(state == WORD || state == VAR)
		{
			if(!lexeme.empty())
				setToken(lexeme, line, source, tokens.get());
		}
		else
		{
			if(state == QUOTE)
			{
				OGRE_EXCEPT(Exception::ERR_INVALID_STATE, 
					Ogre::String("no matching \" found for \" at line ") + 
						Ogre::StringConverter::toString(lastQuote),
					"ScriptLexer::tokenize");
			}
		}

		return tokens;
	}
 void StringUtils::toLower(String& str)
 {
     CharFolder::toLower(str.begin(), str.end());
 }
Example #8
0
String EntityResolver::resolveEntity(const String& entity) const
{
    if (!entity.empty() && entity[0] == L'#')
    {
        int code = 0;
        if (entity.size() > 2 && entity[1] == L'x')
        {
            // hex notation: &#xABCD;
            for (String::const_iterator it = entity.begin() + 2; it != entity.end(); ++it)
            {
                if (*it >= L'0' && *it <= L'9')
                    code = code * 16 + (it->value() - L'0');
                else if (*it >= L'A' && *it <= L'F')
                    code = code * 16 + (it->value() - L'A' + 10);
                else if (*it >= L'a' && *it <= L'f')
                    code = code * 16 + (it->value() - L'a' + 10);
                else
                    throw std::runtime_error(std::string("invalid entity ") + entity.narrow());
            }
        }
        else
        {
            // dec notation: &#9999;
            for (String::const_iterator it = entity.begin() + 1; it != entity.end(); ++it)
            {
                if (*it >= L'0' && *it <= L'9')
                    code = code * 10 + (it->value() - '0');
                else
                    throw std::runtime_error(std::string("invalid entity ") + entity.narrow());
            }
        }

        return String( 1, Char(code) );
    }

    unsigned u = 0;
    unsigned o = sizeof(ent)/sizeof(Ent) - 1;
    while (o - u > 1)
    {
        unsigned m = (o + u) / 2;
        int c = entity.compare(ent[m].entity);
        if (c == 0)
            return String(1, Char(ent[m].charValue));
        else if (c < 0)
            o = m;
        else
            u = m;
    }

    if (entity.compare(ent[u].entity) == 0)
        return String(1, Char(ent[u].charValue));

    if (entity.compare(ent[o].entity) == 0)
        return String(1, Char(ent[o].charValue));

    EntityMap::const_iterator it = _entityMap.find(entity);
    if( it == _entityMap.end() )
    {
        it = _entityMap.find(entity);
        if( it == _entityMap.end() )
            throw std::runtime_error("invalid entity " + entity.narrow());
    }

    return it->second;
}
Example #9
0
bool Preprocessor::getToken() {
	eatComments();

	// Save current position
	PreprocessorPosition pos = PreprocessorPosition (*this, curFileName, lineNumber, colNumber);

	char firstChar = getChar();
	char secondChar;
	while (true) {
		if (!firstChar)
			return false;

		// Options
		if (firstChar == '#') {
			String option;
			firstChar = getChar();
			while (nextIdentifierChars [firstChar]) {
				option += firstChar;
				firstChar = getChar();
			}
			while (firstChar == ' ')
				firstChar = getChar();
			String param;
			while (true) {
				if (firstChar == '\n' || firstChar == '\r')
					break;
				if (firstChar == '\\') {
					firstChar = getChar();
					while (firstChar != '\n') {
						if (!isWhiteSpace (firstChar))
							startError() << "\"" << firstChar << "\" found after \"\\\"." << endl;
						firstChar = getChar();
					}
					while (isWhiteSpace (firstChar)) {
						firstChar = getChar();
					}
					param += ' ';
				} else {
					param += firstChar;
					firstChar = getChar();
				}
			}
			param += ' ';
			String::const_iterator i = param.end();
			do {
				i --;
			} while (i != param.begin() && isWhiteSpace (*i));
			addOption (option, String (param.begin(), i + 1), pos);
		} else
		{
			// Identifiers
			if (firstIdentifierChars [firstChar]) {
				// Get identifier
				String identifier;
				do {
					identifier += firstChar;
					firstChar = getChar();
				} while (nextIdentifierChars [firstChar]);

				if (firstChar)
					putBackChar (firstChar);
				tokens.push_back (Token (identifier, pos));
				return true;
			} else
			{
				// Numbers
				if (firstNumberChars [firstChar]) {
					// Get number
					String number;
					do {
						number += firstChar;
						firstChar = getChar();
					} while (nextNumberChars [firstChar]);

					if (firstChar)
						putBackChar (firstChar);
					tokens.push_back (Token (number, pos));
					return true;
				} else
				{
					// Special sequences like "==" or "->"
					if (specialChars [firstChar]) {
						secondChar = peekChar();
						if (isSpecialToken(firstChar, secondChar)) {
							tokens.push_back (Token (String (firstChar) + String (secondChar), pos));
							getChar();
							return true;
						}
					}
					tokens.push_back (Token (String (firstChar), pos));
					return true;
				}
			}
		}

		eatComments();
		pos.fileName = curFileName;
		pos.lineNumber = lineNumber;
		pos.colNumber = colNumber;
		firstChar = getChar();
	}
}
Example #10
0
	WString toWString(const String& source)
	{
		return WString(source.begin(), source.end());
	}
Example #11
0
 void StringUtil::toUpperCase(String& str) 
 {
     std::transform(str.begin(), str.end(), str.begin(), toupper);
 }
		void toUpper(String& _str){
			std::transform(_str.begin(), _str.end(), _str.begin(), toupper);
		}
		void toLower(String& _str){
			std::transform(_str.begin(), _str.end(), _str.begin(), tolower);
		}
static String platformGetFontPath(const String& faceName) {
	static const LPWSTR fontRegistryPath = L"Software\\Microsoft\\Windows NT\\CurrentVersion\\Fonts";
	HKEY hKey;
	LONG result;
	std::wstring wsFaceName(faceName.begin(), faceName.end());

	// Open Windows font registry key
	result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, fontRegistryPath, 0, KEY_READ, &hKey);
	if (result != ERROR_SUCCESS) {
		throw std::runtime_error("Cant open registry!");
	}

	DWORD maxValueNameSize, maxValueDataSize;
	result = RegQueryInfoKey(hKey, 0, 0, 0, 0, 0, 0, 0, &maxValueNameSize, &maxValueDataSize, 0, 0);

	if (result != ERROR_SUCCESS) {
		throw std::runtime_error("Cant query registry!");
	}

	DWORD valueIndex = 0;
	LPWSTR valueName = new WCHAR[maxValueNameSize];
	LPBYTE valueData = new BYTE[maxValueDataSize];
	DWORD valueNameSize, valueDataSize, valueType;
	std::wstring wsFontFile;

	// Look for a matching font name
	do {
		wsFontFile.clear();
		valueDataSize = maxValueDataSize;
		valueNameSize = maxValueNameSize;

		result = RegEnumValue(hKey, valueIndex, valueName, &valueNameSize, 0, &valueType, valueData, &valueDataSize);

		valueIndex++;

		if (result != ERROR_SUCCESS || valueType != REG_SZ) {
			continue;
		}

		std::wstring wsValueName(valueName, valueNameSize);

		// Found a match
		if (_wcsnicmp(wsFaceName.c_str(), wsValueName.c_str(), wsFaceName.size()) == 0) {
			wsFontFile.assign((LPWSTR)valueData, valueDataSize);
			break;
		}
	} while (result != ERROR_NO_MORE_ITEMS);

	delete[] valueName;
	delete[] valueData;

	RegCloseKey(hKey);

	if (wsFontFile.empty()) {
		throw std::runtime_error("Did not find matching font!");
	}

	// Build full font file path
	WCHAR winDir[MAX_PATH];
	GetWindowsDirectory(winDir, MAX_PATH);

	std::wstringstream ss;
	ss << winDir << "\\Fonts\\" << wsFontFile;
	wsFontFile = ss.str();

	return String(wsFontFile.begin(), wsFontFile.end());
}
 Bytes TestCase1Uncompressed()
 {
   static const String data = "REPEATREPEATREPEATREPEATREPEATREPEAT";
   return Bytes(new Bytes::element_type(data.begin(), data.end()));
 }
Example #16
0
START_SECTION((static String number(double d, UInt n)))
	TEST_EQUAL(String::number(123.1234,0),"123")
	TEST_EQUAL(String::number(123.1234,1),"123.1")
	TEST_EQUAL(String::number(123.1234,2),"123.12")
	TEST_EQUAL(String::number(123.1234,3),"123.123")
	TEST_EQUAL(String::number(123.1234,4),"123.1234")
	TEST_EQUAL(String::number(123.1234,5),"123.12340")
	TEST_EQUAL(String::number(0.0,5),"0.00000")
END_SECTION


START_SECTION((template<class InputIterator> String(InputIterator first, InputIterator last)))
	String s("ABCDEFGHIJKLMNOP");
	String::Iterator i = s.begin();
	String::Iterator j = s.end();
	String s2(i,j);
	TEST_EQUAL(s,s2)
	++i;++i;
	--j;--j;
	s2 = String(i,j);
	TEST_EQUAL(s2,"CDEFGHIJKLMN")

	//test cases where the begin is equal to the end
	i = s.begin();
	j = s.begin();
	s2 = String(i,j);
	TEST_EQUAL(s2,"")
	TEST_EQUAL(s2.size(),0U)

	i = s.end();
 Bytes TestCase2Uncompressed()
 {
   static const String data = "Hello World";
   return Bytes(new Bytes::element_type(data.begin(), data.end()));
 }
Example #18
0
inline boost::iterator_range<typename String::const_iterator> endTrimmedOf(String const& str, Space const& space) {
  typename String::const_iterator begin = str.begin();
  return trimEndOf(begin, chompEnd(begin, str.end()), space);
}
Example #19
0
/*
   See RFC 2047 for the description of the encodings used in the mail headers.
   Briefly, "encoded words" can be inserted which have the form of

      encoded-word = "=?" charset "?" encoding "?" encoded-text "?="

   where charset and encoding can't contain space, control chars or "specials"
   and encoded-text can't contain spaces nor "?".

   NB: don't be confused by 2 meanings of encoding here: it is both the
       charset encoding for us and also QP/Base64 encoding for RFC 2047
 */
static
String DecodeHeaderOnce(const String& in, wxFontEncoding *pEncoding)
{
   // we don't enforce the sanity checks on charset and encoding - should we?
   // const char *specials = "()<>@,;:\\\"[].?=";

   // there can be words in different encodings inside the same header so this
   // variable doesn't really make sense but in practice only one encoding will
   // be used in the entire header
   wxFontEncoding encodingHeader = wxFONTENCODING_SYSTEM;

   // if the header starts with an encoded word, preceding whitespace must be
   // ignored, so the flag must be set to true initially
   bool maybeBetweenEncodedWords = true;

   String out,
          space;
   // we can't define a valid "last" iterator below for empty string
   if ( in.empty() )
      return String();

   out.reserve(in.length());
   for ( wxString::const_iterator p = in.begin(),
                                end = in.end(),
                               last = in.end() - 1; p != end; ++p )
   {
      if ( *p == '=' && p != last && *(p + 1) == '?' )
      {
         // found encoded word

         // save the start of it
         const wxString::const_iterator encWordStart = p++;

         // get the charset
         String csName;
         for ( ++p; p != end && *p != '?'; ++p ) // initial "++" to skip '?'
         {
            csName += *p;
         }

         if ( p == end )
         {
            wxLogDebug(_T("Invalid encoded word syntax in '%s': missing charset."),
                       in.c_str());
            out += wxString(encWordStart, end);

            break;
         }

         // pass false to prevent asking the user from here: we can be called
         // during non-interactive operations and popping up a dialog for an
         // unknown charset can be inappropriate
         const wxFontEncoding encodingWord = wxFontMapperBase::Get()->
                                               CharsetToEncoding(csName, false);

         if ( encodingWord == wxFONTENCODING_SYSTEM )
         {
            wxLogDebug(_T("Unrecognized charset name \"%s\""), csName.mb_str());
         }

         // this is not a problem in Unicode build
#if !wxUSE_UNICODE
         if ( encodingHeader != wxFONTENCODING_SYSTEM &&
               encodingHeader != encodingWord )
         {
            // this is a bug (well, missing feature) in ANSI build of Mahogany
            wxLogDebug(_T("This header contains encoded words with different ")
                       _T("encodings and won't be rendered correctly."));
         }
#endif // !wxUSE_UNICODE

         encodingHeader = encodingWord;


         // get the encoding in RFC 2047 sense
         enum
         {
            Encoding_Unknown,
            Encoding_Base64,
            Encoding_QuotedPrintable
         } enc2047 = Encoding_Unknown;

         ++p; // skip '?'
         if ( *(p + 1) == '?' )
         {
            if ( *p == 'B' || *p == 'b' )
               enc2047 = Encoding_Base64;
            else if ( *p == 'Q' || *p == 'q' )
               enc2047 = Encoding_QuotedPrintable;
         }
         //else: multi letter encoding unrecognized

         if ( enc2047 == Encoding_Unknown )
         {
            wxLogDebug(_T("Unrecognized header encoding in '%s'."), in.c_str());

            // scan until the end of the encoded word
            const size_t posEncWordStart = p - in.begin();
            const size_t posEncWordEnd = in.find("?=", p - in.begin());
            if ( posEncWordEnd == wxString::npos )
            {
               wxLogDebug(_T("Missing encoded word end marker in '%s'."),
                          in.c_str());
               out += wxString(encWordStart, end);

               break;
            }

            // +1 to skip '?' of "?=" (don't skip '=', this will be accounted
            // for by p increment in the loop statement)
            p += posEncWordEnd - posEncWordStart + 1;

            // leave this word undecoded
            out += wxString(encWordStart, p + 1);

            continue;
         }

         p += 2; // skip "Q?" or "B?"

         // get the encoded text
         bool hasUnderscore = false;
         const wxString::const_iterator encTextStart = p;
         while ( p != last && (*p != '?' || *(p + 1) != '=') )
         {
            // this is needed for QP hack below
            if ( *p == '_' )
               hasUnderscore = true;

            ++p;
         }

         if ( p == last )
         {
            wxLogDebug(_T("Missing encoded word end marker in '%s'."),
                       in.c_str());
            out += wxString(encWordStart, end);

            break;
         }

         // convert the encoded word to char[] buffer for c-client
         wxCharBuffer encWord(wxString(encTextStart, p).To8BitData());

         // skip '=' following '?'
         ++p;

         String textDecoded;
         if ( encWord )
         {
            const unsigned long lenEncWord = strlen(encWord);

            // now decode the text using c-client functions
            unsigned long len;
            void *text;
            if ( enc2047 == Encoding_Base64 )
            {
               text = rfc822_base64(UCHAR_CCAST(encWord), lenEncWord, &len);
            }
            else // QP
            {
               // cclient rfc822_qprint() behaves correctly and leaves '_' in the
               // QP encoded text because this is what RFC says, however many
               // broken clients replace spaces with underscores and so we undo it
               // here -- in this case it's better to be user-friendly than
               // standard-conforming
               if ( hasUnderscore )
               {
                  for ( char *pc = encWord.data(); *pc; ++pc )
                  {
                     if ( *pc == '_' )
                        *pc = ' ';
                  }
               }

               text = rfc822_qprint(UCHAR_CCAST(encWord), lenEncWord, &len);
            }

            if ( text )
            {
               const char * const ctext = static_cast<char *>(text);

               if ( encodingWord == wxFONTENCODING_DEFAULT )
               {
                  // CharsetToEncoding() returns this for US-ASCII but
                  // wxCSConv() doesn't accept it
                  textDecoded = wxString::FromAscii(ctext, len);
               }
               else // real conversion needed
               {
                  textDecoded = wxString(ctext, wxCSConv(encodingWord), len);
               }

               fs_give(&text);
            }
         }

         if ( textDecoded.empty() )
         {
            // if decoding failed it is probably better to show undecoded
            // text than nothing at all
            textDecoded = wxString(encWordStart, p + 1);
         }

         // normally we leave the (8 bit) string as is and remember its
         // encoding so that we may choose the font for displaying it
         // correctly, but in case of UTF-7/8 we really need to transform it
         // here as we don't have any UTF-7/8 fonts, so we should display a
         // different string
#if !wxUSE_UNICODE
         if ( encodingHeader == wxFONTENCODING_UTF7 ||
                  encodingHeader == wxFONTENCODING_UTF8 )
         {
            encodingHeader = ConvertUTFToMB(&textDecoded, encodingHeader);
         }
#endif // !wxUSE_UNICODE

         out += textDecoded;

         // forget the space before this encoded word, it must be ignored
         space.clear();
         maybeBetweenEncodedWords = true;
      }
      else if ( maybeBetweenEncodedWords &&
                  (*p == ' ' || *p == '\r' || *p == '\n') )
      {
         // spaces separating the encoded words must be ignored according
         // to section 6.2 of the RFC 2047, so we don't output them immediately
         // but delay until we know that what follows is not an encoded word
         space += *p;
      }
      else // just another normal char
      {
         // if we got any delayed whitespace (see above), flush it now
         if ( !space.empty() )
         {
            out += space;
            space.clear();
         }

         out += *p;

         maybeBetweenEncodedWords = false;
      }
   }

   if ( pEncoding )
      *pEncoding = encodingHeader;

   return out;
}
Example #20
0
inline boost::iterator_range<typename String::const_iterator> trimmed(String const& str, char space = ' ') {
  typename String::const_iterator begin = str.begin();
  return trimOfChar(begin, chompEnd(begin, str.end()), space);
}
Example #21
0
//-----------------------------------------------------------------------
void Compositor::createGlobalTextures()
{
    static size_t dummyCounter = 0;
    if (mSupportedTechniques.empty())
        return;

    //To make sure that we are consistent, it is demanded that all composition
    //techniques define the same set of global textures.

    typedef std::set<String> StringSet;
    StringSet globalTextureNames;

    //Initialize global textures from first supported technique
    CompositionTechnique* firstTechnique = mSupportedTechniques[0];

    CompositionTechnique::TextureDefinitionIterator texDefIt =
        firstTechnique->getTextureDefinitionIterator();
    while (texDefIt.hasMoreElements())
    {
        CompositionTechnique::TextureDefinition* def = texDefIt.getNext();
        if (def->scope == CompositionTechnique::TS_GLOBAL)
        {
            //Check that this is a legit global texture
            if (!def->refCompName.empty())
            {
                OGRE_EXCEPT(Exception::ERR_INVALID_STATE,
                            "Global compositor texture definition can not be a reference",
                            "Compositor::createGlobalTextures");
            }
            if (def->width == 0 || def->height == 0)
            {
                OGRE_EXCEPT(Exception::ERR_INVALID_STATE,
                            "Global compositor texture definition must have absolute size",
                            "Compositor::createGlobalTextures");
            }
            if (def->pooled)
            {
                LogManager::getSingleton().logMessage(
                    "Pooling global compositor textures has no effect");
            }
            globalTextureNames.insert(def->name);

            //TODO GSOC : Heavy copy-pasting from CompositorInstance. How to we solve it?

            /// Make the tetxure
            RenderTarget* rendTarget;
            if (def->formatList.size() > 1)
            {
                String MRTbaseName = "c" + StringConverter::toString(dummyCounter++) +
                                     "/" + mName + "/" + def->name;
                MultiRenderTarget* mrt =
                    Root::getSingleton().getRenderSystem()->createMultiRenderTarget(MRTbaseName);
                mGlobalMRTs[def->name] = mrt;

                // create and bind individual surfaces
                size_t atch = 0;
                for (PixelFormatList::iterator p = def->formatList.begin();
                        p != def->formatList.end(); ++p, ++atch)
                {

                    String texname = MRTbaseName + "/" + StringConverter::toString(atch);
                    TexturePtr tex;

                    tex = TextureManager::getSingleton().createManual(
                              texname,
                              ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME, TEX_TYPE_2D,
                              (uint)def->width, (uint)def->height, 0, *p, TU_RENDERTARGET, 0,
                              def->hwGammaWrite && !PixelUtil::isFloatingPoint(*p), def->fsaa);

                    RenderTexture* rt = tex->getBuffer()->getRenderTarget();
                    rt->setAutoUpdated(false);
                    mrt->bindSurface(atch, rt);

                    // Also add to local textures so we can look up
                    String mrtLocalName = getMRTTexLocalName(def->name, atch);
                    mGlobalTextures[mrtLocalName] = tex;

                }

                rendTarget = mrt;
            }
            else
            {
                String texName =  "c" + StringConverter::toString(dummyCounter++) +
                                  "/" + mName + "/" + def->name;

                // space in the name mixup the cegui in the compositor demo
                // this is an auto generated name - so no spaces can't hart us.
                std::replace( texName.begin(), texName.end(), ' ', '_' );

                TexturePtr tex;
                tex = TextureManager::getSingleton().createManual(
                          texName,
                          ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME, TEX_TYPE_2D,
                          (uint)def->width, (uint)def->height, 0, def->formatList[0], TU_RENDERTARGET, 0,
                          def->hwGammaWrite && !PixelUtil::isFloatingPoint(def->formatList[0]), def->fsaa);


                rendTarget = tex->getBuffer()->getRenderTarget();
                mGlobalTextures[def->name] = tex;
            }

            //Set DepthBuffer pool for sharing
            rendTarget->setDepthBufferPool( def->depthBufferId );
        }
    }

    //Validate that all other supported techniques expose the same set of global textures.
    for (size_t i=1; i<mSupportedTechniques.size(); i++)
    {
        CompositionTechnique* technique = mSupportedTechniques[i];
        bool isConsistent = true;
        size_t numGlobals = 0;
        texDefIt = technique->getTextureDefinitionIterator();
        while (texDefIt.hasMoreElements())
        {
            CompositionTechnique::TextureDefinition* texDef = texDefIt.getNext();
            if (texDef->scope == CompositionTechnique::TS_GLOBAL)
            {
                if (globalTextureNames.find(texDef->name) == globalTextureNames.end())
                {
                    isConsistent = false;
                    break;
                }
                numGlobals++;
            }
        }
        if (numGlobals != globalTextureNames.size())
            isConsistent = false;

        if (!isConsistent)
        {
            OGRE_EXCEPT(Exception::ERR_INVALID_STATE,
                        "Different composition techniques define different global textures",
                        "Compositor::createGlobalTextures");
        }

    }

}
Example #22
0
inline typename String::const_iterator chompEnd(String const& str) {
  return chompEnd(str.begin(), str.end());
}
bool operator==(const String& lhs, const String& rhs){
    return (lhs.size() == rhs.size() && equal(lhs.begin(), lhs.end(), rhs.begin()));
}
Example #24
0
 iterator<typename String::const_iterator> begin_lines(const String& s_)
 {
   return iterator<typename String::const_iterator>(s_.begin(), s_.end());
 }
String realpath(String const& _path)
{

	String path = (_path);
	std::replace(path.begin(), path.end(),'\\','/');
	
	const String & delims="/";

	// Skip delims at beginning, find start of first token
	String::size_type lastPos = path.find_first_not_of(delims, 0);
	// Find next delimiter @ end of token
	String::size_type pos     = path.find_first_of(delims, lastPos);

	// output vector
	Vector<String> tokens;
	
	
	while (String::npos != pos || String::npos != lastPos)
	{
		// Found a token, add it to the vector.
		tokens.push_back(path.substr(lastPos, pos - lastPos));
		// Skip delims.  Note the "not_of". this is beginning of token
		lastPos = path.find_first_not_of(delims, pos);
		// Find next delimiter at end of token.
		pos     = path.find_first_of(delims, lastPos);
	}

	String result;
	
	for (int i = 0; i < (int)tokens.size(); ++i)
	{
		if (tokens[i] == String("."))
		{		
			for (int k = i + 1; k < (int)tokens.size(); ++k)
			{
				tokens[k - 1] = tokens[k];
			}
			i--;
			tokens.pop_back();
		}
		if (tokens[i] == String(".."))
		{		
			for (int k = i + 1; k < (int)tokens.size(); ++k)
			{
				tokens[k - 2] = tokens[k];
			}
			i-=2;
			tokens.pop_back();
			tokens.pop_back();
		}	
	}
#ifndef _WIN32
	result = "/";
#endif
	for (int k = 0; k < (int)tokens.size(); ++k)
	{
		result += tokens[k];
		if (k + 1 != (int)tokens.size())
			result += String("/");
	}
	return result;
}
//-----------------------------------------------------------------------
void CompositorInstance::createResources()
{
static size_t dummyCounter = 0;
    freeResources();
    /// Create temporary textures
    /// In principle, temporary textures could be shared between multiple viewports
    /// (CompositorChains). This will save a lot of memory in case more viewports
    /// are composited.
    CompositionTechnique::TextureDefinitionIterator it = mTechnique->getTextureDefinitionIterator();
    while(it.hasMoreElements())
    {
        CompositionTechnique::TextureDefinition *def = it.getNext();
        /// Determine width and height
        size_t width = def->width;
        size_t height = def->height;
		uint fsaa = 0;
		bool hwGammaWrite = false;

		deriveTextureRenderTargetOptions(def->name, &hwGammaWrite, &fsaa);

        if(width == 0)
            width = static_cast<size_t>(
				static_cast<float>(mChain->getViewport()->getActualWidth()) * def->widthFactor);
        if(height == 0)
			height = static_cast<size_t>(
				static_cast<float>(mChain->getViewport()->getActualHeight()) * def->heightFactor);
        /// Make the tetxure
		RenderTarget* rendTarget;
		if (def->formatList.size() > 1)
		{
			String MRTbaseName = "c" + StringConverter::toString(dummyCounter++) + 
				"/" + def->name + "/" + mChain->getViewport()->getTarget()->getName();
			MultiRenderTarget* mrt = 
				Root::getSingleton().getRenderSystem()->createMultiRenderTarget(MRTbaseName);
			mLocalMRTs[def->name] = mrt;

			// create and bind individual surfaces
			size_t atch = 0;
			for (PixelFormatList::iterator p = def->formatList.begin(); 
				p != def->formatList.end(); ++p, ++atch)
			{

				TexturePtr tex = TextureManager::getSingleton().createManual(
					MRTbaseName + "/" + StringConverter::toString(atch),
					ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME, TEX_TYPE_2D, 
					(uint)width, (uint)height, 0, *p, TU_RENDERTARGET ); 
				
				RenderTexture* rt = tex->getBuffer()->getRenderTarget();
				rt->setAutoUpdated(false);
				mrt->bindSurface(atch, rt);

				// Also add to local textures so we can look up
				String mrtLocalName = getMRTTexLocalName(def->name, atch);
				mLocalTextures[mrtLocalName] = tex;
				
			}

			rendTarget = mrt;
		}
		else
		{
			String texName =  "c" + StringConverter::toString(dummyCounter++) + 
				"/" + def->name + "/" + mChain->getViewport()->getTarget()->getName();
			
			// space in the name mixup the cegui in the compositor demo
			// this is an auto generated name - so no spaces can't hart us.
			std::replace( texName.begin(), texName.end(), ' ', '_' ); 

			TexturePtr tex = TextureManager::getSingleton().createManual(
				texName, 
				ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME, TEX_TYPE_2D, 
				(uint)width, (uint)height, 0, def->formatList[0], TU_RENDERTARGET, 0,
				hwGammaWrite, fsaa); 

			rendTarget = tex->getBuffer()->getRenderTarget();
			mLocalTextures[def->name] = tex;
		}
        
        
        /// Set up viewport over entire texture
        rendTarget->setAutoUpdated( false );

        Camera* camera = mChain->getViewport()->getCamera();

        // Save last viewport and current aspect ratio
        Viewport* oldViewport = camera->getViewport();
        Real aspectRatio = camera->getAspectRatio();

        Viewport* v = rendTarget->addViewport( camera );
        v->setClearEveryFrame( false );
        v->setOverlaysEnabled( false );
        v->setBackgroundColour( ColourValue( 0, 0, 0, 0 ) );

        // Should restore aspect ratio, in case of auto aspect ratio
        // enabled, it'll changed when add new viewport.
        camera->setAspectRatio(aspectRatio);
        // Should restore last viewport, i.e. never disturb user code
        // which might based on that.
        camera->_notifyViewport(oldViewport);
    }
    
}
Example #27
0
ObjectHost::ObjectHost(ObjectHostContext* ctx, Network::IOService *ioServ, const String&options)
 : mContext(ctx),
   mStorage(NULL),
   mPersistentSet(NULL),
   mQueryProcessor(NULL),
   mActiveHostedObjects(0)
{
    mContext->objectHost = this;
    OptionValue *protocolOptions;
    OptionValue *scriptManagers;
    OptionValue *simOptions;
    InitializeClassOptions ico("objecthost",this,
                           protocolOptions=new OptionValue("protocols","",OptionValueType<std::map<std::string,std::string> >(),"passes options into protocol specific libraries like \"tcpsst:{--send-buffer-size=1440 --parallel-sockets=1},udp:{--send-buffer-size=1500}\""),
                           scriptManagers=new OptionValue("scriptManagers","simplecamera:{},js:{}",OptionValueType<std::map<std::string,std::string> >(),"Instantiates script managers with specified options like \"simplecamera:{},js:{--import-paths=/path/to/scripts}\""),
                           simOptions=new OptionValue("simOptions","ogregraphics:{}",OptionValueType<std::map<std::string,std::string> >(),"Passes initialization strings to simulations, by name"),

                           NULL);

    OptionSet* oh_options = OptionSet::getOptions("objecthost",this);
    oh_options->parse(options);
    mSimOptions=simOptions->as<std::map<std::string,std::string> > ();
    {
        std::map<std::string,std::string> *options=&protocolOptions->as<std::map<std::string,std::string> > ();
        for (std::map<std::string,std::string>::iterator i=options->begin(),ie=options->end();i!=ie;++i) {
            mSpaceConnectionProtocolOptions[i->first]=Network::StreamFactory::getSingleton().getOptionParser(i->first)(i->second);
        }
    }

    {
        std::map<std::string,std::string> *options=&scriptManagers->as<std::map<std::string,std::string> > ();
        for (std::map<std::string,std::string>::iterator i=options->begin(),ie=options->end();i!=ie;++i) {
            if (!ObjectScriptManagerFactory::getSingleton().hasConstructor(i->first)) continue;
            ObjectScriptManager* newmgr = ObjectScriptManagerFactory::getSingleton().getConstructor(i->first)(mContext, i->second);
            if (newmgr)
                mScriptManagers[i->first] = newmgr;
        }
    }

    if (mContext->commander() != NULL) {
        mContext->commander()->registerCommand(
            "oh.objects.list",
            mContext->mainStrand->wrap(std::tr1::bind(&ObjectHost::commandListObjects, this, _1, _2, _3))
        );
        mContext->commander()->registerCommand(
            "oh.objects.create",
            mContext->mainStrand->wrap(std::tr1::bind(&ObjectHost::commandCreateObject, this, _1, _2, _3))
        );
        mContext->commander()->registerCommand(
            "oh.objects.destroy",
            mContext->mainStrand->wrap(std::tr1::bind(&ObjectHost::commandDestroyObject, this, _1, _2, _3))
        );

        // To register only one copy of the command, we register HO commands
        // here and dispatch them to the appropriate HO.
        mContext->commander()->registerCommand(
            "oh.objects.presences",
            mContext->mainStrand->wrap(std::tr1::bind(&ObjectHost::commandObjectPresences, this, _1, _2, _3))
        );

    }

    mTransferMediator = &(Transfer::TransferMediator::getSingleton());
    mTransferPool = mTransferMediator->registerClient<Transfer::AggregatedTransferPool>("ObjectHost");
}
  void Console_State::fire_command(const String &text) {
    if(text.empty())
      return;

    String command;
    std::vector<String> args;

    String token;
    bool in_quotes = false;
    bool escaped = false;
    for(String::const_iterator it = text.begin(); it != text.end(); ++it) {
      if(escaped) {
        token += *it;
        escaped = false;
      }
      else {
        switch(*it) {
          case '"':
            if(in_quotes || !token.empty()) {
              if(command.empty())
                command = token;
              else
                args.push_back(token);
              token.clear();
            }
            in_quotes = !in_quotes;
            break;

          case ' ':
          case '\t':
            if(in_quotes)
              token += *it;
            else if(!token.empty()) {
              if(command.empty())
                command = token;
              else
                args.push_back(token);
              token.clear();
            }
            break;

          case '\\':
            escaped = true;
            break;

          default:
            token += *it;
            break;
        }
      }
    }

    if(!token.empty())
      if(command.empty())
        command = token;
      else
        args.push_back(token);
    else if(command.empty())
      return;

    std::map<String, Console_Function *>::iterator func = m_functions.find(command);
    if(func != m_functions.end())
      (*(func->second))(*this, command, args);
    else
      write_to_log("Unrecognized command: " + command);
  }
Example #29
0
    //-----------------------------------------------------------------------
    bool StringUtil::match(const String& str, const String& pattern, bool caseSensitive)
    {
        String tmpStr = str;
		String tmpPattern = pattern;
        if (!caseSensitive)
        {
            StringUtil::toLowerCase(tmpStr);
            StringUtil::toLowerCase(tmpPattern);
        }

        String::const_iterator strIt = tmpStr.begin();
        String::const_iterator patIt = tmpPattern.begin();
		String::const_iterator lastWildCardIt = tmpPattern.end();
        while (strIt != tmpStr.end() && patIt != tmpPattern.end())
        {
            if (*patIt == '*')
            {
				lastWildCardIt = patIt;
                // Skip over looking for next character
                ++patIt;
                if (patIt == tmpPattern.end())
				{
					// Skip right to the end since * matches the entire rest of the string
					strIt = tmpStr.end();
				}
				else
                {
					// scan until we find next pattern character
                    while(strIt != tmpStr.end() && *strIt != *patIt)
                        ++strIt;
                }
            }
            else
            {
                if (*patIt != *strIt)
                {
					if (lastWildCardIt != tmpPattern.end())
					{
						// The last wildcard can match this incorrect sequence
						// rewind pattern to wildcard and keep searching
						patIt = lastWildCardIt;
						lastWildCardIt = tmpPattern.end();
					}
					else
					{
						// no wildwards left
						return false;
					}
                }
                else
                {
                    ++patIt;
                    ++strIt;
                }
            }

        }
		// If we reached the end of both the pattern and the string, we succeeded
		if (patIt == tmpPattern.end() && strIt == tmpStr.end())
		{
        	return true;
		}
		else
		{
			return false;
		}

    }
Example #30
0
//TODO factorize code with cairolistimporter.cpp
ListImporter::ListImporter(const FileSystem::Identifier &identifier):
    Importer(identifier)
{
    fps=15;

    ifstream stream(identifier.filename.c_str());

    if(!stream)
    {
        synfig::error("Unable to open "+identifier.filename);
        return;
    }

    String line;
    String prefix=etl::dirname(identifier.filename)+ETL_DIRECTORY_SEPARATOR;

    ///! read first line and check whether it is a Papagayo lip sync file
    if(!FileSystem::safe_get_line(stream, line).eof())
        if (line == "MohoSwitch1")
        {
            //! it is a Papagayo lipsync file
            String phoneme, prevphoneme, prevext, ext(".jpg"); // default image format
            int frame, prevframe = -1; // it means that the previous phoneme is not known

            while(!FileSystem::safe_get_line(stream, line).eof())
            {
                if(line.find(String("FPS ")) == 0)
                {
                    float f = atof(String(line.begin()+4,line.end()).c_str());
                    if (f) fps = f;
                    continue;
                }

                if (line == "bmp"  ||
                        line == "gif"  ||
                        line == "jpg"  ||
                        line == "png"  ||
                        line == "ppm"  ||
                        line == "tiff" )
                {
                    ext = String(".") + line;
                    continue;
                }
                //! find space position. The format is "frame phoneme-name".
                size_t pos = line.find(String(" "));
                if(pos != String::npos)
                {
                    frame = atoi(String(line.begin(),line.begin()+pos).c_str());
                    phoneme = String(line.begin()+pos+1, line.end());

                    if (prevframe != -1)
                        while (prevframe < frame)
                        {
                            filename_list.push_back(prefix + prevphoneme + prevext);
                            synfig::info("frame %d, phoneme = %s, path = '%s'", prevframe, prevphoneme.c_str(), (prefix + prevphoneme + prevext).c_str());
                            prevframe++;
                        }

                    prevext = ext;
                    prevframe = frame;
                    prevphoneme = phoneme;
                }
            }

            filename_list.push_back(prefix + prevphoneme + prevext);	// do it one more time for the last phoneme
            synfig::info("finally, frame %d, phoneme = %s, path = '%s'", prevframe, prevphoneme.c_str(), (prefix + prevphoneme + prevext).c_str());

            return;
        }

    stream.seekg(ios_base::beg);
    while(!FileSystem::safe_get_line(stream, line).eof())
    {
        if(line.empty())
            continue;
        //! If we have a framerate, then use it
        if(line.find(String("FPS "))==0)
        {
            fps=atof(String(line.begin()+4,line.end()).c_str());
            //synfig::warning("FPS=%f",fps);
            if(!fps)
                fps=15;
            continue;
        }
        filename_list.push_back(prefix+line);
    }
}