SharedPtr<Technique> Technique::CloneWithDefines(const String& vsDefines, const String& psDefines) { // Return self if no actual defines if (vsDefines.Empty() && psDefines.Empty()) return SharedPtr<Technique>(this); Pair<StringHash, StringHash> key = MakePair(StringHash(vsDefines), StringHash(psDefines)); // Return existing if possible HashMap<Pair<StringHash, StringHash>, SharedPtr<Technique> >::Iterator i = cloneTechniques_.Find(key); if (i != cloneTechniques_.End()) return i->second_; // Set same name as the original for the clones to ensure proper serialization of the material. This should not be a problem // since the clones are never stored to the resource cache i = cloneTechniques_.Insert(MakePair(key, Clone(GetName()))); for (Vector<SharedPtr<Pass> >::ConstIterator j = i->second_->passes_.Begin(); j != i->second_->passes_.End(); ++j) { Pass* pass = (*j); if (!pass) continue; if (!vsDefines.Empty()) pass->SetVertexShaderDefines(pass->GetVertexShaderDefines() + " " + vsDefines); if (!psDefines.Empty()) pass->SetPixelShaderDefines(pass->GetPixelShaderDefines() + " " + psDefines); } return i->second_; }
bool CreateDirectory ( String dir ) { if ( dir.Empty() ) return true; int max = 0; String *dirs = dir.FindReplace ( "/", "\\" ).FindReplace ( "\\\\", "\\" ).SplitToken ( '\\', &max ); int start = 1; String curDir = dirs[0]; // if ( !curDir.IsIn(":\\") ) // { curDir = ""; start = 0; // } for ( int i = start; i < max; i++ ) { if ( !curDir.Empty() ) curDir += "\\"; curDir += dirs[i]; #ifdef _WIN32 CreateDirectory ( curDir.c_str(), 0 ); #else String newDir = curDir; newDir = newDir.FindReplace ( "\\", "/" ); mkdir(newDir.c_str(), 0755); #endif } return true; }
MessageBox::MessageBox(Context* context, const String& messageString, const String& titleString, XMLFile* layoutFile, XMLFile* styleFile) : Object(context), titleText_(0), messageText_(0), okButton_(0) { // If layout file is not given, use the default message box layout if (!layoutFile) { ResourceCache* cache = GetSubsystem<ResourceCache>(); layoutFile = cache->GetResource<XMLFile>("UI/MessageBox.xml"); if (!layoutFile) // Error is already logged return; // Note: windowless MessageBox should not be used! } UI* ui = GetSubsystem<UI>(); window_ = ui->LoadLayout(layoutFile, styleFile); ui->GetRoot()->AddChild(window_); // Set the title and message strings if they are given titleText_ = dynamic_cast<Text*>(window_->GetChild("TitleText", true)); if (titleText_ && !titleString.Empty()) titleText_->SetText(titleString); messageText_ = dynamic_cast<Text*>(window_->GetChild("MessageText", true)); if (messageText_ && !messageString.Empty()) messageText_->SetText(messageString); // Center window after the message is set Window* window = dynamic_cast<Window*>(window_.Get()); if (window) { Graphics* graphics = GetSubsystem<Graphics>(); // May be null if headless if (graphics) { const IntVector2& size = window->GetSize(); window->SetPosition((graphics->GetWidth() - size.x_) / 2, (graphics->GetHeight() - size.y_) / 2); } else LOGWARNING("Instantiating a modal window in headless mode!"); window->SetModal(true); SubscribeToEvent(window, E_MODALCHANGED, HANDLER(MessageBox, HandleMessageAcknowledged)); } // Bind the buttons (if any in the loaded UI layout) to event handlers okButton_ = dynamic_cast<Button*>(window_->GetChild("OkButton", true)); if (okButton_) { ui->SetFocusElement(okButton_); SubscribeToEvent(okButton_, E_RELEASED, HANDLER(MessageBox, HandleMessageAcknowledged)); } Button* cancelButton = dynamic_cast<Button*>(window_->GetChild("CancelButton", true)); if (cancelButton) SubscribeToEvent(cancelButton, E_RELEASED, HANDLER(MessageBox, HandleMessageAcknowledged)); Button* closeButton = dynamic_cast<Button*>(window_->GetChild("CloseButton", true)); if (closeButton) SubscribeToEvent(closeButton, E_RELEASED, HANDLER(MessageBox, HandleMessageAcknowledged)); }
Element* XMLNodeHandlerHead::ElementStart(XMLParser* parser, const String& name, const XMLAttributes& attributes) { if (name == "head") { // Process the head attribute parser->GetDocumentHeader()->source = parser->GetSourceURL().GetURL(); } // Is it a link tag? else if (name == "link") { // Lookup the type and href String type = attributes.Get<String>("type", "").ToLower(); String href = attributes.Get<String>("href", ""); if (!type.Empty() && !href.Empty()) { // If its RCSS (... or CSS!), add to the RCSS fields. if (type == "text/rcss" || type == "text/css") { parser->GetDocumentHeader()->rcss_external.push_back(href); } // If its an template, add to the template fields else if (type == "text/template") { parser->GetDocumentHeader()->template_resources.push_back(href); } else { Log::ParseError(parser->GetSourceURL().GetURL(), parser->GetLineNumber(), "Invalid link type '%s'", type.CString()); } } else { Log::ParseError(parser->GetSourceURL().GetURL(), parser->GetLineNumber(), "Link tag requires type and href attributes"); } } // Process script tags else if (name == "script") { // Check if its an external string String src = attributes.Get<String>("src", ""); if (src.Length() > 0) { parser->GetDocumentHeader()->scripts_external.push_back(src); } } // No elements constructed return NULL; }
bool CFile::UncompressToFile ( String toFile, CBaseFile *spkfile, bool includedir, CProgressInfo *progress ) { #ifdef _WIN32 if ( (!m_sData) || (!m_lDataSize) ) return false; // if theres a tmp file, open it and check it still exists if ( !m_sTmpFile.Empty() ) { FILE *id = fopen ( m_sTmpFile.c_str(), "rb" ); if ( id ) { fclose ( id ); return true; } m_sTmpFile = ""; } // now uncompress to the file String file = toFile; if ( file.Empty() ) { m_iTempNum++; file = String("uncompr") + (long)m_iTempNum + ".tmp"; } else file = GetFullFileToDir ( file, includedir, spkfile ); FILE *id = fopen ( "compr.tmp", "wb" ); if ( !id ) return false; fwrite ( m_sData, sizeof(unsigned char), m_lDataSize, id ); bool ret = false; int err = ferror(id); fclose ( id ); if ( !err ) { if ( LZMADecodeFile ( "compr.tmp", file.c_str(), (CProgressInfo7Zip *)progress ) ) { ret = true; if ( toFile.Empty() ) m_sTmpFile = file; } } remove ( "compr.tmp" ); return ret; #else return false; #endif }
std::vector<String> IMAPFetchParser::_ParseString(String &sString) { std::vector<String> vecResult; _CleanFetchString(sString); while (!sString.IsEmpty()) { long lFirstLeftBracket = sString.Find(_T("[")); long lFirstSpace = sString.Find(_T(" ")); if (lFirstLeftBracket >= 0 && lFirstLeftBracket < lFirstSpace) { // Find end bracket. long lFirstRightBracket = sString.Find(_T("]"), lFirstLeftBracket); // Check if we got a <> directly after the [] if (sString.SafeGetAt(lFirstRightBracket + 1) == '<') lFirstRightBracket = sString.Find(_T(">"), lFirstRightBracket); // Parse out string between brackets. if (lFirstRightBracket <= 0) { sString = sString.Mid(lFirstRightBracket + 1); continue; } // String between brackets. String sResString = sString.Mid(0, lFirstRightBracket+1 ); vecResult.push_back(sResString); // Cut away this from the start string. sString = sString.Mid(lFirstRightBracket + 1); } else if (lFirstSpace >= 0) { // Copy string from here to end. String sResString = sString.Mid(0, lFirstSpace ); vecResult.push_back(sResString); sString = sString.Mid(lFirstSpace + 1); } else { vecResult.push_back(sString); sString.Empty(); } _CleanFetchString(sString); } return vecResult; }
void StringParser::Base64Decode(const String &sInput, String &sOutput) { if (sInput.GetLength() == 0) { sOutput.Empty(); return; } AnsiString sInputStr = sInput; MimeCodeBase64 DeCoder; DeCoder.AddLineBreak(false); DeCoder.SetInput(sInputStr, sInputStr.GetLength(), false); AnsiString output; DeCoder.GetOutput(output); int length = output.GetLength(); // Since we're going to store the result in // a normal StdString, we can't return null // characters. for (int i = 0; i < length; i++) { if (output[i] == 0) output[i] = '\t'; } sOutput = output; }
void FileSystem::RegisterPath(const String& pathName) { if (pathName.Empty()) return; allowedPaths_.Insert(AddTrailingSlash(pathName)); }
bool FileSystem::SystemOpen(const String& fileName, const String& mode) { if (allowedPaths_.Empty()) { if (!FileExists(fileName) && !DirExists(fileName)) { LOGERROR("File or directory " + fileName + " not found"); return false; } #ifdef WIN32 bool success = (size_t)ShellExecuteW(0, !mode.Empty() ? WString(mode).CString() : 0, GetWideNativePath(fileName).CString(), 0, 0, SW_SHOW) > 32; #else Vector<String> arguments; arguments.Push(fileName); bool success = SystemRun( #if defined(__APPLE__) "/usr/bin/open", #else "/usr/bin/xdg-open", #endif arguments) == 0; #endif if (!success) LOGERROR("Failed to open " + fileName + " externally"); return success; } else { LOGERROR("Opening a file externally is not allowed"); return false; } }
bool LuaScript::LoadRawFile(const String& fileName) { PROFILE(LoadRawFile); LOGINFO("Finding Lua file on file system: " + fileName); ResourceCache* cache = GetSubsystem<ResourceCache>(); String filePath = cache->GetResourceFileName(fileName); if (filePath.Empty()) { LOGINFO("Lua file not found: " + fileName); return false; } filePath = GetNativePath(filePath); LOGINFO("Loading Lua file from file system: " + filePath); if (luaL_loadfile(luaState_, filePath.CString())) { const char* message = lua_tostring(luaState_, -1); LOGERRORF("Load Lua file failed: %s", message); lua_pop(luaState_, 1); return false; } LOGINFO("Lua file loaded: " + filePath); return true; }
void Console::HandleTextFinished(StringHash eventType, VariantMap& eventData) { using namespace TextFinished; String line = lineEdit_->GetText(); if (!line.Empty()) { // Send the command as an event for script subsystem using namespace ConsoleCommand; SendEvent(E_CONSOLECOMMAND, P_COMMAND, line, P_ID, static_cast<Text*>(interpreters_->GetSelectedItem())->GetText()); // Make sure the line isn't the same as the last one if (history_.Empty() || line != history_.Back()) { // Store to history, then clear the lineedit history_.Push(line); if (history_.Size() > historyRows_) history_.Erase(history_.Begin()); } historyPosition_ = history_.Size(); // Reset autoCompletePosition_ = autoComplete_.Size(); // Reset currentRow_.Clear(); lineEdit_->SetText(currentRow_); } }
bool ScriptFile::Load(Deserializer& source) { PROFILE(LoadScript); ReleaseModule(); // Create the module. Discard previous module if there was one asIScriptEngine* engine = script_->GetScriptEngine(); scriptModule_ = engine->GetModule(GetName().CString(), asGM_ALWAYS_CREATE); if (!scriptModule_) { LOGERROR("Failed to create script module " + GetName()); return false; } // Check if this file is precompiled bytecode if (source.ReadFileID() == "ASBC") { ByteCodeDeserializer deserializer = ByteCodeDeserializer(source); if (scriptModule_->LoadByteCode(&deserializer) >= 0) { LOGINFO("Loaded script module " + GetName() + " from bytecode"); compiled_ = true; // Map script module to script resource with userdata scriptModule_->SetUserData(this); return true; } else return false; } else source.Seek(0); // Not bytecode: add the initial section and check for includes if (!AddScriptSection(engine, source)) return false; // Compile. Set script engine logging to retained mode so that potential exceptions can show all error info ScriptLogMode oldLogMode = script_->GetLogMode(); script_->SetLogMode(LOGMODE_RETAINED); script_->ClearLogMessages(); int result = scriptModule_->Build(); String errors = script_->GetLogMessages(); script_->SetLogMode(oldLogMode); if (result < 0) { LOGERROR("Failed to compile script module " + GetName() + ":\n" + errors); return false; } if (!errors.Empty()) LOGWARNING(errors); LOGINFO("Compiled script module " + GetName()); compiled_ = true; // Map script module to script resource with userdata scriptModule_->SetUserData(this); return true; }
bool ElementImage::LoadTexture() { // Get the source URL for the image. String source = GetAttribute< String >("src", ""); bool nocache = GetAttribute< int >("nocache", 0) != 0; SetPseudoClass( "loading", true ); if( !source.Empty() ) { if( trap::FS_IsUrl( source.CString() ) ) { texture_dirty = false; // the stream cache object references this element // (passed as the void * pointer below) AddReference(); UI_Main::Get()->getStreamCache()->PerformRequest( source.CString(), "GET", NULL, NULL, NULL, &CacheRead, (void *)this, WSW_UI_STREAMCACHE_TIMEOUT, nocache ? 0 : WSW_UI_IMAGES_CACHE_TTL ); return false; } } bool res = LoadDiskTexture(); SetPseudoClass( "loading", false ); return res; }
void Console::HandleTextFinished(StringHash eventType, VariantMap& eventData) { using namespace TextFinished; String line = lineEdit_->GetText(); if (!line.Empty()) { // Send the command as an event for script subsystem using namespace ConsoleCommand; VariantMap& eventData = GetEventDataMap(); eventData[P_COMMAND] = line; eventData[P_ID] = static_cast<Text*>(interpreters_->GetSelectedItem())->GetText(); SendEvent(E_CONSOLECOMMAND, eventData); // Store to history, then clear the lineedit history_.Push(line); if (history_.Size() > historyRows_) history_.Erase(history_.Begin()); historyPosition_ = history_.Size(); currentRow_.Clear(); lineEdit_->SetText(currentRow_); } }
String CFile::GetNameDirectory ( CBaseFile *file ) { String dir = GetDirectory( file ); if ( !dir.Empty() ) dir += "/"; return String(dir + m_sName).FindReplace ( "\\", "/" ); }
void UI_ScriptDocument::LoadScript( Stream *stream, const String &source_name ) { String code; stream->Read( code, stream->Length() ); if( !isLoading ) { return; } as = UI_Main::Get()->getAS(); if( !module ) { if( !as ) { return; } module = as->startBuilding( GetSourceURL().CString() ); } String script_name = source_name; if( script_name.Empty() ) { script_name.FormatString( 100, "_script_%d", numScripts ); } numScripts++; if( module && !code.Empty() && isLoading ) { as->addScript( module, script_name.CString(), code.CString() ); numScriptsAdded++; } }
String Localization::Get(const String& id) { if (id.Empty()) return String::EMPTY; if (GetNumLanguages() == 0) { LOGWARNING("Localization::Get(id): no loaded languages"); return id; } String result = strings_[StringHash(GetLanguage())][StringHash(id)]; if (result.Empty()) { LOGWARNING("Localization::Get(\"" + id + "\") not found translation, language=\"" + GetLanguage() + "\""); return id; } return result; }
String AddTrailingSlash(const String& pathName) { String ret = pathName.Trimmed(); ret.Replace('\\', '/'); if (!ret.Empty() && ret.Back() != '/') ret += '/'; return ret; }
String RemoveTrailingSlash(const String& pathName) { String ret = pathName.Trimmed(); ret.Replace('\\', '/'); if (!ret.Empty() && ret.Back() == '/') ret.Resize(ret.Length() - 1); return ret; }
bool XMLFile::FromString(const String& source) { if (source.Empty()) return false; MemoryBuffer buffer(source.CString(), source.Length()); return Load(buffer); }
bool CFile::WriteToDir ( String &dir, CBaseFile *spkfile, bool includedir, String appendDir, unsigned char *data, long len ) { String fullfile = GetFullFileToDir ( dir, includedir, spkfile ); if ( !appendDir.Empty() ) { if ( !fullfile.Empty() ) fullfile += "/"; fullfile += appendDir; } String fulldir = fullfile.GetToken ( 1, fullfile.NumToken('/') - 2, '/' ); if ( !fulldir.Empty() ) CreateDirectory ( fulldir ); return WriteToFile ( fullfile, data, len ); }
void ShaderVariation::SaveByteCode(const String& binaryShaderName) { ResourceCache* cache = owner_->GetSubsystem<ResourceCache>(); FileSystem* fileSystem = owner_->GetSubsystem<FileSystem>(); // Filename may or may not be inside the resource system String fullName = binaryShaderName; if (!IsAbsolutePath(fullName)) { // If not absolute, use the resource dir of the shader String shaderFileName = cache->GetResourceFileName(owner_->GetName()); if (shaderFileName.Empty()) return; fullName = shaderFileName.Substring(0, shaderFileName.Find(owner_->GetName())) + binaryShaderName; } String path = GetPath(fullName); if (!fileSystem->DirExists(path)) fileSystem->CreateDir(path); SharedPtr<File> file(new File(owner_->GetContext(), fullName, FILE_WRITE)); if (!file->IsOpen()) return; file->WriteFileID("USHD"); file->WriteShort((unsigned short)type_); file->WriteShort(3); file->WriteUInt(parameters_.Size()); for (HashMap<StringHash, ShaderParameter>::ConstIterator i = parameters_.Begin(); i != parameters_.End(); ++i) { file->WriteString(i->second_.name_); file->WriteUByte((unsigned char)i->second_.register_); file->WriteUByte((unsigned char)i->second_.regCount_); } unsigned usedTextureUnits = 0; for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i) { if (useTextureUnit_[i]) ++usedTextureUnits; } file->WriteUInt(usedTextureUnits); for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i) { if (useTextureUnit_[i]) { file->WriteString(graphics_->GetTextureUnitName((TextureUnit)i)); file->WriteUByte((unsigned char)i); } } unsigned dataSize = byteCode_.Size(); file->WriteUInt(dataSize); if (dataSize) file->Write(&byteCode_[0], dataSize); }
void replace_macro_tokens(const char *text, String &fixed_text) { const char*curptr=&text[0]; char tmpm[3]; const char*endat = curptr + strlen(text); fixed_text.Empty(); char tempo[STD_BUFFER_SIZE]; while (1) { if (curptr[0]==0) break; if (curptr>=endat) break; if (curptr[0]=='@') { const char *curptrWasAt = curptr; char macroname[21]; int idd=0; curptr++; for (idd=0;idd<20;idd++) { if (curptr[0]=='@') { macroname[idd]=0; curptr++; break; } // unterminated macro (eg. "@SCORETEXT"), so abort if (curptr[0] == 0) break; macroname[idd]=curptr[0]; curptr++; } macroname[idd]=0; tempo[0]=0; if (stricmp(macroname,"score")==0) sprintf(tempo,"%d",play.score); else if (stricmp(macroname,"totalscore")==0) sprintf(tempo,"%d",MAXSCORE); else if (stricmp(macroname,"scoretext")==0) sprintf(tempo,"%d of %d",play.score,MAXSCORE); else if (stricmp(macroname,"gamename")==0) strcpy(tempo, play.game_name); else if (stricmp(macroname,"overhotspot")==0) { // While game is in Wait mode, no overhotspot text if (!IsInterfaceEnabled()) tempo[0] = 0; else GetLocationName(divide_down_coordinate(mousex), divide_down_coordinate(mousey), tempo); } else { // not a macro, there's just a @ in the message curptr = curptrWasAt + 1; strcpy(tempo, "@"); } fixed_text.Append(tempo); } else { tmpm[0]=curptr[0]; tmpm[1]=0; fixed_text.Append(tmpm); curptr++; } } }
void Urho::Setup() { // On Android and iOS, read command line from a file as parameters can not otherwise be easily given #if defined(ANDROID) || defined(IOS) SharedPtr<File> commandFile(new File(context_, GetSubsystem<FileSystem>()->GetProgramDir() + "Data/CommandLine.txt", FILE_READ)); String commandLine = commandFile->ReadLine(); ParseArguments(commandLine, false); commandFile->Close(); #endif // Check for script file name const Vector<String>& arguments = GetArguments(); String scriptFileName; for (unsigned i = 0; i < arguments.Size(); ++i) { if (arguments[i][0] != '-') { scriptFileName_ = GetInternalPath(arguments[i]); break; } } // Show usage if not found if (scriptFileName_.Empty()) { ErrorExit("Usage: Urho3D <scriptfile> [options]\n\n" "The script file should implement the function void Start() for initializing the " "application and subscribing to all necessary events, such as the frame update.\n" #ifndef WIN32 "\nCommand line options:\n" "-x<res> Horizontal resolution\n" "-y<res> Vertical resolution\n" "-m<level> Enable hardware multisampling\n" "-v Enable vertical sync\n" "-t Enable triple buffering\n" "-w Start in windowed mode\n" "-s Enable resizing when in windowed mode\n" "-q Enable quiet mode which does not log to standard output stream\n" "-b<length> Sound buffer length in milliseconds\n" "-r<freq> Sound mixing frequency in Hz\n" "-headless Headless mode. No application window will be created\n" "-log<level> Change the log level, valid 'level' values are 'debug', 'info', 'warning', 'error'\n" "-prepass Use light pre-pass rendering\n" "-deferred Use deferred rendering\n" "-lqshadows Use low-quality (1-sample) shadow filtering\n" "-noshadows Disable shadow rendering\n" "-nolimit Disable frame limiter\n" "-nothreads Disable worker threads\n" "-nosound Disable sound output\n" "-noip Disable sound mixing interpolation\n" "-sm2 Force SM2.0 rendering\n" #endif ); } }
bool JSONFile::Save(Serializer& dest, const String& indendation) const { StringBuffer buffer; PrettyWriter<StringBuffer> writer(buffer, &(document_->GetAllocator())); writer.SetIndent(!indendation.Empty() ? indendation.Front() : '\0', indendation.Length()); document_->Accept(writer); unsigned size = (unsigned)buffer.GetSize(); return dest.Write(buffer.GetString(), size) == size; }
void RigidBody::RequestMesh() { Entity *parent = ParentEntity(); String collisionMesh = collisionMeshRef.Get().ref.Trimmed(); if (collisionMesh.Empty() && parent) // We use the mesh ref in Mesh as the collision mesh ref if no collision mesh is set in RigidBody. { SharedPtr<Mesh> mesh = parent->Component<Mesh>(); if (!mesh) return; collisionMesh = mesh->meshRef.Get().ref.Trimmed(); } if (!collisionMesh.Empty()) { // Do not create shape right now, but request the mesh resource AssetTransferPtr transfer = GetFramework()->Asset()->RequestAsset(collisionMesh); if (transfer) transfer->Succeeded.Connect(this, &RigidBody::OnCollisionMeshAssetLoaded); } }
String CFile::GetFullFileToDir ( String dir, bool includedir, CBaseFile *file ) { String fullfile = dir; if ( includedir ) { String d = GetDirectory ( file ); if ( !d.Empty() ) { if ( !fullfile.Empty() ) fullfile += "/"; fullfile += d; } } if ( !fullfile.Empty() ) fullfile += "/"; fullfile += m_sName; fullfile = fullfile.FindReplace ( "\\", "/" ); return fullfile; }
/* Func: GetFilePointer Desc: Returns the file pointer name Joins dir and name together Works for relative paths as well */ String CFile::GetFilePointer () { String fullfile = m_sFullDir; if ( !fullfile.Empty() ) fullfile += "/"; if ( !m_sName.Empty() ) fullfile += m_sName; return fullfile; }
XMLElement XMLFile::GetRoot(const String& name) { pugi::xml_node root = document_->first_child(); if (root.empty()) return XMLElement(); if (!name.Empty() && name != root.name()) return XMLElement(); else return XMLElement(this, root.internal_object()); }
void Client::OnConnectionAttemptFailed() { // Provide a reason why the connection failed. String address = LoginProperty("address").GetString(); String port = LoginProperty("port").GetString(); String protocol = LoginProperty("protocol").GetString(); String failReason = "Could not connect to host"; if (!address.Empty()) { failReason.Append(" " + address); if (!port.Empty()) failReason.Append(":" + port); if (!protocol.Empty()) failReason.Append(" with " + protocol.ToUpper()); } SetLoginProperty("LoginFailed", failReason); DoLogout(true); }