/// <summary> /// Registers a type of logging message. /// <para>This function should be run once for each type of message the programmer creates.</para> /// <para>If a parent is supplied the supplied <paramref name="name"/> will be a child to this parent. If a parent /// is registered with <see cref="Logger::RegisterInterest"/> the childs logging messages will /// also be seen.</para> /// <para><paramref name="parent"/> can be left empty if a parent is not desired.</para> /// <remarks>The parent name supplied with <paramref name="parent"/> needs to be registered before /// any children can be added</remarks> /// </summary> /// <param name="name">Name of the logging message</param> /// <param name="parent">Parent of the supplied name (optional)</param> void Logger::RegisterType ( const rString& name, const rString& parent ) { if ( parent != "" ) { // If a parent is supplied, find it rMap<std::string, LogType>::iterator it = LogTypes.find ( parent.c_str( ) ); // Check if parent was found if ( it != LogTypes.end() ) { // Create LogType, emplace it and record the child in the parent. LogType lt; lt.Parent = parent; LogTypes.emplace ( name.c_str( ), lt ); it->second.Children.push_back ( name ); } else { cerr << Colors::BRed << "Failed to find parent log type for log type: " << name << Colors::Reset << endl; return; } } else { // No parent was supplied so create LogType with no parent. LogType lt; lt.Parent = ""; LogTypes.emplace ( name.c_str( ), lt ); } }
//+---------------------------------------------------+ //|bool CreateSample(const rString &path, AudioBuffer* &buffer, const SDL_AudioSpec* sysSpec) //\---------------------------------------------------+ bool SoundSDL::CreateSample(const rString &path, AudioBuffer* &buffer, const SDL_AudioSpec* sysSpec) { ///Load the wav and recieve the buffer containing the audio data if(!m_AudioFile->LoadSample(path.c_str(), m_BufferData)) { fprintf(stderr, "Failed to load sample %s\n", path.c_str()); return false; } buffer->chunkSize = buffer->spec.size; ///Create audio converter using the data from the wav header int ret = RebuildAudioCVT(m_BufferData, sysSpec); if(ret < 0) { fprintf(stderr, "Failed to build converter: %s\n", path.c_str()); return false; } //Convert the loaded data into matching engine format //If ret == 1 the loaded audio needs not to be converted if(ret == 1) { if(!ConvertBufferData(buffer, m_AudioCVT)) { fprintf(stderr, "Failed to convert audio: %s\n", path.c_str()); return false; } } return true; }
unsigned int rOpenGLGraphicsDevice::CreateShaderProgram(const rString& vertex, const rString& fragment){ GLuint vertexShader; GLuint fragmentShader; GLuint programObject; GLint linked; vertexShader = CompileShader(GL_VERTEX_SHADER, vertex.c_str()); if (!vertexShader) return 0; fragmentShader = CompileShader(GL_FRAGMENT_SHADER, fragment.c_str()); if (!fragmentShader){ glDeleteShader(vertexShader); return 0; } programObject = glCreateProgram(); if (!programObject) return 0; glAttachShader(programObject, vertexShader); glAttachShader(programObject, fragmentShader); glLinkProgram(programObject); glGetProgramiv(programObject, GL_LINK_STATUS, &linked); if (!linked){ GLint infoLen = 0; glGetProgramiv(programObject, GL_INFO_LOG_LENGTH, &infoLen); if (infoLen > 1){ char* infoLog = new char[infoLen]; glGetProgramInfoLog(programObject, infoLen, NULL, infoLog); m_lastError.assign(infoLog, infoLen); delete [] infoLog; } glDeleteProgram(programObject); return 0; } glDeleteShader(vertexShader); glDeleteShader(fragmentShader); m_lastError.clear(); return programObject; }
rString gfx::MaterialBank::GetDir(rString& filename) { bool found = false; for (int i = static_cast<int>(filename.size()); i > 0; i--) { if (filename.c_str()[i] == '/' || filename.c_str()[i] == '\\' ) found = true; if (!found) { filename.erase(i); } } return filename; }
//Creates a shader with defines void gfx::ShaderProgram::CreateShader ( ifstream* FileStream, GLenum shaderType, const rString& filename,bool print, ShaderDefineContainer& container ) { rString line; size_t found; rString shaderText; getline(*FileStream, line); shaderText += line; shaderText += "\n"; shaderText += container.GetAllDefineLines(); shaderText += container.GetDefinesShaderStage ( shaderType ); bool end = false; while ( !end ) { getline ( *FileStream, line ); //search for the end of the shader found = line.find ( "#include " ); if ( found != rString::npos ) { int i = static_cast<int> ( found ) + 9; //found + "#include " rString s; while ( i < static_cast<int> ( line.length() ) ) { s += line[i]; i++; } rString str = GetDir ( rString ( filename.c_str() ) ) + s; shaderText += LoadText ( str.c_str() ); shaderText += "\n"; } else { found = line.find ( "#end_shader" ); if ( found != rString::npos ) { //break loop end = true; break; } else if ( FileStream->eof() ) { Logger::Log( "Could not find end of file " + filename, "ShaderProgram", LogSeverity::ERROR_MSG ); return; } else { shaderText += line; shaderText += '\n'; } } } if ( shaderText.length() > 0 ) { Shader* shader = tNew( Shader ); shader->CreateFromString ( shaderText, shaderType, filename,print ); m_Shaders.push_back ( shader ); shaderText.clear(); } }
void ruiStylesheetLoader::ParseColorProperty(const rString& name, const rString& value){ int r,g,b,a; if (sscanf(value.c_str(), "%i %i %i %i", &r, &g, &b, &a) == 4){ m_currentStyle->SetColor(name, rColor(r,g,b,a)); } }
void GUIEngine::SetWindowClickThrough( const rString& name, bool clickThrough ) { auto windowIt = m_Windows.find( name ) ; if( windowIt != m_Windows.end() ) windowIt->second->SetClickThrough( clickThrough ); else Logger::Log( "Couldn't get window: " + rString( name.c_str()) + ", it doesn't exist.", "GUIEngine", LogSeverity::ERROR_MSG ); }
//+----------------------------------------------------------------------------+ //|bool Initialize(AudioEngine* engine, const rString &path, SoundType type) //\----------------------------------------------------------------------------+ bool SoundSDL::Initialize(AudioEngine* engine, const rString &path, SoundType type) { AudioEngineSDL* audioEngine = reinterpret_cast<AudioEngineSDL*>(engine); const SDL_AudioSpec* sysSpec = audioEngine->GetSystemSpec(); m_AudioEngine = audioEngine; m_Type = type; m_Name = path; m_ChunkSize = sysSpec->size; m_AudioCVT = pNew(SDL_AudioCVT); m_BufferData = tNew(AudioBuffer); m_AudioFile = nullptr; ///Check which file format the requested audiofile are ///Only wav and ogg are supported ///Is wave file if(path.find(".wav", 0) != std::string::npos) { m_AudioFile = pNew(WavFileReader); } ///Is ogg file else if(path.find(".ogg", 0) != std::string::npos) { m_AudioFile = pNew(OggFileReader); } ///Not supported format else { fprintf(stderr, "SoundSDL. Trying to load unsupported file format %s \n", path.c_str()); return false; } m_AudioFile->Initialize(); ///Read as sample, read everything into buffer if(type == SoundType::SAMPLE) { CreateSample(path, m_BufferData, sysSpec); } ///Read as stream, prepare for buffer streaming else if(type == SoundType::STREAM) { CreateStream(path, m_BufferData, sysSpec); } else { ///This should not happend.. fprintf(stderr, "SoundSDL. Unexpected error loading %s while setting sound type \n", path.c_str()); return false; } return true; }
bool KeyBindingCollection::AddMappingWithName( const rString& keyName, ActionIdentifier action, KeyBindingType keyBindType, bool overwrite, bool clearConflicting, rString* errorString ) { SDL_Scancode scanCode = SDL_GetScancodeFromName( keyName.c_str() ); if ( scanCode != SDL_SCANCODE_UNKNOWN ) { return AddMappingWithScancode( scanCode, action, keyBindType, overwrite, clearConflicting, errorString ); } else { LogInput( "Failed to get scancode from name: " + keyName, "KeyBindings", LogSeverity::WARNING_MSG ); if ( errorString != nullptr ) { *errorString = "Failed to get scancode from name: " + keyName; } return false; } }
/// <summary> /// Registers interest in a type of logging message that has been registered with /// <see cref="Logger::RegisterType"/>. /// <para>If a parent is registered all its children will also be registered</para> /// </summary> /// <param name="name">Path to the file to be read</param> /// <param name="severityMask">Bitmask of type <see cref="LogSeverity::BitFlag"/></param> void Logger::RegisterInterest ( const rString& name, int severityMask ) { rMap<std::string, LogType>::iterator it = LogTypes.find ( name.c_str( ) ); if ( it != LogTypes.end() ) { // Create interest entry with supplied severitymask and name. InterestEntry ie; ie.Parent = it->second.Parent; ie.SeverityMask = severityMask; InterestedLogTypes.emplace ( name.c_str( ), ie ); // Add all children as well. for ( rVector<rString>::iterator chit = it->second.Children.begin(); chit != it->second.Children.end(); ++chit ) { RegisterInterest ( *chit, severityMask ); } } else { cerr << Colors::BRed << "Failed to find log type " << name << " interest not registered." << Colors::Reset << endl; } }
//+---------------------------------------------------+ //|bool CreateStream(const rString &path, AudioBuffer* &buffer, const SDL_AudioSpec* sysSpec) //\---------------------------------------------------+ bool SoundSDL::CreateStream(const rString &path, AudioBuffer* &buffer, const SDL_AudioSpec* sysSpec) { if(!m_AudioFile->OpenStream(path.c_str(), m_ChunkSize, buffer)) { fprintf(stderr, "Failed to open wav stream %s\n", path.c_str()); return false; } ///Load the first chunk into memory if(!m_AudioFile->ReadStream(m_BufferData, m_ChunkSize)) { fprintf(stderr, "Failed to stream data %s\n", m_Name.c_str()); return false; } ///Create audio converter using the data from the wav header int ret = RebuildAudioCVT(m_BufferData, sysSpec); if(ret < 0) { fprintf(stderr, "Failed to build converter: %s\n", path.c_str()); return false; } //Convert the loaded data into matching engine format //If ret == 0 the loaded audio needs not to be converted if(ret == 1) { if(!ConvertBufferData(buffer, m_AudioCVT)) { fprintf(stderr, "Failed to convert audio: %s\n", path.c_str()); return false; } } return true; }
rString gfx::ShaderProgram::GetDir ( rString filename ) { bool found = false; for ( int i = static_cast<int> ( filename.size() ); i > 0; i-- ) { if ( filename.c_str() [i] == '/' ) { found = true; } if ( !found ) { filename.erase ( i ); } } return filename; }
rString Logger::GetParentString ( const rString& name, unsigned int treeHeight ) { if ( treeHeight == 0 ) { return ""; } rMap<std::string, LogType>::const_iterator pit = LogTypes.find ( name.c_str( ) ); if ( pit == LogTypes.end() ) { return name; } else if ( pit->second.Parent == "" ) { return name; } return GetParentString ( pit->second.Parent, treeHeight - 1 ) + NameSeparator.c_str( ) + name; }
rString gfx::TextureAtlas::GetDir ( rString str ) { bool found = false; for ( int i = static_cast<int> ( str.size() ); i > 0; i-- ) { if ( str.c_str() [i] == '/' ) { found = true; } if ( !found ) { str.erase ( i ); } } return str; }
unsigned short NetworkUtility::GetPortFromString( const rString& input ) { if ( input != "" && StringUtility::IsDigitsOnly(input) ) { unsigned int port = 0; try { port = static_cast<unsigned int>( std::stoul( input.c_str() ) ); } catch ( ... ) { return 0; } if ( port <= SHRT_MAX ) { return port; } else return 0; } else return 0; }
void rLogContentListener::BeginManifestLoad(const rString& path, int total){ rLog::Info("Begin Loading manifest: %s", path.c_str()); }
/// <summary> /// Logs a message in the logger. /// <para>Logs a message in the logger with the selected type, message and severity.</para> /// <para>Use <see cref="Logger::RegisterType"/> to register types for use with the logger.</para> /// <para>Use <see cref="Logger::RegisterInterest"/> to register interest in a type of /// log message that has been registered.</para> /// </summary> /// <param name="message">A string containing the message to be displayed</param> /// <param name="type">A string defining what type of message it is. (ex. Network or Game)</param> /// <param name="logSeve">The severity of the message to be logged</param> void Logger::Log ( const rString& message, const rString& type, LogSeverity::BitFlag logSev ) { rMap<std::string, InterestEntry>::const_iterator cit = InterestedLogTypes.find ( type.c_str( ) ); // Don't log things we are not interested in if ( cit == InterestedLogTypes.end() ) { return; } else if ( ! ( cit->second.SeverityMask & logSev ) ) { return; } rOStringStream oss; rOStringStream oss2; //Used by the other output stream if ( TimeStamp ) { // TODOJM, Implement } // TODOJM dicuss good way to make threadsafe cout printing if ( HighPrecisionStamp ) { oss << Colors::Yellow << SDL_GetPerformanceCounter() - StartTime << " "; oss2 << "<C=YELLOW>" << SDL_GetPerformanceCounter() - StartTime << " "; } switch ( logSev ) { case LogSeverity::INFO_MSG: { oss << Colors::White << "INFO "; oss2 << "[C=WHITE]" << "INFO "; break; } case LogSeverity::WARNING_MSG: { oss << Colors::BPurple << "WARNING "; oss2 << "[C=PURPLE]" << "WARNING "; break; } case LogSeverity::ERROR_MSG: { oss << Colors::BRed << "ERROR "; oss2 << "[C=RED]" << "ERROR "; break; } case LogSeverity::DEBUG_MSG: { oss << Colors::Green << "DEBUG "; oss2 << "[C=GREEN]" << "DEBUG "; break; } case LogSeverity::ALL: { oss << "WRONG_SEVERITY_DO_NOT_USE "; oss2 << "WRONG_SEVERITY_DO_NOT_USE "; break; } } oss << GetParentString ( cit->first.c_str( ), TreeHeight ) << ": " << message << Colors::Reset << endl; cout << oss.str(); Mutex.lock(); //Needed because it doesn't seem to be threadsafe. It crashes randomly at startup on Linux. oss2 << GetParentString ( cit->first.c_str( ), TreeHeight ) << ": " << message << endl; OutputStream << oss2.str(); Mutex.unlock(); }
bool gfx::TextureAtlas::LoadFile(const rString& filename) { //load file std::ifstream file; file.open(filename.c_str()); if(!file.is_open()) { Logger::Log("Failed to open TextureAtlas " + filename, "Texture",LogSeverity::ERROR_MSG ); return false; } rString line; std::string json; //picojson only wants a std::string m_Filename = filename; while(!file.eof()) { std::getline(file,line); json += line.c_str(); } file.close(); //parse json picojson::value val; picojson::parse(val,json); //check if file was parsed if (! val.is<picojson::object>()) { Logger::Log("Failed to parse json file", "Texture", LogSeverity::ERROR_MSG ); return false; } //Get root objects picojson::object obj = val.get<picojson::object>(); for ( auto& it : obj ) { if(it.first == "frames") { gfx::TextureFrame texFrame; picojson::object filenames = it.second.get<picojson::object>(); for(auto& it2 : filenames) { texFrame.Filename = rString(it2.first.c_str()); picojson::object framedata = it2.second.get<picojson::object>(); for(auto& data : framedata) { if(data.first == "frame") { texFrame.X = stoi(data.second.get("x").to_str()); texFrame.Y = stoi(data.second.get("y").to_str()); texFrame.Width = stoi(data.second.get("w").to_str()); texFrame.Height = stoi(data.second.get("h").to_str()); } } m_Frames.push_back(texFrame); } } //end textureframe data else if(it.first == "meta") { picojson::object atlassData = it.second.get<picojson::object>(); for(auto& data : atlassData) { if(data.first == "image") { m_ImageFilename = rString(data.second.to_str().c_str()); } if(data.first == "size") { m_Width = stoi(data.second.get("w").to_str()); m_Height = stoi(data.second.get("h").to_str()); } } } } //end outer for m_Texture = pNew(Texture); m_Texture->Init((GetDir(m_Filename) + m_ImageFilename).c_str(),TEXTURE_2D); //generate handles int numerator = 0; for(auto& it : m_Frames) { it.Y = it.Y + it.Height; m_Handles[it.Filename] = numerator++; } //generate gpu frames GPUTexture tex; for(auto& t : m_Frames) { tex.S = (t.X / (float) m_Width); tex.T = ((m_Height - t.Y) / (float) m_Height); tex.NormWidth = t.Width / (float) m_Width; tex.NormHeight = t.Height / (float) m_Height; m_GPUFrames.push_back(tex); } m_Frames.clear(); return true; }
GLuint gfx::ShaderProgram::GetUniformLocationByName ( const rString& name ) { return glGetUniformLocation ( m_Handle,name.c_str() ); }
bool gfx::Shader::CreateFromFile( const rString& Filename, GLenum ShaderType, bool print ) { m_Path = Filename; m_Type = ShaderType; std::ifstream fin; fin.open ( Filename.c_str() ); if ( !fin.is_open() ) { if ( print ) { Logger::Log( "Cant open shader file " + Filename, "Shader", LogSeverity::ERROR_MSG ); } return false; } rString shadertext; size_t found; rString line; while ( !fin.eof() ) { getline ( fin, line ); found = line.find ( "#include " ); if ( found != rString::npos ) { int i = static_cast<int> ( found ) + 9; //found + "#include " rString s; while ( i < line.length() ) { s += line[i]; i++; } rString str = GetDir ( rString ( Filename ) ) + s; shadertext += LoadText ( str.c_str() ); shadertext += "\n"; } else { shadertext += line; shadertext += '\n'; } } fin.close(); //create shader object m_Handle = glCreateShader ( ShaderType ); if ( m_Handle == 0 ) { if ( print ) { Logger::Log( "Error creating shader", "Shader", LogSeverity::ERROR_MSG ); } } const char* text = shadertext.c_str(); glShaderSource ( m_Handle,1,&text,nullptr ); glCompileShader ( m_Handle ); int result = 0; glGetShaderiv ( m_Handle, GL_COMPILE_STATUS, &result ); if ( result == GL_FALSE ) { if ( print ) { Logger::Log( "ERROR, compiling shader " + Filename, "Shader", LogSeverity::ERROR_MSG ); } int length = 0; glGetShaderiv ( m_Handle, GL_INFO_LOG_LENGTH, &length ); if ( length > 0 ) { // create a log of error messages char* errorLog = fNewArray (char, length); int written = 0; glGetShaderInfoLog ( m_Handle, length, &written, errorLog ); if ( print ) { Logger::Log( "Error log: " + rString( errorLog ), "Shader", LogSeverity::ERROR_MSG ); } fDeleteArray (errorLog); } return false; }
// Create shaderprogram with a define container bool gfx::ShaderProgram::LoadCompleteShaderProgramFromFile ( const rString& filename, bool print, ShaderDefineContainer& container ) { //this function is used to load a set of shaders from a single file //seperate each shader with a #new_shader ******* and a #end_shader //where **** can be a vertex, geometry, control, evaluation or fragment //extra code can be loaded into the current shader by the #include filename macro m_Filename = rString ( filename.c_str() ); m_LoadedShaders = true; m_Defines = container; ifstream fin; fin.open ( filename.c_str() ); if ( !fin.is_open() ) { if ( print ) { Logger::Log( "Could not open file " + filename, "ShaderProgram", LogSeverity::ERROR_MSG ); return false; } return false; } rString line; size_t found; while ( !fin.eof() ) { getline ( fin, line ); if ( (found = line.find( "#new_shader" )) != rString::npos ) { if ( (found = line.find( "vertex" )) != rString::npos ) { CreateShader ( &fin, GL_VERTEX_SHADER, filename,print,container ); } if ( (found = line.find( "geometry" )) != rString::npos ) { CreateShader ( &fin, GL_GEOMETRY_SHADER, filename, print,container ); } if ( (found = line.find( "control" )) != rString::npos ) { CreateShader ( &fin, GL_TESS_CONTROL_SHADER, filename, print,container ); } if ( (found = line.find( "evaluation" )) != rString::npos ) { CreateShader ( &fin, GL_TESS_EVALUATION_SHADER, filename, print,container ); } if ( (found = line.find( "fragment" )) != rString::npos ) { CreateShader ( &fin, GL_FRAGMENT_SHADER, filename, print,container ); } if ( (found = line.find( "compute" )) != rString::npos ) { CreateShader ( &fin, GL_COMPUTE_SHADER, filename, print,container ); } } } m_Handle = glCreateProgram(); if ( m_Handle == 0 ) { if ( print ) { Logger::Log( "Could not create shader program", "ShaderProgram", LogSeverity::ERROR_MSG ); return false; } return false; } //attach shaders to program for ( int i = 0; i < static_cast<int> ( m_Shaders.size() ); i++ ) { glAttachShader ( m_Handle, m_Shaders[i]->GetHandle() ); } //link shaders glLinkProgram ( m_Handle ); //error checking GLint status; glGetProgramiv ( m_Handle, GL_LINK_STATUS, &status ); if ( status == GL_FALSE ) { char log[1024]; int len = 0; Logger::Log( "Could not link shaders to program", "ShaderProgram", LogSeverity::ERROR_MSG ); glGetProgramInfoLog ( m_Handle, sizeof ( log ), &len, log ); Logger::Log( "Error log: " + rString( log ), "ShaderProgram", LogSeverity::ERROR_MSG ); return false; } if ( print ) { Logger::Log( "Linked Shaders to program", "ShaderProgram", LogSeverity::DEBUG_MSG ); } Validate(); return true; }
void rLogContentListener::EndManifestLoad(const rString& path){ rLog::Info("Finished Loading manifest: %s", path.c_str()); }
void rLogContentListener::ManifestLoadError(rAssetType type, const rString& name, const rString& path, rContentError error, int current, int total){ rString typeStr = rAsset::StringForType(type); rLog::Error("Error %d loading %s %s from %s", (int)error, typeStr.c_str(), name.c_str(), path.c_str()); }
//note this is a temporary implementation for now rString FormatString(const rString format, va_list args) { char buffer[2056]; vsprintf(buffer, format.c_str(), args); return rString(buffer); }
rIStringStream::rIStringStream(const rString& str) :m_stream(str.c_str()) { }
void rLogContentListener::ManifestLoadProgress(rAssetType type, const rString& name, const rString& path, int current, int total){ rString typeStr = rAsset::StringForType(type); rLog::Info("Loaded %s %s from %s", typeStr.c_str(), name.c_str(), path.c_str()); }